cifs.upcall: replace SMB_STRNDUP with strndup
[jlayton/cifs-utils.git] / cifs.upcall.c
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
12 create cifs.spnego * * /usr/local/sbin/cifs.upcall %k
13 create 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
41 /*
42  * samba forces the build to fail if strncasecmp is used, disable that for now
43  */
44 #ifdef strncasecmp
45 #undef strncasecmp
46 #endif
47
48 const char *CIFSSPNEGO_VERSION = "1.3";
49 static const char *prog = "cifs.upcall";
50 typedef enum _sectype {
51         NONE = 0,
52         KRB5,
53         MS_KRB5
54 } sectype_t;
55
56 /*
57  * smb_krb5_principal_get_realm
58  *
59  * @brief Get realm of a principal
60  *
61  * @param[in] context           The krb5_context
62  * @param[in] principal         The principal
63  * @return pointer to the realm
64  *
65  */
66
67 static char *cifs_krb5_principal_get_realm(krb5_context context,
68                                    krb5_principal principal)
69 {
70 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
71         return krb5_principal_get_realm(context, principal);
72 #elif defined(krb5_princ_realm) /* MIT */
73         krb5_data *realm;
74         realm = krb5_princ_realm(context, principal);
75         return (char *)realm->data;
76 #else
77         return NULL;
78 #endif
79 }
80
81 #if !defined(HAVE_KRB5_FREE_UNPARSED_NAME)
82 void krb5_free_unparsed_name(krb5_context context, char *val)
83 {
84         SAFE_FREE(val);
85 }
86 #endif
87
88 /* does the ccache have a valid TGT? */
89 static time_t
90 get_tgt_time(const char *ccname) {
91         krb5_context context;
92         krb5_ccache ccache;
93         krb5_cc_cursor cur;
94         krb5_creds creds;
95         krb5_principal principal;
96         time_t credtime = 0;
97         char *realm = NULL;
98
99         if (krb5_init_context(&context)) {
100                 syslog(LOG_DEBUG, "%s: unable to init krb5 context", __func__);
101                 return 0;
102         }
103
104         if (krb5_cc_resolve(context, ccname, &ccache)) {
105                 syslog(LOG_DEBUG, "%s: unable to resolve krb5 cache", __func__);
106                 goto err_cache;
107         }
108
109         if (krb5_cc_set_flags(context, ccache, 0)) {
110                 syslog(LOG_DEBUG, "%s: unable to set flags", __func__);
111                 goto err_cache;
112         }
113
114         if (krb5_cc_get_principal(context, ccache, &principal)) {
115                 syslog(LOG_DEBUG, "%s: unable to get principal", __func__);
116                 goto err_princ;
117         }
118
119         if (krb5_cc_start_seq_get(context, ccache, &cur)) {
120                 syslog(LOG_DEBUG, "%s: unable to seq start", __func__);
121                 goto err_ccstart;
122         }
123
124         if ((realm = cifs_krb5_principal_get_realm(context, principal)) == NULL) {
125                 syslog(LOG_DEBUG, "%s: unable to get realm", __func__);
126                 goto err_ccstart;
127         }
128
129         while (!credtime && !krb5_cc_next_cred(context, ccache, &cur, &creds)) {
130                 char *name;
131                 if (krb5_unparse_name(context, creds.server, &name)) {
132                         syslog(LOG_DEBUG, "%s: unable to unparse name", __func__);
133                         goto err_endseq;
134                 }
135                 if (krb5_realm_compare(context, creds.server, principal) &&
136                     !strncasecmp(name, KRB5_TGS_NAME, KRB5_TGS_NAME_SIZE) &&
137                     !strncasecmp(name+KRB5_TGS_NAME_SIZE+1, realm, strlen(realm)) &&
138                     creds.times.endtime > time(NULL))
139                         credtime = creds.times.endtime;
140                 krb5_free_cred_contents(context, &creds);
141                 krb5_free_unparsed_name(context, name);
142         }
143 err_endseq:
144         krb5_cc_end_seq_get(context, ccache, &cur);
145 err_ccstart:
146         krb5_free_principal(context, principal);
147 err_princ:
148 #if defined(KRB5_TC_OPENCLOSE)
149         krb5_cc_set_flags(context, ccache, KRB5_TC_OPENCLOSE);
150 #endif
151         krb5_cc_close(context, ccache);
152 err_cache:
153         krb5_free_context(context);
154         return credtime;
155 }
156
157 static int
158 krb5cc_filter(const struct dirent *dirent)
159 {
160         if (strstr(dirent->d_name, CIFS_DEFAULT_KRB5_PREFIX))
161                 return 1;
162         else
163                 return 0;
164 }
165
166 /* search for a credcache that looks like a likely candidate */
167 static char *
168 find_krb5_cc(const char *dirname, uid_t uid)
169 {
170         struct dirent **namelist;
171         struct stat sbuf;
172         char ccname[MAX_CCNAME_LEN], *credpath, *best_cache = NULL;
173         int i, n;
174         time_t cred_time, best_time = 0;
175
176         n = scandir(dirname, &namelist, krb5cc_filter, NULL);
177         if (n < 0) {
178                 syslog(LOG_DEBUG, "%s: scandir error on directory '%s': %s",
179                                   __func__, dirname, strerror(errno));
180                 return NULL;
181         }
182
183         for (i = 0; i < n; i++) {
184                 snprintf(ccname, sizeof(ccname), "FILE:%s/%s", dirname,
185                          namelist[i]->d_name);
186                 credpath = ccname + 5;
187                 syslog(LOG_DEBUG, "%s: considering %s", __func__, credpath);
188
189                 if (lstat(credpath, &sbuf)) {
190                         syslog(LOG_DEBUG, "%s: stat error on '%s': %s",
191                                           __func__, credpath, strerror(errno));
192                         free(namelist[i]);
193                         continue;
194                 }
195                 if (sbuf.st_uid != uid) {
196                         syslog(LOG_DEBUG, "%s: %s is owned by %u, not %u",
197                                         __func__, credpath, sbuf.st_uid, uid);
198                         free(namelist[i]);
199                         continue;
200                 }
201                 if (!S_ISREG(sbuf.st_mode)) {
202                         syslog(LOG_DEBUG, "%s: %s is not a regular file",
203                                         __func__, credpath);
204                         free(namelist[i]);
205                         continue;
206                 }
207                 if (!(cred_time = get_tgt_time(ccname))) {
208                         syslog(LOG_DEBUG, "%s: %s is not a valid credcache.",
209                                         __func__, ccname);
210                         free(namelist[i]);
211                         continue;
212                 }
213
214                 if (cred_time <= best_time) {
215                         syslog(LOG_DEBUG, "%s: %s expires sooner than current "
216                                           "best.", __func__, ccname);
217                         free(namelist[i]);
218                         continue;
219                 }
220
221                 syslog(LOG_DEBUG, "%s: %s is valid ccache", __func__, ccname);
222                 free(best_cache);
223                 best_cache = strndup(ccname, MAX_CCNAME_LEN);
224                 best_time = cred_time;
225                 free(namelist[i]);
226         }
227         free(namelist);
228
229         return best_cache;
230 }
231
232 static int
233 cifs_krb5_get_req(const char *principal, const char *ccname,
234                   DATA_BLOB *mechtoken, DATA_BLOB *sess_key)
235 {
236         krb5_error_code ret;
237         krb5_keyblock *tokb;
238         krb5_context context;
239         krb5_ccache ccache;
240         krb5_creds in_creds = { }, *out_creds;
241         krb5_data apreq_pkt, in_data;
242         krb5_auth_context auth_context = NULL;
243
244         ret = krb5_init_context(&context);
245         if (ret) {
246                 syslog(LOG_DEBUG, "%s: unable to init krb5 context", __func__);
247                 return ret;
248         }
249
250         ret = krb5_cc_resolve(context, ccname, &ccache);
251         if (ret) {
252                 syslog(LOG_DEBUG, "%s: unable to resolve %s to ccache\n",
253                                 __func__, ccname);
254                 goto out_free_context;
255         }
256
257         ret = krb5_cc_get_principal(context, ccache, &in_creds.client);
258         if (ret) {
259                 syslog(LOG_DEBUG, "%s: unable to get client principal name",
260                                   __func__);
261                 goto out_free_ccache;
262         }
263
264         ret = krb5_parse_name(context, principal, &in_creds.server);
265         if (ret) {
266                 syslog(LOG_DEBUG, "%s: unable to parse principal (%s).",
267                                   __func__, principal);
268                 goto out_free_principal;
269         }
270
271         in_creds.keyblock.enctype = 0;
272         ret = krb5_get_credentials(context, 0, ccache, &in_creds, &out_creds);
273         krb5_free_principal(context, in_creds.server);
274         if (ret) {
275                 syslog(LOG_DEBUG, "%s: unable to get credentials for %s",
276                                 __func__, principal);
277                 goto out_free_principal;
278         }
279
280         apreq_pkt.data = NULL;
281         in_data.length = 0;
282         ret = krb5_mk_req_extended(context, &auth_context, AP_OPTS_USE_SUBKEY,
283                                         &in_data, out_creds, &apreq_pkt);
284         if (ret) {
285                 syslog(LOG_DEBUG, "%s: unable to make AP-REQ for %s",
286                                 __func__, principal);
287                 goto out_free_creds;
288         }
289
290         ret = krb5_auth_con_getsendsubkey(context, auth_context, &tokb);
291         if (ret) {
292                 syslog(LOG_DEBUG, "%s: unable to get session key for %s",
293                                 __func__, principal);
294                 goto out_free_creds;
295         }
296
297         *mechtoken = data_blob(apreq_pkt.data, apreq_pkt.length);
298         *sess_key = data_blob(tokb->contents, tokb->length);
299
300         krb5_free_keyblock(context, tokb);
301 out_free_creds:
302         krb5_free_creds(context, out_creds);
303 out_free_principal:
304         krb5_free_principal(context, in_creds.client);
305 out_free_ccache:
306 #if defined(KRB5_TC_OPENCLOSE)
307         krb5_cc_set_flags(context, ccache, KRB5_TC_OPENCLOSE);
308 #endif
309         krb5_cc_close(context, ccache);
310 out_free_context:
311         krb5_free_context(context);
312         return ret;
313 }
314
315 /*
316  * Prepares AP-REQ data for mechToken and gets session key
317  * Uses credentials from cache. It will not ask for password
318  * you should receive credentials for yuor name manually using
319  * kinit or whatever you wish.
320  *
321  * in:
322  *      oid -           string with OID/ Could be OID_KERBEROS5
323  *                      or OID_KERBEROS5_OLD
324  *      principal -     Service name.
325  *                      Could be "cifs/FQDN" for KRB5 OID
326  *                      or for MS_KRB5 OID style server principal
327  *                      like "pdc$@YOUR.REALM.NAME"
328  *
329  * out:
330  *      secblob -       pointer for spnego wrapped AP-REQ data to be stored
331  *      sess_key-       pointer for SessionKey data to be stored
332  *
333  * ret: 0 - success, others - failure
334  */
335 static int
336 handle_krb5_mech(const char *oid, const char *principal, DATA_BLOB *secblob,
337                  DATA_BLOB *sess_key, const char *ccname)
338 {
339         int retval;
340         DATA_BLOB tkt, tkt_wrapped;
341
342         syslog(LOG_DEBUG, "%s: getting service ticket for %s", __func__,
343                           principal);
344
345         /* get a kerberos ticket for the service and extract the session key */
346         retval = cifs_krb5_get_req(principal, ccname, &tkt, sess_key);
347         if (retval) {
348                 syslog(LOG_DEBUG, "%s: failed to obtain service ticket (%d)",
349                                   __func__, retval);
350                 return retval;
351         }
352
353         syslog(LOG_DEBUG, "%s: obtained service ticket", __func__);
354
355         /* wrap that up in a nice GSS-API wrapping */
356         tkt_wrapped = spnego_gen_krb5_wrap(tkt, TOK_ID_KRB_AP_REQ);
357
358         /* and wrap that in a shiny SPNEGO wrapper */
359         *secblob = gen_negTokenInit(oid, tkt_wrapped);
360
361         data_blob_free(&tkt_wrapped);
362         data_blob_free(&tkt);
363         return retval;
364 }
365
366 #define DKD_HAVE_HOSTNAME       0x1
367 #define DKD_HAVE_VERSION        0x2
368 #define DKD_HAVE_SEC            0x4
369 #define DKD_HAVE_IP             0x8
370 #define DKD_HAVE_UID            0x10
371 #define DKD_HAVE_PID            0x20
372 #define DKD_MUSTHAVE_SET (DKD_HAVE_HOSTNAME|DKD_HAVE_VERSION|DKD_HAVE_SEC)
373
374 struct decoded_args {
375         int             ver;
376         char            *hostname;
377         char            *ip;
378         uid_t           uid;
379         pid_t           pid;
380         sectype_t       sec;
381 };
382
383 static unsigned int
384 decode_key_description(const char *desc, struct decoded_args *arg)
385 {
386         int len;
387         int retval = 0;
388         char *pos;
389         const char *tkn = desc;
390
391         do {
392                 pos = index(tkn, ';');
393                 if (strncmp(tkn, "host=", 5) == 0) {
394
395                         if (pos == NULL)
396                                 len = strlen(tkn);
397                         else
398                                 len = pos - tkn;
399
400                         len -= 4;
401                         SAFE_FREE(arg->hostname);
402                         arg->hostname = SMB_XMALLOC_ARRAY(char, len);
403                         strlcpy(arg->hostname, tkn + 5, len);
404                         retval |= DKD_HAVE_HOSTNAME;
405                 } else if (!strncmp(tkn, "ip4=", 4) ||
406                            !strncmp(tkn, "ip6=", 4)) {
407                         if (pos == NULL)
408                                 len = strlen(tkn);
409                         else
410                                 len = pos - tkn;
411
412                         len -= 3;
413                         SAFE_FREE(arg->ip);
414                         arg->ip = SMB_XMALLOC_ARRAY(char, len);
415                         strlcpy(arg->ip, tkn + 4, len);
416                         retval |= DKD_HAVE_IP;
417                 } else if (strncmp(tkn, "pid=", 4) == 0) {
418                         errno = 0;
419                         arg->pid = strtol(tkn + 4, NULL, 0);
420                         if (errno != 0) {
421                                 syslog(LOG_ERR, "Invalid pid format: %s",
422                                        strerror(errno));
423                                 return 1;
424                         } else {
425                                 retval |= DKD_HAVE_PID;
426                         }
427                 } else if (strncmp(tkn, "sec=", 4) == 0) {
428                         if (strncmp(tkn + 4, "krb5", 4) == 0) {
429                                 retval |= DKD_HAVE_SEC;
430                                 arg->sec = KRB5;
431                         } else if (strncmp(tkn + 4, "mskrb5", 6) == 0) {
432                                 retval |= DKD_HAVE_SEC;
433                                 arg->sec = MS_KRB5;
434                         }
435                 } else if (strncmp(tkn, "uid=", 4) == 0) {
436                         errno = 0;
437                         arg->uid = strtol(tkn + 4, NULL, 16);
438                         if (errno != 0) {
439                                 syslog(LOG_ERR, "Invalid uid format: %s",
440                                        strerror(errno));
441                                 return 1;
442                         } else {
443                                 retval |= DKD_HAVE_UID;
444                         }
445                 } else if (strncmp(tkn, "ver=", 4) == 0) {      /* if version */
446                         errno = 0;
447                         arg->ver = strtol(tkn + 4, NULL, 16);
448                         if (errno != 0) {
449                                 syslog(LOG_ERR, "Invalid version format: %s",
450                                        strerror(errno));
451                                 return 1;
452                         } else {
453                                 retval |= DKD_HAVE_VERSION;
454                         }
455                 }
456                 if (pos == NULL)
457                         break;
458                 tkn = pos + 1;
459         } while (tkn);
460         return retval;
461 }
462
463 static int
464 cifs_resolver(const key_serial_t key, const char *key_descr)
465 {
466         int c;
467         struct addrinfo *addr;
468         char ip[INET6_ADDRSTRLEN];
469         void *p;
470         const char *keyend = key_descr;
471         /* skip next 4 ';' delimiters to get to description */
472         for (c = 1; c <= 4; c++) {
473                 keyend = index(keyend+1, ';');
474                 if (!keyend) {
475                         syslog(LOG_ERR, "invalid key description: %s",
476                                         key_descr);
477                         return 1;
478                 }
479         }
480         keyend++;
481
482         /* resolve name to ip */
483         c = getaddrinfo(keyend, NULL, NULL, &addr);
484         if (c) {
485                 syslog(LOG_ERR, "unable to resolve hostname: %s [%s]",
486                                 keyend, gai_strerror(c));
487                 return 1;
488         }
489
490         /* conver ip to string form */
491         if (addr->ai_family == AF_INET)
492                 p = &(((struct sockaddr_in *)addr->ai_addr)->sin_addr);
493         else
494                 p = &(((struct sockaddr_in6 *)addr->ai_addr)->sin6_addr);
495
496         if (!inet_ntop(addr->ai_family, p, ip, sizeof(ip))) {
497                 syslog(LOG_ERR, "%s: inet_ntop: %s", __func__, strerror(errno));
498                 freeaddrinfo(addr);
499                 return 1;
500         }
501
502         /* setup key */
503         c = keyctl_instantiate(key, ip, strlen(ip)+1, 0);
504         if (c == -1) {
505                 syslog(LOG_ERR, "%s: keyctl_instantiate: %s", __func__,
506                                 strerror(errno));
507                 freeaddrinfo(addr);
508                 return 1;
509         }
510
511         freeaddrinfo(addr);
512         return 0;
513 }
514
515 /*
516  * Older kernels sent IPv6 addresses without colons. Well, at least
517  * they're fixed-length strings. Convert these addresses to have colon
518  * delimiters to make getaddrinfo happy.
519  */
520 static void
521 convert_inet6_addr(const char *from, char *to)
522 {
523         int i = 1;
524
525         while (*from) {
526                 *to++ = *from++;
527                 if (!(i++ % 4) && *from)
528                         *to++ = ':';
529         }
530         *to = 0;
531 }
532
533 static int
534 ip_to_fqdn(const char *addrstr, char *host, size_t hostlen)
535 {
536         int rc;
537         struct addrinfo hints = { .ai_flags = AI_NUMERICHOST };
538         struct addrinfo *res;
539         const char *ipaddr = addrstr;
540         char converted[INET6_ADDRSTRLEN + 1];
541
542         if ((strlen(ipaddr) > INET_ADDRSTRLEN) && !strchr(ipaddr, ':')) {
543                 convert_inet6_addr(ipaddr, converted);
544                 ipaddr = converted;
545         }
546
547         rc = getaddrinfo(ipaddr, NULL, &hints, &res);
548         if (rc) {
549                 syslog(LOG_DEBUG, "%s: failed to resolve %s to "
550                         "ipaddr: %s", __func__, ipaddr,
551                 rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
552                 return rc;
553         }
554
555         rc = getnameinfo(res->ai_addr, res->ai_addrlen, host, hostlen,
556                          NULL, 0, NI_NAMEREQD);
557         freeaddrinfo(res);
558         if (rc) {
559                 syslog(LOG_DEBUG, "%s: failed to resolve %s to fqdn: %s",
560                         __func__, ipaddr,
561                         rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
562                 return rc;
563         }
564
565         syslog(LOG_DEBUG, "%s: resolved %s to %s", __func__, ipaddr, host);
566         return 0;
567 }
568
569 static void
570 usage(void)
571 {
572         syslog(LOG_INFO, "Usage: %s [-t] [-v] key_serial", prog);
573         fprintf(stderr, "Usage: %s [-t] [-v] key_serial\n", prog);
574 }
575
576 const struct option long_options[] = {
577         { "trust-dns",  0, NULL, 't' },
578         { "version",    0, NULL, 'v' },
579         { NULL,         0, NULL, 0 }
580 };
581
582 int main(const int argc, char *const argv[])
583 {
584         struct cifs_spnego_msg *keydata = NULL;
585         DATA_BLOB secblob = data_blob_null;
586         DATA_BLOB sess_key = data_blob_null;
587         key_serial_t key = 0;
588         size_t datalen;
589         unsigned int have;
590         long rc = 1;
591         int c, try_dns = 0;
592         char *buf, *princ = NULL, *ccname = NULL;
593         char hostbuf[NI_MAXHOST], *host;
594         struct decoded_args arg = { };
595         const char *oid;
596
597         hostbuf[0] = '\0';
598
599         openlog(prog, 0, LOG_DAEMON);
600
601         while ((c = getopt_long(argc, argv, "ctv", long_options, NULL)) != -1) {
602                 switch (c) {
603                 case 'c':
604                         /* legacy option -- skip it */
605                         break;
606                 case 't':
607                         try_dns++;
608                         break;
609                 case 'v':
610                         printf("version: %s\n", CIFSSPNEGO_VERSION);
611                         goto out;
612                 default:
613                         syslog(LOG_ERR, "unknown option: %c", c);
614                         goto out;
615                 }
616         }
617
618         /* is there a key? */
619         if (argc <= optind) {
620                 usage();
621                 goto out;
622         }
623
624         /* get key and keyring values */
625         errno = 0;
626         key = strtol(argv[optind], NULL, 10);
627         if (errno != 0) {
628                 key = 0;
629                 syslog(LOG_ERR, "Invalid key format: %s", strerror(errno));
630                 goto out;
631         }
632
633         rc = keyctl_describe_alloc(key, &buf);
634         if (rc == -1) {
635                 syslog(LOG_ERR, "keyctl_describe_alloc failed: %s",
636                        strerror(errno));
637                 rc = 1;
638                 goto out;
639         }
640
641         syslog(LOG_DEBUG, "key description: %s", buf);
642
643         if ((strncmp(buf, "cifs.resolver", sizeof("cifs.resolver")-1) == 0) ||
644             (strncmp(buf, "dns_resolver", sizeof("dns_resolver")-1) == 0)) {
645                 rc = cifs_resolver(key, buf);
646                 goto out;
647         }
648
649         have = decode_key_description(buf, &arg);
650         SAFE_FREE(buf);
651         if ((have & DKD_MUSTHAVE_SET) != DKD_MUSTHAVE_SET) {
652                 syslog(LOG_ERR, "unable to get necessary params from key "
653                                 "description (0x%x)", have);
654                 rc = 1;
655                 goto out;
656         }
657
658         if (arg.ver > CIFS_SPNEGO_UPCALL_VERSION) {
659                 syslog(LOG_ERR, "incompatible kernel upcall version: 0x%x",
660                                 arg.ver);
661                 rc = 1;
662                 goto out;
663         }
664
665         if (have & DKD_HAVE_UID) {
666                 rc = setuid(arg.uid);
667                 if (rc == -1) {
668                         syslog(LOG_ERR, "setuid: %s", strerror(errno));
669                         goto out;
670                 }
671
672                 ccname = find_krb5_cc(CIFS_DEFAULT_KRB5_DIR, arg.uid);
673         }
674
675         host = arg.hostname;
676
677         // do mech specific authorization
678         switch (arg.sec) {
679         case MS_KRB5:
680         case KRB5:
681 retry_new_hostname:
682                 /* for "cifs/" service name + terminating 0 */
683                 datalen = strlen(host) + 5 + 1;
684                 princ = SMB_XMALLOC_ARRAY(char, datalen);
685                 if (!princ) {
686                         rc = -ENOMEM;
687                         break;
688                 }
689
690                 if (arg.sec == MS_KRB5)
691                         oid = OID_KERBEROS5_OLD;
692                 else
693                         oid = OID_KERBEROS5;
694
695                 /*
696                  * try getting a cifs/ principal first and then fall back to
697                  * getting a host/ principal if that doesn't work.
698                  */
699                 strlcpy(princ, "cifs/", datalen);
700                 strlcpy(princ + 5, host, datalen - 5);
701                 rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
702                 if (!rc)
703                         break;
704
705                 memcpy(princ, "host/", 5);
706                 rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
707                 if (!rc)
708                         break;
709
710                 if (!try_dns || !(have & DKD_HAVE_IP))
711                         break;
712
713                 rc = ip_to_fqdn(arg.ip, hostbuf, sizeof(hostbuf));
714                 if (rc)
715                         break;
716
717                 SAFE_FREE(princ);
718                 try_dns = 0;
719                 host = hostbuf;
720                 goto retry_new_hostname;
721         default:
722                 syslog(LOG_ERR, "sectype: %d is not implemented", arg.sec);
723                 rc = 1;
724                 break;
725         }
726
727         SAFE_FREE(princ);
728
729         if (rc)
730                 goto out;
731
732         /* pack SecurityBLob and SessionKey into downcall packet */
733         datalen =
734             sizeof(struct cifs_spnego_msg) + secblob.length + sess_key.length;
735         keydata = (struct cifs_spnego_msg*)SMB_XMALLOC_ARRAY(char, datalen);
736         if (!keydata) {
737                 rc = 1;
738                 goto out;
739         }
740         keydata->version = arg.ver;
741         keydata->flags = 0;
742         keydata->sesskey_len = sess_key.length;
743         keydata->secblob_len = secblob.length;
744         memcpy(&(keydata->data), sess_key.data, sess_key.length);
745         memcpy(&(keydata->data) + keydata->sesskey_len,
746                secblob.data, secblob.length);
747
748         /* setup key */
749         rc = keyctl_instantiate(key, keydata, datalen, 0);
750         if (rc == -1) {
751                 syslog(LOG_ERR, "keyctl_instantiate: %s", strerror(errno));
752                 goto out;
753         }
754
755         /* BB: maybe we need use timeout for key: for example no more then
756          * ticket lifietime? */
757         /* keyctl_set_timeout( key, 60); */
758 out:
759         /*
760          * on error, negatively instantiate the key ourselves so that we can
761          * make sure the kernel doesn't hang it off of a searchable keyring
762          * and interfere with the next attempt to instantiate the key.
763          */
764         if (rc != 0  && key == 0)
765                 keyctl_negate(key, 1, KEY_REQKEY_DEFL_DEFAULT);
766         data_blob_free(&secblob);
767         data_blob_free(&sess_key);
768         SAFE_FREE(ccname);
769         SAFE_FREE(arg.hostname);
770         SAFE_FREE(arg.ip);
771         SAFE_FREE(keydata);
772         return rc;
773 }