s4:dsdb: add validate_update module
[Samba/fernandojvsilva.git] / client / cifs.upcall.c
blobbfc70d15ed116e9d93b09026565e244ae4890b85
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 "smb_krb5.h"
31 #include <keyutils.h>
32 #include <getopt.h>
34 #include "cifs_spnego.h"
36 #define CIFS_DEFAULT_KRB5_DIR "/tmp"
37 #define CIFS_DEFAULT_KRB5_PREFIX "krb5cc_"
39 #define MAX_CCNAME_LEN PATH_MAX + 5
41 const char *CIFSSPNEGO_VERSION = "1.3";
42 static const char *prog = "cifs.upcall";
43 typedef enum _sectype {
44 NONE = 0,
45 KRB5,
46 MS_KRB5
47 } sectype_t;
49 /* does the ccache have a valid TGT? */
50 static time_t
51 get_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;
60 if (krb5_init_context(&context)) {
61 syslog(LOG_DEBUG, "%s: unable to init krb5 context", __func__);
62 return 0;
65 if (krb5_cc_resolve(context, ccname, &ccache)) {
66 syslog(LOG_DEBUG, "%s: unable to resolve krb5 cache", __func__);
67 goto err_cache;
70 if (krb5_cc_set_flags(context, ccache, 0)) {
71 syslog(LOG_DEBUG, "%s: unable to set flags", __func__);
72 goto err_cache;
75 if (krb5_cc_get_principal(context, ccache, &principal)) {
76 syslog(LOG_DEBUG, "%s: unable to get principal", __func__);
77 goto err_princ;
80 if (krb5_cc_start_seq_get(context, ccache, &cur)) {
81 syslog(LOG_DEBUG, "%s: unable to seq start", __func__);
82 goto err_ccstart;
85 if ((realm = smb_krb5_principal_get_realm(context, principal)) == NULL) {
86 syslog(LOG_DEBUG, "%s: unable to get realm", __func__);
87 goto err_ccstart;
90 while (!credtime && !krb5_cc_next_cred(context, ccache, &cur, &creds)) {
91 char *name;
92 if (smb_krb5_unparse_name(NULL, context, creds.server, &name)) {
93 syslog(LOG_DEBUG, "%s: unable to unparse name", __func__);
94 goto err_endseq;
96 if (krb5_realm_compare(context, creds.server, principal) &&
97 strnequal(name, KRB5_TGS_NAME, KRB5_TGS_NAME_SIZE) &&
98 strnequal(name+KRB5_TGS_NAME_SIZE+1, realm, strlen(realm)) &&
99 creds.times.endtime > time(NULL))
100 credtime = creds.times.endtime;
101 krb5_free_cred_contents(context, &creds);
102 TALLOC_FREE(name);
104 err_endseq:
105 krb5_cc_end_seq_get(context, ccache, &cur);
106 err_ccstart:
107 krb5_free_principal(context, principal);
108 err_princ:
109 #if defined(KRB5_TC_OPENCLOSE)
110 krb5_cc_set_flags(context, ccache, KRB5_TC_OPENCLOSE);
111 #endif
112 krb5_cc_close(context, ccache);
113 err_cache:
114 krb5_free_context(context);
115 return credtime;
118 static int
119 krb5cc_filter(const struct dirent *dirent)
121 if (strstr(dirent->d_name, CIFS_DEFAULT_KRB5_PREFIX))
122 return 1;
123 else
124 return 0;
127 /* search for a credcache that looks like a likely candidate */
128 static char *
129 find_krb5_cc(const char *dirname, uid_t uid)
131 struct dirent **namelist;
132 struct stat sbuf;
133 char ccname[MAX_CCNAME_LEN], *credpath, *best_cache = NULL;
134 int i, n;
135 time_t cred_time, best_time = 0;
137 n = scandir(dirname, &namelist, krb5cc_filter, NULL);
138 if (n < 0) {
139 syslog(LOG_DEBUG, "%s: scandir error on directory '%s': %s",
140 __func__, dirname, strerror(errno));
141 return NULL;
144 for (i = 0; i < n; i++) {
145 snprintf(ccname, sizeof(ccname), "FILE:%s/%s", dirname,
146 namelist[i]->d_name);
147 credpath = ccname + 5;
148 syslog(LOG_DEBUG, "%s: considering %s", __func__, credpath);
150 if (lstat(credpath, &sbuf)) {
151 syslog(LOG_DEBUG, "%s: stat error on '%s': %s",
152 __func__, credpath, strerror(errno));
153 free(namelist[i]);
154 continue;
156 if (sbuf.st_uid != uid) {
157 syslog(LOG_DEBUG, "%s: %s is owned by %u, not %u",
158 __func__, credpath, sbuf.st_uid, uid);
159 free(namelist[i]);
160 continue;
162 if (!S_ISREG(sbuf.st_mode)) {
163 syslog(LOG_DEBUG, "%s: %s is not a regular file",
164 __func__, credpath);
165 free(namelist[i]);
166 continue;
168 if (!(cred_time = get_tgt_time(ccname))) {
169 syslog(LOG_DEBUG, "%s: %s is not a valid credcache.",
170 __func__, ccname);
171 free(namelist[i]);
172 continue;
175 if (cred_time <= best_time) {
176 syslog(LOG_DEBUG, "%s: %s expires sooner than current "
177 "best.", __func__, ccname);
178 free(namelist[i]);
179 continue;
182 syslog(LOG_DEBUG, "%s: %s is valid ccache", __func__, ccname);
183 free(best_cache);
184 best_cache = SMB_STRNDUP(ccname, MAX_CCNAME_LEN);
185 best_time = cred_time;
186 free(namelist[i]);
188 free(namelist);
190 return best_cache;
194 * Prepares AP-REQ data for mechToken and gets session key
195 * Uses credentials from cache. It will not ask for password
196 * you should receive credentials for yuor name manually using
197 * kinit or whatever you wish.
199 * in:
200 * oid - string with OID/ Could be OID_KERBEROS5
201 * or OID_KERBEROS5_OLD
202 * principal - Service name.
203 * Could be "cifs/FQDN" for KRB5 OID
204 * or for MS_KRB5 OID style server principal
205 * like "pdc$@YOUR.REALM.NAME"
207 * out:
208 * secblob - pointer for spnego wrapped AP-REQ data to be stored
209 * sess_key- pointer for SessionKey data to be stored
211 * ret: 0 - success, others - failure
213 static int
214 handle_krb5_mech(const char *oid, const char *principal, DATA_BLOB *secblob,
215 DATA_BLOB *sess_key, const char *ccname)
217 int retval;
218 DATA_BLOB tkt, tkt_wrapped;
220 syslog(LOG_DEBUG, "%s: getting service ticket for %s", __func__,
221 principal);
223 /* get a kerberos ticket for the service and extract the session key */
224 retval = cli_krb5_get_ticket(principal, 0, &tkt, sess_key, 0, ccname,
225 NULL, NULL);
227 if (retval) {
228 syslog(LOG_DEBUG, "%s: failed to obtain service ticket (%d)",
229 __func__, retval);
230 return retval;
233 syslog(LOG_DEBUG, "%s: obtained service ticket", __func__);
235 /* wrap that up in a nice GSS-API wrapping */
236 tkt_wrapped = spnego_gen_krb5_wrap(tkt, TOK_ID_KRB_AP_REQ);
238 /* and wrap that in a shiny SPNEGO wrapper */
239 *secblob = gen_negTokenInit(oid, tkt_wrapped);
241 data_blob_free(&tkt_wrapped);
242 data_blob_free(&tkt);
243 return retval;
246 #define DKD_HAVE_HOSTNAME 0x1
247 #define DKD_HAVE_VERSION 0x2
248 #define DKD_HAVE_SEC 0x4
249 #define DKD_HAVE_IP 0x8
250 #define DKD_HAVE_UID 0x10
251 #define DKD_HAVE_PID 0x20
252 #define DKD_MUSTHAVE_SET (DKD_HAVE_HOSTNAME|DKD_HAVE_VERSION|DKD_HAVE_SEC)
254 struct decoded_args {
255 int ver;
256 char *hostname;
257 char *ip;
258 uid_t uid;
259 pid_t pid;
260 sectype_t sec;
263 static unsigned int
264 decode_key_description(const char *desc, struct decoded_args *arg)
266 int len;
267 int retval = 0;
268 char *pos;
269 const char *tkn = desc;
271 do {
272 pos = index(tkn, ';');
273 if (strncmp(tkn, "host=", 5) == 0) {
275 if (pos == NULL)
276 len = strlen(tkn);
277 else
278 len = pos - tkn;
280 len -= 4;
281 SAFE_FREE(arg->hostname);
282 arg->hostname = SMB_XMALLOC_ARRAY(char, len);
283 strlcpy(arg->hostname, tkn + 5, len);
284 retval |= DKD_HAVE_HOSTNAME;
285 } else if (!strncmp(tkn, "ip4=", 4) ||
286 !strncmp(tkn, "ip6=", 4)) {
287 if (pos == NULL)
288 len = strlen(tkn);
289 else
290 len = pos - tkn;
292 len -= 3;
293 SAFE_FREE(arg->ip);
294 arg->ip = SMB_XMALLOC_ARRAY(char, len);
295 strlcpy(arg->ip, tkn + 4, len);
296 retval |= DKD_HAVE_IP;
297 } else if (strncmp(tkn, "pid=", 4) == 0) {
298 errno = 0;
299 arg->pid = strtol(tkn + 4, NULL, 0);
300 if (errno != 0) {
301 syslog(LOG_ERR, "Invalid pid format: %s",
302 strerror(errno));
303 return 1;
304 } else {
305 retval |= DKD_HAVE_PID;
307 } else if (strncmp(tkn, "sec=", 4) == 0) {
308 if (strncmp(tkn + 4, "krb5", 4) == 0) {
309 retval |= DKD_HAVE_SEC;
310 arg->sec = KRB5;
311 } else if (strncmp(tkn + 4, "mskrb5", 6) == 0) {
312 retval |= DKD_HAVE_SEC;
313 arg->sec = MS_KRB5;
315 } else if (strncmp(tkn, "uid=", 4) == 0) {
316 errno = 0;
317 arg->uid = strtol(tkn + 4, NULL, 16);
318 if (errno != 0) {
319 syslog(LOG_ERR, "Invalid uid format: %s",
320 strerror(errno));
321 return 1;
322 } else {
323 retval |= DKD_HAVE_UID;
325 } else if (strncmp(tkn, "ver=", 4) == 0) { /* if version */
326 errno = 0;
327 arg->ver = strtol(tkn + 4, NULL, 16);
328 if (errno != 0) {
329 syslog(LOG_ERR, "Invalid version format: %s",
330 strerror(errno));
331 return 1;
332 } else {
333 retval |= DKD_HAVE_VERSION;
336 if (pos == NULL)
337 break;
338 tkn = pos + 1;
339 } while (tkn);
340 return retval;
343 static int
344 cifs_resolver(const key_serial_t key, const char *key_descr)
346 int c;
347 struct addrinfo *addr;
348 char ip[INET6_ADDRSTRLEN];
349 void *p;
350 const char *keyend = key_descr;
351 /* skip next 4 ';' delimiters to get to description */
352 for (c = 1; c <= 4; c++) {
353 keyend = index(keyend+1, ';');
354 if (!keyend) {
355 syslog(LOG_ERR, "invalid key description: %s",
356 key_descr);
357 return 1;
360 keyend++;
362 /* resolve name to ip */
363 c = getaddrinfo(keyend, NULL, NULL, &addr);
364 if (c) {
365 syslog(LOG_ERR, "unable to resolve hostname: %s [%s]",
366 keyend, gai_strerror(c));
367 return 1;
370 /* conver ip to string form */
371 if (addr->ai_family == AF_INET)
372 p = &(((struct sockaddr_in *)addr->ai_addr)->sin_addr);
373 else
374 p = &(((struct sockaddr_in6 *)addr->ai_addr)->sin6_addr);
376 if (!inet_ntop(addr->ai_family, p, ip, sizeof(ip))) {
377 syslog(LOG_ERR, "%s: inet_ntop: %s", __func__, strerror(errno));
378 freeaddrinfo(addr);
379 return 1;
382 /* setup key */
383 c = keyctl_instantiate(key, ip, strlen(ip)+1, 0);
384 if (c == -1) {
385 syslog(LOG_ERR, "%s: keyctl_instantiate: %s", __func__,
386 strerror(errno));
387 freeaddrinfo(addr);
388 return 1;
391 freeaddrinfo(addr);
392 return 0;
396 * Older kernels sent IPv6 addresses without colons. Well, at least
397 * they're fixed-length strings. Convert these addresses to have colon
398 * delimiters to make getaddrinfo happy.
400 static void
401 convert_inet6_addr(const char *from, char *to)
403 int i = 1;
405 while (*from) {
406 *to++ = *from++;
407 if (!(i++ % 4) && *from)
408 *to++ = ':';
410 *to = 0;
413 static int
414 ip_to_fqdn(const char *addrstr, char *host, size_t hostlen)
416 int rc;
417 struct addrinfo hints = { .ai_flags = AI_NUMERICHOST };
418 struct addrinfo *res;
419 const char *ipaddr = addrstr;
420 char converted[INET6_ADDRSTRLEN + 1];
422 if ((strlen(ipaddr) > INET_ADDRSTRLEN) && !strchr(ipaddr, ':')) {
423 convert_inet6_addr(ipaddr, converted);
424 ipaddr = converted;
427 rc = getaddrinfo(ipaddr, NULL, &hints, &res);
428 if (rc) {
429 syslog(LOG_DEBUG, "%s: failed to resolve %s to "
430 "ipaddr: %s", __func__, ipaddr,
431 rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
432 return rc;
435 rc = getnameinfo(res->ai_addr, res->ai_addrlen, host, hostlen,
436 NULL, 0, NI_NAMEREQD);
437 freeaddrinfo(res);
438 if (rc) {
439 syslog(LOG_DEBUG, "%s: failed to resolve %s to fqdn: %s",
440 __func__, ipaddr,
441 rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
442 return rc;
445 syslog(LOG_DEBUG, "%s: resolved %s to %s", __func__, ipaddr, host);
446 return 0;
449 static void
450 usage(void)
452 syslog(LOG_INFO, "Usage: %s [-t] [-v] key_serial", prog);
453 fprintf(stderr, "Usage: %s [-t] [-v] key_serial\n", prog);
456 const struct option long_options[] = {
457 { "trust-dns", 0, NULL, 't' },
458 { "version", 0, NULL, 'v' },
459 { NULL, 0, NULL, 0 }
462 int main(const int argc, char *const argv[])
464 struct cifs_spnego_msg *keydata = NULL;
465 DATA_BLOB secblob = data_blob_null;
466 DATA_BLOB sess_key = data_blob_null;
467 key_serial_t key = 0;
468 size_t datalen;
469 unsigned int have;
470 long rc = 1;
471 int c, try_dns = 0;
472 char *buf, *princ = NULL, *ccname = NULL;
473 char hostbuf[NI_MAXHOST], *host;
474 struct decoded_args arg = { };
475 const char *oid;
477 hostbuf[0] = '\0';
479 openlog(prog, 0, LOG_DAEMON);
481 while ((c = getopt_long(argc, argv, "ctv", long_options, NULL)) != -1) {
482 switch (c) {
483 case 'c':
484 /* legacy option -- skip it */
485 break;
486 case 't':
487 try_dns++;
488 break;
489 case 'v':
490 printf("version: %s\n", CIFSSPNEGO_VERSION);
491 goto out;
492 default:
493 syslog(LOG_ERR, "unknown option: %c", c);
494 goto out;
498 /* is there a key? */
499 if (argc <= optind) {
500 usage();
501 goto out;
504 /* get key and keyring values */
505 errno = 0;
506 key = strtol(argv[optind], NULL, 10);
507 if (errno != 0) {
508 key = 0;
509 syslog(LOG_ERR, "Invalid key format: %s", strerror(errno));
510 goto out;
513 rc = keyctl_describe_alloc(key, &buf);
514 if (rc == -1) {
515 syslog(LOG_ERR, "keyctl_describe_alloc failed: %s",
516 strerror(errno));
517 rc = 1;
518 goto out;
521 syslog(LOG_DEBUG, "key description: %s", buf);
523 if ((strncmp(buf, "cifs.resolver", sizeof("cifs.resolver")-1) == 0) ||
524 (strncmp(buf, "dns_resolver", sizeof("dns_resolver")-1) == 0)) {
525 rc = cifs_resolver(key, buf);
526 goto out;
529 have = decode_key_description(buf, &arg);
530 SAFE_FREE(buf);
531 if ((have & DKD_MUSTHAVE_SET) != DKD_MUSTHAVE_SET) {
532 syslog(LOG_ERR, "unable to get necessary params from key "
533 "description (0x%x)", have);
534 rc = 1;
535 goto out;
538 if (arg.ver > CIFS_SPNEGO_UPCALL_VERSION) {
539 syslog(LOG_ERR, "incompatible kernel upcall version: 0x%x",
540 arg.ver);
541 rc = 1;
542 goto out;
545 if (have & DKD_HAVE_UID) {
546 rc = setuid(arg.uid);
547 if (rc == -1) {
548 syslog(LOG_ERR, "setuid: %s", strerror(errno));
549 goto out;
552 ccname = find_krb5_cc(CIFS_DEFAULT_KRB5_DIR, arg.uid);
555 host = arg.hostname;
557 // do mech specific authorization
558 switch (arg.sec) {
559 case MS_KRB5:
560 case KRB5:
561 retry_new_hostname:
562 /* for "cifs/" service name + terminating 0 */
563 datalen = strlen(host) + 5 + 1;
564 princ = SMB_XMALLOC_ARRAY(char, datalen);
565 if (!princ) {
566 rc = -ENOMEM;
567 break;
570 if (arg.sec == MS_KRB5)
571 oid = OID_KERBEROS5_OLD;
572 else
573 oid = OID_KERBEROS5;
576 * try getting a cifs/ principal first and then fall back to
577 * getting a host/ principal if that doesn't work.
579 strlcpy(princ, "cifs/", datalen);
580 strlcpy(princ + 5, host, datalen - 5);
581 rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
582 if (!rc)
583 break;
585 memcpy(princ, "host/", 5);
586 rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
587 if (!rc)
588 break;
590 if (!try_dns || !(have & DKD_HAVE_IP))
591 break;
593 rc = ip_to_fqdn(arg.ip, hostbuf, sizeof(hostbuf));
594 if (rc)
595 break;
597 SAFE_FREE(princ);
598 try_dns = 0;
599 host = hostbuf;
600 goto retry_new_hostname;
601 default:
602 syslog(LOG_ERR, "sectype: %d is not implemented", arg.sec);
603 rc = 1;
604 break;
607 SAFE_FREE(princ);
609 if (rc)
610 goto out;
612 /* pack SecurityBLob and SessionKey into downcall packet */
613 datalen =
614 sizeof(struct cifs_spnego_msg) + secblob.length + sess_key.length;
615 keydata = (struct cifs_spnego_msg*)SMB_XMALLOC_ARRAY(char, datalen);
616 if (!keydata) {
617 rc = 1;
618 goto out;
620 keydata->version = arg.ver;
621 keydata->flags = 0;
622 keydata->sesskey_len = sess_key.length;
623 keydata->secblob_len = secblob.length;
624 memcpy(&(keydata->data), sess_key.data, sess_key.length);
625 memcpy(&(keydata->data) + keydata->sesskey_len,
626 secblob.data, secblob.length);
628 /* setup key */
629 rc = keyctl_instantiate(key, keydata, datalen, 0);
630 if (rc == -1) {
631 syslog(LOG_ERR, "keyctl_instantiate: %s", strerror(errno));
632 goto out;
635 /* BB: maybe we need use timeout for key: for example no more then
636 * ticket lifietime? */
637 /* keyctl_set_timeout( key, 60); */
638 out:
640 * on error, negatively instantiate the key ourselves so that we can
641 * make sure the kernel doesn't hang it off of a searchable keyring
642 * and interfere with the next attempt to instantiate the key.
644 if (rc != 0 && key == 0)
645 keyctl_negate(key, 1, KEY_REQKEY_DEFL_DEFAULT);
646 data_blob_free(&secblob);
647 data_blob_free(&sess_key);
648 SAFE_FREE(ccname);
649 SAFE_FREE(arg.hostname);
650 SAFE_FREE(arg.ip);
651 SAFE_FREE(keydata);
652 return rc;