1/*
2* CIFS user-space helper.
3* Copyright (C) Igor Mammedov (niallain@gmail.com) 2007
4* Copyright (C) Jeff Layton (jlayton@redhat.com) 2009
5*
6* Used by /sbin/request-key for handling
7* cifs upcall for kerberos authorization of access to share and
8* cifs upcall for DFS srver name resolving (IPv4/IPv6 aware).
9* You should have keyutils installed and add something like the
10* following lines to /etc/request-key.conf file:
11
12create cifs.spnego * * /usr/local/sbin/cifs.upcall %k
13create dns_resolver * * /usr/local/sbin/cifs.upcall %k
14
15* This program is free software; you can redistribute it and/or modify
16* it under the terms of the GNU General Public License as published by
17* the Free Software Foundation; either version 2 of the License, or
18* (at your option) any later version.
19* This program is distributed in the hope that it will be useful,
20* but WITHOUT ANY WARRANTY; without even the implied warranty of
21* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22* GNU General Public License for more details.
23* You should have received a copy of the GNU General Public License
24* along with this program; if not, write to the Free Software
25* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26*/
27
28#include "includes.h"
29#include "../libcli/auth/spnego.h"
30#include "smb_krb5.h"
31#include <keyutils.h>
32#include <getopt.h>
33
34#include "cifs_spnego.h"
35
36#define	CIFS_DEFAULT_KRB5_DIR		"/tmp"
37#define	CIFS_DEFAULT_KRB5_PREFIX	"krb5cc_"
38
39#define	MAX_CCNAME_LEN			PATH_MAX + 5
40
41const char *CIFSSPNEGO_VERSION = "1.3";
42static const char *prog = "cifs.upcall";
43typedef enum _sectype {
44	NONE = 0,
45	KRB5,
46	MS_KRB5
47} sectype_t;
48
49/* does the ccache have a valid TGT? */
50static time_t
51get_tgt_time(const char *ccname) {
52	krb5_context context;
53	krb5_ccache ccache;
54	krb5_cc_cursor cur;
55	krb5_creds creds;
56	krb5_principal principal;
57	time_t credtime = 0;
58	char *realm = NULL;
59	TALLOC_CTX *mem_ctx;
60
61	if (krb5_init_context(&context)) {
62		syslog(LOG_DEBUG, "%s: unable to init krb5 context", __func__);
63		return 0;
64	}
65
66	if (krb5_cc_resolve(context, ccname, &ccache)) {
67		syslog(LOG_DEBUG, "%s: unable to resolve krb5 cache", __func__);
68		goto err_cache;
69	}
70
71	if (krb5_cc_set_flags(context, ccache, 0)) {
72		syslog(LOG_DEBUG, "%s: unable to set flags", __func__);
73		goto err_cache;
74	}
75
76	if (krb5_cc_get_principal(context, ccache, &principal)) {
77		syslog(LOG_DEBUG, "%s: unable to get principal", __func__);
78		goto err_princ;
79	}
80
81	if (krb5_cc_start_seq_get(context, ccache, &cur)) {
82		syslog(LOG_DEBUG, "%s: unable to seq start", __func__);
83		goto err_ccstart;
84	}
85
86	if ((realm = smb_krb5_principal_get_realm(context, principal)) == NULL) {
87		syslog(LOG_DEBUG, "%s: unable to get realm", __func__);
88		goto err_ccstart;
89	}
90
91	mem_ctx = talloc_init("cifs.upcall");
92	while (!credtime && !krb5_cc_next_cred(context, ccache, &cur, &creds)) {
93		char *name;
94		if (smb_krb5_unparse_name(mem_ctx, context, creds.server, &name)) {
95			syslog(LOG_DEBUG, "%s: unable to unparse name", __func__);
96			goto err_endseq;
97		}
98		if (krb5_realm_compare(context, creds.server, principal) &&
99		    strnequal(name, KRB5_TGS_NAME, KRB5_TGS_NAME_SIZE) &&
100		    strnequal(name+KRB5_TGS_NAME_SIZE+1, realm, strlen(realm)) &&
101		    creds.times.endtime > time(NULL))
102			credtime = creds.times.endtime;
103                krb5_free_cred_contents(context, &creds);
104		TALLOC_FREE(name);
105        }
106err_endseq:
107	TALLOC_FREE(mem_ctx);
108        krb5_cc_end_seq_get(context, ccache, &cur);
109err_ccstart:
110	krb5_free_principal(context, principal);
111err_princ:
112#if defined(KRB5_TC_OPENCLOSE)
113	krb5_cc_set_flags(context, ccache, KRB5_TC_OPENCLOSE);
114#endif
115	krb5_cc_close(context, ccache);
116err_cache:
117	krb5_free_context(context);
118	return credtime;
119}
120
121static int
122krb5cc_filter(const struct dirent *dirent)
123{
124	if (strstr(dirent->d_name, CIFS_DEFAULT_KRB5_PREFIX))
125		return 1;
126	else
127		return 0;
128}
129
130/* search for a credcache that looks like a likely candidate */
131static char *
132find_krb5_cc(const char *dirname, uid_t uid)
133{
134	struct dirent **namelist;
135	struct stat sbuf;
136	char ccname[MAX_CCNAME_LEN], *credpath, *best_cache = NULL;
137	int i, n;
138	time_t cred_time, best_time = 0;
139
140	n = scandir(dirname, &namelist, krb5cc_filter, NULL);
141	if (n < 0) {
142		syslog(LOG_DEBUG, "%s: scandir error on directory '%s': %s",
143				  __func__, dirname, strerror(errno));
144		return NULL;
145	}
146
147	for (i = 0; i < n; i++) {
148		snprintf(ccname, sizeof(ccname), "FILE:%s/%s", dirname,
149			 namelist[i]->d_name);
150		credpath = ccname + 5;
151		syslog(LOG_DEBUG, "%s: considering %s", __func__, credpath);
152
153		if (lstat(credpath, &sbuf)) {
154			syslog(LOG_DEBUG, "%s: stat error on '%s': %s",
155					  __func__, credpath, strerror(errno));
156			free(namelist[i]);
157			continue;
158		}
159		if (sbuf.st_uid != uid) {
160			syslog(LOG_DEBUG, "%s: %s is owned by %u, not %u",
161					__func__, credpath, sbuf.st_uid, uid);
162			free(namelist[i]);
163			continue;
164		}
165		if (!S_ISREG(sbuf.st_mode)) {
166			syslog(LOG_DEBUG, "%s: %s is not a regular file",
167					__func__, credpath);
168			free(namelist[i]);
169			continue;
170		}
171		if (!(cred_time = get_tgt_time(ccname))) {
172			syslog(LOG_DEBUG, "%s: %s is not a valid credcache.",
173					__func__, ccname);
174			free(namelist[i]);
175			continue;
176		}
177
178		if (cred_time <= best_time) {
179			syslog(LOG_DEBUG, "%s: %s expires sooner than current "
180					  "best.", __func__, ccname);
181			free(namelist[i]);
182			continue;
183		}
184
185		syslog(LOG_DEBUG, "%s: %s is valid ccache", __func__, ccname);
186		free(best_cache);
187		best_cache = SMB_STRNDUP(ccname, MAX_CCNAME_LEN);
188		best_time = cred_time;
189		free(namelist[i]);
190	}
191	free(namelist);
192
193	return best_cache;
194}
195
196/*
197 * Prepares AP-REQ data for mechToken and gets session key
198 * Uses credentials from cache. It will not ask for password
199 * you should receive credentials for yuor name manually using
200 * kinit or whatever you wish.
201 *
202 * in:
203 * 	oid -		string with OID/ Could be OID_KERBEROS5
204 * 			or OID_KERBEROS5_OLD
205 * 	principal -	Service name.
206 * 			Could be "cifs/FQDN" for KRB5 OID
207 * 			or for MS_KRB5 OID style server principal
208 * 			like "pdc$@YOUR.REALM.NAME"
209 *
210 * out:
211 * 	secblob -	pointer for spnego wrapped AP-REQ data to be stored
212 * 	sess_key-	pointer for SessionKey data to be stored
213 *
214 * ret: 0 - success, others - failure
215 */
216static int
217handle_krb5_mech(const char *oid, const char *principal, DATA_BLOB *secblob,
218		 DATA_BLOB *sess_key, const char *ccname)
219{
220	int retval;
221	DATA_BLOB tkt, tkt_wrapped;
222
223	syslog(LOG_DEBUG, "%s: getting service ticket for %s", __func__,
224			  principal);
225
226	/* get a kerberos ticket for the service and extract the session key */
227	retval = cli_krb5_get_ticket(principal, 0, &tkt, sess_key, 0, ccname,
228				     NULL, NULL);
229
230	if (retval) {
231		syslog(LOG_DEBUG, "%s: failed to obtain service ticket (%d)",
232				  __func__, retval);
233		return retval;
234	}
235
236	syslog(LOG_DEBUG, "%s: obtained service ticket", __func__);
237
238	/* wrap that up in a nice GSS-API wrapping */
239	tkt_wrapped = spnego_gen_krb5_wrap(tkt, TOK_ID_KRB_AP_REQ);
240
241	/* and wrap that in a shiny SPNEGO wrapper */
242	*secblob = gen_negTokenInit(oid, tkt_wrapped);
243
244	data_blob_free(&tkt_wrapped);
245	data_blob_free(&tkt);
246	return retval;
247}
248
249#define DKD_HAVE_HOSTNAME	0x1
250#define DKD_HAVE_VERSION	0x2
251#define DKD_HAVE_SEC		0x4
252#define DKD_HAVE_IP		0x8
253#define DKD_HAVE_UID		0x10
254#define DKD_HAVE_PID		0x20
255#define DKD_MUSTHAVE_SET (DKD_HAVE_HOSTNAME|DKD_HAVE_VERSION|DKD_HAVE_SEC)
256
257struct decoded_args {
258	int		ver;
259	char		*hostname;
260	char		*ip;
261	uid_t		uid;
262	pid_t		pid;
263	sectype_t	sec;
264};
265
266static unsigned int
267decode_key_description(const char *desc, struct decoded_args *arg)
268{
269	int len;
270	int retval = 0;
271	char *pos;
272	const char *tkn = desc;
273
274	do {
275		pos = index(tkn, ';');
276		if (strncmp(tkn, "host=", 5) == 0) {
277
278			if (pos == NULL)
279				len = strlen(tkn);
280			else
281				len = pos - tkn;
282
283			len -= 4;
284			SAFE_FREE(arg->hostname);
285			arg->hostname = SMB_XMALLOC_ARRAY(char, len);
286			strlcpy(arg->hostname, tkn + 5, len);
287			retval |= DKD_HAVE_HOSTNAME;
288		} else if (!strncmp(tkn, "ip4=", 4) ||
289			   !strncmp(tkn, "ip6=", 4)) {
290			if (pos == NULL)
291				len = strlen(tkn);
292			else
293				len = pos - tkn;
294
295			len -= 3;
296			SAFE_FREE(arg->ip);
297			arg->ip = SMB_XMALLOC_ARRAY(char, len);
298			strlcpy(arg->ip, tkn + 4, len);
299			retval |= DKD_HAVE_IP;
300		} else if (strncmp(tkn, "pid=", 4) == 0) {
301			errno = 0;
302			arg->pid = strtol(tkn + 4, NULL, 0);
303			if (errno != 0) {
304				syslog(LOG_ERR, "Invalid pid format: %s",
305				       strerror(errno));
306				return 1;
307			} else {
308				retval |= DKD_HAVE_PID;
309			}
310		} else if (strncmp(tkn, "sec=", 4) == 0) {
311			if (strncmp(tkn + 4, "krb5", 4) == 0) {
312				retval |= DKD_HAVE_SEC;
313				arg->sec = KRB5;
314			} else if (strncmp(tkn + 4, "mskrb5", 6) == 0) {
315				retval |= DKD_HAVE_SEC;
316				arg->sec = MS_KRB5;
317			}
318		} else if (strncmp(tkn, "uid=", 4) == 0) {
319			errno = 0;
320			arg->uid = strtol(tkn + 4, NULL, 16);
321			if (errno != 0) {
322				syslog(LOG_ERR, "Invalid uid format: %s",
323				       strerror(errno));
324				return 1;
325			} else {
326				retval |= DKD_HAVE_UID;
327			}
328		} else if (strncmp(tkn, "ver=", 4) == 0) {	/* if version */
329			errno = 0;
330			arg->ver = strtol(tkn + 4, NULL, 16);
331			if (errno != 0) {
332				syslog(LOG_ERR, "Invalid version format: %s",
333				       strerror(errno));
334				return 1;
335			} else {
336				retval |= DKD_HAVE_VERSION;
337			}
338		}
339		if (pos == NULL)
340			break;
341		tkn = pos + 1;
342	} while (tkn);
343	return retval;
344}
345
346static int
347cifs_resolver(const key_serial_t key, const char *key_descr)
348{
349	int c;
350	struct addrinfo *addr;
351	char ip[INET6_ADDRSTRLEN];
352	void *p;
353	const char *keyend = key_descr;
354	/* skip next 4 ';' delimiters to get to description */
355	for (c = 1; c <= 4; c++) {
356		keyend = index(keyend+1, ';');
357		if (!keyend) {
358			syslog(LOG_ERR, "invalid key description: %s",
359					key_descr);
360			return 1;
361		}
362	}
363	keyend++;
364
365	/* resolve name to ip */
366	c = getaddrinfo(keyend, NULL, NULL, &addr);
367	if (c) {
368		syslog(LOG_ERR, "unable to resolve hostname: %s [%s]",
369				keyend, gai_strerror(c));
370		return 1;
371	}
372
373	/* conver ip to string form */
374	if (addr->ai_family == AF_INET)
375		p = &(((struct sockaddr_in *)addr->ai_addr)->sin_addr);
376	else
377		p = &(((struct sockaddr_in6 *)addr->ai_addr)->sin6_addr);
378
379	if (!inet_ntop(addr->ai_family, p, ip, sizeof(ip))) {
380		syslog(LOG_ERR, "%s: inet_ntop: %s", __func__, strerror(errno));
381		freeaddrinfo(addr);
382		return 1;
383	}
384
385	/* setup key */
386	c = keyctl_instantiate(key, ip, strlen(ip)+1, 0);
387	if (c == -1) {
388		syslog(LOG_ERR, "%s: keyctl_instantiate: %s", __func__,
389				strerror(errno));
390		freeaddrinfo(addr);
391		return 1;
392	}
393
394	freeaddrinfo(addr);
395	return 0;
396}
397
398/*
399 * Older kernels sent IPv6 addresses without colons. Well, at least
400 * they're fixed-length strings. Convert these addresses to have colon
401 * delimiters to make getaddrinfo happy.
402 */
403static void
404convert_inet6_addr(const char *from, char *to)
405{
406	int i = 1;
407
408	while (*from) {
409		*to++ = *from++;
410		if (!(i++ % 4) && *from)
411			*to++ = ':';
412	}
413	*to = 0;
414}
415
416static int
417ip_to_fqdn(const char *addrstr, char *host, size_t hostlen)
418{
419	int rc;
420	struct addrinfo hints = { .ai_flags = AI_NUMERICHOST };
421	struct addrinfo *res;
422	const char *ipaddr = addrstr;
423	char converted[INET6_ADDRSTRLEN + 1];
424
425	if ((strlen(ipaddr) > INET_ADDRSTRLEN) && !strchr(ipaddr, ':')) {
426		convert_inet6_addr(ipaddr, converted);
427		ipaddr = converted;
428	}
429
430	rc = getaddrinfo(ipaddr, NULL, &hints, &res);
431	if (rc) {
432		syslog(LOG_DEBUG, "%s: failed to resolve %s to "
433			"ipaddr: %s", __func__, ipaddr,
434		rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
435		return rc;
436	}
437
438	rc = getnameinfo(res->ai_addr, res->ai_addrlen, host, hostlen,
439			 NULL, 0, NI_NAMEREQD);
440	freeaddrinfo(res);
441	if (rc) {
442		syslog(LOG_DEBUG, "%s: failed to resolve %s to fqdn: %s",
443			__func__, ipaddr,
444			rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
445		return rc;
446	}
447
448	syslog(LOG_DEBUG, "%s: resolved %s to %s", __func__, ipaddr, host);
449	return 0;
450}
451
452static void
453usage(void)
454{
455	syslog(LOG_INFO, "Usage: %s [-t] [-v] key_serial", prog);
456	fprintf(stderr, "Usage: %s [-t] [-v] key_serial\n", prog);
457}
458
459const struct option long_options[] = {
460	{ "trust-dns",	0, NULL, 't' },
461	{ "version",	0, NULL, 'v' },
462	{ NULL,		0, NULL, 0 }
463};
464
465int main(const int argc, char *const argv[])
466{
467	struct cifs_spnego_msg *keydata = NULL;
468	DATA_BLOB secblob = data_blob_null;
469	DATA_BLOB sess_key = data_blob_null;
470	key_serial_t key = 0;
471	size_t datalen;
472	unsigned int have;
473	long rc = 1;
474	int c, try_dns = 0;
475	char *buf, *princ = NULL, *ccname = NULL;
476	char hostbuf[NI_MAXHOST], *host;
477	struct decoded_args arg = { };
478	const char *oid;
479
480	hostbuf[0] = '\0';
481
482	openlog(prog, 0, LOG_DAEMON);
483
484	while ((c = getopt_long(argc, argv, "ctv", long_options, NULL)) != -1) {
485		switch (c) {
486		case 'c':
487			/* legacy option -- skip it */
488			break;
489		case 't':
490			try_dns++;
491			break;
492		case 'v':
493			printf("version: %s\n", CIFSSPNEGO_VERSION);
494			goto out;
495		default:
496			syslog(LOG_ERR, "unknown option: %c", c);
497			goto out;
498		}
499	}
500
501	/* is there a key? */
502	if (argc <= optind) {
503		usage();
504		goto out;
505	}
506
507	/* get key and keyring values */
508	errno = 0;
509	key = strtol(argv[optind], NULL, 10);
510	if (errno != 0) {
511		key = 0;
512		syslog(LOG_ERR, "Invalid key format: %s", strerror(errno));
513		goto out;
514	}
515
516	rc = keyctl_describe_alloc(key, &buf);
517	if (rc == -1) {
518		syslog(LOG_ERR, "keyctl_describe_alloc failed: %s",
519		       strerror(errno));
520		rc = 1;
521		goto out;
522	}
523
524	syslog(LOG_DEBUG, "key description: %s", buf);
525
526	if ((strncmp(buf, "cifs.resolver", sizeof("cifs.resolver")-1) == 0) ||
527	    (strncmp(buf, "dns_resolver", sizeof("dns_resolver")-1) == 0)) {
528		rc = cifs_resolver(key, buf);
529		goto out;
530	}
531
532	have = decode_key_description(buf, &arg);
533	SAFE_FREE(buf);
534	if ((have & DKD_MUSTHAVE_SET) != DKD_MUSTHAVE_SET) {
535		syslog(LOG_ERR, "unable to get necessary params from key "
536				"description (0x%x)", have);
537		rc = 1;
538		goto out;
539	}
540
541	if (arg.ver > CIFS_SPNEGO_UPCALL_VERSION) {
542		syslog(LOG_ERR, "incompatible kernel upcall version: 0x%x",
543				arg.ver);
544		rc = 1;
545		goto out;
546	}
547
548	if (have & DKD_HAVE_UID) {
549		rc = setuid(arg.uid);
550		if (rc == -1) {
551			syslog(LOG_ERR, "setuid: %s", strerror(errno));
552			goto out;
553		}
554
555		ccname = find_krb5_cc(CIFS_DEFAULT_KRB5_DIR, arg.uid);
556	}
557
558	host = arg.hostname;
559
560	// do mech specific authorization
561	switch (arg.sec) {
562	case MS_KRB5:
563	case KRB5:
564retry_new_hostname:
565		/* for "cifs/" service name + terminating 0 */
566		datalen = strlen(host) + 5 + 1;
567		princ = SMB_XMALLOC_ARRAY(char, datalen);
568		if (!princ) {
569			rc = -ENOMEM;
570			break;
571		}
572
573		if (arg.sec == MS_KRB5)
574			oid = OID_KERBEROS5_OLD;
575		else
576			oid = OID_KERBEROS5;
577
578		/*
579		 * try getting a cifs/ principal first and then fall back to
580		 * getting a host/ principal if that doesn't work.
581		 */
582		strlcpy(princ, "cifs/", datalen);
583		strlcpy(princ + 5, host, datalen - 5);
584		rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
585		if (!rc)
586			break;
587
588		memcpy(princ, "host/", 5);
589		rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
590		if (!rc)
591			break;
592
593		if (!try_dns || !(have & DKD_HAVE_IP))
594			break;
595
596		rc = ip_to_fqdn(arg.ip, hostbuf, sizeof(hostbuf));
597		if (rc)
598			break;
599
600		SAFE_FREE(princ);
601		try_dns = 0;
602		host = hostbuf;
603		goto retry_new_hostname;
604	default:
605		syslog(LOG_ERR, "sectype: %d is not implemented", arg.sec);
606		rc = 1;
607		break;
608	}
609
610	SAFE_FREE(princ);
611
612	if (rc)
613		goto out;
614
615	/* pack SecurityBLob and SessionKey into downcall packet */
616	datalen =
617	    sizeof(struct cifs_spnego_msg) + secblob.length + sess_key.length;
618	keydata = (struct cifs_spnego_msg*)SMB_XMALLOC_ARRAY(char, datalen);
619	if (!keydata) {
620		rc = 1;
621		goto out;
622	}
623	keydata->version = arg.ver;
624	keydata->flags = 0;
625	keydata->sesskey_len = sess_key.length;
626	keydata->secblob_len = secblob.length;
627	memcpy(&(keydata->data), sess_key.data, sess_key.length);
628	memcpy(&(keydata->data) + keydata->sesskey_len,
629	       secblob.data, secblob.length);
630
631	/* setup key */
632	rc = keyctl_instantiate(key, keydata, datalen, 0);
633	if (rc == -1) {
634		syslog(LOG_ERR, "keyctl_instantiate: %s", strerror(errno));
635		goto out;
636	}
637
638	/* BB: maybe we need use timeout for key: for example no more then
639	 * ticket lifietime? */
640	/* keyctl_set_timeout( key, 60); */
641out:
642	/*
643	 * on error, negatively instantiate the key ourselves so that we can
644	 * make sure the kernel doesn't hang it off of a searchable keyring
645	 * and interfere with the next attempt to instantiate the key.
646	 */
647	if (rc != 0  && key == 0)
648		keyctl_negate(key, 1, KEY_REQKEY_DEFL_DEFAULT);
649	data_blob_free(&secblob);
650	data_blob_free(&sess_key);
651	SAFE_FREE(ccname);
652	SAFE_FREE(arg.hostname);
653	SAFE_FREE(arg.ip);
654	SAFE_FREE(keydata);
655	return rc;
656}
657