summaryrefslogtreecommitdiffstats
path: root/third_party/heimdal/lib/gssapi/gss-token.c
blob: a4c02967cf3f15730cc3258797791c127af7f951 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
/* */

/*-
 * Copyright (c) 1997-2011 Roland C. Dowdeswell
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer and
 *    dedication in the documentation and/or other materials provided
 *    with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

#include <errno.h>
#ifdef __APPLE__
#include <malloc/malloc.h>
#elif HAVE_MALLOC_H
#include <malloc.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <gssapi/gssapi.h>
#include <gssapi/gssapi_krb5.h>
#include <krb5.h>
#include <base64.h>
#include <getarg.h>
#include <roken.h>
#include <vers.h>

#define GBAIL(x, _maj, _min)	do {					\
		if (GSS_ERROR(_maj)) {					\
			char	*the_gss_err;				\
									\
			ret = 1;					\
			the_gss_err = gss_mk_err(_maj, _min, x);	\
			if (the_gss_err)				\
				fprintf(stderr, "%s\n", the_gss_err);	\
			else						\
				fprintf(stderr, "err making err\n");	\
			free(the_gss_err);				\
			goto bail;					\
		}							\
	} while (0)

#define K5BAIL(x)	do {						\
		kret = x;						\
		if (kret) {						\
			const char 	*k5err;				\
									\
			k5err = krb5_get_error_message(kctx, kret);	\
			if (k5err) {					\
				fprintf(stderr, "%s in %s:%s\n", k5err,	\
				    #x, __func__);			\
				krb5_free_error_message(kctx, k5err);	\
			} else {					\
				fprintf(stderr, "unknown error %d in "	\
				    "%s:%s\n", kret, #x, __func__);	\
			}						\
			exit(1); /* XXXrcd: shouldn't exit */		\
		}							\
	} while (0)


/*
 * global variables
 */

int	Sflag = 0;
int	nflag = 0;
gss_OID	global_mech = GSS_C_NO_OID;

static char *
gss_mk_err(OM_uint32 maj_stat, OM_uint32 min_stat, const char *preamble)
{
	gss_buffer_desc	 status;
	OM_uint32	 new_stat;
	OM_uint32	 cur_stat;
	OM_uint32	 msg_ctx = 0;
	OM_uint32	 ret;
	int		 type;
	size_t		 newlen;
	char		*str = NULL;
	char		*tmp = NULL;

	cur_stat = maj_stat;
	type = GSS_C_GSS_CODE;

	for (;;) {

		/*
		 * GSS_S_FAILURE produces a rather unhelpful message, so
		 * we skip straight to the mech specific error in this case.
		 */

		if (type == GSS_C_GSS_CODE && cur_stat == GSS_S_FAILURE) {
			type = GSS_C_MECH_CODE;
			cur_stat = min_stat;
		}

		ret = gss_display_status(&new_stat, cur_stat, type,
		    GSS_C_NO_OID, &msg_ctx, &status);

		if (GSS_ERROR(ret))
			return str;	/* XXXrcd: hmmm, not quite?? */

		if (str)
			newlen = strlen(str);
		else
			newlen = strlen(preamble);

		newlen += status.length + 3;

		tmp = str;
		str = malloc(newlen);

		if (!str) {
			gss_release_buffer(&new_stat, &status);
			return tmp;	/* XXXrcd: hmmm, not quite?? */
		}

		snprintf(str, newlen, "%s%s%.*s", tmp?tmp:preamble,
		    tmp?", ":": ", (int)status.length, (char *)status.value);

		gss_release_buffer(&new_stat, &status);
		free(tmp);

		/*
		 * If we are finished processing for maj_stat, then
		 * move onto min_stat.
		 */

		if (msg_ctx == 0 && type == GSS_C_GSS_CODE && min_stat != 0) {
			type = GSS_C_MECH_CODE;
			cur_stat = min_stat;
			continue;
		}

		if (msg_ctx == 0)
			break;
	}

	return str;
}

static char *
read_buffer(FILE *fp)
{
	char	 buf[65536];
	char	*p;
	char	*ret = NULL;
	size_t	 buflen;
	size_t	 retlen = 0;

	while (fgets(buf, sizeof(buf), fp) != NULL) {
		if ((p = strchr(buf, '\n')) == NULL) {
			fprintf(stderr, "Long line, exiting.\n");
			exit(1);
		}
		*p = '\0';
		buflen = strlen(buf);
		if (buflen == 0)
			break;

		ret = realloc(ret, retlen + buflen + 1);
		if (!ret) {
			perror("realloc");
			exit(1);
		}
		memcpy(ret + retlen, buf, buflen);
		ret[retlen + buflen] = '\0';
		retlen += buflen;
	}

	if (ferror(stdin)) {
		perror("fgets");
		exit(1);
	}

	return ret;
}

