2 * CIFS user-space helper.
3 * Copyright (C) Igor Mammedov (niallain@gmail.com) 2007
4 * Copyright (C) Jeff Layton (jlayton@samba.org) 2010
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
30 #endif /* HAVE_CONFIG_H */
34 #ifdef HAVE_KRB5_KRB5_H
35 #include <krb5/krb5.h>
36 #elif defined(HAVE_KRB5_H)
40 #include <gssapi/gssapi_krb5.h>
41 #include <sys/utsname.h>
45 #include <sys/types.h>
52 #include <arpa/inet.h>
60 #include <sys/types.h>
63 #include "data_blob.h"
65 #include "cifs_spnego.h"
72 #define discard_const(ptr) ((void *)((intptr_t)(ptr)))
75 static krb5_context context;
76 static const char *prog = "cifs.upcall";
78 #define DNS_RESOLVER_DEFAULT_TIMEOUT 600 /* 10 minutes */
80 typedef enum _sectype {
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
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
101 trim_capabilities(bool need_environ)
103 capng_select_t set = CAPNG_SELECT_CAPS;
105 capng_clear(CAPNG_SELECT_BOTH);
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__);
114 /* Need PTRACE and READ_SEARCH for /proc/pid/environ scraping */
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__);
122 if (capng_have_capability(CAPNG_EFFECTIVE, CAP_SETPCAP)) {
123 set = CAPNG_SELECT_BOTH;
125 if (capng_apply(set)) {
126 syslog(LOG_ERR, "%s: Unable to apply capability set: %m\n", __func__);
133 drop_all_capabilities(void)
135 capng_select_t set = CAPNG_SELECT_CAPS;
137 capng_clear(CAPNG_SELECT_BOTH);
138 if (capng_have_capability(CAPNG_EFFECTIVE, CAP_SETPCAP)) {
139 set = CAPNG_SELECT_BOTH;
141 if (capng_apply(set)) {
142 syslog(LOG_ERR, "%s: Unable to apply capability set: %m\n", __func__);
147 #else /* HAVE_LIBCAP_NG */
149 trim_capabilities(bool unused)
156 drop_all_capabilities(void)
160 #endif /* HAVE_LIBCAP_NG */
163 * smb_krb5_principal_get_realm
165 * @brief Get realm of a principal
167 * @param[in] context The krb5_context
168 * @param[in] principal The principal
169 * @return pointer to the realm
172 static char *cifs_krb5_principal_get_realm(krb5_principal principal)
174 #ifdef HAVE_KRB5_PRINCIPAL_GET_REALM /* Heimdal */
175 return krb5_principal_get_realm(context, principal);
176 #elif defined(krb5_princ_realm) /* MIT */
178 realm = krb5_princ_realm(context, principal);
179 return (char *)realm->data;
185 #if !defined(HAVE_KRB5_FREE_UNPARSED_NAME)
186 static void krb5_free_unparsed_name(krb5_context context, char *val)
192 #if !defined(HAVE_KRB5_FREE_STRING) /* Heimdal */
193 static void krb5_free_string(krb5_context context, char *val)
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)
206 return krb5_auth_con_getlocalsubkey(context, auth_context, keyblock);
210 /* does the ccache have a valid TGT? */
211 static time_t get_tgt_time(krb5_ccache ccache)
215 krb5_principal principal;
219 if (krb5_cc_set_flags(context, ccache, 0)) {
220 syslog(LOG_DEBUG, "%s: unable to set flags", __func__);
224 if (krb5_cc_get_principal(context, ccache, &principal)) {
225 syslog(LOG_DEBUG, "%s: unable to get principal", __func__);
229 if (krb5_cc_start_seq_get(context, ccache, &cur)) {
230 syslog(LOG_DEBUG, "%s: unable to seq start", __func__);
234 if ((realm = cifs_krb5_principal_get_realm(principal)) == NULL) {
235 syslog(LOG_DEBUG, "%s: unable to get realm", __func__);
239 while (!credtime && !krb5_cc_next_cred(context, ccache, &cur, &creds)) {
241 if (krb5_unparse_name(context, creds.server, &name)) {
242 syslog(LOG_DEBUG, "%s: unable to unparse name",
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,
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);
256 krb5_cc_end_seq_get(context, ccache, &cur);
258 krb5_free_principal(context, principal);
263 static struct namespace_file {
267 } namespace_files[] = {
269 #ifdef CLONE_NEWCGROUP
270 { CLONE_NEWCGROUP, "cgroup", -1 },
274 { CLONE_NEWIPC, "ipc", -1 },
278 { CLONE_NEWUTS, "uts", -1 },
282 { CLONE_NEWNET, "net", -1 },
286 { CLONE_NEWPID, "pid", -1 },
290 { CLONE_NEWTIME, "time", -1 },
294 { CLONE_NEWNS, "mnt", -1 },
298 { CLONE_NEWUSER, "user", -1 },
302 #define NS_PATH_FMT "/proc/%d/ns/%s"
303 #define NS_PATH_MAXLEN (6 + 10 + 4 + 6 + 1)
306 * in_same_user_ns - return true if two processes are in the same user
308 * @pid_a: the pid of the first process
309 * @pid_b: the pid of the second process
311 * Works by comparing the inode numbers for /proc/<pid>/user.
314 in_same_user_ns(pid_t pid_a, pid_t pid_b)
316 char path[NS_PATH_MAXLEN];
320 snprintf(path, sizeof(path), NS_PATH_FMT, pid_a, "user");
321 if (stat(path, &st) != 0)
325 snprintf(path, sizeof(path), NS_PATH_FMT, pid_b, "user");
326 if (stat(path, &st) != 0)
330 return a_ino == b_ino;
334 * switch_to_process_ns - change the namespace to the one for the specified
336 * @pid: initiating pid value from the upcall string
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.
343 switch_to_process_ns(pid_t pid)
345 int count = sizeof(namespace_files) / sizeof(struct namespace_file);
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];
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;
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__);
375 fd = open(nspath, O_RDONLY);
376 if (fd < 0 && errno != ENOENT) {
378 * don't stop on non-existing ns
379 * but stop for other errors
386 namespace_files[n].fd = fd;
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)
395 rc = setns(namespace_files[n].fd, namespace_files[n].nstype);
398 syslog(LOG_DEBUG, "%s: setns() failed for %s\n",
399 __func__, namespace_files[n].name);
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;
421 #define ENV_PATH_FMT "/proc/%d/environ"
422 #define ENV_PATH_MAXLEN (6 + 10 + 8 + 1)
424 #define ENV_NAME "KRB5CCNAME"
425 #define ENV_PREFIX "KRB5CCNAME="
426 #define ENV_PREFIX_LEN 11
428 #define ENV_BUF_START (4096)
429 #define ENV_BUF_MAX (131072)
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
436 * Open the /proc/<pid>/environ file for the given pid, and scrape it for
437 * KRB5CCNAME entries.
439 * We start with a page-size buffer, and then progressively double it until
440 * we can slurp in the whole thing.
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
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
451 get_cachename_from_process_env(pid_t pid)
455 ssize_t bufsize = ENV_BUF_START;
456 char pathname[ENV_PATH_MAXLEN];
457 char *cachename = NULL;
458 char *buf = NULL, *pos;
461 syslog(LOG_DEBUG, "%s: pid == 0\n", __func__);
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__);
472 syslog(LOG_DEBUG, "%s: pathname=%s\n", __func__, pathname);
473 fd = open(pathname, O_RDONLY);
475 syslog(LOG_DEBUG, "%s: open failed: %d\n", __func__, errno);
479 if (bufsize > ENV_BUF_MAX) {
480 syslog(LOG_DEBUG, "%s: buffer too big: %zd\n",
485 buf = malloc(bufsize);
487 syslog(LOG_DEBUG, "%s: malloc failure\n", __func__);
491 buflen = read(fd, buf, bufsize);
493 syslog(LOG_DEBUG, "%s: read failed: %d\n", __func__, errno);
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",
503 if (lseek(fd, 0, SEEK_SET) < 0)
510 size_t len = strnlen(pos, buflen);
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);
530 get_existing_cc(const char *env_cachename)
537 if (setenv(ENV_NAME, env_cachename, 1))
538 syslog(LOG_DEBUG, "%s: failed to setenv %d\n", __func__, errno);
541 ret = krb5_cc_default(context, &cc);
543 syslog(LOG_DEBUG, "%s: krb5_cc_default returned %d", __func__, ret);
547 ret = krb5_cc_get_full_name(context, cc, &cachename);
549 syslog(LOG_DEBUG, "%s: krb5_cc_get_full_name failed: %d\n", __func__, ret);
551 syslog(LOG_DEBUG, "%s: default ccache is %s\n", __func__, cachename);
552 krb5_free_string(context, cachename);
555 if (!get_tgt_time(cc)) {
556 krb5_cc_close(context, cc);
563 init_cc_from_keytab(const char *keytab_name, const char *user)
567 krb5_keytab keytab = NULL;
568 krb5_principal me = NULL;
569 krb5_ccache cc = NULL;
571 memset((char *) &my_creds, 0, sizeof(my_creds));
574 * Unset the environment variable, if any. If we're creating our own
575 * credcache here, stick it in the default location.
580 ret = krb5_kt_resolve(context, keytab_name, &keytab);
582 ret = krb5_kt_default(context, &keytab);
585 syslog(LOG_DEBUG, "%s: %d",
586 keytab_name ? "krb5_kt_resolve" : "krb5_kt_default",
591 ret = krb5_parse_name(context, user, &me);
593 syslog(LOG_DEBUG, "krb5_parse_name: %d", (int)ret);
597 ret = krb5_get_init_creds_keytab(context, &my_creds, me,
598 keytab, 0, NULL, NULL);
600 syslog(LOG_DEBUG, "krb5_get_init_creds_keytab: %d", (int)ret);
604 ret = krb5_cc_resolve(context, "MEMORY:", &cc);
606 syslog(LOG_DEBUG, "krb5_cc_resolve: %d", (int)ret);
610 ret = krb5_cc_initialize(context, cc, me);
612 syslog(LOG_DEBUG, "krb5_cc_initialize: %d", (int)ret);
616 ret = krb5_cc_store_cred(context, cc, &my_creds);
618 syslog(LOG_DEBUG, "krb5_cc_store_cred: %d", (int)ret);
622 my_creds.client = (krb5_principal)0;
623 krb5_free_cred_contents(context, &my_creds);
626 krb5_free_principal(context, me);
628 krb5_kt_close(context, keytab);
632 krb5_cc_close(context, cc);
638 #define CIFS_SERVICE_NAME "cifs"
641 cifs_krb5_get_req(const char *host, krb5_ccache ccache,
642 DATA_BLOB * mechtoken, DATA_BLOB * sess_key)
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, /* ... */};
652 memset(&in_creds, 0, sizeof(in_creds));
654 ret = krb5_cc_get_principal(context, ccache, &in_creds.client);
656 syslog(LOG_DEBUG, "%s: unable to get client principal name",
661 ret = krb5_sname_to_principal(context, host, CIFS_SERVICE_NAME,
662 KRB5_NT_UNKNOWN, &in_creds.server);
664 syslog(LOG_DEBUG, "%s: unable to convert sname to princ (%s).",
666 goto out_free_principal;
669 ret = krb5_get_credentials(context, 0, ccache, &in_creds, &out_creds);
670 krb5_free_principal(context, in_creds.server);
672 syslog(LOG_DEBUG, "%s: unable to get credentials for %s",
674 goto out_free_principal;
680 ret = krb5_auth_con_init(context, &auth_context);
682 syslog(LOG_DEBUG, "%s: unable to create auth_context: %d",
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);
691 syslog(LOG_DEBUG, "%s: unable to set NULL addrs: %d",
697 * Create a GSSAPI checksum (0x8003), see RFC 4121.
699 * The current layout is
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
708 * GSS_C_NO_CHANNEL_BINDINGS means 16 zero bytes,
709 * this is needed to work against some closed source
712 * See https://bugzilla.samba.org/show_bug.cgi?id=7890
714 in_data.data = gss_cksum;
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);
723 ret = krb5_auth_con_set_req_cksumtype(context, auth_context, 0x8003);
725 syslog(LOG_DEBUG, "%s: unable to set 0x8003 checksum",
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);
736 syslog(LOG_DEBUG, "%s: unable to make AP-REQ for %s",
741 ret = krb5_auth_con_getsendsubkey(context, auth_context, &tokb);
743 syslog(LOG_DEBUG, "%s: unable to get session key for %s",
748 *mechtoken = data_blob(apreq_pkt.data, apreq_pkt.length);
749 *sess_key = data_blob(KRB5_KEY_DATA(tokb), KRB5_KEY_LENGTH(tokb));
751 krb5_free_keyblock(context, tokb);
753 krb5_auth_con_free(context, auth_context);
755 krb5_free_creds(context, out_creds);
757 krb5_free_principal(context, in_creds.client);
761 static void cifs_gss_display_status_1(char *m, OM_uint32 code, int type) {
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);
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);
784 cifs_gss_get_req(const char *host, DATA_BLOB *mechtoken, DATA_BLOB *sess_key)
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;
793 size_t service_name_len = sizeof(CIFS_SERVICE_NAME) + 1 /* @ */ +
795 char *service_name = malloc(service_name_len);
797 syslog(LOG_DEBUG, "out of memory allocating service name");
798 maj_stat = GSS_S_FAILURE;
802 snprintf(service_name, service_name_len, "%s@%s", CIFS_SERVICE_NAME,
804 gss_buffer_desc target_name_buf;
805 target_name_buf.value = service_name;
806 target_name_buf.length = service_name_len;
808 maj_stat = gss_import_name(&min_stat, &target_name_buf,
809 GSS_C_NT_HOSTBASED_SERVICE, &target_name);
811 if (GSS_ERROR(maj_stat)) {
812 cifs_gss_display_status("gss_import_name", maj_stat, min_stat);
816 maj_stat = gss_init_sec_context(&min_stat,
817 GSS_C_NO_CREDENTIAL, /* claimant_cred_handle */
820 discard_const(gss_mech_krb5), /* force krb5 */
823 GSS_C_NO_CHANNEL_BINDINGS, /* input_chan_bindings */
825 NULL, /* actual mech type */
827 NULL, /* ret_flags */
828 NULL); /* time_rec */
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;
836 /* as luck would have it, GSS-API hands us the finished article */
837 *mechtoken = data_blob(output_token.value, output_token.length);
839 maj_stat = gss_krb5_export_lucid_sec_context(&min_stat, &ctx, 1,
840 (void **)&lucid_ctx);
842 if (GSS_ERROR(maj_stat)) {
843 cifs_gss_display_status("gss_krb5_export_lucid_sec_context",
845 goto out_free_sec_ctx;
848 switch (lucid_ctx->protocol) {
850 key = &lucid_ctx->rfc1964_kd.ctx_key;
853 if (lucid_ctx->cfx_kd.have_acceptor_subkey) {
854 key = &lucid_ctx->cfx_kd.acceptor_subkey;
856 key = &lucid_ctx->cfx_kd.ctx_key;
860 syslog(LOG_DEBUG, "wrong lucid context protocol %d",
861 lucid_ctx->protocol);
862 goto out_free_lucid_ctx;
865 *sess_key = data_blob(key->data, key->length);
868 (void) gss_krb5_free_lucid_sec_context(&min_stat, lucid_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);
875 return GSS_ERROR(maj_stat);
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.
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"
893 * secblob - pointer for spnego wrapped AP-REQ data to be stored
894 * sess_key- pointer for SessionKey data to be stored
896 * ret: 0 - success, others - failure
899 handle_krb5_mech(const char *oid, const char *host, DATA_BLOB * secblob,
900 DATA_BLOB * sess_key, krb5_ccache ccache)
903 DATA_BLOB tkt_wrapped;
905 syslog(LOG_DEBUG, "%s: getting service ticket for %s", __func__, host);
908 * Fall back to gssapi if there's no credential cache or no TGT
909 * so that gssproxy can maybe help out.
912 syslog(LOG_DEBUG, "%s: using GSS-API", __func__);
913 retval = cifs_gss_get_req(host, &tkt_wrapped, sess_key);
915 syslog(LOG_DEBUG, "%s: failed to obtain service ticket via GSS (%d)",
921 syslog(LOG_DEBUG, "%s: using native krb5", __func__);
923 /* get a kerberos ticket for the service and extract the session key */
924 retval = cifs_krb5_get_req(host, ccache, &tkt, sess_key);
926 syslog(LOG_DEBUG, "%s: failed to obtain service ticket (%d)",
931 syslog(LOG_DEBUG, "%s: obtained service ticket", __func__);
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);
938 /* and wrap that in a shiny SPNEGO wrapper */
939 *secblob = gen_negTokenInit(oid, tkt_wrapped);
941 data_blob_free(&tkt_wrapped);
947 struct decoded_args {
949 char hostname[NI_MAXHOST + 1];
950 char ip[NI_MAXHOST + 1];
952 /* Max user name length. */
953 #define MAX_USERNAME_SIZE 256
954 char username[MAX_USERNAME_SIZE + 1];
962 * Flags to keep track of what was provided
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)
977 __decode_key_description(const char *desc, struct decoded_args *arg)
981 const char *tkn = desc;
984 pos = index(tkn, ';');
985 if (strncmp(tkn, "host=", 5) == 0) {
993 if (len > sizeof(arg->hostname)-1) {
994 syslog(LOG_ERR, "host= value too long for buffer");
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)) {
1008 if (len > sizeof(arg->ip)-1) {
1009 syslog(LOG_ERR, "ip[46]= value too long for buffer");
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) {
1023 if (len > sizeof(arg->username)-1) {
1024 syslog(LOG_ERR, "user= value too long for buffer");
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) {
1033 arg->pid = strtol(tkn + 4, NULL, 0);
1035 syslog(LOG_ERR, "Invalid pid format: %s",
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;
1045 } else if (strncmp(tkn + 4, "mskrb5", 6) == 0) {
1046 arg->have |= DKD_HAVE_SEC;
1049 syslog(LOG_DEBUG, "sec=%d", arg->sec);
1050 } else if (strncmp(tkn, "uid=", 4) == 0) {
1052 arg->uid = strtol(tkn + 4, NULL, 16);
1054 syslog(LOG_ERR, "Invalid uid format: %s",
1058 arg->have |= DKD_HAVE_UID;
1059 syslog(LOG_DEBUG, "uid=%u", arg->uid);
1060 } else if (strncmp(tkn, "creduid=", 8) == 0) {
1062 arg->creduid = strtol(tkn + 8, NULL, 16);
1064 syslog(LOG_ERR, "Invalid creduid format: %s",
1068 arg->have |= DKD_HAVE_CREDUID;
1069 syslog(LOG_DEBUG, "creduid=%u", arg->creduid);
1070 } else if (strncmp(tkn, "ver=", 4) == 0) { /* if version */
1072 arg->ver = strtol(tkn + 4, NULL, 16);
1074 syslog(LOG_ERR, "Invalid version format: %s",
1078 arg->have |= DKD_HAVE_VERSION;
1079 syslog(LOG_DEBUG, "ver=%d", arg->ver);
1089 decode_key_description(const char *desc, struct decoded_args **arg)
1096 * Do all the decoding/string processing in a child process
1097 * with low privileges.
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));
1109 syslog(LOG_ERR, "%s: fork failed: %s", __func__, strerror(errno));
1110 munmap(*arg, sizeof(struct decoded_args));
1115 /* do the parsing in child */
1116 drop_all_capabilities();
1117 exit(__decode_key_description(desc, *arg));
1120 rc = waitpid(pid, &status, 0);
1121 if (rc < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1122 munmap(*arg, sizeof(struct decoded_args));
1130 static int setup_key(const key_serial_t key, const void *data, size_t datalen)
1134 rc = keyctl_instantiate(key, data, datalen, 0);
1139 rc = keyctl_clear(key);
1141 syslog(LOG_ERR, "%s: keyctl_clear: %s",
1142 __func__, strerror(errno));
1145 rc = keyctl_instantiate(key, data, datalen, 0);
1152 syslog(LOG_ERR, "%s: keyctl_instantiate: %s",
1153 __func__, strerror(errno));
1158 static int cifs_resolver(const key_serial_t key, const char *key_descr,
1159 const char *key_buf, unsigned expire_time)
1162 struct addrinfo *addr;
1163 char ip[INET6_ADDRSTRLEN];
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, ';');
1170 syslog(LOG_ERR, "invalid key description: %s",
1177 /* resolve name to ip */
1178 c = getaddrinfo(keyend, NULL, NULL, &addr);
1180 syslog(LOG_ERR, "unable to resolve hostname: %s [%s]",
1181 keyend, gai_strerror(c));
1185 /* conver ip to string form */
1186 if (addr->ai_family == AF_INET)
1187 p = &(((struct sockaddr_in *)addr->ai_addr)->sin_addr);
1189 p = &(((struct sockaddr_in6 *)addr->ai_addr)->sin6_addr);
1191 if (!inet_ntop(addr->ai_family, p, ip, sizeof(ip))) {
1192 syslog(LOG_ERR, "%s: inet_ntop: %s", __func__, strerror(errno));
1197 /* needed for keyctl_set_timeout() */
1198 request_key("keyring", key_descr, NULL, KEY_SPEC_THREAD_KEYRING);
1200 c = setup_key(key, ip, strlen(ip) + 1);
1205 c = keyctl_set_timeout(key, expire_time);
1207 syslog(LOG_ERR, "%s: keyctl_set_timeout: %s", __func__,
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.
1221 static void convert_inet6_addr(const char *from, char *to)
1227 if (!(i++ % 4) && *from)
1233 static int ip_to_fqdn(const char *addrstr, char *host, size_t hostlen)
1236 struct addrinfo hints = {.ai_flags = AI_NUMERICHOST };
1237 struct addrinfo *res;
1238 const char *ipaddr = addrstr;
1239 char converted[INET6_ADDRSTRLEN + 1];
1241 if ((strlen(ipaddr) > INET_ADDRSTRLEN) && !strchr(ipaddr, ':')) {
1242 convert_inet6_addr(ipaddr, converted);
1246 rc = getaddrinfo(ipaddr, NULL, &hints, &res);
1248 syslog(LOG_DEBUG, "%s: failed to resolve %s to "
1249 "ipaddr: %s", __func__, ipaddr,
1250 rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
1254 rc = getnameinfo(res->ai_addr, res->ai_addrlen, host, hostlen,
1255 NULL, 0, NI_NAMEREQD);
1258 syslog(LOG_DEBUG, "%s: failed to resolve %s to fqdn: %s",
1260 rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
1264 syslog(LOG_DEBUG, "%s: resolved %s to %s", __func__, ipaddr, host);
1268 /* walk a string and lowercase it in-place */
1270 lowercase_string(char *c)
1278 static void usage(void)
1280 fprintf(stderr, "Usage: %s [ -K /path/to/keytab] [-k /path/to/krb5.conf] [-E] [-t] [-v] [-l] [-e nsecs] key_serial\n", prog);
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'},
1294 int main(const int argc, char *const argv[])
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;
1303 bool try_dns = false, legacy_uid = false , env_probe = true;
1305 char hostbuf[NI_MAXHOST], *host;
1306 struct decoded_args *arg = NULL;
1309 char *keytab_name = NULL;
1310 char *env_cachename = NULL;
1311 krb5_ccache ccache = NULL;
1313 unsigned expire_time = DNS_RESOLVER_DEFAULT_TIMEOUT;
1314 const char *key_descr = NULL;
1318 openlog(prog, 0, LOG_DAEMON);
1320 while ((c = getopt_long(argc, argv, "cEk:K:ltve:", long_options, NULL)) != -1) {
1323 /* legacy option -- skip it */
1326 /* skip probing initiating process env */
1333 if (setenv("KRB5_CONFIG", optarg, 1) != 0) {
1334 syslog(LOG_ERR, "unable to set $KRB5_CONFIG: %d", errno);
1339 keytab_name = optarg;
1346 printf("version: %s\n", VERSION);
1349 expire_time = strtoul(optarg, NULL, 10);
1352 syslog(LOG_ERR, "unknown option: %c", c);
1357 /* is there a key? */
1358 if (argc <= optind) {
1363 /* get key and keyring values */
1365 key = strtol(argv[optind], NULL, 10);
1368 syslog(LOG_ERR, "Invalid key format: %s", strerror(errno));
1372 rc = keyctl_describe_alloc(key, &buf);
1374 syslog(LOG_ERR, "keyctl_describe_alloc failed: %s",
1380 syslog(LOG_DEBUG, "key description: %s", buf);
1383 * If we are requested a simple DNS query, do it and exit
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";
1391 rc = cifs_resolver(key, key_descr, buf, expire_time);
1396 * Otherwise, it's a spnego key request
1399 rc = decode_key_description(buf, &arg);
1402 syslog(LOG_ERR, "failed to decode key description");
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);
1413 if (arg->ver > CIFS_SPNEGO_UPCALL_VERSION) {
1414 syslog(LOG_ERR, "incompatible kernel upcall version: 0x%x",
1420 if (strlen(arg->hostname) >= NI_MAXHOST) {
1421 syslog(LOG_ERR, "hostname provided by kernel is too long");
1427 if (!legacy_uid && (arg->have & DKD_HAVE_CREDUID))
1429 else if (arg->have & DKD_HAVE_UID)
1432 /* no uid= or creduid= parm -- something is wrong */
1433 syslog(LOG_ERR, "No uid= or creduid= parm specified");
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.
1443 rc = switch_to_process_ns(arg->pid);
1445 syslog(LOG_ERR, "unable to switch to process namespace: %s", strerror(errno));
1450 if (trim_capabilities(env_probe))
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.
1461 syslog(LOG_ERR, "Unable to find pw entry for uid %d: %s\n",
1462 uid, strerror(errno));
1468 * The kernel should send down a zero-length grouplist already, but
1469 * just to be on the safe side...
1471 rc = setgroups(0, NULL);
1473 syslog(LOG_ERR, "setgroups: %s", strerror(errno));
1478 rc = setgid(pw->pw_gid);
1480 syslog(LOG_ERR, "setgid: %s", strerror(errno));
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.
1494 * Must do this before setuid, as we need elevated capabilities to
1495 * look at the environ file.
1498 get_cachename_from_process_env(env_probe ? arg->pid : 0);
1502 syslog(LOG_ERR, "setuid: %s", strerror(errno));
1507 rc = drop_all_capabilities();
1511 rc = krb5_init_context(&context);
1513 syslog(LOG_ERR, "unable to init krb5 context: %ld", rc);
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);
1523 host = arg->hostname;
1525 // do mech specific authorization
1530 * Andrew Bartlett's suggested scheme for picking a principal
1531 * name, based on a supplied hostname.
1536 * cifs/fooo.<guessed domain ?>@REALM
1538 * INPUT: bar.example.com
1540 * cifs/bar.example.com@REALM
1542 if (arg->sec == MS_KRB5)
1543 oid = OID_KERBEROS5_OLD;
1545 oid = OID_KERBEROS5;
1548 lowercase_string(host);
1549 rc = handle_krb5_mech(oid, host, &secblob, &sess_key, ccache);
1554 * If hostname has a '.', assume it's a FQDN, otherwise we
1555 * want to guess the domainname.
1557 if (!strchr(host, '.')) {
1558 struct addrinfo hints;
1559 struct addrinfo *ai;
1561 char fqdn[NI_MAXHOST];
1564 * use getaddrinfo() to resolve the hostname of the
1565 * server and set ai_canonname.
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);
1572 syslog(LOG_ERR, "Unable to resolve host address: %s [%s]",
1573 host, gai_strerror(rc));
1577 /* scan forward to first '.' in ai_canonnname */
1578 domainname = strchr(ai->ai_canonname, '.');
1584 lowercase_string(domainname);
1585 rc = snprintf(fqdn, sizeof(fqdn), "%s%s",
1588 if (rc < 0 || (size_t)rc >= sizeof(fqdn)) {
1589 syslog(LOG_ERR, "Problem setting hostname in string: %ld", rc);
1594 rc = handle_krb5_mech(oid, fqdn, &secblob, &sess_key, ccache);
1599 if (!try_dns || !(arg->have & DKD_HAVE_IP))
1602 rc = ip_to_fqdn(arg->ip, hostbuf, sizeof(hostbuf));
1608 goto retry_new_hostname;
1610 syslog(LOG_ERR, "sectype: %d is not implemented", arg->sec);
1616 syslog(LOG_DEBUG, "Unable to obtain service ticket");
1620 /* pack SecurityBlob and SessionKey into downcall packet */
1622 sizeof(struct cifs_spnego_msg) + secblob.length + sess_key.length;
1623 keydata = (struct cifs_spnego_msg *)calloc(sizeof(char), datalen);
1628 keydata->version = arg->ver;
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);
1636 rc = setup_key(key, keydata, datalen);
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.
1644 if (rc != 0 && key == 0) {
1645 syslog(LOG_DEBUG, "Negating key");
1646 keyctl_negate(key, 1, KEY_REQKEY_DEFL_DEFAULT);
1648 data_blob_free(&secblob);
1649 data_blob_free(&sess_key);
1651 krb5_cc_close(context, ccache);
1653 krb5_free_context(context);
1655 free(env_cachename);
1657 munmap(arg, sizeof(*arg));
1658 syslog(LOG_DEBUG, "Exit status %ld", rc);