cifs.upcall: Fix Bug #6868: support building with Heimdal we well as with MIT.
[Samba.git] / source / client / cifs.upcall.c
blob6d4ff7551122e556405b877e175172e1714359f8
1 /*
2 * CIFS user-space helper.
3 * Copyright (C) Igor Mammedov (niallain@gmail.com) 2007
4 * Copyright (C) Jeff Layton (jlayton@redhat.com) 2009
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:
12 create cifs.spnego * * /usr/local/sbin/cifs.upcall %k
13 create dns_resolver * * /usr/local/sbin/cifs.upcall %k
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
28 #include "includes.h"
29 #include <keyutils.h>
30 #include <getopt.h>
32 #include "cifs_spnego.h"
34 #define CIFS_DEFAULT_KRB5_DIR "/tmp"
35 #define CIFS_DEFAULT_KRB5_PREFIX "krb5cc_"
37 #define MAX_CCNAME_LEN PATH_MAX + 5
39 const char *CIFSSPNEGO_VERSION = "1.3";
40 static const char *prog = "cifs.upcall";
41 typedef enum _sectype {
42 NONE = 0,
43 KRB5,
44 MS_KRB5
45 } sectype_t;
47 /* does the ccache have a valid TGT? */
48 static time_t
49 get_tgt_time(const char *ccname) {
50 krb5_context context;
51 krb5_ccache ccache;
52 krb5_cc_cursor cur;
53 krb5_creds creds;
54 krb5_principal principal;
55 time_t credtime = 0;
56 char *realm = NULL;
58 if (krb5_init_context(&context)) {
59 syslog(LOG_DEBUG, "%s: unable to init krb5 context", __func__);
60 return 0;
63 if (krb5_cc_resolve(context, ccname, &ccache)) {
64 syslog(LOG_DEBUG, "%s: unable to resolve krb5 cache", __func__);
65 goto err_cache;
68 if (krb5_cc_set_flags(context, ccache, 0)) {
69 syslog(LOG_DEBUG, "%s: unable to set flags", __func__);
70 goto err_cache;
73 if (krb5_cc_get_principal(context, ccache, &principal)) {
74 syslog(LOG_DEBUG, "%s: unable to get principal", __func__);
75 goto err_princ;
78 if (krb5_cc_start_seq_get(context, ccache, &cur)) {
79 syslog(LOG_DEBUG, "%s: unable to seq start", __func__);
80 goto err_ccstart;
83 if ((realm = smb_krb5_principal_get_realm(context, principal)) == NULL) {
84 syslog(LOG_DEBUG, "%s: unable to get realm", __func__);
85 goto err_ccstart;
88 while (!credtime && !krb5_cc_next_cred(context, ccache, &cur, &creds)) {
89 char *name;
90 if (smb_krb5_unparse_name(context, creds.server, &name)) {
91 syslog(LOG_DEBUG, "%s: unable to unparse name", __func__);
92 goto err_endseq;
94 if (krb5_realm_compare(context, creds.server, principal) &&
95 strnequal(name, KRB5_TGS_NAME, KRB5_TGS_NAME_SIZE) &&
96 strnequal(name+KRB5_TGS_NAME_SIZE+1, realm, strlen(realm)) &&
97 creds.times.endtime > time(NULL))
98 credtime = creds.times.endtime;
99 krb5_free_cred_contents(context, &creds);
100 SAFE_FREE(name);
102 err_endseq:
103 krb5_cc_end_seq_get(context, ccache, &cur);
104 err_ccstart:
105 krb5_free_principal(context, principal);
106 err_princ:
107 krb5_cc_set_flags(context, ccache, KRB5_TC_OPENCLOSE);
108 krb5_cc_close(context, ccache);
109 err_cache:
110 krb5_free_context(context);
111 return credtime;
114 static int
115 krb5cc_filter(const struct dirent *dirent)
117 if (strstr(dirent->d_name, CIFS_DEFAULT_KRB5_PREFIX))
118 return 1;
119 else
120 return 0;
123 /* search for a credcache that looks like a likely candidate */
124 static char *
125 find_krb5_cc(const char *dirname, uid_t uid)
127 struct dirent **namelist;
128 struct stat sbuf;
129 char ccname[MAX_CCNAME_LEN], *credpath, *best_cache = NULL;
130 int i, n;
131 time_t cred_time, best_time = 0;
133 n = scandir(dirname, &namelist, krb5cc_filter, NULL);
134 if (n < 0) {
135 syslog(LOG_DEBUG, "%s: scandir error on directory '%s': %s",
136 __func__, dirname, strerror(errno));
137 return NULL;
140 for (i = 0; i < n; i++) {
141 snprintf(ccname, sizeof(ccname), "FILE:%s/%s", dirname,
142 namelist[i]->d_name);
143 credpath = ccname + 5;
144 syslog(LOG_DEBUG, "%s: considering %s", __func__, credpath);
146 if (lstat(credpath, &sbuf)) {
147 syslog(LOG_DEBUG, "%s: stat error on '%s': %s",
148 __func__, credpath, strerror(errno));
149 free(namelist[i]);
150 continue;
152 if (sbuf.st_uid != uid) {
153 syslog(LOG_DEBUG, "%s: %s is owned by %u, not %u",
154 __func__, credpath, sbuf.st_uid, uid);
155 free(namelist[i]);
156 continue;
158 if (!S_ISREG(sbuf.st_mode)) {
159 syslog(LOG_DEBUG, "%s: %s is not a regular file",
160 __func__, credpath);
161 free(namelist[i]);
162 continue;
164 if (!(cred_time = get_tgt_time(ccname))) {
165 syslog(LOG_DEBUG, "%s: %s is not a valid credcache.",
166 __func__, ccname);
167 free(namelist[i]);
168 continue;
171 if (cred_time <= best_time) {
172 syslog(LOG_DEBUG, "%s: %s expires sooner than current "
173 "best.", __func__, ccname);
174 free(namelist[i]);
175 continue;
178 syslog(LOG_DEBUG, "%s: %s is valid ccache", __func__, ccname);
179 free(best_cache);
180 best_cache = SMB_STRNDUP(ccname, MAX_CCNAME_LEN);
181 best_time = cred_time;
182 free(namelist[i]);
184 free(namelist);
186 return best_cache;
190 * Prepares AP-REQ data for mechToken and gets session key
191 * Uses credentials from cache. It will not ask for password
192 * you should receive credentials for yuor name manually using
193 * kinit or whatever you wish.
195 * in:
196 * oid - string with OID/ Could be OID_KERBEROS5
197 * or OID_KERBEROS5_OLD
198 * principal - Service name.
199 * Could be "cifs/FQDN" for KRB5 OID
200 * or for MS_KRB5 OID style server principal
201 * like "pdc$@YOUR.REALM.NAME"
203 * out:
204 * secblob - pointer for spnego wrapped AP-REQ data to be stored
205 * sess_key- pointer for SessionKey data to be stored
207 * ret: 0 - success, others - failure
209 static int
210 handle_krb5_mech(const char *oid, const char *principal, DATA_BLOB *secblob,
211 DATA_BLOB *sess_key, const char *ccname)
213 int retval;
214 DATA_BLOB tkt, tkt_wrapped;
216 syslog(LOG_DEBUG, "%s: getting service ticket for %s", __func__,
217 principal);
219 /* get a kerberos ticket for the service and extract the session key */
220 retval = cli_krb5_get_ticket(principal, 0, &tkt, sess_key, 0, ccname,
221 NULL);
223 if (retval) {
224 syslog(LOG_DEBUG, "%s: failed to obtain service ticket (%d)",
225 __func__, retval);
226 return retval;
229 syslog(LOG_DEBUG, "%s: obtained service ticket", __func__);
231 /* wrap that up in a nice GSS-API wrapping */
232 tkt_wrapped = spnego_gen_krb5_wrap(tkt, TOK_ID_KRB_AP_REQ);
234 /* and wrap that in a shiny SPNEGO wrapper */
235 *secblob = gen_negTokenInit(oid, tkt_wrapped);
237 data_blob_free(&tkt_wrapped);
238 data_blob_free(&tkt);
239 return retval;
242 #define DKD_HAVE_HOSTNAME 0x1
243 #define DKD_HAVE_VERSION 0x2
244 #define DKD_HAVE_SEC 0x4
245 #define DKD_HAVE_IP 0x8
246 #define DKD_HAVE_UID 0x10
247 #define DKD_HAVE_PID 0x20
248 #define DKD_MUSTHAVE_SET (DKD_HAVE_HOSTNAME|DKD_HAVE_VERSION|DKD_HAVE_SEC)
250 struct decoded_args {
251 int ver;
252 char *hostname;
253 char *ip;
254 uid_t uid;
255 pid_t pid;
256 sectype_t sec;
259 static unsigned int
260 decode_key_description(const char *desc, struct decoded_args *arg)
262 int len;
263 int retval = 0;
264 char *pos;
265 const char *tkn = desc;
267 do {
268 pos = index(tkn, ';');
269 if (strncmp(tkn, "host=", 5) == 0) {
271 if (pos == NULL)
272 len = strlen(tkn);
273 else
274 len = pos - tkn;
276 len -= 4;
277 SAFE_FREE(arg->hostname);
278 arg->hostname = SMB_XMALLOC_ARRAY(char, len);
279 strlcpy(arg->hostname, tkn + 5, len);
280 retval |= DKD_HAVE_HOSTNAME;
281 } else if (!strncmp(tkn, "ip4=", 4) ||
282 !strncmp(tkn, "ip6=", 4)) {
283 if (pos == NULL)
284 len = strlen(tkn);
285 else
286 len = pos - tkn;
288 len -= 3;
289 SAFE_FREE(arg->ip);
290 arg->ip = SMB_XMALLOC_ARRAY(char, len);
291 strlcpy(arg->ip, tkn + 4, len);
292 retval |= DKD_HAVE_IP;
293 } else if (strncmp(tkn, "pid=", 4) == 0) {
294 errno = 0;
295 arg->pid = strtol(tkn + 4, NULL, 0);
296 if (errno != 0) {
297 syslog(LOG_ERR, "Invalid pid format: %s",
298 strerror(errno));
299 return 1;
300 } else {
301 retval |= DKD_HAVE_PID;
303 } else if (strncmp(tkn, "sec=", 4) == 0) {
304 if (strncmp(tkn + 4, "krb5", 4) == 0) {
305 retval |= DKD_HAVE_SEC;
306 arg->sec = KRB5;
307 } else if (strncmp(tkn + 4, "mskrb5", 6) == 0) {
308 retval |= DKD_HAVE_SEC;
309 arg->sec = MS_KRB5;
311 } else if (strncmp(tkn, "uid=", 4) == 0) {
312 errno = 0;
313 arg->uid = strtol(tkn + 4, NULL, 16);
314 if (errno != 0) {
315 syslog(LOG_ERR, "Invalid uid format: %s",
316 strerror(errno));
317 return 1;
318 } else {
319 retval |= DKD_HAVE_UID;
321 } else if (strncmp(tkn, "ver=", 4) == 0) { /* if version */
322 errno = 0;
323 arg->ver = strtol(tkn + 4, NULL, 16);
324 if (errno != 0) {
325 syslog(LOG_ERR, "Invalid version format: %s",
326 strerror(errno));
327 return 1;
328 } else {
329 retval |= DKD_HAVE_VERSION;
332 if (pos == NULL)
333 break;
334 tkn = pos + 1;
335 } while (tkn);
336 return retval;
339 static int
340 cifs_resolver(const key_serial_t key, const char *key_descr)
342 int c;
343 struct addrinfo *addr;
344 char ip[INET6_ADDRSTRLEN];
345 void *p;
346 const char *keyend = key_descr;
347 /* skip next 4 ';' delimiters to get to description */
348 for (c = 1; c <= 4; c++) {
349 keyend = index(keyend+1, ';');
350 if (!keyend) {
351 syslog(LOG_ERR, "invalid key description: %s",
352 key_descr);
353 return 1;
356 keyend++;
358 /* resolve name to ip */
359 c = getaddrinfo(keyend, NULL, NULL, &addr);
360 if (c) {
361 syslog(LOG_ERR, "unable to resolve hostname: %s [%s]",
362 keyend, gai_strerror(c));
363 return 1;
366 /* conver ip to string form */
367 if (addr->ai_family == AF_INET)
368 p = &(((struct sockaddr_in *)addr->ai_addr)->sin_addr);
369 else
370 p = &(((struct sockaddr_in6 *)addr->ai_addr)->sin6_addr);
372 if (!inet_ntop(addr->ai_family, p, ip, sizeof(ip))) {
373 syslog(LOG_ERR, "%s: inet_ntop: %s", __func__, strerror(errno));
374 freeaddrinfo(addr);
375 return 1;
378 /* setup key */
379 c = keyctl_instantiate(key, ip, strlen(ip)+1, 0);
380 if (c == -1) {
381 syslog(LOG_ERR, "%s: keyctl_instantiate: %s", __func__,
382 strerror(errno));
383 freeaddrinfo(addr);
384 return 1;
387 freeaddrinfo(addr);
388 return 0;
392 * Older kernels sent IPv6 addresses without colons. Well, at least
393 * they're fixed-length strings. Convert these addresses to have colon
394 * delimiters to make getaddrinfo happy.
396 static void
397 convert_inet6_addr(const char *from, char *to)
399 int i = 1;
401 while (*from) {
402 *to++ = *from++;
403 if (!(i++ % 4) && *from)
404 *to++ = ':';
406 *to = 0;
409 static int
410 ip_to_fqdn(const char *addrstr, char *host, size_t hostlen)
412 int rc;
413 struct addrinfo hints = { .ai_flags = AI_NUMERICHOST };
414 struct addrinfo *res;
415 const char *ipaddr = addrstr;
416 char converted[INET6_ADDRSTRLEN + 1];
418 if ((strlen(ipaddr) > INET_ADDRSTRLEN) && !strchr(ipaddr, ':')) {
419 convert_inet6_addr(ipaddr, converted);
420 ipaddr = converted;
423 rc = getaddrinfo(ipaddr, NULL, &hints, &res);
424 if (rc) {
425 syslog(LOG_DEBUG, "%s: failed to resolve %s to "
426 "ipaddr: %s", __func__, ipaddr,
427 rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
428 return rc;
431 rc = getnameinfo(res->ai_addr, res->ai_addrlen, host, hostlen,
432 NULL, 0, NI_NAMEREQD);
433 freeaddrinfo(res);
434 if (rc) {
435 syslog(LOG_DEBUG, "%s: failed to resolve %s to fqdn: %s",
436 __func__, ipaddr,
437 rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
438 return rc;
441 syslog(LOG_DEBUG, "%s: resolved %s to %s", __func__, ipaddr, host);
442 return 0;
445 static void
446 usage(void)
448 syslog(LOG_INFO, "Usage: %s [-t] [-v] key_serial", prog);
449 fprintf(stderr, "Usage: %s [-t] [-v] key_serial\n", prog);
452 const struct option long_options[] = {
453 { "trust-dns", 0, NULL, 't' },
454 { "version", 0, NULL, 'v' },
455 { NULL, 0, NULL, 0 }
458 int main(const int argc, char *const argv[])
460 struct cifs_spnego_msg *keydata = NULL;
461 DATA_BLOB secblob = data_blob_null;
462 DATA_BLOB sess_key = data_blob_null;
463 key_serial_t key = 0;
464 size_t datalen;
465 unsigned int have;
466 long rc = 1;
467 int c, try_dns = 0;
468 char *buf, *princ = NULL, *ccname = NULL;
469 char hostbuf[NI_MAXHOST], *host;
470 struct decoded_args arg = { };
471 const char *oid;
473 hostbuf[0] = '\0';
475 openlog(prog, 0, LOG_DAEMON);
477 while ((c = getopt_long(argc, argv, "ctv", long_options, NULL)) != -1) {
478 switch (c) {
479 case 'c':
480 /* legacy option -- skip it */
481 break;
482 case 't':
483 try_dns++;
484 break;
485 case 'v':
486 printf("version: %s\n", CIFSSPNEGO_VERSION);
487 goto out;
488 default:
489 syslog(LOG_ERR, "unknown option: %c", c);
490 goto out;
494 /* is there a key? */
495 if (argc <= optind) {
496 usage();
497 goto out;
500 /* get key and keyring values */
501 errno = 0;
502 key = strtol(argv[optind], NULL, 10);
503 if (errno != 0) {
504 key = 0;
505 syslog(LOG_ERR, "Invalid key format: %s", strerror(errno));
506 goto out;
509 rc = keyctl_describe_alloc(key, &buf);
510 if (rc == -1) {
511 syslog(LOG_ERR, "keyctl_describe_alloc failed: %s",
512 strerror(errno));
513 rc = 1;
514 goto out;
517 syslog(LOG_DEBUG, "key description: %s", buf);
519 if ((strncmp(buf, "cifs.resolver", sizeof("cifs.resolver")-1) == 0) ||
520 (strncmp(buf, "dns_resolver", sizeof("dns_resolver")-1) == 0)) {
521 rc = cifs_resolver(key, buf);
522 goto out;
525 have = decode_key_description(buf, &arg);
526 SAFE_FREE(buf);
527 if ((have & DKD_MUSTHAVE_SET) != DKD_MUSTHAVE_SET) {
528 syslog(LOG_ERR, "unable to get necessary params from key "
529 "description (0x%x)", have);
530 rc = 1;
531 goto out;
534 if (arg.ver > CIFS_SPNEGO_UPCALL_VERSION) {
535 syslog(LOG_ERR, "incompatible kernel upcall version: 0x%x",
536 arg.ver);
537 rc = 1;
538 goto out;
541 if (have & DKD_HAVE_UID) {
542 rc = setuid(arg.uid);
543 if (rc == -1) {
544 syslog(LOG_ERR, "setuid: %s", strerror(errno));
545 goto out;
548 ccname = find_krb5_cc(CIFS_DEFAULT_KRB5_DIR, arg.uid);
551 host = arg.hostname;
553 // do mech specific authorization
554 switch (arg.sec) {
555 case MS_KRB5:
556 case KRB5:
557 retry_new_hostname:
558 /* for "cifs/" service name + terminating 0 */
559 datalen = strlen(host) + 5 + 1;
560 princ = SMB_XMALLOC_ARRAY(char, datalen);
561 if (!princ) {
562 rc = -ENOMEM;
563 break;
566 if (arg.sec == MS_KRB5)
567 oid = OID_KERBEROS5_OLD;
568 else
569 oid = OID_KERBEROS5;
572 * try getting a cifs/ principal first and then fall back to
573 * getting a host/ principal if that doesn't work.
575 strlcpy(princ, "cifs/", datalen);
576 strlcpy(princ + 5, host, datalen - 5);
577 rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
578 if (!rc)
579 break;
581 memcpy(princ, "host/", 5);
582 rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
583 if (!rc)
584 break;
586 if (!try_dns || !(have & DKD_HAVE_IP))
587 break;
589 rc = ip_to_fqdn(arg.ip, hostbuf, sizeof(hostbuf));
590 if (rc)
591 break;
593 SAFE_FREE(princ);
594 try_dns = 0;
595 host = hostbuf;
596 goto retry_new_hostname;
597 default:
598 syslog(LOG_ERR, "sectype: %d is not implemented", arg.sec);
599 rc = 1;
600 break;
603 SAFE_FREE(princ);
605 if (rc)
606 goto out;
608 /* pack SecurityBLob and SessionKey into downcall packet */
609 datalen =
610 sizeof(struct cifs_spnego_msg) + secblob.length + sess_key.length;
611 keydata = (struct cifs_spnego_msg*)SMB_XMALLOC_ARRAY(char, datalen);
612 if (!keydata) {
613 rc = 1;
614 goto out;
616 keydata->version = arg.ver;
617 keydata->flags = 0;
618 keydata->sesskey_len = sess_key.length;
619 keydata->secblob_len = secblob.length;
620 memcpy(&(keydata->data), sess_key.data, sess_key.length);
621 memcpy(&(keydata->data) + keydata->sesskey_len,
622 secblob.data, secblob.length);
624 /* setup key */
625 rc = keyctl_instantiate(key, keydata, datalen, 0);
626 if (rc == -1) {
627 syslog(LOG_ERR, "keyctl_instantiate: %s", strerror(errno));
628 goto out;
631 /* BB: maybe we need use timeout for key: for example no more then
632 * ticket lifietime? */
633 /* keyctl_set_timeout( key, 60); */
634 out:
636 * on error, negatively instantiate the key ourselves so that we can
637 * make sure the kernel doesn't hang it off of a searchable keyring
638 * and interfere with the next attempt to instantiate the key.
640 if (rc != 0 && key == 0)
641 keyctl_negate(key, 1, KEY_REQKEY_DEFL_DEFAULT);
642 data_blob_free(&secblob);
643 data_blob_free(&sess_key);
644 SAFE_FREE(ccname);
645 SAFE_FREE(arg.hostname);
646 SAFE_FREE(arg.ip);
647 SAFE_FREE(keydata);
648 return rc;