static int
write_and_free_token(gss_buffer_t out, int negotiate)
{
	OM_uint32	 min;
	char		*outstr = NULL;
	char		*p = out->value;
	size_t		 len = out->length;
	size_t		 inc;
	int		 ret = 0;
	int		 first = 1;

	if (nflag)
		goto bail;

	/*
	 * According to RFC 2744 page 25, we simply don't output
	 * zero length output tokens.
	 */
	if (len == 0)
		goto bail;

	inc = len;
	if (Sflag)
		inc = Sflag;

	do {
		if (first)
			first = 0;
		else
			printf("\n");
		if (len < inc)
			inc = len;
		if (rk_base64_encode(p, inc, &outstr) < 0) {
			fprintf(stderr, "Out of memory.\n");
			ret = errno;
			goto bail;
		}
                ret = 0;
		printf("%s%s\n", negotiate?"Negotiate ":"", outstr);
		free(outstr);
		p   += inc;
		len -= inc;
	} while (len > 0);
        ret = 0;

bail:
	gss_release_buffer(&min, out);
	return ret;
}

static int
read_token(gss_buffer_t in, int negotiate)
{
	char	*inbuf = NULL;
	char	*tmp;
	size_t	 len;
	int	 ret = 0;

	/* We must flush before we block wanting input */
	fflush(stdout);

	*in = (gss_buffer_desc)GSS_C_EMPTY_BUFFER;
	inbuf = read_buffer(stdin);
	if (!inbuf)
		/* Just a couple of \n's in a row or EOF, no error. */
		return 0;

	tmp = inbuf;
	if (negotiate) {
		if (strncasecmp("Negotiate ", inbuf, 10) != 0) {
			fprintf(stderr, "Token doesn't begin with "
			    "\"Negotiate \"\n");
			ret = -1;
			goto bail;
		}

		tmp += 10;
	}

	len = strlen(tmp);
	in->value = malloc(len + 1);
	if (!in->value) {
		fprintf(stderr, "Out of memory.\n");
		ret = -1;
		goto bail;
	}
	ret = rk_base64_decode(tmp, in->value);
	if (ret < 0) {
		free(in->value);
		in->value = NULL;
		if (errno == EOVERFLOW)
			fprintf(stderr, "Token is too big\n");
		else
			fprintf(stderr, "Token encoding is not valid "
			    "base64\n");
		goto bail;
	} else {
		in->length = ret;
	}
	ret = 0;

bail:
	free(inbuf);
	return ret;
}

static int
initiate_one(gss_name_t service, int delegate, int negotiate)
{
	gss_ctx_id_t	 ctx = GSS_C_NO_CONTEXT;
	gss_buffer_desc	 in;
	gss_buffer_desc	 out;
	OM_uint32	 maj;
	OM_uint32	 min;
	OM_uint32	 flags = 0;
	int		 first = 1;
	int		 ret = 0;

	if (delegate)
		flags |= GSS_C_DELEG_FLAG;

	do {
		out.length = 0;
		out.value  = 0;

		if (first) {
			in.length  = 0;
			in.value   = 0;
			first      = 0;
		} else {
			printf("\n");
			ret = read_token(&in, negotiate);
			if (ret)
				return ret;
			if (feof(stdin))
				return -1;
		}

		maj = gss_init_sec_context(&min, GSS_C_NO_CREDENTIAL, &ctx,
		    service, global_mech, flags, 0,
		    GSS_C_NO_CHANNEL_BINDINGS, &in, NULL, &out,
		    NULL, NULL);

		ret = write_and_free_token(&out, negotiate);
		if (ret)
			return ret;

		GBAIL("gss_init_sec_context", maj, min);
	} while (maj & GSS_S_CONTINUE_NEEDED);

bail:
	if (ctx != GSS_C_NO_CONTEXT) {
		/*
		 * XXXrcd: here we ignore the fact that we might have an
		 *         output token as this program doesn't do terribly
		 *         well in that case.
		 */
		gss_delete_sec_context(&min, &ctx, NULL);
	}

	return ret;
}

static krb5_error_code
copy_cache(krb5_context kctx, krb5_ccache from, krb5_ccache to)
{
	krb5_error_code	kret;
	krb5_principal	princ = NULL;
	krb5_cc_cursor	cursor;
	krb5_creds	cred;

	K5BAIL(krb5_cc_get_principal(kctx, from, &princ));
	K5BAIL(krb5_cc_initialize(kctx, to, princ));
	K5BAIL(krb5_cc_start_seq_get(kctx, from, &cursor));
	for (;;) {
		kret = krb5_cc_next_cred(kctx, from, &cursor, &cred);
		if (kret)
			break;
		kret = krb5_cc_store_cred(kctx, to, &cred);
		krb5_free_cred_contents(kctx, &cred);
		if (kret)
			break;
	}
	krb5_cc_end_seq_get(kctx, from, &cursor);

	if (kret == KRB5_CC_END)
		kret = 0;
	K5BAIL(kret);

	if (princ)
		krb5_free_principal(kctx, princ);

	return kret;
}

