tdb: always set tdb->tracefd to -1 to be safe on goto fail
[Samba/bb.git] / client / cifs.upcall.c
blobd3ff5f17a2d8c956ce625447e2b334e5714fe471
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 "../libcli/auth/spnego.h"
30 #include <keyutils.h>
31 #include <getopt.h>
33 #include "cifs_spnego.h"
35 #define CIFS_DEFAULT_KRB5_DIR "/tmp"
36 #define CIFS_DEFAULT_KRB5_PREFIX "krb5cc_"
38 #define MAX_CCNAME_LEN PATH_MAX + 5
40 const char *CIFSSPNEGO_VERSION = "1.3";
41 static const char *prog = "cifs.upcall";
42 typedef enum _sectype {
43 NONE = 0,
44 KRB5,
45 MS_KRB5
46 } sectype_t;
48 /* does the ccache have a valid TGT? */
49 static time_t
50 get_tgt_time(const char *ccname) {
51 krb5_context context;
52 krb5_ccache ccache;
53 krb5_cc_cursor cur;
54 krb5_creds creds;
55 krb5_principal principal;
56 time_t credtime = 0;
57 char *realm = NULL;
59 if (krb5_init_context(&context)) {
60 syslog(LOG_DEBUG, "%s: unable to init krb5 context", __func__);
61 return 0;
64 if (krb5_cc_resolve(context, ccname, &ccache)) {
65 syslog(LOG_DEBUG, "%s: unable to resolve krb5 cache", __func__);
66 goto err_cache;
69 if (krb5_cc_set_flags(context, ccache, 0)) {
70 syslog(LOG_DEBUG, "%s: unable to set flags", __func__);
71 goto err_cache;
74 if (krb5_cc_get_principal(context, ccache, &principal)) {
75 syslog(LOG_DEBUG, "%s: unable to get principal", __func__);
76 goto err_princ;
79 if (krb5_cc_start_seq_get(context, ccache, &cur)) {
80 syslog(LOG_DEBUG, "%s: unable to seq start", __func__);
81 goto err_ccstart;
84 if ((realm = smb_krb5_principal_get_realm(context, principal)) == NULL) {
85 syslog(LOG_DEBUG, "%s: unable to get realm", __func__);
86 goto err_ccstart;
89 while (!credtime && !krb5_cc_next_cred(context, ccache, &cur, &creds)) {
90 char *name;
91 if (smb_krb5_unparse_name(NULL, context, creds.server, &name)) {
92 syslog(LOG_DEBUG, "%s: unable to unparse name", __func__);
93 goto err_endseq;
95 if (krb5_realm_compare(context, creds.server, principal) &&
96 strnequal(name, KRB5_TGS_NAME, KRB5_TGS_NAME_SIZE) &&
97 strnequal(name+KRB5_TGS_NAME_SIZE+1, realm, strlen(realm)) &&
98 creds.times.endtime > time(NULL))
99 credtime = creds.times.endtime;
100 krb5_free_cred_contents(context, &creds);
101 TALLOC_FREE(name);
103 err_endseq:
104 krb5_cc_end_seq_get(context, ccache, &cur);
105 err_ccstart:
106 krb5_free_principal(context, principal);
107 err_princ:
108 krb5_cc_set_flags(context, ccache, KRB5_TC_OPENCLOSE);
109 krb5_cc_close(context, ccache);
110 err_cache:
111 krb5_free_context(context);
112 return credtime;
115 static int
116 krb5cc_filter(const struct dirent *dirent)
118 if (strstr(dirent->d_name, CIFS_DEFAULT_KRB5_PREFIX))
119 return 1;
120 else
121 return 0;
124 /* search for a credcache that looks like a likely candidate */
125 static char *
126 find_krb5_cc(const char *dirname, uid_t uid)
128 struct dirent **namelist;
129 struct stat sbuf;
130 char ccname[MAX_CCNAME_LEN], *credpath, *best_cache = NULL;
131 int i, n;
132 time_t cred_time, best_time = 0;
134 n = scandir(dirname, &namelist, krb5cc_filter, NULL);
135 if (n < 0) {
136 syslog(LOG_DEBUG, "%s: scandir error on directory '%s': %s",
137 __func__, dirname, strerror(errno));
138 return NULL;
141 for (i = 0; i < n; i++) {
142 snprintf(ccname, sizeof(ccname), "FILE:%s/%s", dirname,
143 namelist[i]->d_name);
144 credpath = ccname + 5;
145 syslog(LOG_DEBUG, "%s: considering %s", __func__, credpath);
147 if (lstat(credpath, &sbuf)) {
148 syslog(LOG_DEBUG, "%s: stat error on '%s': %s",
149 __func__, credpath, strerror(errno));
150 free(namelist[i]);
151 continue;
153 if (sbuf.st_uid != uid) {
154 syslog(LOG_DEBUG, "%s: %s is owned by %u, not %u",
155 __func__, credpath, sbuf.st_uid, uid);
156 free(namelist[i]);
157 continue;
159 if (!S_ISREG(sbuf.st_mode)) {
160 syslog(LOG_DEBUG, "%s: %s is not a regular file",
161 __func__, credpath);
162 free(namelist[i]);
163 continue;
165 if (!(cred_time = get_tgt_time(ccname))) {
166 syslog(LOG_DEBUG, "%s: %s is not a valid credcache.",
167 __func__, ccname);
168 free(namelist[i]);
169 continue;
172 if (cred_time <= best_time) {
173 syslog(LOG_DEBUG, "%s: %s expires sooner than current "
174 "best.", __func__, ccname);
175 free(namelist[i]);
176 continue;
179 syslog(LOG_DEBUG, "%s: %s is valid ccache", __func__, ccname);
180 free(best_cache);
181 best_cache = SMB_STRNDUP(ccname, MAX_CCNAME_LEN);
182 best_time = cred_time;
183 free(namelist[i]);
185 free(namelist);
187 return best_cache;
191 * Prepares AP-REQ data for mechToken and gets session key
192 * Uses credentials from cache. It will not ask for password
193 * you should receive credentials for yuor name manually using
194 * kinit or whatever you wish.
196 * in:
197 * oid - string with OID/ Could be OID_KERBEROS5
198 * or OID_KERBEROS5_OLD
199 * principal - Service name.
200 * Could be "cifs/FQDN" for KRB5 OID
201 * or for MS_KRB5 OID style server principal
202 * like "pdc$@YOUR.REALM.NAME"
204 * out:
205 * secblob - pointer for spnego wrapped AP-REQ data to be stored
206 * sess_key- pointer for SessionKey data to be stored
208 * ret: 0 - success, others - failure
210 static int
211 handle_krb5_mech(const char *oid, const char *principal, DATA_BLOB *secblob,
212 DATA_BLOB *sess_key, const char *ccname)
214 int retval;
215 DATA_BLOB tkt, tkt_wrapped;
217 syslog(LOG_DEBUG, "%s: getting service ticket for %s", __func__,
218 principal);
220 /* get a kerberos ticket for the service and extract the session key */
221 retval = cli_krb5_get_ticket(principal, 0, &tkt, sess_key, 0, ccname,
222 NULL, NULL);
224 if (retval) {
225 syslog(LOG_DEBUG, "%s: failed to obtain service ticket (%d)",
226 __func__, retval);
227 return retval;
230 syslog(LOG_DEBUG, "%s: obtained service ticket", __func__);
232 /* wrap that up in a nice GSS-API wrapping */
233 tkt_wrapped = spnego_gen_krb5_wrap(tkt, TOK_ID_KRB_AP_REQ);
235 /* and wrap that in a shiny SPNEGO wrapper */
236 *secblob = gen_negTokenInit(oid, tkt_wrapped);
238 data_blob_free(&tkt_wrapped);
239 data_blob_free(&tkt);
240 return retval;
243 #define DKD_HAVE_HOSTNAME 0x1
244 #define DKD_HAVE_VERSION 0x2
245 #define DKD_HAVE_SEC 0x4
246 #define DKD_HAVE_IP 0x8
247 #define DKD_HAVE_UID 0x10
248 #define DKD_HAVE_PID 0x20
249 #define DKD_MUSTHAVE_SET (DKD_HAVE_HOSTNAME|DKD_HAVE_VERSION|DKD_HAVE_SEC)
251 struct decoded_args {
252 int ver;
253 char *hostname;
254 char *ip;
255 uid_t uid;
256 pid_t pid;
257 sectype_t sec;
260 static unsigned int
261 decode_key_description(const char *desc, struct decoded_args *arg)
263 int len;
264 int retval = 0;
265 char *pos;
266 const char *tkn = desc;
268 do {
269 pos = index(tkn, ';');
270 if (strncmp(tkn, "host=", 5) == 0) {
272 if (pos == NULL)
273 len = strlen(tkn);
274 else
275 len = pos - tkn;
277 len -= 4;
278 SAFE_FREE(arg->hostname);
279 arg->hostname = SMB_XMALLOC_ARRAY(char, len);
280 strlcpy(arg->hostname, tkn + 5, len);
281 retval |= DKD_HAVE_HOSTNAME;
282 } else if (!strncmp(tkn, "ip4=", 4) ||
283 !strncmp(tkn, "ip6=", 4)) {
284 if (pos == NULL)
285 len = strlen(tkn);
286 else
287 len = pos - tkn;
289 len -= 3;
290 SAFE_FREE(arg->ip);
291 arg->ip = SMB_XMALLOC_ARRAY(char, len);
292 strlcpy(arg->ip, tkn + 4, len);
293 retval |= DKD_HAVE_IP;
294 } else if (strncmp(tkn, "pid=", 4) == 0) {
295 errno = 0;
296 arg->pid = strtol(tkn + 4, NULL, 0);
297 if (errno != 0) {
298 syslog(LOG_ERR, "Invalid pid format: %s",
299 strerror(errno));
300 return 1;
301 } else {
302 retval |= DKD_HAVE_PID;
304 } else if (strncmp(tkn, "sec=", 4) == 0) {
305 if (strncmp(tkn + 4, "krb5", 4) == 0) {
306 retval |= DKD_HAVE_SEC;
307 arg->sec = KRB5;
308 } else if (strncmp(tkn + 4, "mskrb5", 6) == 0) {
309 retval |= DKD_HAVE_SEC;
310 arg->sec = MS_KRB5;
312 } else if (strncmp(tkn, "uid=", 4) == 0) {
313 errno = 0;
314 arg->uid = strtol(tkn + 4, NULL, 16);
315 if (errno != 0) {
316 syslog(LOG_ERR, "Invalid uid format: %s",
317 strerror(errno));
318 return 1;
319 } else {
320 retval |= DKD_HAVE_UID;
322 } else if (strncmp(tkn, "ver=", 4) == 0) { /* if version */
323 errno = 0;
324 arg->ver = strtol(tkn + 4, NULL, 16);
325 if (errno != 0) {
326 syslog(LOG_ERR, "Invalid version format: %s",
327 strerror(errno));
328 return 1;
329 } else {
330 retval |= DKD_HAVE_VERSION;
333 if (pos == NULL)
334 break;
335 tkn = pos + 1;
336 } while (tkn);
337 return retval;
340 static int
341 cifs_resolver(const key_serial_t key, const char *key_descr)
343 int c;
344 struct addrinfo *addr;
345 char ip[INET6_ADDRSTRLEN];
346 void *p;
347 const char *keyend = key_descr;
348 /* skip next 4 ';' delimiters to get to description */
349 for (c = 1; c <= 4; c++) {
350 keyend = index(keyend+1, ';');
351 if (!keyend) {
352 syslog(LOG_ERR, "invalid key description: %s",
353 key_descr);
354 return 1;
357 keyend++;
359 /* resolve name to ip */
360 c = getaddrinfo(keyend, NULL, NULL, &addr);
361 if (c) {
362 syslog(LOG_ERR, "unable to resolve hostname: %s [%s]",
363 keyend, gai_strerror(c));
364 return 1;
367 /* conver ip to string form */
368 if (addr->ai_family == AF_INET)
369 p = &(((struct sockaddr_in *)addr->ai_addr)->sin_addr);
370 else
371 p = &(((struct sockaddr_in6 *)addr->ai_addr)->sin6_addr);
373 if (!inet_ntop(addr->ai_family, p, ip, sizeof(ip))) {
374 syslog(LOG_ERR, "%s: inet_ntop: %s", __func__, strerror(errno));
375 freeaddrinfo(addr);
376 return 1;
379 /* setup key */
380 c = keyctl_instantiate(key, ip, strlen(ip)+1, 0);
381 if (c == -1) {
382 syslog(LOG_ERR, "%s: keyctl_instantiate: %s", __func__,
383 strerror(errno));
384 freeaddrinfo(addr);
385 return 1;
388 freeaddrinfo(addr);
389 return 0;
393 * Older kernels sent IPv6 addresses without colons. Well, at least
394 * they're fixed-length strings. Convert these addresses to have colon
395 * delimiters to make getaddrinfo happy.
397 static void
398 convert_inet6_addr(const char *from, char *to)
400 int i = 1;
402 while (*from) {
403 *to++ = *from++;
404 if (!(i++ % 4) && *from)
405 *to++ = ':';
407 *to = 0;
410 static int
411 ip_to_fqdn(const char *addrstr, char *host, size_t hostlen)
413 int rc;
414 struct addrinfo hints = { .ai_flags = AI_NUMERICHOST };
415 struct addrinfo *res;
416 const char *ipaddr = addrstr;
417 char converted[INET6_ADDRSTRLEN + 1];
419 if ((strlen(ipaddr) > INET_ADDRSTRLEN) && !strchr(ipaddr, ':')) {
420 convert_inet6_addr(ipaddr, converted);
421 ipaddr = converted;
424 rc = getaddrinfo(ipaddr, NULL, &hints, &res);
425 if (rc) {
426 syslog(LOG_DEBUG, "%s: failed to resolve %s to "
427 "ipaddr: %s", __func__, ipaddr,
428 rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
429 return rc;
432 rc = getnameinfo(res->ai_addr, res->ai_addrlen, host, hostlen,
433 NULL, 0, NI_NAMEREQD);
434 freeaddrinfo(res);
435 if (rc) {
436 syslog(LOG_DEBUG, "%s: failed to resolve %s to fqdn: %s",
437 __func__, ipaddr,
438 rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
439 return rc;
442 syslog(LOG_DEBUG, "%s: resolved %s to %s", __func__, ipaddr, host);
443 return 0;
446 static void
447 usage(void)
449 syslog(LOG_INFO, "Usage: %s [-t] [-v] key_serial", prog);
450 fprintf(stderr, "Usage: %s [-t] [-v] key_serial\n", prog);
453 const struct option long_options[] = {
454 { "trust-dns", 0, NULL, 't' },
455 { "version", 0, NULL, 'v' },
456 { NULL, 0, NULL, 0 }
459 int main(const int argc, char *const argv[])
461 struct cifs_spnego_msg *keydata = NULL;
462 DATA_BLOB secblob = data_blob_null;
463 DATA_BLOB sess_key = data_blob_null;
464 key_serial_t key = 0;
465 size_t datalen;
466 unsigned int have;
467 long rc = 1;
468 int c, try_dns = 0;
469 char *buf, *princ = NULL, *ccname = NULL;
470 char hostbuf[NI_MAXHOST], *host;
471 struct decoded_args arg = { };
472 const char *oid;
474 hostbuf[0] = '\0';
476 openlog(prog, 0, LOG_DAEMON);
478 while ((c = getopt_long(argc, argv, "ctv", long_options, NULL)) != -1) {
479 switch (c) {
480 case 'c':
481 /* legacy option -- skip it */
482 break;
483 case 't':
484 try_dns++;
485 break;
486 case 'v':
487 printf("version: %s\n", CIFSSPNEGO_VERSION);
488 goto out;
489 default:
490 syslog(LOG_ERR, "unknown option: %c", c);
491 goto out;
495 /* is there a key? */
496 if (argc <= optind) {
497 usage();
498 goto out;
501 /* get key and keyring values */
502 errno = 0;
503 key = strtol(argv[optind], NULL, 10);
504 if (errno != 0) {
505 key = 0;
506 syslog(LOG_ERR, "Invalid key format: %s", strerror(errno));
507 goto out;
510 rc = keyctl_describe_alloc(key, &buf);
511 if (rc == -1) {
512 syslog(LOG_ERR, "keyctl_describe_alloc failed: %s",
513 strerror(errno));
514 rc = 1;
515 goto out;
518 syslog(LOG_DEBUG, "key description: %s", buf);
520 if ((strncmp(buf, "cifs.resolver", sizeof("cifs.resolver")-1) == 0) ||
521 (strncmp(buf, "dns_resolver", sizeof("dns_resolver")-1) == 0)) {
522 rc = cifs_resolver(key, buf);
523 goto out;
526 have = decode_key_description(buf, &arg);
527 SAFE_FREE(buf);
528 if ((have & DKD_MUSTHAVE_SET) != DKD_MUSTHAVE_SET) {
529 syslog(LOG_ERR, "unable to get necessary params from key "
530 "description (0x%x)", have);
531 rc = 1;
532 goto out;
535 if (arg.ver > CIFS_SPNEGO_UPCALL_VERSION) {
536 syslog(LOG_ERR, "incompatible kernel upcall version: 0x%x",
537 arg.ver);
538 rc = 1;
539 goto out;
542 if (have & DKD_HAVE_UID) {
543 rc = setuid(arg.uid);
544 if (rc == -1) {
545 syslog(LOG_ERR, "setuid: %s", strerror(errno));
546 goto out;
549 ccname = find_krb5_cc(CIFS_DEFAULT_KRB5_DIR, arg.uid);
552 host = arg.hostname;
554 // do mech specific authorization
555 switch (arg.sec) {
556 case MS_KRB5:
557 case KRB5:
558 retry_new_hostname:
559 /* for "cifs/" service name + terminating 0 */
560 datalen = strlen(host) + 5 + 1;
561 princ = SMB_XMALLOC_ARRAY(char, datalen);
562 if (!princ) {
563 rc = -ENOMEM;
564 break;
567 if (arg.sec == MS_KRB5)
568 oid = OID_KERBEROS5_OLD;
569 else
570 oid = OID_KERBEROS5;
573 * try getting a cifs/ principal first and then fall back to
574 * getting a host/ principal if that doesn't work.
576 strlcpy(princ, "cifs/", datalen);
577 strlcpy(princ + 5, host, datalen - 5);
578 rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
579 if (!rc)
580 break;
582 memcpy(princ, "host/", 5);
583 rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
584 if (!rc)
585 break;
587 if (!try_dns || !(have & DKD_HAVE_IP))
588 break;
590 rc = ip_to_fqdn(arg.ip, hostbuf, sizeof(hostbuf));
591 if (rc)
592 break;
594 SAFE_FREE(princ);
595 try_dns = 0;
596 host = hostbuf;
597 goto retry_new_hostname;
598 default:
599 syslog(LOG_ERR, "sectype: %d is not implemented", arg.sec);
600 rc = 1;
601 break;
604 SAFE_FREE(princ);
606 if (rc)
607 goto out;
609 /* pack SecurityBLob and SessionKey into downcall packet */
610 datalen =
611 sizeof(struct cifs_spnego_msg) + secblob.length + sess_key.length;
612 keydata = (struct cifs_spnego_msg*)SMB_XMALLOC_ARRAY(char, datalen);
613 if (!keydata) {
614 rc = 1;
615 goto out;
617 keydata->version = arg.ver;
618 keydata->flags = 0;
619 keydata->sesskey_len = sess_key.length;
620 keydata->secblob_len = secblob.length;
621 memcpy(&(keydata->data), sess_key.data, sess_key.length);
622 memcpy(&(keydata->data) + keydata->sesskey_len,
623 secblob.data, secblob.length);
625 /* setup key */
626 rc = keyctl_instantiate(key, keydata, datalen, 0);
627 if (rc == -1) {
628 syslog(LOG_ERR, "keyctl_instantiate: %s", strerror(errno));
629 goto out;
632 /* BB: maybe we need use timeout for key: for example no more then
633 * ticket lifietime? */
634 /* keyctl_set_timeout( key, 60); */
635 out:
637 * on error, negatively instantiate the key ourselves so that we can
638 * make sure the kernel doesn't hang it off of a searchable keyring
639 * and interfere with the next attempt to instantiate the key.
641 if (rc != 0 && key == 0)
642 keyctl_negate(key, 1, KEY_REQKEY_DEFL_DEFAULT);
643 data_blob_free(&secblob);
644 data_blob_free(&sess_key);
645 SAFE_FREE(ccname);
646 SAFE_FREE(arg.hostname);
647 SAFE_FREE(arg.ip);
648 SAFE_FREE(keydata);
649 return rc;