summaryrefslogtreecommitdiffstats
path: root/src/credmonger.c
blob: df9d2ac259af3b4f6c29a5c8a5c5015ab5b5b1f0 (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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include <krb5.h>

#define CONFIG_DIR "/etc/credmonger.d"
#define FCC_PREFIX "FILE:"
#define DEFAULT_RETRY_TIME 300

/* A ccache that we need to maintain. */
static struct monger_entry {
	uid_t uid;		/* UID of ccache owner. */
	gid_t gid;		/* GID of ccache owner. */
	char *keytab;		/* Name of keytab. */
	char *principal_name;	/* Client name. */
	char *fccache;		/* Name of existing ccache, or NULL. */
	char *fccache_pattern;	/* Pattern to use for naming ccache. */
	krb5_timestamp when;	/* When the creds in the ccache expire. */
} **entries, **cleanup;

/* Time to exit. */
static int quit = 0;

/* Configuration directory. */
static const char *configdir = CONFIG_DIR;

/* Read the configuration and return a list of ccache names. */
static struct monger_entry **
entries_read(void)
{
	char buf[LINE_MAX], *p, *uids, *keytab, *principal, *fccache_pattern;
	char fccache[PATH_MAX];
	struct monger_entry **list, **tmp, *entry;
	struct passwd *pwd;
	uid_t uid;
	gid_t gid;
	FILE *fp;
	int n_entries;
	DIR *dir;
	struct dirent *ent;

	list = NULL;
	n_entries = 0;
	for (dir = opendir(configdir);
	     (dir != NULL) && ((ent = readdir(dir)) != NULL);
	     closedir(dir)) {
		if (strchr(".#~", ent->d_name[0]) != NULL) {
			continue;
		}
		snprintf(buf, sizeof(buf), "%s/%.*s",
			 configdir, NAME_MAX, ent->d_name);
		if (strlen(buf) > 0) {
			p = buf + strlen(buf) - 1;
			if (strchr("#~", *p) != NULL) {
				continue;
			}
			if (strcmp(buf + strlen(buf) - 8, ".rpmsave") == 0) {
				continue;
			}
			if (strcmp(buf + strlen(buf) - 8, ".rpmorig") == 0) {
				continue;
			}
			if (strcmp(buf + strlen(buf) - 7, ".rpmnew") == 0) {
				continue;
			}
		}
		fp = fopen(buf, "r");
		if (fp != NULL) {
			while (fgets(buf, sizeof(buf), fp) != NULL) {
				/* Trim end-of-line characters. */
				buf[strcspn(buf, "\r\n")] = '\0';
				/* Skip comments. */
				if (strchr("#:", buf[0]) != NULL) {
					continue;
				}
				/* Trim end-of-line characters. */
				uids = buf;
				/* Skip ahead to the keytab name and close the
				 * user name. */
				keytab = strchr(uids, ':');
				if (keytab == NULL) {
					fprintf(stderr,
						"No keytab name field.\n");
					continue;
				}
				*keytab++ = '\0';
				/* Skip ahead to the client principal name and
				 * close the keytab name. */
				principal = strchr(keytab, ':');
				if (principal == NULL) {
					fprintf(stderr,
						"No principal name field.\n");
					continue;
				}
				*principal++ = '\0';
				/* Skip ahead to the ccache name pattern and
				 * close the principal name. */
				fccache_pattern = strchr(principal, ':');
				if (fccache_pattern != NULL) {
					*fccache_pattern++ = '\0';
					/* Close the principal name. */
					p = strchr(fccache_pattern, ':');
					if (p != NULL) {
						*p++ = '\0';
					}
				}
				/* Now figure out the UID/GID. */
				uid = (uid_t) strtol(uids, &p, 10);
				if ((p == NULL) || (*p != '\0')) {
					/* Not a number, so treat it as a user
					 * name. */
					pwd = getpwnam(uids);
					if (pwd != NULL) {
						uid = pwd->pw_uid;
						gid = pwd->pw_gid;
					} else {
						fprintf(stderr,
							"Unknown user "
							"\"%s\".\n", uids);
						continue;
					}
				} else {
					/* Treat it as a number. */
					pwd = getpwuid(uid);
					if (pwd != NULL) {
						gid = pwd->pw_gid;
					} else {
						fprintf(stderr,
							"Unknown user %lu.\n",
							(unsigned long) uid);
						continue;
					}
				}
				/* Now go back and figure out the ccache name
				 * pattern.  If it's empty, assume that we want
				 * a unique file in the temporary directory. */
				if ((fccache_pattern == NULL) ||
				    (strlen(fccache_pattern) == 0)) {
					snprintf(fccache, sizeof(fccache),
						 "FILE:%s/krb5cc_%lu_XXXXXX",
						 getenv("TMPDIR") ?: "/tmp",
						 (unsigned long) uid);
				} else {
					/* If the user supplied us with a typed
					 * ccache name, just use it as-is. */
					if (strncmp(fccache_pattern, FCC_PREFIX,
						    strlen(FCC_PREFIX)) == 0) {
						snprintf(fccache, sizeof(fccache),
							 "%s", fccache_pattern);
					} else {
						/* Mark it as a file-based
						 * ccache, and take the
						 * filename as-is. */
						snprintf(fccache,
							 sizeof(fccache),
							 "FILE:%s",
							 fccache_pattern);
					}
				}
				fccache_pattern = fccache;
				/* Make space for this entry in the list. */
				tmp = realloc(list,
					      sizeof(*list) * (n_entries + 2));
				if (tmp == NULL) {
					fprintf(stderr, "Out of memory.\n");
					break;
				}
				list = tmp;
				/* Allocate this entry. */
				list[n_entries] = malloc(sizeof(**list));
				if (list[n_entries] == NULL) {
					fprintf(stderr, "Out of memory.\n");
					break;
				}
				entry = list[n_entries];
				/* NULL-terminate the list. */
				n_entries++;
				list[n_entries] = NULL;
				/* Initialize this entry. */
				memset(entry, 0, sizeof(*entry));
				entry->uid = uid;
				entry->gid = gid;
				entry->keytab = strdup(keytab);
				if (entry->keytab == NULL) {
					fprintf(stderr, "Out of memory.\n");
					break;
				}
				entry->principal_name = strdup(principal);
				if (entry->principal_name == NULL) {
					fprintf(stderr, "Out of memory.\n");
					break;
				}
				entry->fccache_pattern =
					strdup(fccache_pattern);
				if (entry->fccache_pattern == NULL) {
					fprintf(stderr, "Out of memory.\n");
					break;
				}
			}
			fclose(fp);
		}
	}
	return list;
}

/* Do the heavy lifting. */
static void
entries_poll(void)
{
	int i, j, fd, len, need_rename;
	krb5_error_code ret;
	krb5_context ctx;
	krb5_creds creds;
	krb5_keytab keytab;
	krb5_ccache ccache;
	krb5_principal client;
	krb5_get_init_creds_opt *gic_opts;
	char host[LINE_MAX], fccache[PATH_MAX + strlen(FCC_PREFIX) + 1];
	char *principal_name, *oldfile;

	/* Figure out the client hostname. */
	memset(host, '\0', sizeof(host));
	if (gethostname(host, sizeof(host) - 1) != 0) {
		fprintf(stderr, "Error determining hostname.\n");
		snprintf(host, sizeof(host), "localhost");
	}

	ctx = NULL;
	gic_opts = NULL;
	if (krb5_init_context(&ctx) != 0) {
		fprintf(stderr, "Error initializing Kerberos.\n");
	} else {
		/* Initialize the get_init_creds options. */
		if (krb5_get_init_creds_opt_alloc(ctx, &gic_opts) != 0) {
			gic_opts = NULL;
		} else {
			krb5_get_init_creds_opt_set_forwardable(gic_opts, 0);
			krb5_get_init_creds_opt_set_proxiable(gic_opts, 0);
		}
		/* Walk the list of entries. */
		for (i = 0; (entries != NULL) && (entries[i] != NULL); i++) {
			fprintf(stderr,
				"uid=%ld,keytab=%s,client=%s,ccache=%s\n",
				(unsigned long) entries[i]->uid,
				entries[i]->keytab,
				entries[i]->principal_name,
				entries[i]->fccache_pattern);
			/* Open the keytab. */
			keytab = NULL;
			if ((entries[i]->keytab == NULL) ||
			    (strlen(entries[i]->keytab) == 0)) {
				ret = krb5_kt_default(ctx, &keytab);
			} else {
				ret = krb5_kt_resolve(ctx, entries[i]->keytab,
						      &keytab);
			}
			if (ret != 0) {
				fprintf(stderr, "Error resolving keytab: %s.\n",
					error_message(ret));
				continue;
			}
			/* If the principal name ends with "/", append the
			 * local host name.  Parse it. */
			client = NULL;
			len = strlen(entries[i]->principal_name);
			if ((len > 0) &&
			    (entries[i]->principal_name[len - 1] == '/')) {
				principal_name = malloc(len + strlen(host) + 1);
				if (principal_name == NULL) {
					fprintf(stderr, "Out of memory.\n");
					krb5_kt_close(ctx, keytab);
					continue;
				}
				strcpy(principal_name,
				       entries[i]->principal_name);
				strcat(principal_name, host);
			} else {
				principal_name = strdup(entries[i]->principal_name);
				if (principal_name == NULL) {
					fprintf(stderr, "Out of memory.\n");
					krb5_kt_close(ctx, keytab);
					continue;
				}
			}
			ret = krb5_parse_name(ctx, principal_name, &client);
			if (ret != 0) {
				fprintf(stderr, "Error parsing client \"%s\": "
					"%s.\n", principal_name,
					error_message(ret));
				free(principal_name);
				krb5_kt_close(ctx, keytab);
				continue;
			}
			free(principal_name);
			/* Now "unparse" it. */
			principal_name = NULL;
			ret = krb5_unparse_name(ctx, client, &principal_name);
			if (ret != 0) {
				fprintf(stderr, "Error unparsing name: %s.\n",
					error_message(ret));
				krb5_kt_close(ctx, keytab);
				krb5_free_principal(ctx, client);
				continue;
			}
			/* Okay, we have everything we need.  Give it a shot. */
			memset(&creds, 0, sizeof(creds));
			ret = krb5_get_init_creds_keytab(ctx, &creds, client,
							 keytab, 0, NULL,
							 gic_opts);
			if (ret != 0) {
				fprintf(stderr, "Error getting creds for %s: "
					"%s.\n", principal_name,
					error_message(ret));
				krb5_kt_close(ctx, keytab);
				krb5_free_unparsed_name(ctx, principal_name);
				krb5_free_principal(ctx, client);
				continue;
			}
			/* Create a temporary file to hold the creds. */
			snprintf(fccache, sizeof(fccache), "%s",
				 entries[i]->fccache_pattern);
			need_rename = 0;
			fd = mkstemp(fccache + strlen(FCC_PREFIX));
			/* If we got EINVAL, then it's not a pattern, so create
			 * a pattern and note that we'll need to rename it over
			 * the "real" name when we're done setting it up. */
			if ((fd == -1) && (errno == EINVAL)) {
				need_rename++;
				snprintf(fccache, sizeof(fccache),
					 "%sXXXXXX",
					 entries[i]->fccache_pattern);
				fd = mkstemp(fccache + strlen(FCC_PREFIX));
			}
			if (fd == -1) {
				fprintf(stderr, "Error creating temporary "
					"ccache.\n");
				krb5_free_cred_contents(ctx, &creds);
				krb5_kt_close(ctx, keytab);
				krb5_free_unparsed_name(ctx, principal_name);
				krb5_free_principal(ctx, client);
				continue;
			}
			close(fd);
			/* Open the ccache. */
			ccache = NULL;
			ret = krb5_cc_resolve(ctx, fccache, &ccache);
			if (ret != 0) {
				fprintf(stderr, "Error opening temporary "
					"ccache: %s.\n", error_message(ret));
				unlink(fccache + strlen(FCC_PREFIX));
				krb5_free_cred_contents(ctx, &creds);
				krb5_kt_close(ctx, keytab);
				krb5_free_unparsed_name(ctx, principal_name);
				krb5_free_principal(ctx, client);
				continue;
			}
			/* Write the client's name to the ccache. */
			ret = krb5_cc_initialize(ctx, ccache, client);
			if (ret != 0) {
				fprintf(stderr, "Error initializing temporary "
					"ccache: %s.\n", error_message(ret));
				krb5_cc_close(ctx, ccache);
				unlink(fccache + strlen(FCC_PREFIX));
				krb5_free_cred_contents(ctx, &creds);
				krb5_kt_close(ctx, keytab);
				krb5_free_unparsed_name(ctx, principal_name);
				krb5_free_principal(ctx, client);
				continue;
			}
			/* Store the TGT. */
			ret = krb5_cc_store_cred(ctx, ccache, &creds);
			if (ret != 0) {
				fprintf(stderr, "Error storing creds: %s.\n",
					error_message(ret));
				krb5_cc_close(ctx, ccache);
				unlink(fccache + strlen(FCC_PREFIX));
				krb5_free_cred_contents(ctx, &creds);
				krb5_kt_close(ctx, keytab);
				krb5_free_unparsed_name(ctx, principal_name);
				krb5_free_principal(ctx, client);
				continue;
			}
			/* Done with the ccache structure. */
			krb5_cc_close(ctx, ccache);
			/* Fixup permissions. */
			chown(fccache + strlen(FCC_PREFIX),
			      entries[i]->uid, entries[i]->gid);
			/* If the configuration doesn't want a unique ccache
			 * name, overwrite the destination with the contents of
			 * this temporary file. */
			if (need_rename) {
				rename(fccache + strlen(FCC_PREFIX),
				       entries[i]->fccache_pattern +
				       strlen(FCC_PREFIX));
				entries[i]->fccache =
					entries[i]->fccache_pattern;
				entries[i]->when = creds.times.endtime;
			} else {
				/* Remove the old file, and record this one. */
				oldfile = entries[i]->fccache;
				entries[i]->fccache = strdup(fccache);
				if (entries[i]->fccache == NULL) {
					/* Better luck next time, which is
					 * soon. */
					entries[i]->fccache = oldfile;
					entries[i]->when = DEFAULT_RETRY_TIME;
					unlink(fccache + strlen(FCC_PREFIX));
				} else {
					/* Get rid of a previously-initialized
					 * file. */
					if (oldfile != NULL) {
						unlink(oldfile + strlen(FCC_PREFIX));
						free(oldfile);
					}
					/* Record the renewal time. */
					entries[i]->when = creds.times.endtime;
				}
			}
			fprintf(stderr, "Saved creds for \"%s\" to \"%s\".\n",
				principal_name, entries[i]->fccache);
			krb5_free_cred_contents(ctx, &creds);
			krb5_kt_close(ctx, keytab);
			krb5_free_unparsed_name(ctx, principal_name);
			krb5_free_principal(ctx, client);
		}
		krb5_get_init_creds_opt_free(ctx, gic_opts);
		krb5_free_context(ctx);
	}

	/* Walk the list of to-be-cleaned-up entries. */
	for (i = 0; (cleanup != NULL) && (cleanup[i] != NULL); i++) {
		/* Remove the ccache, if there is one. */
		if (cleanup[i]->fccache != NULL) {
			for (j = 0;
			     (entries != NULL) && (entries[j] != NULL);
			     j++) {
				/* ... unless it's being used elsewhere. */
				if ((entries[j]->fccache != NULL) &&
				    (strcmp(cleanup[i]->fccache,
				    	    entries[j]->fccache) == 0)) {
					break;
				}
			}
			if ((entries == NULL) || (entries[j] == NULL)) {
				fprintf(stderr, "Removing \"%s\".\n",
					cleanup[i]->fccache);
				unlink(cleanup[i]->fccache +
				       strlen(FCC_PREFIX));
			}
		}
		free(cleanup[i]->fccache);
		/* Free the pattern if it's not a plain filename. */
		if (cleanup[i]->fccache != cleanup[i]->fccache_pattern) {
			free(cleanup[i]->fccache_pattern);
		}
		/* Finish up. */
		free(cleanup[i]->principal_name);
		free(cleanup[i]->keytab);
		free(cleanup[i]);
	}
	free(cleanup);
	cleanup = NULL;
}

static void
entries_reload(void)
{
	struct monger_entry **list, **cleanup;
	list = entries_read();
	cleanup = entries;
	entries = list;
	entries_poll();
}

static void
entries_unload(void)
{
	cleanup = entries;
	entries = NULL;
	entries_poll();
}

static int
entries_waittime(void)
{
	int i;
	krb5_timestamp last;
	for (i = 0, last = 0; (entries != NULL) && (entries[i] != NULL); i++) {
		if (entries[i]->fccache != NULL) {
			if ((last == 0) || (entries[i]->when < last)) {
				last = entries[i]->when;
			}
		}
	}
	if (last == 0) {
		i = DEFAULT_RETRY_TIME;
	} else {
		i = (last - time(NULL)) * 9 / 10;
	}
	return i;
}

static void
setquit(int signum)
{
	quit++;
}

int
main(int argc, char **argv)
{
	time_t howlong;
	char *pidfile;
	int c, nofork;
	FILE *fp;

	nofork = 0;
	pidfile = NULL;
	while ((c = getopt(argc, argv, "c:np:")) != -1) {
		switch (c) {
		case 'c':
			configdir = optarg;
			break;
		case 'n':
			nofork++;
			break;
		case 'p':
			pidfile = optarg;
			break;
		default:
			break;
		}
	}

	entries = entries_read();
	if (entries == NULL) {
		fprintf(stderr, "Nothing configured.\n");
	}

	if (!nofork) {
		daemon(0, 0);
	}

	fp = fopen(pidfile, "w");
	if (fp != NULL) {
		fprintf(fp, "%lu\n", (long unsigned) (getpid()));
		fclose(fp);
	}

	signal(SIGINT, setquit);
	signal(SIGQUIT, setquit);

	/* Make sure we initialize the first time through. */
	howlong = 0;
	while (quit == 0) {
		/* Either (re-)initialize, or don't. */
		if (howlong == 0) {
			/* Normal. */
			entries_poll();
		} else {
			/* Load or reload configuration. */
			entries_reload();
		}
		/* If there are no entries, bail. */
		if (entries == NULL) {
			break;
		}
		/* Figure out how long to wait. */
		howlong = entries_waittime();
		fprintf(stderr, "Waiting for %ld seconds.\n", (long) howlong);
		howlong = sleep(howlong);
	};
	/* Clean up. */
	entries_unload();
	if (pidfile != NULL) {
		fprintf(stderr, "Removing \"%s\".\n", pidfile);
		unlink(pidfile);
	}
	return 0;
}