static int
initiate_many(gss_name_t service, int delegate, int negotiate, int memcache,
	      size_t count)
{
	krb5_error_code	kret = 0;
	krb5_context	kctx = NULL;
	krb5_ccache	def_cache = NULL;
	krb5_ccache	mem_cache = NULL;
	size_t		i;

	if (memcache) {
		K5BAIL(krb5_init_context(&kctx));
		K5BAIL(krb5_cc_default(kctx, &def_cache));
		K5BAIL(krb5_cc_resolve(kctx, "MEMORY:mem_cache", &mem_cache));
		putenv("KRB5CCNAME=MEMORY:mem_cache");
	}

	for (i=0; i < count; i++) {
		if (memcache)
			K5BAIL(copy_cache(kctx, def_cache, mem_cache));
		kret = initiate_one(service, delegate, negotiate);

		if (!nflag && i < count - 1)
			printf("\n");
	}

	if (kctx)
		krb5_free_context(kctx);
	if (def_cache)
		krb5_cc_close(kctx, def_cache);
	if (mem_cache)
		krb5_cc_close(kctx, mem_cache);

	return kret;
}

static int
accept_one(gss_name_t service, const char *ccname, int negotiate)
{
	gss_cred_id_t	 cred = NULL;
	gss_cred_id_t	 deleg_creds = NULL;
        gss_name_t       client;
        gss_OID          mech_oid;
        gss_ctx_id_t     ctx = GSS_C_NO_CONTEXT;
        gss_buffer_desc  in = GSS_C_EMPTY_BUFFER;
        gss_buffer_desc  out;
        gss_buffer_desc  dname = GSS_C_EMPTY_BUFFER;
	krb5_context	 kctx = NULL;
	krb5_ccache	 ccache = NULL;
	krb5_error_code	 kret;
        OM_uint32        maj, min;
	int		 ret = 0;

	if (service) {
		maj = gss_acquire_cred(&min, service, 0, NULL, GSS_C_ACCEPT,
		    &cred, NULL, NULL);
		GBAIL("gss_acquire_cred", maj, min);
	}

	do {
		if (feof(stdin))
			return -1;
		ret = read_token(&in, negotiate);
		if (ret)
			return ret;

		out.length = 0;
		out.value  = 0;

		maj = gss_accept_sec_context(&min, &ctx, cred, &in,
		    GSS_C_NO_CHANNEL_BINDINGS, &client, &mech_oid, &out,
		    NULL, NULL, &deleg_creds);

		ret = write_and_free_token(&out, negotiate);
		if (ret) {
			OM_uint32 junk;

			(void) gss_delete_sec_context(&junk, &ctx,
						      GSS_C_NO_BUFFER);
			return ret;
		}
		GBAIL("gss_accept_sec_context", maj, min);
	} while (maj & GSS_S_CONTINUE_NEEDED);

	/*
	 * XXXrcd: not bothering to clean up because we're about to exit.
	 *         Probably should fix this in case the code is used as
	 *         an example by someone.
	 */

	maj = gss_display_name(&min, client, &dname, NULL);
	GBAIL("gss_display_name", maj, min);

	if (!nflag)
		printf("Authenticated: %.*s\n", (int)dname.length,
		    (char *)dname.value);
	(void) gss_release_buffer(&min, &dname);
	(void) gss_release_name(&min, &client);
	(void) gss_delete_sec_context(&min, &ctx, GSS_C_NO_BUFFER);

	if (ccname) {
#ifdef HAVE_GSS_STORE_CRED_INTO
		gss_key_value_set_desc		store;
		gss_key_value_element_desc	elem;
		int				overwrite_cred = 1;
		int				default_cred = 0;

		elem.key = "ccache";
		elem.value = ccname;
		store.count = 1;
		store.elements = &elem;

		maj = gss_store_cred_into(&min, deleg_creds, GSS_C_INITIATE,
		    GSS_C_NO_OID, overwrite_cred, default_cred, &store, NULL,
		    NULL);
		GBAIL("gss_store_cred_into", maj, min);
#else
		K5BAIL(krb5_init_context(&kctx));
		K5BAIL(krb5_cc_resolve(kctx, ccname, &ccache));

		maj = gss_krb5_copy_ccache(&min, deleg_creds, ccache);
		GBAIL("gss_krb5_copy_ccache", maj, min);
#endif
	}

bail:
	if (kctx)
		krb5_free_context(kctx);
	if (ccache)
		krb5_cc_close(kctx, ccache);
	if (cred)
		gss_release_cred(&min, &cred);
	if (deleg_creds)
		gss_release_cred(&min, &deleg_creds);

	free(in.value);

	return ret;
}

