Remove __contains__ from mock object for consistency with actual
[samba.git] / client / cifs.upcall.c
index 904ec8e1c1c35ad8d67456b0ca2b6fe53e2d6ae4..42632a0da09308ebc1f54256932b489626253c18 100644 (file)
@@ -26,10 +26,18 @@ create dns_resolver * * /usr/local/sbin/cifs.upcall %k
 */
 
 #include "includes.h"
+#include "../libcli/auth/spnego.h"
+#include "smb_krb5.h"
 #include <keyutils.h>
+#include <getopt.h>
 
 #include "cifs_spnego.h"
 
+#define        CIFS_DEFAULT_KRB5_DIR           "/tmp"
+#define        CIFS_DEFAULT_KRB5_PREFIX        "krb5cc_"
+
+#define        MAX_CCNAME_LEN                  PATH_MAX + 5
+
 const char *CIFSSPNEGO_VERSION = "1.3";
 static const char *prog = "cifs.upcall";
 typedef enum _sectype {
@@ -38,60 +46,151 @@ typedef enum _sectype {
        MS_KRB5
 } sectype_t;
 
-/*
- * given a process ID, get the value of the KRB5CCNAME environment variable
- * in the context of that process. On error, just return NULL.
- */
-static char *
-get_krb5_ccname(pid_t pid)
-{
-       int fd;
-       ssize_t len, left;
+/* does the ccache have a valid TGT? */
+static time_t
+get_tgt_time(const char *ccname) {
+       krb5_context context;
+       krb5_ccache ccache;
+       krb5_cc_cursor cur;
+       krb5_creds creds;
+       krb5_principal principal;
+       time_t credtime = 0;
+       char *realm = NULL;
+       TALLOC_CTX *mem_ctx;
+
+       if (krb5_init_context(&context)) {
+               syslog(LOG_DEBUG, "%s: unable to init krb5 context", __func__);
+               return 0;
+       }
 
-       /*
-        * FIXME: sysconf for ARG_MAX instead? Kernel seems to be limited to a
-        * page however, so it may not matter.
-        */
-       char buf[4096];
-       char *p, *value = NULL;
-       
-       buf[4095] = '\0';
-       snprintf(buf, 4095, "/proc/%d/environ", pid);
-       fd = open(buf, O_RDONLY);
-       if (fd < 0) {
-               syslog(LOG_DEBUG, "%s: unable to open %s: %d", __func__, buf,
-                       errno);
-               return NULL;
+       if (krb5_cc_resolve(context, ccname, &ccache)) {
+               syslog(LOG_DEBUG, "%s: unable to resolve krb5 cache", __func__);
+               goto err_cache;
        }
 
-       /* FIXME: don't assume that we get it all in the first read? */
-       len = read(fd, buf, 4096);
-       close(fd);
-       if (len < 0) {
-               syslog(LOG_DEBUG, "%s: unable to read from /proc/%d/environ: "
-                                 "%d", __func__, pid, errno);
+       if (krb5_cc_set_flags(context, ccache, 0)) {
+               syslog(LOG_DEBUG, "%s: unable to set flags", __func__);
+               goto err_cache;
+       }
+
+       if (krb5_cc_get_principal(context, ccache, &principal)) {
+               syslog(LOG_DEBUG, "%s: unable to get principal", __func__);
+               goto err_princ;
+       }
+
+       if (krb5_cc_start_seq_get(context, ccache, &cur)) {
+               syslog(LOG_DEBUG, "%s: unable to seq start", __func__);
+               goto err_ccstart;
+       }
+
+       if ((realm = smb_krb5_principal_get_realm(context, principal)) == NULL) {
+               syslog(LOG_DEBUG, "%s: unable to get realm", __func__);
+               goto err_ccstart;
+       }
+
+       mem_ctx = talloc_init("cifs.upcall");
+       while (!credtime && !krb5_cc_next_cred(context, ccache, &cur, &creds)) {
+               char *name;
+               if (smb_krb5_unparse_name(mem_ctx, context, creds.server, &name)) {
+                       syslog(LOG_DEBUG, "%s: unable to unparse name", __func__);
+                       goto err_endseq;
+               }
+               if (krb5_realm_compare(context, creds.server, principal) &&
+                   strnequal(name, KRB5_TGS_NAME, KRB5_TGS_NAME_SIZE) &&
+                   strnequal(name+KRB5_TGS_NAME_SIZE+1, realm, strlen(realm)) &&
+                   creds.times.endtime > time(NULL))
+                       credtime = creds.times.endtime;
+                krb5_free_cred_contents(context, &creds);
+               TALLOC_FREE(name);
+        }
+err_endseq:
+       TALLOC_FREE(mem_ctx);
+        krb5_cc_end_seq_get(context, ccache, &cur);
+err_ccstart:
+       krb5_free_principal(context, principal);
+err_princ:
+#if defined(KRB5_TC_OPENCLOSE)
+       krb5_cc_set_flags(context, ccache, KRB5_TC_OPENCLOSE);
+#endif
+       krb5_cc_close(context, ccache);
+err_cache:
+       krb5_free_context(context);
+       return credtime;
+}
+
+static int
+krb5cc_filter(const struct dirent *dirent)
+{
+       if (strstr(dirent->d_name, CIFS_DEFAULT_KRB5_PREFIX))
+               return 1;
+       else
+               return 0;
+}
+
+/* search for a credcache that looks like a likely candidate */
+static char *
+find_krb5_cc(const char *dirname, uid_t uid)
+{
+       struct dirent **namelist;
+       struct stat sbuf;
+       char ccname[MAX_CCNAME_LEN], *credpath, *best_cache = NULL;
+       int i, n;
+       time_t cred_time, best_time = 0;
+
+       n = scandir(dirname, &namelist, krb5cc_filter, NULL);
+       if (n < 0) {
+               syslog(LOG_DEBUG, "%s: scandir error on directory '%s': %s",
+                                 __func__, dirname, strerror(errno));
                return NULL;
        }
 
-       left = len;
-       p = buf;
+       for (i = 0; i < n; i++) {
+               snprintf(ccname, sizeof(ccname), "FILE:%s/%s", dirname,
+                        namelist[i]->d_name);
+               credpath = ccname + 5;
+               syslog(LOG_DEBUG, "%s: considering %s", __func__, credpath);
 
-       /* can't have valid KRB5CCNAME if there are < 13 bytes left */
-       while (left > 12) {
-               if (strncmp("KRB5CCNAME=", p, 11)) {
-                       p += strnlen(p, left);
-                       ++p;
-                       left = buf + len - p;
+               if (lstat(credpath, &sbuf)) {
+                       syslog(LOG_DEBUG, "%s: stat error on '%s': %s",
+                                         __func__, credpath, strerror(errno));
+                       free(namelist[i]);
                        continue;
                }
-               p += 11;
-               left -= 11;
-               value = SMB_STRNDUP(p, left);
-               break;
+               if (sbuf.st_uid != uid) {
+                       syslog(LOG_DEBUG, "%s: %s is owned by %u, not %u",
+                                       __func__, credpath, sbuf.st_uid, uid);
+                       free(namelist[i]);
+                       continue;
+               }
+               if (!S_ISREG(sbuf.st_mode)) {
+                       syslog(LOG_DEBUG, "%s: %s is not a regular file",
+                                       __func__, credpath);
+                       free(namelist[i]);
+                       continue;
+               }
+               if (!(cred_time = get_tgt_time(ccname))) {
+                       syslog(LOG_DEBUG, "%s: %s is not a valid credcache.",
+                                       __func__, ccname);
+                       free(namelist[i]);
+                       continue;
+               }
+
+               if (cred_time <= best_time) {
+                       syslog(LOG_DEBUG, "%s: %s expires sooner than current "
+                                         "best.", __func__, ccname);
+                       free(namelist[i]);
+                       continue;
+               }
+
+               syslog(LOG_DEBUG, "%s: %s is valid ccache", __func__, ccname);
+               free(best_cache);
+               best_cache = SMB_STRNDUP(ccname, MAX_CCNAME_LEN);
+               best_time = cred_time;
+               free(namelist[i]);
        }
-       syslog(LOG_DEBUG, "%s: KRB5CCNAME=%s", __func__,
-                               value ? value : "(null)");
-       return value;
+       free(namelist);
+
+       return best_cache;
 }
 
 /*
@@ -126,7 +225,7 @@ handle_krb5_mech(const char *oid, const char *principal, DATA_BLOB *secblob,
 
        /* get a kerberos ticket for the service and extract the session key */
        retval = cli_krb5_get_ticket(principal, 0, &tkt, sess_key, 0, ccname,
-                                    NULL);
+                                    NULL, NULL);
 
        if (retval) {
                syslog(LOG_DEBUG, "%s: failed to obtain service ticket (%d)",
@@ -150,15 +249,15 @@ handle_krb5_mech(const char *oid, const char *principal, DATA_BLOB *secblob,
 #define DKD_HAVE_HOSTNAME      0x1
 #define DKD_HAVE_VERSION       0x2
 #define DKD_HAVE_SEC           0x4
-#define DKD_HAVE_IPV4          0x8
-#define DKD_HAVE_IPV6          0x10
-#define DKD_HAVE_UID           0x20
-#define DKD_HAVE_PID           0x40
+#define DKD_HAVE_IP            0x8
+#define DKD_HAVE_UID           0x10
+#define DKD_HAVE_PID           0x20
 #define DKD_MUSTHAVE_SET (DKD_HAVE_HOSTNAME|DKD_HAVE_VERSION|DKD_HAVE_SEC)
 
-static struct decoded_args {
+struct decoded_args {
        int             ver;
        char            *hostname;
+       char            *ip;
        uid_t           uid;
        pid_t           pid;
        sectype_t       sec;
@@ -167,6 +266,7 @@ static struct decoded_args {
 static unsigned int
 decode_key_description(const char *desc, struct decoded_args *arg)
 {
+       int len;
        int retval = 0;
        char *pos;
        const char *tkn = desc;
@@ -174,7 +274,6 @@ decode_key_description(const char *desc, struct decoded_args *arg)
        do {
                pos = index(tkn, ';');
                if (strncmp(tkn, "host=", 5) == 0) {
-                       int len;
 
                        if (pos == NULL)
                                len = strlen(tkn);
@@ -186,10 +285,18 @@ decode_key_description(const char *desc, struct decoded_args *arg)
                        arg->hostname = SMB_XMALLOC_ARRAY(char, len);
                        strlcpy(arg->hostname, tkn + 5, len);
                        retval |= DKD_HAVE_HOSTNAME;
-               } else if (strncmp(tkn, "ipv4=", 5) == 0) {
-                       /* BB: do we need it if we have hostname already? */
-               } else if (strncmp(tkn, "ipv6=", 5) == 0) {
-                       /* BB: do we need it if we have hostname already? */
+               } else if (!strncmp(tkn, "ip4=", 4) ||
+                          !strncmp(tkn, "ip6=", 4)) {
+                       if (pos == NULL)
+                               len = strlen(tkn);
+                       else
+                               len = pos - tkn;
+
+                       len -= 3;
+                       SAFE_FREE(arg->ip);
+                       arg->ip = SMB_XMALLOC_ARRAY(char, len);
+                       strlcpy(arg->ip, tkn + 4, len);
+                       retval |= DKD_HAVE_IP;
                } else if (strncmp(tkn, "pid=", 4) == 0) {
                        errno = 0;
                        arg->pid = strtol(tkn + 4, NULL, 0);
@@ -288,13 +395,73 @@ cifs_resolver(const key_serial_t key, const char *key_descr)
        return 0;
 }
 
+/*
+ * Older kernels sent IPv6 addresses without colons. Well, at least
+ * they're fixed-length strings. Convert these addresses to have colon
+ * delimiters to make getaddrinfo happy.
+ */
+static void
+convert_inet6_addr(const char *from, char *to)
+{
+       int i = 1;
+
+       while (*from) {
+               *to++ = *from++;
+               if (!(i++ % 4) && *from)
+                       *to++ = ':';
+       }
+       *to = 0;
+}
+
+static int
+ip_to_fqdn(const char *addrstr, char *host, size_t hostlen)
+{
+       int rc;
+       struct addrinfo hints = { .ai_flags = AI_NUMERICHOST };
+       struct addrinfo *res;
+       const char *ipaddr = addrstr;
+       char converted[INET6_ADDRSTRLEN + 1];
+
+       if ((strlen(ipaddr) > INET_ADDRSTRLEN) && !strchr(ipaddr, ':')) {
+               convert_inet6_addr(ipaddr, converted);
+               ipaddr = converted;
+       }
+
+       rc = getaddrinfo(ipaddr, NULL, &hints, &res);
+       if (rc) {
+               syslog(LOG_DEBUG, "%s: failed to resolve %s to "
+                       "ipaddr: %s", __func__, ipaddr,
+               rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
+               return rc;
+       }
+
+       rc = getnameinfo(res->ai_addr, res->ai_addrlen, host, hostlen,
+                        NULL, 0, NI_NAMEREQD);
+       freeaddrinfo(res);
+       if (rc) {
+               syslog(LOG_DEBUG, "%s: failed to resolve %s to fqdn: %s",
+                       __func__, ipaddr,
+                       rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
+               return rc;
+       }
+
+       syslog(LOG_DEBUG, "%s: resolved %s to %s", __func__, ipaddr, host);
+       return 0;
+}
+
 static void
 usage(void)
 {
-       syslog(LOG_INFO, "Usage: %s [-v] key_serial", prog);
-       fprintf(stderr, "Usage: %s [-v] key_serial\n", prog);
+       syslog(LOG_INFO, "Usage: %s [-t] [-v] key_serial", prog);
+       fprintf(stderr, "Usage: %s [-t] [-v] key_serial\n", prog);
 }
 
+const struct option long_options[] = {
+       { "trust-dns",  0, NULL, 't' },
+       { "version",    0, NULL, 'v' },
+       { NULL,         0, NULL, 0 }
+};
+
 int main(const int argc, char *const argv[])
 {
        struct cifs_spnego_msg *keydata = NULL;
@@ -304,18 +471,24 @@ int main(const int argc, char *const argv[])
        size_t datalen;
        unsigned int have;
        long rc = 1;
-       int c;
-       char *buf, *princ, *ccname = NULL;
+       int c, try_dns = 0;
+       char *buf, *princ = NULL, *ccname = NULL;
+       char hostbuf[NI_MAXHOST], *host;
        struct decoded_args arg = { };
        const char *oid;
 
+       hostbuf[0] = '\0';
+
        openlog(prog, 0, LOG_DAEMON);
 
-       while ((c = getopt(argc, argv, "cv")) != -1) {
+       while ((c = getopt_long(argc, argv, "ctv", long_options, NULL)) != -1) {
                switch (c) {
                case 'c':
                        /* legacy option -- skip it */
                        break;
+               case 't':
+                       try_dns++;
+                       break;
                case 'v':
                        printf("version: %s\n", CIFSSPNEGO_VERSION);
                        goto out;
@@ -378,20 +551,22 @@ int main(const int argc, char *const argv[])
                        syslog(LOG_ERR, "setuid: %s", strerror(errno));
                        goto out;
                }
+
+               ccname = find_krb5_cc(CIFS_DEFAULT_KRB5_DIR, arg.uid);
        }
 
-       if (have & DKD_HAVE_PID)
-               ccname = get_krb5_ccname(arg.pid);
+       host = arg.hostname;
 
        // do mech specific authorization
        switch (arg.sec) {
        case MS_KRB5:
        case KRB5:
+retry_new_hostname:
                /* for "cifs/" service name + terminating 0 */
-               datalen = strlen(arg.hostname) + 5 + 1;
+               datalen = strlen(host) + 5 + 1;
                princ = SMB_XMALLOC_ARRAY(char, datalen);
                if (!princ) {
-                       rc = 1;
+                       rc = -ENOMEM;
                        break;
                }
 
@@ -405,21 +580,35 @@ int main(const int argc, char *const argv[])
                 * getting a host/ principal if that doesn't work.
                 */
                strlcpy(princ, "cifs/", datalen);
-               strlcpy(princ + 5, arg.hostname, datalen - 5);
+               strlcpy(princ + 5, host, datalen - 5);
                rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
-               if (rc) {
-                       memcpy(princ, "host/", 5);
-                       rc = handle_krb5_mech(oid, princ, &secblob, &sess_key,
-                                               ccname);
-               }
+               if (!rc)
+                       break;
+
+               memcpy(princ, "host/", 5);
+               rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
+               if (!rc)
+                       break;
+
+               if (!try_dns || !(have & DKD_HAVE_IP))
+                       break;
+
+               rc = ip_to_fqdn(arg.ip, hostbuf, sizeof(hostbuf));
+               if (rc)
+                       break;
+
                SAFE_FREE(princ);
-               break;
+               try_dns = 0;
+               host = hostbuf;
+               goto retry_new_hostname;
        default:
                syslog(LOG_ERR, "sectype: %d is not implemented", arg.sec);
                rc = 1;
                break;
        }
 
+       SAFE_FREE(princ);
+
        if (rc)
                goto out;
 
@@ -461,6 +650,7 @@ out:
        data_blob_free(&sess_key);
        SAFE_FREE(ccname);
        SAFE_FREE(arg.hostname);
+       SAFE_FREE(arg.ip);
        SAFE_FREE(keydata);
        return rc;
 }