idl: rebuild drsuapi.idl
[Samba/aatanasov.git] / client / cifs.upcall.c
blobbf6a861544c80b01c8c1ac904bfe54ff3f3d70c2
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 static inline int
49 k5_data_equal(krb5_data d1, krb5_data d2, unsigned int length)
51 if (!length)
52 length = d1.length;
54 return (d1.length == length &&
55 d1.length == d2.length &&
56 memcmp(d1.data, d2.data, length) == 0);
60 /* does the ccache have a valid TGT? */
61 static time_t
62 get_tgt_time(const char *ccname) {
63 krb5_context context;
64 krb5_ccache ccache;
65 krb5_cc_cursor cur;
66 krb5_creds creds;
67 krb5_principal principal;
68 krb5_data tgt = { .data = "krbtgt",
69 .length = 6 };
70 time_t credtime = 0;
72 if (krb5_init_context(&context)) {
73 syslog(LOG_DEBUG, "%s: unable to init krb5 context", __func__);
74 return 0;
77 if (krb5_cc_resolve(context, ccname, &ccache)) {
78 syslog(LOG_DEBUG, "%s: unable to resolve krb5 cache", __func__);
79 goto err_cache;
82 if (krb5_cc_set_flags(context, ccache, 0)) {
83 syslog(LOG_DEBUG, "%s: unable to set flags", __func__);
84 goto err_cache;
87 if (krb5_cc_get_principal(context, ccache, &principal)) {
88 syslog(LOG_DEBUG, "%s: unable to get principal", __func__);
89 goto err_princ;
92 if (krb5_cc_start_seq_get(context, ccache, &cur)) {
93 syslog(LOG_DEBUG, "%s: unable to seq start", __func__);
94 goto err_ccstart;
97 while (!credtime && !krb5_cc_next_cred(context, ccache, &cur, &creds)) {
98 if (k5_data_equal(creds.server->realm, principal->realm, 0) &&
99 k5_data_equal(creds.server->data[0], tgt, tgt.length) &&
100 k5_data_equal(creds.server->data[1], principal->realm, 0) &&
101 creds.times.endtime > time(NULL))
102 credtime = creds.times.endtime;
103 krb5_free_cred_contents(context, &creds);
105 krb5_cc_end_seq_get(context, ccache, &cur);
107 err_ccstart:
108 krb5_free_principal(context, principal);
109 err_princ:
110 krb5_cc_set_flags(context, ccache, KRB5_TC_OPENCLOSE);
111 krb5_cc_close(context, ccache);
112 err_cache:
113 krb5_free_context(context);
114 return credtime;
117 static int
118 krb5cc_filter(const struct dirent *dirent)
120 if (strstr(dirent->d_name, CIFS_DEFAULT_KRB5_PREFIX))
121 return 1;
122 else
123 return 0;
126 /* search for a credcache that looks like a likely candidate */
127 static char *
128 find_krb5_cc(const char *dirname, uid_t uid)
130 struct dirent **namelist;
131 struct stat sbuf;
132 char ccname[MAX_CCNAME_LEN], *credpath, *best_cache = NULL;
133 int i, n;
134 time_t cred_time, best_time = 0;
136 n = scandir(dirname, &namelist, krb5cc_filter, NULL);
137 if (n < 0) {
138 syslog(LOG_DEBUG, "%s: scandir error on directory '%s': %s",
139 __func__, dirname, strerror(errno));
140 return NULL;
143 for (i = 0; i < n; i++) {
144 snprintf(ccname, sizeof(ccname), "FILE:%s/%s", dirname,
145 namelist[i]->d_name);
146 credpath = ccname + 5;
147 syslog(LOG_DEBUG, "%s: considering %s", __func__, credpath);
149 if (lstat(credpath, &sbuf)) {
150 syslog(LOG_DEBUG, "%s: stat error on '%s': %s",
151 __func__, credpath, strerror(errno));
152 free(namelist[i]);
153 continue;
155 if (sbuf.st_uid != uid) {
156 syslog(LOG_DEBUG, "%s: %s is owned by %u, not %u",
157 __func__, credpath, sbuf.st_uid, uid);
158 free(namelist[i]);
159 continue;
161 if (!S_ISREG(sbuf.st_mode)) {
162 syslog(LOG_DEBUG, "%s: %s is not a regular file",
163 __func__, credpath);
164 free(namelist[i]);
165 continue;
167 if (!(cred_time = get_tgt_time(ccname))) {
168 syslog(LOG_DEBUG, "%s: %s is not a valid credcache.",
169 __func__, ccname);
170 free(namelist[i]);
171 continue;
174 if (cred_time <= best_time) {
175 syslog(LOG_DEBUG, "%s: %s expires sooner than current "
176 "best.", __func__, ccname);
177 free(namelist[i]);
178 continue;
181 syslog(LOG_DEBUG, "%s: %s is valid ccache", __func__, ccname);
182 free(best_cache);
183 best_cache = SMB_STRNDUP(ccname, MAX_CCNAME_LEN);
184 best_time = cred_time;
185 free(namelist[i]);
187 free(namelist);
189 return best_cache;
193 * Prepares AP-REQ data for mechToken and gets session key
194 * Uses credentials from cache. It will not ask for password
195 * you should receive credentials for yuor name manually using
196 * kinit or whatever you wish.
198 * in:
199 * oid - string with OID/ Could be OID_KERBEROS5
200 * or OID_KERBEROS5_OLD
201 * principal - Service name.
202 * Could be "cifs/FQDN" for KRB5 OID
203 * or for MS_KRB5 OID style server principal
204 * like "pdc$@YOUR.REALM.NAME"
206 * out:
207 * secblob - pointer for spnego wrapped AP-REQ data to be stored
208 * sess_key- pointer for SessionKey data to be stored
210 * ret: 0 - success, others - failure
212 static int
213 handle_krb5_mech(const char *oid, const char *principal, DATA_BLOB *secblob,
214 DATA_BLOB *sess_key, const char *ccname)
216 int retval;
217 DATA_BLOB tkt, tkt_wrapped;
219 syslog(LOG_DEBUG, "%s: getting service ticket for %s", __func__,
220 principal);
222 /* get a kerberos ticket for the service and extract the session key */
223 retval = cli_krb5_get_ticket(principal, 0, &tkt, sess_key, 0, ccname,
224 NULL);
226 if (retval) {
227 syslog(LOG_DEBUG, "%s: failed to obtain service ticket (%d)",
228 __func__, retval);
229 return retval;
232 syslog(LOG_DEBUG, "%s: obtained service ticket", __func__);
234 /* wrap that up in a nice GSS-API wrapping */
235 tkt_wrapped = spnego_gen_krb5_wrap(tkt, TOK_ID_KRB_AP_REQ);
237 /* and wrap that in a shiny SPNEGO wrapper */
238 *secblob = gen_negTokenInit(oid, tkt_wrapped);
240 data_blob_free(&tkt_wrapped);
241 data_blob_free(&tkt);
242 return retval;
245 #define DKD_HAVE_HOSTNAME 0x1
246 #define DKD_HAVE_VERSION 0x2
247 #define DKD_HAVE_SEC 0x4
248 #define DKD_HAVE_IP 0x8
249 #define DKD_HAVE_UID 0x10
250 #define DKD_HAVE_PID 0x20
251 #define DKD_MUSTHAVE_SET (DKD_HAVE_HOSTNAME|DKD_HAVE_VERSION|DKD_HAVE_SEC)
253 struct decoded_args {
254 int ver;
255 char *hostname;
256 char *ip;
257 uid_t uid;
258 pid_t pid;
259 sectype_t sec;
262 static unsigned int
263 decode_key_description(const char *desc, struct decoded_args *arg)
265 int len;
266 int retval = 0;
267 char *pos;
268 const char *tkn = desc;
270 do {
271 pos = index(tkn, ';');
272 if (strncmp(tkn, "host=", 5) == 0) {
274 if (pos == NULL)
275 len = strlen(tkn);
276 else
277 len = pos - tkn;
279 len -= 4;
280 SAFE_FREE(arg->hostname);
281 arg->hostname = SMB_XMALLOC_ARRAY(char, len);
282 strlcpy(arg->hostname, tkn + 5, len);
283 retval |= DKD_HAVE_HOSTNAME;
284 } else if (!strncmp(tkn, "ip4=", 4) ||
285 !strncmp(tkn, "ip6=", 4)) {
286 if (pos == NULL)
287 len = strlen(tkn);
288 else
289 len = pos - tkn;
291 len -= 3;
292 SAFE_FREE(arg->ip);
293 arg->ip = SMB_XMALLOC_ARRAY(char, len);
294 strlcpy(arg->ip, tkn + 4, len);
295 retval |= DKD_HAVE_IP;
296 } else if (strncmp(tkn, "pid=", 4) == 0) {
297 errno = 0;
298 arg->pid = strtol(tkn + 4, NULL, 0);
299 if (errno != 0) {
300 syslog(LOG_ERR, "Invalid pid format: %s",
301 strerror(errno));
302 return 1;
303 } else {
304 retval |= DKD_HAVE_PID;
306 } else if (strncmp(tkn, "sec=", 4) == 0) {
307 if (strncmp(tkn + 4, "krb5", 4) == 0) {
308 retval |= DKD_HAVE_SEC;
309 arg->sec = KRB5;
310 } else if (strncmp(tkn + 4, "mskrb5", 6) == 0) {
311 retval |= DKD_HAVE_SEC;
312 arg->sec = MS_KRB5;
314 } else if (strncmp(tkn, "uid=", 4) == 0) {
315 errno = 0;
316 arg->uid = strtol(tkn + 4, NULL, 16);
317 if (errno != 0) {
318 syslog(LOG_ERR, "Invalid uid format: %s",
319 strerror(errno));
320 return 1;
321 } else {
322 retval |= DKD_HAVE_UID;
324 } else if (strncmp(tkn, "ver=", 4) == 0) { /* if version */
325 errno = 0;
326 arg->ver = strtol(tkn + 4, NULL, 16);
327 if (errno != 0) {
328 syslog(LOG_ERR, "Invalid version format: %s",
329 strerror(errno));
330 return 1;
331 } else {
332 retval |= DKD_HAVE_VERSION;
335 if (pos == NULL)
336 break;
337 tkn = pos + 1;
338 } while (tkn);
339 return retval;
342 static int
343 cifs_resolver(const key_serial_t key, const char *key_descr)
345 int c;
346 struct addrinfo *addr;
347 char ip[INET6_ADDRSTRLEN];
348 void *p;
349 const char *keyend = key_descr;
350 /* skip next 4 ';' delimiters to get to description */
351 for (c = 1; c <= 4; c++) {
352 keyend = index(keyend+1, ';');
353 if (!keyend) {
354 syslog(LOG_ERR, "invalid key description: %s",
355 key_descr);
356 return 1;
359 keyend++;
361 /* resolve name to ip */
362 c = getaddrinfo(keyend, NULL, NULL, &addr);
363 if (c) {
364 syslog(LOG_ERR, "unable to resolve hostname: %s [%s]",
365 keyend, gai_strerror(c));
366 return 1;
369 /* conver ip to string form */
370 if (addr->ai_family == AF_INET)
371 p = &(((struct sockaddr_in *)addr->ai_addr)->sin_addr);
372 else
373 p = &(((struct sockaddr_in6 *)addr->ai_addr)->sin6_addr);
375 if (!inet_ntop(addr->ai_family, p, ip, sizeof(ip))) {
376 syslog(LOG_ERR, "%s: inet_ntop: %s", __func__, strerror(errno));
377 freeaddrinfo(addr);
378 return 1;
381 /* setup key */
382 c = keyctl_instantiate(key, ip, strlen(ip)+1, 0);
383 if (c == -1) {
384 syslog(LOG_ERR, "%s: keyctl_instantiate: %s", __func__,
385 strerror(errno));
386 freeaddrinfo(addr);
387 return 1;
390 freeaddrinfo(addr);
391 return 0;
395 * Older kernels sent IPv6 addresses without colons. Well, at least
396 * they're fixed-length strings. Convert these addresses to have colon
397 * delimiters to make getaddrinfo happy.
399 static void
400 convert_inet6_addr(const char *from, char *to)
402 int i = 1;
404 while (*from) {
405 *to++ = *from++;
406 if (!(i++ % 4) && *from)
407 *to++ = ':';
409 *to = 0;
412 static int
413 ip_to_fqdn(const char *addrstr, char *host, size_t hostlen)
415 int rc;
416 struct addrinfo hints = { .ai_flags = AI_NUMERICHOST };
417 struct addrinfo *res;
418 const char *ipaddr = addrstr;
419 char converted[INET6_ADDRSTRLEN + 1];
421 if ((strlen(ipaddr) > INET_ADDRSTRLEN) && !strchr(ipaddr, ':')) {
422 convert_inet6_addr(ipaddr, converted);
423 ipaddr = converted;
426 rc = getaddrinfo(ipaddr, NULL, &hints, &res);
427 if (rc) {
428 syslog(LOG_DEBUG, "%s: failed to resolve %s to "
429 "ipaddr: %s", __func__, ipaddr,
430 rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
431 return rc;
434 rc = getnameinfo(res->ai_addr, res->ai_addrlen, host, hostlen,
435 NULL, 0, NI_NAMEREQD);
436 freeaddrinfo(res);
437 if (rc) {
438 syslog(LOG_DEBUG, "%s: failed to resolve %s to fqdn: %s",
439 __func__, ipaddr,
440 rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
441 return rc;
444 syslog(LOG_DEBUG, "%s: resolved %s to %s", __func__, ipaddr, host);
445 return 0;
448 static void
449 usage(void)
451 syslog(LOG_INFO, "Usage: %s [-t] [-v] key_serial", prog);
452 fprintf(stderr, "Usage: %s [-t] [-v] key_serial\n", prog);
455 const struct option long_options[] = {
456 { "trust-dns", 0, NULL, 't' },
457 { "version", 0, NULL, 'v' },
458 { NULL, 0, NULL, 0 }
461 int main(const int argc, char *const argv[])
463 struct cifs_spnego_msg *keydata = NULL;
464 DATA_BLOB secblob = data_blob_null;
465 DATA_BLOB sess_key = data_blob_null;
466 key_serial_t key = 0;
467 size_t datalen;
468 unsigned int have;
469 long rc = 1;
470 int c, try_dns = 0;
471 char *buf, *princ = NULL, *ccname = NULL;
472 char hostbuf[NI_MAXHOST], *host;
473 struct decoded_args arg = { };
474 const char *oid;
476 hostbuf[0] = '\0';
478 openlog(prog, 0, LOG_DAEMON);
480 while ((c = getopt_long(argc, argv, "ctv", long_options, NULL)) != -1) {
481 switch (c) {
482 case 'c':
483 /* legacy option -- skip it */
484 break;
485 case 't':
486 try_dns++;
487 break;
488 case 'v':
489 printf("version: %s\n", CIFSSPNEGO_VERSION);
490 goto out;
491 default:
492 syslog(LOG_ERR, "unknown option: %c", c);
493 goto out;
497 /* is there a key? */
498 if (argc <= optind) {
499 usage();
500 goto out;
503 /* get key and keyring values */
504 errno = 0;
505 key = strtol(argv[optind], NULL, 10);
506 if (errno != 0) {
507 key = 0;
508 syslog(LOG_ERR, "Invalid key format: %s", strerror(errno));
509 goto out;
512 rc = keyctl_describe_alloc(key, &buf);
513 if (rc == -1) {
514 syslog(LOG_ERR, "keyctl_describe_alloc failed: %s",
515 strerror(errno));
516 rc = 1;
517 goto out;
520 syslog(LOG_DEBUG, "key description: %s", buf);
522 if ((strncmp(buf, "cifs.resolver", sizeof("cifs.resolver")-1) == 0) ||
523 (strncmp(buf, "dns_resolver", sizeof("dns_resolver")-1) == 0)) {
524 rc = cifs_resolver(key, buf);
525 goto out;
528 have = decode_key_description(buf, &arg);
529 SAFE_FREE(buf);
530 if ((have & DKD_MUSTHAVE_SET) != DKD_MUSTHAVE_SET) {
531 syslog(LOG_ERR, "unable to get necessary params from key "
532 "description (0x%x)", have);
533 rc = 1;
534 goto out;
537 if (arg.ver > CIFS_SPNEGO_UPCALL_VERSION) {
538 syslog(LOG_ERR, "incompatible kernel upcall version: 0x%x",
539 arg.ver);
540 rc = 1;
541 goto out;
544 if (have & DKD_HAVE_UID) {
545 rc = setuid(arg.uid);
546 if (rc == -1) {
547 syslog(LOG_ERR, "setuid: %s", strerror(errno));
548 goto out;
551 ccname = find_krb5_cc(CIFS_DEFAULT_KRB5_DIR, arg.uid);
554 host = arg.hostname;
556 // do mech specific authorization
557 switch (arg.sec) {
558 case MS_KRB5:
559 case KRB5:
560 retry_new_hostname:
561 /* for "cifs/" service name + terminating 0 */
562 datalen = strlen(host) + 5 + 1;
563 princ = SMB_XMALLOC_ARRAY(char, datalen);
564 if (!princ) {
565 rc = -ENOMEM;
566 break;
569 if (arg.sec == MS_KRB5)
570 oid = OID_KERBEROS5_OLD;
571 else
572 oid = OID_KERBEROS5;
575 * try getting a cifs/ principal first and then fall back to
576 * getting a host/ principal if that doesn't work.
578 strlcpy(princ, "cifs/", datalen);
579 strlcpy(princ + 5, host, datalen - 5);
580 rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
581 if (!rc)
582 break;
584 memcpy(princ, "host/", 5);
585 rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
586 if (!rc)
587 break;
589 if (!try_dns || !(have & DKD_HAVE_IP))
590 break;
592 rc = ip_to_fqdn(arg.ip, hostbuf, sizeof(hostbuf));
593 if (rc)
594 break;
596 SAFE_FREE(princ);
597 try_dns = 0;
598 host = hostbuf;
599 goto retry_new_hostname;
600 default:
601 syslog(LOG_ERR, "sectype: %d is not implemented", arg.sec);
602 rc = 1;
603 break;
606 SAFE_FREE(princ);
608 if (rc)
609 goto out;
611 /* pack SecurityBLob and SessionKey into downcall packet */
612 datalen =
613 sizeof(struct cifs_spnego_msg) + secblob.length + sess_key.length;
614 keydata = (struct cifs_spnego_msg*)SMB_XMALLOC_ARRAY(char, datalen);
615 if (!keydata) {
616 rc = 1;
617 goto out;
619 keydata->version = arg.ver;
620 keydata->flags = 0;
621 keydata->sesskey_len = sess_key.length;
622 keydata->secblob_len = secblob.length;
623 memcpy(&(keydata->data), sess_key.data, sess_key.length);
624 memcpy(&(keydata->data) + keydata->sesskey_len,
625 secblob.data, secblob.length);
627 /* setup key */
628 rc = keyctl_instantiate(key, keydata, datalen, 0);
629 if (rc == -1) {
630 syslog(LOG_ERR, "keyctl_instantiate: %s", strerror(errno));
631 goto out;
634 /* BB: maybe we need use timeout for key: for example no more then
635 * ticket lifietime? */
636 /* keyctl_set_timeout( key, 60); */
637 out:
639 * on error, negatively instantiate the key ourselves so that we can
640 * make sure the kernel doesn't hang it off of a searchable keyring
641 * and interfere with the next attempt to instantiate the key.
643 if (rc != 0 && key == 0)
644 keyctl_negate(key, 1, KEY_REQKEY_DEFL_DEFAULT);
645 data_blob_free(&secblob);
646 data_blob_free(&sess_key);
647 SAFE_FREE(ccname);
648 SAFE_FREE(arg.hostname);
649 SAFE_FREE(arg.ip);
650 SAFE_FREE(keydata);
651 return rc;