static gss_name_t
import_service(char *service)
{
	gss_buffer_desc	name;
	gss_name_t	svc = NULL;
	OM_uint32	maj;
	OM_uint32	min;
	int		ret = 0;

	name.length = strlen(service);
	name.value  = service;

	maj = gss_import_name(&min, &name, GSS_C_NT_HOSTBASED_SERVICE, &svc);

	GBAIL("gss_import_name", maj, min);

bail:
	if (ret)
		exit(1);
	return svc;
}

static void
print_all_mechs(void)
{
	OM_uint32	maj, min;
	gss_OID_set	mech_set;
	size_t		i;
	int		ret = 0;

	maj = gss_indicate_mechs(&min, &mech_set);
	GBAIL("gss_indicate_mechs", maj, min);

	for (i=0; i < mech_set->count; i++)
		printf("%s\n", gss_oid_to_name(&mech_set->elements[i]));

	(void) gss_release_oid_set(&min, &mech_set);

bail:
	exit(ret);
}

static void
usage(int ecode)
{
	FILE *f = ecode == 0 ? stdout : stderr;
	fprintf(f, "Usage: gss-token [-DNn] [-c count] service@host\n");
	fprintf(f, "       gss-token -r [-Nln] [-C ccache] [-c count] "
	    "[service@host]\n");
	exit(ecode);
}

int
main(int argc, char **argv)
{
	OM_uint32	 min;
	gss_name_t	 service = NULL;
	size_t		 count = 1;
	int		 Dflag = 0;
	int		 Mflag = 0;
	int		 Nflag = 0;
	int		 hflag = 0;
	int		 lflag = 0;
	int		 rflag = 0;
	int		 version_flag = 0;
	int		 ret = 0;
	int		 optidx = 0;
	char		*ccname = NULL;
	char		*mech = NULL;
	struct getargs	 args[] = {
	    { "help", 'h', arg_flag, &hflag, NULL, NULL },
	    { "version", 0, arg_flag, &version_flag, NULL, NULL },
	    { NULL, 'C', arg_string, &ccname, NULL, NULL },
	    { NULL, 'D', arg_flag, &Dflag, NULL, NULL },
	    { NULL, 'M', arg_flag, &Mflag, NULL, NULL },
	    { NULL, 'N', arg_flag, &Nflag, NULL, NULL },
	    { NULL, 'S', arg_integer, &Sflag, NULL, NULL },
	    { NULL, 'c', arg_integer, &count, NULL, NULL },
	    { NULL, 'l', arg_flag, &lflag, NULL, NULL },
	    { NULL, 'm', arg_string, &mech, NULL, NULL },
	    { NULL, 'n', arg_flag, &nflag, NULL, NULL },
	    { NULL, 'r', arg_flag, &rflag, NULL, NULL },
	};

	setprogname(argv[0]);
	if (argc == 1 || 
	    getarg(args, sizeof(args)/sizeof(args[0]), argc, argv, &optidx))
	    usage(1);
	if (hflag)
	    usage(0);
	if (version_flag) {
	    print_version(NULL);
	    return 0;
	}

	argc -= optidx;
	argv += optidx;

	if (mech) {
		if (mech[0] == '?' && mech[1] == '\0') {
			print_all_mechs();
			exit(0);
		}
		global_mech = gss_name_to_oid(mech);
		if (!global_mech) {
			fprintf(stderr, "Invalid mech \"%s\".\n", mech);
			usage(1);
		}
	}

	if (argc > 0)
		service = import_service(*argv);

	if (!rflag) {
		if (!argc) {
			fprintf(stderr, "Without -r, hostbased_service must "
			    "be provided.\n");
			usage(1);
		}
		if (ccname) {
			fprintf(stderr, "Specifying a target ccache doesn't "
			    "make sense without -r.\n");
			usage(1);
		}
		ret = initiate_many(service, Dflag, Nflag, Mflag, count);
		goto done;
	}

	if (Dflag) {
		fprintf(stderr, "Delegating credentials (-D) doesn't make "
		    "sense when reading tokens (-r).\n");
		usage(1);
	}

	do {
		ret = accept_one(service, ccname, Nflag);
	} while (lflag && !ret && !feof(stdin));

done:
	if (service)
		gss_release_name(&min, &service);

	return ret;
}