52c03280dbe0704c9aa617c24d0dbdba279fbb06
[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@samba.org) 2010
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 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif /* HAVE_CONFIG_H */
31
32 #include <string.h>
33 #include <getopt.h>
34 #ifdef HAVE_KRB5_KRB5_H
35 #include <krb5/krb5.h>
36 #elif defined(HAVE_KRB5_H)
37 #include <krb5.h>
38 #endif
39
40 #include <gssapi/gssapi_krb5.h>
41 #include <sys/utsname.h>
42
43 #include <syslog.h>
44 #include <dirent.h>
45 #include <sys/types.h>
46 #include <sys/stat.h>
47 #include <fcntl.h>
48 #include <unistd.h>
49 #include <keyutils.h>
50 #include <time.h>
51 #include <netdb.h>
52 #include <arpa/inet.h>
53 #include <ctype.h>
54 #include <pwd.h>
55 #include <grp.h>
56 #include <stdbool.h>
57 #include <errno.h>
58 #include <sched.h>
59 #include <sys/mman.h>
60 #include <sys/types.h>
61 #include <sys/wait.h>
62
63 #include "data_blob.h"
64 #include "spnego.h"
65 #include "cifs_spnego.h"
66
67 #ifdef HAVE_LIBCAP_NG
68 #include <cap-ng.h>
69 #endif
70
71 #ifndef discard_const
72 #define discard_const(ptr) ((void *)((intptr_t)(ptr)))
73 #endif
74
75 static krb5_context     context;
76 static const char       *prog = "cifs.upcall";
77
78 #define DNS_RESOLVER_DEFAULT_TIMEOUT 600 /* 10 minutes */
79
80 typedef enum _sectype {
81         NONE = 0,
82         KRB5,
83         MS_KRB5
84 } sectype_t;
85
86 /* These macros unify the keyblock handling of Heimdal and MIT somewhat */
87 #ifdef HAVE_KRB5_KEYBLOCK_KEYVALUE /* Heimdal */
88 #define KRB5_KEY_TYPE(k)        ((k)->keytype)
89 #define KRB5_KEY_LENGTH(k)      ((k)->keyvalue.length)
90 #define KRB5_KEY_DATA(k)        ((k)->keyvalue.data)
91 #define KRB5_KEY_DATA_CAST      void
92 #else /* MIT */
93 #define KRB5_KEY_TYPE(k)        ((k)->enctype)
94 #define KRB5_KEY_LENGTH(k)      ((k)->length)
95 #define KRB5_KEY_DATA(k)        ((k)->contents)
96 #define KRB5_KEY_DATA_CAST      krb5_octet
97 #endif
98
99 #ifdef HAVE_LIBCAP_NG
100 static int
101 trim_capabilities(bool need_environ)
102 {
103         capng_select_t set = CAPNG_SELECT_CAPS;
104
105         capng_clear(CAPNG_SELECT_BOTH);
106
107         /* SETUID and SETGID to change uid, gid, and grouplist */
108         if (capng_updatev(CAPNG_ADD, CAPNG_PERMITTED|CAPNG_EFFECTIVE,
109                         CAP_SETUID, CAP_SETGID, -1)) {
110                 syslog(LOG_ERR, "%s: Unable to update capability set: %m\n", __func__);
111                 return 1;
112         }
113
114          /* Need PTRACE and READ_SEARCH for /proc/pid/environ scraping */
115         if (need_environ &&
116             capng_updatev(CAPNG_ADD, CAPNG_PERMITTED|CAPNG_EFFECTIVE,
117                         CAP_SYS_PTRACE, CAP_DAC_READ_SEARCH, -1)) {
118                 syslog(LOG_ERR, "%s: Unable to update capability set: %m\n", __func__);
119                 return 1;
120         }
121
122         if (capng_have_capability(CAPNG_EFFECTIVE, CAP_SETPCAP)) {
123                 set = CAPNG_SELECT_BOTH;
124         }
125         if (capng_apply(set)) {
126                 syslog(LOG_ERR, "%s: Unable to apply capability set: %m\n", __func__);
127                 return 1;
128         }
129         return 0;
130 }
131
132 static int
133 drop_all_capabilities(void)
134 {
135         capng_select_t set = CAPNG_SELECT_CAPS;
136
137         capng_clear(CAPNG_SELECT_BOTH);
138         if (capng_have_capability(CAPNG_EFFECTIVE, CAP_SETPCAP)) {
139                 set = CAPNG_SELECT_BOTH;
140         }
141         if (capng_apply(set)) {
142                 syslog(LOG_ERR, "%s: Unable to apply capability set: %m\n", __func__);
143                 return 1;
144         }
145         return 0;
146 }
147 #else /* HAVE_LIBCAP_NG */
148 static int
149 trim_capabilities(bool unused)
150 {
151         (void)unused;
152         return 0;
153 }
154
155 static int
156 drop_all_capabilities(void)
157 {
158         return 0;
159 }
160 #endif /* HAVE_LIBCAP_NG */
161
162 /*
163  * smb_krb5_principal_get_realm
164  *
165  * @brief Get realm of a principal
166  *
167  * @param[in] context           The krb5_context
168  * @param[in] principal         The principal
169  * @return pointer to the realm
170  *
171  */
172 static char *cifs_krb5_principal_get_realm(krb5_principal principal)
173 {
174 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM    /* Heimdal */
175         return krb5_principal_get_realm(context, principal);
176 #elif defined(krb5_princ_realm) /* MIT */
177         krb5_data *realm;
178         realm = krb5_princ_realm(context, principal);
179         return (char *)realm->data;
180 #else
181         return NULL;
182 #endif
183 }
184
185 #if !defined(HAVE_KRB5_FREE_UNPARSED_NAME)
186 static void krb5_free_unparsed_name(krb5_context context, char *val)
187 {
188         free(val);
189 }
190 #endif
191
192 #if !defined(HAVE_KRB5_FREE_STRING)     /* Heimdal */
193 static void krb5_free_string(krb5_context context, char *val)
194 {
195         (void)context;
196         krb5_xfree(val);
197 }
198 #endif
199
200 #if !defined(HAVE_KRB5_AUTH_CON_GETSENDSUBKEY)  /* Heimdal */
201 static krb5_error_code
202 krb5_auth_con_getsendsubkey(krb5_context context,
203                             krb5_auth_context auth_context,
204                             krb5_keyblock **keyblock)
205 {
206         return krb5_auth_con_getlocalsubkey(context, auth_context, keyblock);
207 }
208 #endif
209
210 /* does the ccache have a valid TGT? */
211 static time_t get_tgt_time(krb5_ccache ccache)
212 {
213         krb5_cc_cursor cur;
214         krb5_creds creds;
215         krb5_principal principal;
216         time_t credtime = 0;
217         char *realm = NULL;
218
219         if (krb5_cc_set_flags(context, ccache, 0)) {
220                 syslog(LOG_DEBUG, "%s: unable to set flags", __func__);
221                 goto err_cache;
222         }
223
224         if (krb5_cc_get_principal(context, ccache, &principal)) {
225                 syslog(LOG_DEBUG, "%s: unable to get principal", __func__);
226                 goto err_cache;
227         }
228
229         if (krb5_cc_start_seq_get(context, ccache, &cur)) {
230                 syslog(LOG_DEBUG, "%s: unable to seq start", __func__);
231                 goto err_ccstart;
232         }
233
234         if ((realm = cifs_krb5_principal_get_realm(principal)) == NULL) {
235                 syslog(LOG_DEBUG, "%s: unable to get realm", __func__);
236                 goto err_ccstart;
237         }
238
239         while (!credtime && !krb5_cc_next_cred(context, ccache, &cur, &creds)) {
240                 char *name;
241                 if (krb5_unparse_name(context, creds.server, &name)) {
242                         syslog(LOG_DEBUG, "%s: unable to unparse name",
243                                __func__);
244                         goto err_endseq;
245                 }
246                 if (krb5_realm_compare(context, creds.server, principal) &&
247                     !strncasecmp(name, KRB5_TGS_NAME, KRB5_TGS_NAME_SIZE) &&
248                     !strncasecmp(name + KRB5_TGS_NAME_SIZE + 1, realm,
249                                  strlen(realm))
250                     && creds.times.endtime > time(NULL))
251                         credtime = creds.times.endtime;
252                 krb5_free_cred_contents(context, &creds);
253                 krb5_free_unparsed_name(context, name);
254         }
255 err_endseq:
256         krb5_cc_end_seq_get(context, ccache, &cur);
257 err_ccstart:
258         krb5_free_principal(context, principal);
259 err_cache:
260         return credtime;
261 }
262
263 static struct namespace_file {
264         int nstype;
265         const char *name;
266         int fd;
267 } namespace_files[] = {
268
269 #ifdef CLONE_NEWCGROUP
270         { CLONE_NEWCGROUP, "cgroup", -1 },
271 #endif
272
273 #ifdef CLONE_NEWIPC
274         { CLONE_NEWIPC, "ipc", -1 },
275 #endif
276
277 #ifdef CLONE_NEWUTS
278         { CLONE_NEWUTS, "uts", -1 },
279 #endif
280
281 #ifdef CLONE_NEWNET
282         { CLONE_NEWNET, "net", -1 },
283 #endif
284
285 #ifdef CLONE_NEWPID
286         { CLONE_NEWPID, "pid", -1 },
287 #endif
288
289 #ifdef CLONE_NEWTIME
290         { CLONE_NEWTIME, "time", -1 },
291 #endif
292
293 #ifdef CLONE_NEWNS
294         { CLONE_NEWNS, "mnt", -1 },
295 #endif
296
297 #ifdef CLONE_NEWUSER
298         { CLONE_NEWUSER, "user", -1 },
299 #endif
300 };
301
302 #define NS_PATH_FMT    "/proc/%d/ns/%s"
303 #define NS_PATH_MAXLEN (6 + 10 + 4 + 6 + 1)
304
305 /**
306  * in_same_user_ns - return true if two processes are in the same user
307  *                   namespace.
308  * @pid_a: the pid of the first process
309  * @pid_b: the pid of the second process
310  *
311  * Works by comparing the inode numbers for /proc/<pid>/user.
312  */
313 static int
314 in_same_user_ns(pid_t pid_a, pid_t pid_b)
315 {
316         char path[NS_PATH_MAXLEN];
317         ino_t a_ino, b_ino;
318         struct stat st;
319
320         snprintf(path, sizeof(path), NS_PATH_FMT, pid_a, "user");
321         if (stat(path, &st) != 0)
322                 return 0;
323         a_ino = st.st_ino;
324
325         snprintf(path, sizeof(path), NS_PATH_FMT, pid_b, "user");
326         if (stat(path, &st) != 0)
327                 return 0;
328         b_ino = st.st_ino;
329
330         return a_ino == b_ino;
331 }
332
333 /**
334  * switch_to_process_ns - change the namespace to the one for the specified
335  *                        process.
336  * @pid: initiating pid value from the upcall string
337  *
338  * Uses setns() to switch process namespace.
339  * This ensures that we have the same access and configuration as the
340  * process that triggered the lookup.
341  */
342 static int
343 switch_to_process_ns(pid_t pid)
344 {
345         int count = sizeof(namespace_files) / sizeof(struct namespace_file);
346         int n, err = 0;
347         int rc = 0;
348
349         /* First, open all the namespace fds.  We do this first because
350            the namespace changes might prohibit us from opening them. */
351         for (n = 0; n < count; ++n) {
352                 char nspath[NS_PATH_MAXLEN];
353                 int ret, fd;
354
355 #ifdef CLONE_NEWUSER
356                 if (namespace_files[n].nstype == CLONE_NEWUSER
357                     && in_same_user_ns(getpid(), pid)) {
358                         /* Switching to the same user namespace is forbidden,
359                            because switching to a user namespace grants all
360                            capabilities in that namespace regardless of uid. */
361                         namespace_files[n].fd = -1;
362                         continue;
363                 }
364 #endif
365
366                 ret = snprintf(nspath, NS_PATH_MAXLEN, NS_PATH_FMT,
367                                pid, namespace_files[n].name);
368                 if (ret >= NS_PATH_MAXLEN) {
369                         syslog(LOG_DEBUG, "%s: unterminated path!\n", __func__);
370                         err = ENAMETOOLONG;
371                         rc = -1;
372                         goto out;
373                 }
374
375                 fd = open(nspath, O_RDONLY);
376                 if (fd < 0 && errno != ENOENT) {
377                         /*
378                          * don't stop on non-existing ns
379                          * but stop for other errors
380                          */
381                         err = errno;
382                         rc = -1;
383                         goto out;
384                 }
385
386                 namespace_files[n].fd = fd;
387         }
388
389         /* Next, call setns for each of them */
390         for (n = 0; n < count; ++n) {
391                 /* skip non-existing ns */
392                 if (namespace_files[n].fd < 0)
393                         continue;
394
395                 rc = setns(namespace_files[n].fd, namespace_files[n].nstype);
396
397                 if (rc < 0) {
398                         syslog(LOG_DEBUG, "%s: setns() failed for %s\n",
399                                __func__, namespace_files[n].name);
400                         err = errno;
401                         goto out;
402                 }
403         }
404
405 out:
406         /* Finally, close all the fds */
407         for (n = 0; n < count; ++n) {
408                 if (namespace_files[n].fd != -1) {
409                         close(namespace_files[n].fd);
410                         namespace_files[n].fd = -1;
411                 }
412         }
413
414         if (rc != 0) {
415                 errno = err;
416         }
417
418         return rc;
419 }
420
421 #define ENV_PATH_FMT                    "/proc/%d/environ"
422 #define ENV_PATH_MAXLEN                 (6 + 10 + 8 + 1)
423
424 #define ENV_NAME                        "KRB5CCNAME"
425 #define ENV_PREFIX                      "KRB5CCNAME="
426 #define ENV_PREFIX_LEN                  11
427
428 #define ENV_BUF_START                   (4096)
429 #define ENV_BUF_MAX                     (131072)
430
431 /**
432  * get_cachename_from_process_env - scrape value of $KRB5CCNAME out of the
433  *                                  initiating process' environment.
434  * @pid: initiating pid value from the upcall string
435  *
436  * Open the /proc/<pid>/environ file for the given pid, and scrape it for
437  * KRB5CCNAME entries.
438  *
439  * We start with a page-size buffer, and then progressively double it until
440  * we can slurp in the whole thing.
441  *
442  * Note that this is not entirely reliable. If the process is sitting in a
443  * container or something, then this is almost certainly not going to point
444  * where you expect.
445  *
446  * Probably it just won't work, but could a user use this to trick cifs.upcall
447  * into reading a file outside the container, by setting KRB5CCNAME in a
448  * crafty way?
449  */
450 static char *
451 get_cachename_from_process_env(pid_t pid)
452 {
453         int fd, ret;
454         ssize_t buflen;
455         ssize_t bufsize = ENV_BUF_START;
456         char pathname[ENV_PATH_MAXLEN];
457         char *cachename = NULL;
458         char *buf = NULL, *pos;
459
460         if (!pid) {
461                 syslog(LOG_DEBUG, "%s: pid == 0\n", __func__);
462                 return NULL;
463         }
464
465         pathname[ENV_PATH_MAXLEN - 1] = '\0';
466         ret = snprintf(pathname, ENV_PATH_MAXLEN, ENV_PATH_FMT, pid);
467         if (ret >= ENV_PATH_MAXLEN) {
468                 syslog(LOG_DEBUG, "%s: unterminated path!\n", __func__);
469                 return NULL;
470         }
471
472         syslog(LOG_DEBUG, "%s: pathname=%s\n", __func__, pathname);
473         fd = open(pathname, O_RDONLY);
474         if (fd < 0) {
475                 syslog(LOG_DEBUG, "%s: open failed: %d\n", __func__, errno);
476                 return NULL;
477         }
478 retry:
479         if (bufsize > ENV_BUF_MAX) {
480                 syslog(LOG_DEBUG, "%s: buffer too big: %zd\n",
481                                                         __func__, bufsize);
482                 goto out_close;
483         }
484
485         buf = malloc(bufsize);
486         if (!buf) {
487                 syslog(LOG_DEBUG, "%s: malloc failure\n", __func__);
488                 goto out_close;
489         }
490
491         buflen = read(fd, buf, bufsize);
492         if (buflen < 0) {
493                 syslog(LOG_DEBUG, "%s: read failed: %d\n", __func__, errno);
494                 goto out_close;
495         }
496
497         if (buflen >= bufsize) {
498                 /* We read to the end of the buffer. Double and try again */
499                 syslog(LOG_DEBUG, "%s: read to end of buffer (%zu bytes)\n",
500                                         __func__, bufsize);
501                 free(buf);
502                 bufsize *= 2;
503                 if (lseek(fd, 0, SEEK_SET) < 0)
504                         goto out_close;
505                 goto retry;
506         }
507
508         pos = buf;
509         while (buflen > 0) {
510                 size_t len = strnlen(pos, buflen);
511
512                 if (len > ENV_PREFIX_LEN &&
513                     !memcmp(pos, ENV_PREFIX, ENV_PREFIX_LEN)) {
514                         cachename = strndup(pos + ENV_PREFIX_LEN,
515                                                         len - ENV_PREFIX_LEN);
516                         syslog(LOG_DEBUG, "%s: cachename = %s\n",
517                                                         __func__, cachename);
518                         break;
519                 }
520                 buflen -= (len + 1);
521                 pos += (len + 1);
522         }
523 out_close:
524         free(buf);
525         close(fd);
526         return cachename;
527 }
528
529 static krb5_ccache
530 get_existing_cc(const char *env_cachename)
531 {
532         krb5_error_code ret;
533         krb5_ccache cc;
534         char *cachename;
535
536         if (env_cachename) {
537                 if (setenv(ENV_NAME, env_cachename, 1))
538                         syslog(LOG_DEBUG, "%s: failed to setenv %d\n", __func__, errno);
539         }
540
541         ret = krb5_cc_default(context, &cc);
542         if (ret) {
543                 syslog(LOG_DEBUG, "%s: krb5_cc_default returned %d", __func__, ret);
544                 return NULL;
545         }
546
547         ret = krb5_cc_get_full_name(context, cc, &cachename);
548         if (ret) {
549                 syslog(LOG_DEBUG, "%s: krb5_cc_get_full_name failed: %d\n", __func__, ret);
550         } else {
551                 syslog(LOG_DEBUG, "%s: default ccache is %s\n", __func__, cachename);
552                 krb5_free_string(context, cachename);
553         }
554
555         if (!get_tgt_time(cc)) {
556                 krb5_cc_close(context, cc);
557                 cc = NULL;
558         }
559         return cc;
560 }
561
562 static krb5_ccache
563 init_cc_from_keytab(const char *keytab_name, const char *user)
564 {
565         krb5_error_code ret;
566         krb5_creds my_creds;
567         krb5_keytab keytab = NULL;
568         krb5_principal me = NULL;
569         krb5_ccache cc = NULL;
570
571         memset((char *) &my_creds, 0, sizeof(my_creds));
572
573         /*
574          * Unset the environment variable, if any. If we're creating our own
575          * credcache here, stick it in the default location.
576          */
577         unsetenv(ENV_NAME);
578
579         if (keytab_name)
580                 ret = krb5_kt_resolve(context, keytab_name, &keytab);
581         else
582                 ret = krb5_kt_default(context, &keytab);
583
584         if (ret) {
585                 syslog(LOG_DEBUG, "%s: %d",
586                         keytab_name ? "krb5_kt_resolve" : "krb5_kt_default",
587                         (int)ret);
588                 goto icfk_cleanup;
589         }
590
591         ret = krb5_parse_name(context, user, &me);
592         if (ret) {
593                 syslog(LOG_DEBUG, "krb5_parse_name: %d", (int)ret);
594                 goto icfk_cleanup;
595         }
596
597         ret = krb5_get_init_creds_keytab(context, &my_creds, me,
598                         keytab, 0, NULL, NULL);
599         if (ret) {
600                 syslog(LOG_DEBUG, "krb5_get_init_creds_keytab: %d", (int)ret);
601                 goto icfk_cleanup;
602         }
603
604         ret = krb5_cc_resolve(context, "MEMORY:", &cc);
605         if (ret) {
606                 syslog(LOG_DEBUG, "krb5_cc_resolve: %d", (int)ret);
607                 goto icfk_cleanup;
608         }
609
610         ret = krb5_cc_initialize(context, cc, me);
611         if (ret) {
612                 syslog(LOG_DEBUG, "krb5_cc_initialize: %d", (int)ret);
613                 goto icfk_cleanup;
614         }
615
616         ret = krb5_cc_store_cred(context, cc, &my_creds);
617         if (ret) {
618                 syslog(LOG_DEBUG, "krb5_cc_store_cred: %d", (int)ret);
619                 goto icfk_cleanup;
620         }
621 out:
622         my_creds.client = (krb5_principal)0;
623         krb5_free_cred_contents(context, &my_creds);
624
625         if (me)
626                 krb5_free_principal(context, me);
627         if (keytab)
628                 krb5_kt_close(context, keytab);
629         return cc;
630 icfk_cleanup:
631         if (cc) {
632                 krb5_cc_close(context, cc);
633                 cc = NULL;
634         }
635         goto out;
636 }
637
638 #define CIFS_SERVICE_NAME "cifs"
639
640 static int
641 cifs_krb5_get_req(const char *host, krb5_ccache ccache,
642                   DATA_BLOB * mechtoken, DATA_BLOB * sess_key)
643 {
644         krb5_error_code ret;
645         krb5_keyblock *tokb;
646         krb5_creds in_creds, *out_creds;
647         krb5_data apreq_pkt, in_data;
648         krb5_auth_context auth_context = NULL;
649 #if defined(HAVE_KRB5_AUTH_CON_SETADDRS) && defined(HAVE_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE)
650         static char gss_cksum[24] = { 0x10, 0x00, /* ... */};
651 #endif
652         memset(&in_creds, 0, sizeof(in_creds));
653
654         ret = krb5_cc_get_principal(context, ccache, &in_creds.client);
655         if (ret) {
656                 syslog(LOG_DEBUG, "%s: unable to get client principal name",
657                        __func__);
658                 return ret;
659         }
660
661         ret = krb5_sname_to_principal(context, host, CIFS_SERVICE_NAME,
662                                         KRB5_NT_UNKNOWN, &in_creds.server);
663         if (ret) {
664                 syslog(LOG_DEBUG, "%s: unable to convert sname to princ (%s).",
665                        __func__, host);
666                 goto out_free_principal;
667         }
668
669         ret = krb5_get_credentials(context, 0, ccache, &in_creds, &out_creds);
670         krb5_free_principal(context, in_creds.server);
671         if (ret) {
672                 syslog(LOG_DEBUG, "%s: unable to get credentials for %s",
673                        __func__, host);
674                 goto out_free_principal;
675         }
676
677         in_data.length = 0;
678         in_data.data = NULL;
679
680         ret = krb5_auth_con_init(context, &auth_context);
681         if (ret) {
682                 syslog(LOG_DEBUG, "%s: unable to create auth_context: %d",
683                        __func__, ret);
684                 goto out_free_creds;
685         }
686
687 #if defined(HAVE_KRB5_AUTH_CON_SETADDRS) && defined(HAVE_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE)
688         /* Ensure we will get an addressless ticket. */
689         ret = krb5_auth_con_setaddrs(context, auth_context, NULL, NULL);
690         if (ret) {
691                 syslog(LOG_DEBUG, "%s: unable to set NULL addrs: %d",
692                        __func__, ret);
693                 goto out_free_auth;
694         }
695
696         /*
697          * Create a GSSAPI checksum (0x8003), see RFC 4121.
698          *
699          * The current layout is
700          *
701          * 0x10, 0x00, 0x00, 0x00 - length = 16
702          * 0x00, 0x00, 0x00, 0x00 - channel binding info - 16 zero bytes
703          * 0x00, 0x00, 0x00, 0x00
704          * 0x00, 0x00, 0x00, 0x00
705          * 0x00, 0x00, 0x00, 0x00
706          * 0x00, 0x00, 0x00, 0x00 - flags
707          *
708          * GSS_C_NO_CHANNEL_BINDINGS means 16 zero bytes,
709          * this is needed to work against some closed source
710          * SMB servers.
711          *
712          * See https://bugzilla.samba.org/show_bug.cgi?id=7890
713          */
714         in_data.data = gss_cksum;
715         in_data.length = 24;
716
717         /* MIT krb5 < 1.7 is missing the prototype, but still has the symbol */
718 #if !HAVE_DECL_KRB5_AUTH_CON_SET_REQ_CKSUMTYPE
719         krb5_error_code krb5_auth_con_set_req_cksumtype(
720                 krb5_auth_context auth_context,
721                 krb5_cksumtype    cksumtype);
722 #endif
723         ret = krb5_auth_con_set_req_cksumtype(context, auth_context, 0x8003);
724         if (ret) {
725                 syslog(LOG_DEBUG, "%s: unable to set 0x8003 checksum",
726                        __func__);
727                 goto out_free_auth;
728         }
729 #endif
730
731         apreq_pkt.length = 0;
732         apreq_pkt.data = NULL;
733         ret = krb5_mk_req_extended(context, &auth_context, AP_OPTS_USE_SUBKEY,
734                                    &in_data, out_creds, &apreq_pkt);
735         if (ret) {
736                 syslog(LOG_DEBUG, "%s: unable to make AP-REQ for %s",
737                        __func__, host);
738                 goto out_free_auth;
739         }
740
741         ret = krb5_auth_con_getsendsubkey(context, auth_context, &tokb);
742         if (ret) {
743                 syslog(LOG_DEBUG, "%s: unable to get session key for %s",
744                        __func__, host);
745                 goto out_free_auth;
746         }
747
748         *mechtoken = data_blob(apreq_pkt.data, apreq_pkt.length);
749         *sess_key = data_blob(KRB5_KEY_DATA(tokb), KRB5_KEY_LENGTH(tokb));
750
751         krb5_free_keyblock(context, tokb);
752 out_free_auth:
753         krb5_auth_con_free(context, auth_context);
754 out_free_creds:
755         krb5_free_creds(context, out_creds);
756 out_free_principal:
757         krb5_free_principal(context, in_creds.client);
758         return ret;
759 }
760
761 static void cifs_gss_display_status_1(char *m, OM_uint32 code, int type) {
762         OM_uint32 min_stat;
763         gss_buffer_desc msg;
764         OM_uint32 msg_ctx;
765
766         msg_ctx = 0;
767         while (1) {
768                 (void) gss_display_status(&min_stat, code, type,
769                                 GSS_C_NULL_OID, &msg_ctx, &msg);
770                 syslog(LOG_DEBUG, "GSS-API error %s: %s\n", m, (char *) msg.value);
771                 (void) gss_release_buffer(&min_stat, &msg);
772
773                 if (!msg_ctx)
774                         break;
775         }
776 }
777
778 void cifs_gss_display_status(char *msg, OM_uint32 maj_stat, OM_uint32 min_stat) {
779         cifs_gss_display_status_1(msg, maj_stat, GSS_C_GSS_CODE);
780         cifs_gss_display_status_1(msg, min_stat, GSS_C_MECH_CODE);
781 }
782
783 static int
784 cifs_gss_get_req(const char *host, DATA_BLOB *mechtoken, DATA_BLOB *sess_key)
785 {
786         OM_uint32 maj_stat, min_stat;
787         gss_name_t target_name;
788         gss_ctx_id_t ctx = GSS_C_NO_CONTEXT;
789         gss_buffer_desc output_token;
790         gss_krb5_lucid_context_v1_t *lucid_ctx = NULL;
791         gss_krb5_lucid_key_t *key = NULL;
792
793         size_t service_name_len = sizeof(CIFS_SERVICE_NAME) + 1 /* @ */ +
794                 strlen(host) + 1;
795         char *service_name = malloc(service_name_len);
796         if (!service_name) {
797                 syslog(LOG_DEBUG, "out of memory allocating service name");
798                 maj_stat = GSS_S_FAILURE;
799                 goto out;
800         }
801
802         snprintf(service_name, service_name_len, "%s@%s", CIFS_SERVICE_NAME,
803                  host);
804         gss_buffer_desc target_name_buf;
805         target_name_buf.value = service_name;
806         target_name_buf.length = service_name_len;
807
808         maj_stat = gss_import_name(&min_stat, &target_name_buf,
809                         GSS_C_NT_HOSTBASED_SERVICE, &target_name);
810         free(service_name);
811         if (GSS_ERROR(maj_stat)) {
812                 cifs_gss_display_status("gss_import_name", maj_stat, min_stat);
813                 goto out;
814         }
815
816         maj_stat = gss_init_sec_context(&min_stat,
817                         GSS_C_NO_CREDENTIAL, /* claimant_cred_handle */
818                         &ctx,
819                         target_name,
820                         discard_const(gss_mech_krb5), /* force krb5 */
821                         0, /* flags */
822                         0, /* time_req */
823                         GSS_C_NO_CHANNEL_BINDINGS, /* input_chan_bindings */
824                         GSS_C_NO_BUFFER,
825                         NULL, /* actual mech type */
826                         &output_token,
827                         NULL, /* ret_flags */
828                         NULL); /* time_rec */
829
830         if (maj_stat != GSS_S_COMPLETE &&
831                 maj_stat != GSS_S_CONTINUE_NEEDED) {
832                 cifs_gss_display_status("init_sec_context", maj_stat, min_stat);
833                 goto out_release_target_name;
834         }
835
836         /* as luck would have it, GSS-API hands us the finished article */
837         *mechtoken = data_blob(output_token.value, output_token.length);
838
839         maj_stat = gss_krb5_export_lucid_sec_context(&min_stat, &ctx, 1,
840                                                         (void **)&lucid_ctx);
841
842         if (GSS_ERROR(maj_stat)) {
843                 cifs_gss_display_status("gss_krb5_export_lucid_sec_context",
844                                         maj_stat, min_stat);
845                 goto out_free_sec_ctx;
846         }
847
848         switch (lucid_ctx->protocol) {
849         case 0:
850                 key = &lucid_ctx->rfc1964_kd.ctx_key;
851                 break;
852         case 1:
853                 if (lucid_ctx->cfx_kd.have_acceptor_subkey) {
854                         key = &lucid_ctx->cfx_kd.acceptor_subkey;
855                 } else {
856                         key = &lucid_ctx->cfx_kd.ctx_key;
857                 }
858                 break;
859         default:
860                 syslog(LOG_DEBUG, "wrong lucid context protocol %d",
861                        lucid_ctx->protocol);
862                 goto out_free_lucid_ctx;
863         }
864
865         *sess_key = data_blob(key->data, key->length);
866
867 out_free_lucid_ctx:
868         (void) gss_krb5_free_lucid_sec_context(&min_stat, lucid_ctx);
869 out_free_sec_ctx:
870         (void) gss_delete_sec_context(&min_stat, &ctx, GSS_C_NO_BUFFER);
871         (void) gss_release_buffer(&min_stat, &output_token);
872 out_release_target_name:
873         (void) gss_release_name(&min_stat, &target_name);
874 out:
875         return GSS_ERROR(maj_stat);
876 }
877
878 /*
879  * Prepares AP-REQ data for mechToken and gets session key
880  * Uses credentials from cache. It will not ask for password
881  * you should receive credentials for yuor name manually using
882  * kinit or whatever you wish.
883  *
884  * in:
885  *      oid -           string with OID/ Could be OID_KERBEROS5
886  *                      or OID_KERBEROS5_OLD
887  *      principal -     Service name.
888  *                      Could be "cifs/FQDN" for KRB5 OID
889  *                      or for MS_KRB5 OID style server principal
890  *                      like "pdc$@YOUR.REALM.NAME"
891  *
892  * out:
893  *      secblob -       pointer for spnego wrapped AP-REQ data to be stored
894  *      sess_key-       pointer for SessionKey data to be stored
895  *
896  * ret: 0 - success, others - failure
897  */
898 static int
899 handle_krb5_mech(const char *oid, const char *host, DATA_BLOB * secblob,
900                  DATA_BLOB * sess_key, krb5_ccache ccache)
901 {
902         int retval;
903         DATA_BLOB tkt_wrapped;
904
905         syslog(LOG_DEBUG, "%s: getting service ticket for %s", __func__, host);
906
907         /*
908          * Fall back to gssapi if there's no credential cache or no TGT
909          * so that gssproxy can maybe help out.
910          */
911         if (!ccache) {
912                 syslog(LOG_DEBUG, "%s: using GSS-API", __func__);
913                 retval = cifs_gss_get_req(host, &tkt_wrapped, sess_key);
914                 if (retval) {
915                         syslog(LOG_DEBUG, "%s: failed to obtain service ticket via GSS (%d)",
916                         __func__, retval);
917                         return retval;
918                 }
919         } else {
920                 DATA_BLOB tkt;
921                 syslog(LOG_DEBUG, "%s: using native krb5", __func__);
922
923                 /* get a kerberos ticket for the service and extract the session key */
924                 retval = cifs_krb5_get_req(host, ccache, &tkt, sess_key);
925                 if (retval) {
926                         syslog(LOG_DEBUG, "%s: failed to obtain service ticket (%d)",
927                                __func__, retval);
928                         return retval;
929                 }
930
931                 syslog(LOG_DEBUG, "%s: obtained service ticket", __func__);
932
933                 /* wrap that up in a nice GSS-API wrapping */
934                 tkt_wrapped = spnego_gen_krb5_wrap(tkt, TOK_ID_KRB_AP_REQ);
935                 data_blob_free(&tkt);
936         }
937
938         /* and wrap that in a shiny SPNEGO wrapper */
939         *secblob = gen_negTokenInit(oid, tkt_wrapped);
940
941         data_blob_free(&tkt_wrapped);
942         return retval;
943 }
944
945
946
947 struct decoded_args {
948         int ver;
949         char hostname[NI_MAXHOST + 1];
950         char ip[NI_MAXHOST + 1];
951
952 /* Max user name length. */
953 #define MAX_USERNAME_SIZE 256
954         char username[MAX_USERNAME_SIZE + 1];
955
956         uid_t uid;
957         uid_t creduid;
958         pid_t pid;
959         sectype_t sec;
960
961 /*
962  * Flags to keep track of what was provided
963  */
964 #define DKD_HAVE_HOSTNAME       0x1
965 #define DKD_HAVE_VERSION        0x2
966 #define DKD_HAVE_SEC            0x4
967 #define DKD_HAVE_IP             0x8
968 #define DKD_HAVE_UID            0x10
969 #define DKD_HAVE_PID            0x20
970 #define DKD_HAVE_CREDUID        0x40
971 #define DKD_HAVE_USERNAME       0x80
972 #define DKD_MUSTHAVE_SET (DKD_HAVE_HOSTNAME|DKD_HAVE_VERSION|DKD_HAVE_SEC)
973         int have;
974 };
975
976 static unsigned int
977 __decode_key_description(const char *desc, struct decoded_args *arg)
978 {
979         size_t len;
980         char *pos;
981         const char *tkn = desc;
982
983         do {
984                 pos = index(tkn, ';');
985                 if (strncmp(tkn, "host=", 5) == 0) {
986
987                         if (pos == NULL)
988                                 len = strlen(tkn);
989                         else
990                                 len = pos - tkn;
991
992                         len -= 5;
993                         if (len > sizeof(arg->hostname)-1) {
994                                 syslog(LOG_ERR, "host= value too long for buffer");
995                                 return 1;
996                         }
997                         memset(arg->hostname, 0, sizeof(arg->hostname));
998                         strncpy(arg->hostname, tkn + 5, len);
999                         arg->have |= DKD_HAVE_HOSTNAME;
1000                         syslog(LOG_DEBUG, "host=%s", arg->hostname);
1001                 } else if (!strncmp(tkn, "ip4=", 4) || !strncmp(tkn, "ip6=", 4)) {
1002                         if (pos == NULL)
1003                                 len = strlen(tkn);
1004                         else
1005                                 len = pos - tkn;
1006
1007                         len -= 4;
1008                         if (len > sizeof(arg->ip)-1) {
1009                                 syslog(LOG_ERR, "ip[46]= value too long for buffer");
1010                                 return 1;
1011                         }
1012                         memset(arg->ip, 0, sizeof(arg->ip));
1013                         strncpy(arg->ip, tkn + 4, len);
1014                         arg->have |= DKD_HAVE_IP;
1015                         syslog(LOG_DEBUG, "ip=%s", arg->ip);
1016                 } else if (strncmp(tkn, "user=", 5) == 0) {
1017                         if (pos == NULL)
1018                                 len = strlen(tkn);
1019                         else
1020                                 len = pos - tkn;
1021
1022                         len -= 5;
1023                         if (len > sizeof(arg->username)-1) {
1024                                 syslog(LOG_ERR, "user= value too long for buffer");
1025                                 return 1;
1026                         }
1027                         memset(arg->username, 0, sizeof(arg->username));
1028                         strncpy(arg->username, tkn + 5, len);
1029                         arg->have |= DKD_HAVE_USERNAME;
1030                         syslog(LOG_DEBUG, "user=%s", arg->username);
1031                 } else if (strncmp(tkn, "pid=", 4) == 0) {
1032                         errno = 0;
1033                         arg->pid = strtol(tkn + 4, NULL, 0);
1034                         if (errno != 0) {
1035                                 syslog(LOG_ERR, "Invalid pid format: %s",
1036                                        strerror(errno));
1037                                 return 1;
1038                         }
1039                         syslog(LOG_DEBUG, "pid=%u", arg->pid);
1040                         arg->have |= DKD_HAVE_PID;
1041                 } else if (strncmp(tkn, "sec=", 4) == 0) {
1042                         if (strncmp(tkn + 4, "krb5", 4) == 0) {
1043                                 arg->have |= DKD_HAVE_SEC;
1044                                 arg->sec = KRB5;
1045                         } else if (strncmp(tkn + 4, "mskrb5", 6) == 0) {
1046                                 arg->have |= DKD_HAVE_SEC;
1047                                 arg->sec = MS_KRB5;
1048                         }
1049                         syslog(LOG_DEBUG, "sec=%d", arg->sec);
1050                 } else if (strncmp(tkn, "uid=", 4) == 0) {
1051                         errno = 0;
1052                         arg->uid = strtol(tkn + 4, NULL, 16);
1053                         if (errno != 0) {
1054                                 syslog(LOG_ERR, "Invalid uid format: %s",
1055                                        strerror(errno));
1056                                 return 1;
1057                         }
1058                         arg->have |= DKD_HAVE_UID;
1059                         syslog(LOG_DEBUG, "uid=%u", arg->uid);
1060                 } else if (strncmp(tkn, "creduid=", 8) == 0) {
1061                         errno = 0;
1062                         arg->creduid = strtol(tkn + 8, NULL, 16);
1063                         if (errno != 0) {
1064                                 syslog(LOG_ERR, "Invalid creduid format: %s",
1065                                        strerror(errno));
1066                                 return 1;
1067                         }
1068                         arg->have |= DKD_HAVE_CREDUID;
1069                         syslog(LOG_DEBUG, "creduid=%u", arg->creduid);
1070                 } else if (strncmp(tkn, "ver=", 4) == 0) {      /* if version */
1071                         errno = 0;
1072                         arg->ver = strtol(tkn + 4, NULL, 16);
1073                         if (errno != 0) {
1074                                 syslog(LOG_ERR, "Invalid version format: %s",
1075                                        strerror(errno));
1076                                 return 1;
1077                         }
1078                         arg->have |= DKD_HAVE_VERSION;
1079                         syslog(LOG_DEBUG, "ver=%d", arg->ver);
1080                 }
1081                 if (pos == NULL)
1082                         break;
1083                 tkn = pos + 1;
1084         } while (tkn);
1085         return 0;
1086 }
1087
1088 static unsigned int
1089 decode_key_description(const char *desc, struct decoded_args **arg)
1090 {
1091         pid_t pid;
1092         pid_t rc;
1093         int status;
1094
1095         /*
1096          * Do all the decoding/string processing in a child process
1097          * with low privileges.
1098          */
1099
1100         *arg = mmap(NULL, sizeof(struct decoded_args), PROT_READ | PROT_WRITE,
1101                     MAP_ANONYMOUS | MAP_SHARED, -1, 0);
1102         if (*arg == MAP_FAILED) {
1103                 syslog(LOG_ERR, "%s: mmap failed: %s", __func__, strerror(errno));
1104                 return -1;
1105         }
1106
1107         pid = fork();
1108         if (pid < 0) {
1109                 syslog(LOG_ERR, "%s: fork failed: %s", __func__, strerror(errno));
1110                 munmap(*arg, sizeof(struct decoded_args));
1111                 *arg = NULL;
1112                 return -1;
1113         }
1114         if (pid == 0) {
1115                 /* do the parsing in child */
1116                 drop_all_capabilities();
1117                 exit(__decode_key_description(desc, *arg));
1118         }
1119
1120         rc = waitpid(pid, &status, 0);
1121         if (rc < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1122                 munmap(*arg, sizeof(struct decoded_args));
1123                 *arg = NULL;
1124                 return 1;
1125         }
1126
1127         return 0;
1128 }
1129
1130 static int setup_key(const key_serial_t key, const void *data, size_t datalen)
1131 {
1132         int rc;
1133
1134         rc = keyctl_instantiate(key, data, datalen, 0);
1135         if (rc) {
1136                 switch (errno) {
1137                 case ENOMEM:
1138                 case EDQUOT:
1139                         rc = keyctl_clear(key);
1140                         if (rc) {
1141                                 syslog(LOG_ERR, "%s: keyctl_clear: %s",
1142                                        __func__, strerror(errno));
1143                                 return rc;
1144                         }
1145                         rc = keyctl_instantiate(key, data, datalen, 0);
1146                         break;
1147                 default:
1148                         ;
1149                 }
1150         }
1151         if (rc) {
1152                 syslog(LOG_ERR, "%s: keyctl_instantiate: %s",
1153                        __func__, strerror(errno));
1154         }
1155         return rc;
1156 }
1157
1158 static int cifs_resolver(const key_serial_t key, const char *key_descr,
1159                          const char *key_buf, unsigned expire_time)
1160 {
1161         int c;
1162         struct addrinfo *addr;
1163         char ip[INET6_ADDRSTRLEN];
1164         void *p;
1165         const char *keyend = key_buf;
1166         /* skip next 4 ';' delimiters to get to description */
1167         for (c = 1; c <= 4; c++) {
1168                 keyend = index(keyend + 1, ';');
1169                 if (!keyend) {
1170                         syslog(LOG_ERR, "invalid key description: %s",
1171                                key_buf);
1172                         return 1;
1173                 }
1174         }
1175         keyend++;
1176
1177         /* resolve name to ip */
1178         c = getaddrinfo(keyend, NULL, NULL, &addr);
1179         if (c) {
1180                 syslog(LOG_ERR, "unable to resolve hostname: %s [%s]",
1181                        keyend, gai_strerror(c));
1182                 return 1;
1183         }
1184
1185         /* conver ip to string form */
1186         if (addr->ai_family == AF_INET)
1187                 p = &(((struct sockaddr_in *)addr->ai_addr)->sin_addr);
1188         else
1189                 p = &(((struct sockaddr_in6 *)addr->ai_addr)->sin6_addr);
1190
1191         if (!inet_ntop(addr->ai_family, p, ip, sizeof(ip))) {
1192                 syslog(LOG_ERR, "%s: inet_ntop: %s", __func__, strerror(errno));
1193                 freeaddrinfo(addr);
1194                 return 1;
1195         }
1196
1197         /* needed for keyctl_set_timeout() */
1198         request_key("keyring", key_descr, NULL, KEY_SPEC_THREAD_KEYRING);
1199
1200         c = setup_key(key, ip, strlen(ip) + 1);
1201         if (c) {
1202                 freeaddrinfo(addr);
1203                 return 1;
1204         }
1205         c = keyctl_set_timeout(key, expire_time);
1206         if (c) {
1207                 syslog(LOG_ERR, "%s: keyctl_set_timeout: %s", __func__,
1208                        strerror(errno));
1209                 freeaddrinfo(addr);
1210                 return 1;
1211         }
1212         freeaddrinfo(addr);
1213         return 0;
1214 }
1215
1216 /*
1217  * Older kernels sent IPv6 addresses without colons. Well, at least
1218  * they're fixed-length strings. Convert these addresses to have colon
1219  * delimiters to make getaddrinfo happy.
1220  */
1221 static void convert_inet6_addr(const char *from, char *to)
1222 {
1223         int i = 1;
1224
1225         while (*from) {
1226                 *to++ = *from++;
1227                 if (!(i++ % 4) && *from)
1228                         *to++ = ':';
1229         }
1230         *to = 0;
1231 }
1232
1233 static int ip_to_fqdn(const char *addrstr, char *host, size_t hostlen)
1234 {
1235         int rc;
1236         struct addrinfo hints = {.ai_flags = AI_NUMERICHOST };
1237         struct addrinfo *res;
1238         const char *ipaddr = addrstr;
1239         char converted[INET6_ADDRSTRLEN + 1];
1240
1241         if ((strlen(ipaddr) > INET_ADDRSTRLEN) && !strchr(ipaddr, ':')) {
1242                 convert_inet6_addr(ipaddr, converted);
1243                 ipaddr = converted;
1244         }
1245
1246         rc = getaddrinfo(ipaddr, NULL, &hints, &res);
1247         if (rc) {
1248                 syslog(LOG_DEBUG, "%s: failed to resolve %s to "
1249                        "ipaddr: %s", __func__, ipaddr,
1250                        rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
1251                 return rc;
1252         }
1253
1254         rc = getnameinfo(res->ai_addr, res->ai_addrlen, host, hostlen,
1255                          NULL, 0, NI_NAMEREQD);
1256         freeaddrinfo(res);
1257         if (rc) {
1258                 syslog(LOG_DEBUG, "%s: failed to resolve %s to fqdn: %s",
1259                        __func__, ipaddr,
1260                        rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
1261                 return rc;
1262         }
1263
1264         syslog(LOG_DEBUG, "%s: resolved %s to %s", __func__, ipaddr, host);
1265         return 0;
1266 }
1267
1268 /* walk a string and lowercase it in-place */
1269 static void
1270 lowercase_string(char *c)
1271 {
1272         while(*c) {
1273                 *c = tolower(*c);
1274                 ++c;
1275         }
1276 }
1277
1278 static void usage(void)
1279 {
1280         fprintf(stderr, "Usage: %s [ -K /path/to/keytab] [-k /path/to/krb5.conf] [-E] [-t] [-v] [-l] [-e nsecs] key_serial\n", prog);
1281 }
1282
1283 static const struct option long_options[] = {
1284         {"no-env-probe", 0, NULL, 'E'},
1285         {"krb5conf", 1, NULL, 'k'},
1286         {"legacy-uid", 0, NULL, 'l'},
1287         {"trust-dns", 0, NULL, 't'},
1288         {"keytab", 1, NULL, 'K'},
1289         {"version", 0, NULL, 'v'},
1290         {"expire", 1, NULL, 'e'},
1291         {NULL, 0, NULL, 0}
1292 };
1293
1294 int main(const int argc, char *const argv[])
1295 {
1296         struct cifs_spnego_msg *keydata = NULL;
1297         DATA_BLOB secblob = data_blob_null;
1298         DATA_BLOB sess_key = data_blob_null;
1299         key_serial_t key = 0;
1300         size_t datalen;
1301         long rc = 1;
1302         int c;
1303         bool try_dns = false, legacy_uid = false , env_probe = true;
1304         char *buf;
1305         char hostbuf[NI_MAXHOST], *host;
1306         struct decoded_args *arg = NULL;
1307         const char *oid;
1308         uid_t uid;
1309         char *keytab_name = NULL;
1310         char *env_cachename = NULL;
1311         krb5_ccache ccache = NULL;
1312         struct passwd *pw;
1313         unsigned expire_time = DNS_RESOLVER_DEFAULT_TIMEOUT;
1314         const char *key_descr = NULL;
1315
1316         hostbuf[0] = '\0';
1317
1318         openlog(prog, 0, LOG_DAEMON);
1319
1320         while ((c = getopt_long(argc, argv, "cEk:K:ltve:", long_options, NULL)) != -1) {
1321                 switch (c) {
1322                 case 'c':
1323                         /* legacy option -- skip it */
1324                         break;
1325                 case 'E':
1326                         /* skip probing initiating process env */
1327                         env_probe = false;
1328                         break;
1329                 case 't':
1330                         try_dns = true;
1331                         break;
1332                 case 'k':
1333                         if (setenv("KRB5_CONFIG", optarg, 1) != 0) {
1334                                 syslog(LOG_ERR, "unable to set $KRB5_CONFIG: %d", errno);
1335                                 goto out;
1336                         }
1337                         break;
1338                 case 'K':
1339                         keytab_name = optarg;
1340                         break;
1341                 case 'l':
1342                         legacy_uid = true;
1343                         break;
1344                 case 'v':
1345                         rc = 0;
1346                         printf("version: %s\n", VERSION);
1347                         goto out;
1348                 case 'e':
1349                         expire_time = strtoul(optarg, NULL, 10);
1350                         break;
1351                 default:
1352                         syslog(LOG_ERR, "unknown option: %c", c);
1353                         goto out;
1354                 }
1355         }
1356
1357         /* is there a key? */
1358         if (argc <= optind) {
1359                 usage();
1360                 goto out;
1361         }
1362
1363         /* get key and keyring values */
1364         errno = 0;
1365         key = strtol(argv[optind], NULL, 10);
1366         if (errno != 0) {
1367                 key = 0;
1368                 syslog(LOG_ERR, "Invalid key format: %s", strerror(errno));
1369                 goto out;
1370         }
1371
1372         rc = keyctl_describe_alloc(key, &buf);
1373         if (rc == -1) {
1374                 syslog(LOG_ERR, "keyctl_describe_alloc failed: %s",
1375                        strerror(errno));
1376                 rc = 1;
1377                 goto out;
1378         }
1379
1380         syslog(LOG_DEBUG, "key description: %s", buf);
1381
1382         /*
1383          * If we are requested a simple DNS query, do it and exit
1384          */
1385
1386         if (strncmp(buf, "cifs.resolver", sizeof("cifs.resolver") - 1) == 0)
1387                 key_descr = ".cifs.resolver";
1388         else if (strncmp(buf, "dns_resolver", sizeof("dns_resolver") - 1) == 0)
1389                 key_descr = ".dns_resolver";
1390         if (key_descr) {
1391                 rc = cifs_resolver(key, key_descr, buf, expire_time);
1392                 goto out;
1393         }
1394
1395         /*
1396          * Otherwise, it's a spnego key request
1397          */
1398
1399         rc = decode_key_description(buf, &arg);
1400         free(buf);
1401         if (rc) {
1402                 syslog(LOG_ERR, "failed to decode key description");
1403                 goto out;
1404         }
1405
1406         if ((arg->have & DKD_MUSTHAVE_SET) != DKD_MUSTHAVE_SET) {
1407                 syslog(LOG_ERR, "unable to get necessary params from key "
1408                        "description (0x%x)", arg->have);
1409                 rc = 1;
1410                 goto out;
1411         }
1412
1413         if (arg->ver > CIFS_SPNEGO_UPCALL_VERSION) {
1414                 syslog(LOG_ERR, "incompatible kernel upcall version: 0x%x",
1415                        arg->ver);
1416                 rc = 1;
1417                 goto out;
1418         }
1419
1420         if (strlen(arg->hostname) >= NI_MAXHOST) {
1421                 syslog(LOG_ERR, "hostname provided by kernel is too long");
1422                 rc = 1;
1423                 goto out;
1424
1425         }
1426
1427         if (!legacy_uid && (arg->have & DKD_HAVE_CREDUID))
1428                 uid = arg->creduid;
1429         else if (arg->have & DKD_HAVE_UID)
1430                 uid = arg->uid;
1431         else {
1432                 /* no uid= or creduid= parm -- something is wrong */
1433                 syslog(LOG_ERR, "No uid= or creduid= parm specified");
1434                 rc = 1;
1435                 goto out;
1436         }
1437
1438         /*
1439          * Change to the process's namespace. This means that things will work
1440          * acceptably in containers, because we'll be looking at the correct
1441          * filesystem and have the correct network configuration.
1442          */
1443         rc = switch_to_process_ns(arg->pid);
1444         if (rc == -1) {
1445                 syslog(LOG_ERR, "unable to switch to process namespace: %s", strerror(errno));
1446                 rc = 1;
1447                 goto out;
1448         }
1449
1450         if (trim_capabilities(env_probe))
1451                 goto out;
1452
1453         /*
1454          * The kernel doesn't pass down the gid, so we resort here to scraping
1455          * one out of the passwd nss db. Note that this might not reflect the
1456          * actual gid of the process that initiated the upcall. While we could
1457          * scrape that out of /proc, relying on that is a bit more risky.
1458          */
1459         pw = getpwuid(uid);
1460         if (!pw) {
1461                 syslog(LOG_ERR, "Unable to find pw entry for uid %d: %s\n",
1462                         uid, strerror(errno));
1463                 rc = 1;
1464                 goto out;
1465         }
1466
1467         /*
1468          * The kernel should send down a zero-length grouplist already, but
1469          * just to be on the safe side...
1470          */
1471         rc = setgroups(0, NULL);
1472         if (rc == -1) {
1473                 syslog(LOG_ERR, "setgroups: %s", strerror(errno));
1474                 rc = 1;
1475                 goto out;
1476         }
1477
1478         rc = setgid(pw->pw_gid);
1479         if (rc == -1) {
1480                 syslog(LOG_ERR, "setgid: %s", strerror(errno));
1481                 rc = 1;
1482                 goto out;
1483         }
1484
1485         /*
1486          * We can't reasonably do this for root. When mounting a DFS share,
1487          * for instance we can end up with creds being overridden, but the env
1488          * variable left intact.
1489          */
1490         if (uid == 0)
1491                 env_probe = false;
1492
1493         /*
1494          * Must do this before setuid, as we need elevated capabilities to
1495          * look at the environ file.
1496          */
1497         env_cachename =
1498                 get_cachename_from_process_env(env_probe ? arg->pid : 0);
1499
1500         rc = setuid(uid);
1501         if (rc == -1) {
1502                 syslog(LOG_ERR, "setuid: %s", strerror(errno));
1503                 rc = 1;
1504                 goto out;
1505         }
1506
1507         rc = drop_all_capabilities();
1508         if (rc)
1509                 goto out;
1510
1511         rc = krb5_init_context(&context);
1512         if (rc) {
1513                 syslog(LOG_ERR, "unable to init krb5 context: %ld", rc);
1514                 rc = 1;
1515                 goto out;
1516         }
1517
1518         ccache = get_existing_cc(env_cachename);
1519         /* Couldn't find credcache? Try to use keytab */
1520         if (ccache == NULL && arg->username[0] != '\0')
1521                 ccache = init_cc_from_keytab(keytab_name, arg->username);
1522
1523         host = arg->hostname;
1524
1525         // do mech specific authorization
1526         switch (arg->sec) {
1527         case MS_KRB5:
1528         case KRB5:
1529                 /*
1530                  * Andrew Bartlett's suggested scheme for picking a principal
1531                  * name, based on a supplied hostname.
1532                  *
1533                  * INPUT: fooo
1534                  * TRY in order:
1535                  * cifs/fooo@REALM
1536                  * cifs/fooo.<guessed domain ?>@REALM
1537                  *
1538                  * INPUT: bar.example.com
1539                  * TRY only:
1540                  * cifs/bar.example.com@REALM
1541                  */
1542                 if (arg->sec == MS_KRB5)
1543                         oid = OID_KERBEROS5_OLD;
1544                 else
1545                         oid = OID_KERBEROS5;
1546
1547 retry_new_hostname:
1548                 lowercase_string(host);
1549                 rc = handle_krb5_mech(oid, host, &secblob, &sess_key, ccache);
1550                 if (!rc)
1551                         break;
1552
1553                 /*
1554                  * If hostname has a '.', assume it's a FQDN, otherwise we
1555                  * want to guess the domainname.
1556                  */
1557                 if (!strchr(host, '.')) {
1558                         struct addrinfo hints;
1559                         struct addrinfo *ai;
1560                         char *domainname;
1561                         char fqdn[NI_MAXHOST];
1562
1563                         /*
1564                          * use getaddrinfo() to resolve the hostname of the
1565                          * server and set ai_canonname.
1566                          */
1567                         memset(&hints, 0, sizeof(hints));
1568                         hints.ai_family = AF_UNSPEC;
1569                         hints.ai_flags = AI_CANONNAME;
1570                         rc = getaddrinfo(host, NULL, &hints, &ai);
1571                         if (rc) {
1572                                 syslog(LOG_ERR, "Unable to resolve host address: %s [%s]",
1573                                        host, gai_strerror(rc));
1574                                 break;
1575                         }
1576
1577                         /* scan forward to first '.' in ai_canonnname */
1578                         domainname = strchr(ai->ai_canonname, '.');
1579                         if (!domainname) {
1580                                 rc = -EINVAL;
1581                                 freeaddrinfo(ai);
1582                                 break;
1583                         }
1584                         lowercase_string(domainname);
1585                         rc = snprintf(fqdn, sizeof(fqdn), "%s%s",
1586                                         host, domainname);
1587                         freeaddrinfo(ai);
1588                         if (rc < 0 || (size_t)rc >= sizeof(fqdn)) {
1589                                 syslog(LOG_ERR, "Problem setting hostname in string: %ld", rc);
1590                                 rc = -EINVAL;
1591                                 break;
1592                         }
1593
1594                         rc = handle_krb5_mech(oid, fqdn, &secblob, &sess_key, ccache);
1595                         if (!rc)
1596                                 break;
1597                 }
1598
1599                 if (!try_dns || !(arg->have & DKD_HAVE_IP))
1600                         break;
1601
1602                 rc = ip_to_fqdn(arg->ip, hostbuf, sizeof(hostbuf));
1603                 if (rc)
1604                         break;
1605
1606                 try_dns = false;
1607                 host = hostbuf;
1608                 goto retry_new_hostname;
1609         default:
1610                 syslog(LOG_ERR, "sectype: %d is not implemented", arg->sec);
1611                 rc = 1;
1612                 break;
1613         }
1614
1615         if (rc) {
1616                 syslog(LOG_DEBUG, "Unable to obtain service ticket");
1617                 goto out;
1618         }
1619
1620         /* pack SecurityBlob and SessionKey into downcall packet */
1621         datalen =
1622             sizeof(struct cifs_spnego_msg) + secblob.length + sess_key.length;
1623         keydata = (struct cifs_spnego_msg *)calloc(sizeof(char), datalen);
1624         if (!keydata) {
1625                 rc = 1;
1626                 goto out;
1627         }
1628         keydata->version = arg->ver;
1629         keydata->flags = 0;
1630         keydata->sesskey_len = sess_key.length;
1631         keydata->secblob_len = secblob.length;
1632         memcpy(&(keydata->data), sess_key.data, sess_key.length);
1633         memcpy(&(keydata->data) + keydata->sesskey_len,
1634                secblob.data, secblob.length);
1635
1636         rc = setup_key(key, keydata, datalen);
1637
1638 out:
1639         /*
1640          * on error, negatively instantiate the key ourselves so that we can
1641          * make sure the kernel doesn't hang it off of a searchable keyring
1642          * and interfere with the next attempt to instantiate the key.
1643          */
1644         if (rc != 0 && key == 0) {
1645                 syslog(LOG_DEBUG, "Negating key");
1646                 keyctl_negate(key, 1, KEY_REQKEY_DEFL_DEFAULT);
1647         }
1648         data_blob_free(&secblob);
1649         data_blob_free(&sess_key);
1650         if (ccache)
1651                 krb5_cc_close(context, ccache);
1652         if (context)
1653                 krb5_free_context(context);
1654         free(keydata);
1655         free(env_cachename);
1656         if (arg)
1657                 munmap(arg, sizeof(*arg));
1658         syslog(LOG_DEBUG, "Exit status %ld", rc);
1659         return rc;
1660 }