1645322297af503c7268f5720da7ecc220b264b0
[samba.git] / client / cifs.upcall.c
1 /*
2 * CIFS user-space helper.
3 * Copyright (C) Igor Mammedov (niallain@gmail.com) 2007
4 * Copyright (C) Jeff Layton (jlayton@redhat.com) 2009
5 *
6 * Used by /sbin/request-key for handling
7 * cifs upcall for kerberos authorization of access to share and
8 * cifs upcall for DFS srver name resolving (IPv4/IPv6 aware).
9 * You should have keyutils installed and add something like the
10 * following lines to /etc/request-key.conf file:
11
12 create cifs.spnego * * /usr/local/sbin/cifs.upcall %k
13 create dns_resolver * * /usr/local/sbin/cifs.upcall %k
14
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 2 of the License, or
18 * (at your option) any later version.
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program; if not, write to the Free Software
25 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 */
27
28 #include "includes.h"
29 #include <keyutils.h>
30 #include <getopt.h>
31
32 #include "cifs_spnego.h"
33
34 const char *CIFSSPNEGO_VERSION = "1.3";
35 static const char *prog = "cifs.upcall";
36 typedef enum _sectype {
37         NONE = 0,
38         KRB5,
39         MS_KRB5
40 } sectype_t;
41
42 /*
43  * given a process ID, get the value of the KRB5CCNAME environment variable
44  * in the context of that process. On error, just return NULL.
45  */
46 static char *
47 get_krb5_ccname(pid_t pid)
48 {
49         int fd;
50         ssize_t len, left;
51
52         /*
53          * FIXME: sysconf for ARG_MAX instead? Kernel seems to be limited to a
54          * page however, so it may not matter.
55          */
56         char buf[4096];
57         char *p, *value = NULL;
58         
59         buf[4095] = '\0';
60         snprintf(buf, 4095, "/proc/%d/environ", pid);
61         fd = open(buf, O_RDONLY);
62         if (fd < 0) {
63                 syslog(LOG_DEBUG, "%s: unable to open %s: %d", __func__, buf,
64                         errno);
65                 return NULL;
66         }
67
68         /* FIXME: don't assume that we get it all in the first read? */
69         len = read(fd, buf, 4096);
70         close(fd);
71         if (len < 0) {
72                 syslog(LOG_DEBUG, "%s: unable to read from /proc/%d/environ: "
73                                   "%d", __func__, pid, errno);
74                 return NULL;
75         }
76
77         left = len;
78         p = buf;
79
80         /* can't have valid KRB5CCNAME if there are < 13 bytes left */
81         while (left > 12) {
82                 if (strncmp("KRB5CCNAME=", p, 11)) {
83                         p += strnlen(p, left);
84                         ++p;
85                         left = buf + len - p;
86                         continue;
87                 }
88                 p += 11;
89                 left -= 11;
90                 value = SMB_STRNDUP(p, left);
91                 break;
92         }
93         syslog(LOG_DEBUG, "%s: KRB5CCNAME=%s", __func__,
94                                 value ? value : "(null)");
95         return value;
96 }
97
98 /*
99  * Prepares AP-REQ data for mechToken and gets session key
100  * Uses credentials from cache. It will not ask for password
101  * you should receive credentials for yuor name manually using
102  * kinit or whatever you wish.
103  *
104  * in:
105  *      oid -           string with OID/ Could be OID_KERBEROS5
106  *                      or OID_KERBEROS5_OLD
107  *      principal -     Service name.
108  *                      Could be "cifs/FQDN" for KRB5 OID
109  *                      or for MS_KRB5 OID style server principal
110  *                      like "pdc$@YOUR.REALM.NAME"
111  *
112  * out:
113  *      secblob -       pointer for spnego wrapped AP-REQ data to be stored
114  *      sess_key-       pointer for SessionKey data to be stored
115  *
116  * ret: 0 - success, others - failure
117  */
118 static int
119 handle_krb5_mech(const char *oid, const char *principal, DATA_BLOB *secblob,
120                  DATA_BLOB *sess_key, const char *ccname)
121 {
122         int retval;
123         DATA_BLOB tkt, tkt_wrapped;
124
125         syslog(LOG_DEBUG, "%s: getting service ticket for %s", __func__,
126                           principal);
127
128         /* get a kerberos ticket for the service and extract the session key */
129         retval = cli_krb5_get_ticket(principal, 0, &tkt, sess_key, 0, ccname,
130                                      NULL);
131
132         if (retval) {
133                 syslog(LOG_DEBUG, "%s: failed to obtain service ticket (%d)",
134                                   __func__, retval);
135                 return retval;
136         }
137
138         syslog(LOG_DEBUG, "%s: obtained service ticket", __func__);
139
140         /* wrap that up in a nice GSS-API wrapping */
141         tkt_wrapped = spnego_gen_krb5_wrap(tkt, TOK_ID_KRB_AP_REQ);
142
143         /* and wrap that in a shiny SPNEGO wrapper */
144         *secblob = gen_negTokenInit(oid, tkt_wrapped);
145
146         data_blob_free(&tkt_wrapped);
147         data_blob_free(&tkt);
148         return retval;
149 }
150
151 #define DKD_HAVE_HOSTNAME       0x1
152 #define DKD_HAVE_VERSION        0x2
153 #define DKD_HAVE_SEC            0x4
154 #define DKD_HAVE_IP             0x8
155 #define DKD_HAVE_UID            0x10
156 #define DKD_HAVE_PID            0x20
157 #define DKD_MUSTHAVE_SET (DKD_HAVE_HOSTNAME|DKD_HAVE_VERSION|DKD_HAVE_SEC)
158
159 struct decoded_args {
160         int             ver;
161         char            *hostname;
162         char            *ip;
163         uid_t           uid;
164         pid_t           pid;
165         sectype_t       sec;
166 };
167
168 static unsigned int
169 decode_key_description(const char *desc, struct decoded_args *arg)
170 {
171         int len;
172         int retval = 0;
173         char *pos;
174         const char *tkn = desc;
175
176         do {
177                 pos = index(tkn, ';');
178                 if (strncmp(tkn, "host=", 5) == 0) {
179
180                         if (pos == NULL)
181                                 len = strlen(tkn);
182                         else
183                                 len = pos - tkn;
184
185                         len -= 4;
186                         SAFE_FREE(arg->hostname);
187                         arg->hostname = SMB_XMALLOC_ARRAY(char, len);
188                         strlcpy(arg->hostname, tkn + 5, len);
189                         retval |= DKD_HAVE_HOSTNAME;
190                 } else if (!strncmp(tkn, "ip4=", 4) ||
191                            !strncmp(tkn, "ip6=", 4)) {
192                         if (pos == NULL)
193                                 len = strlen(tkn);
194                         else
195                                 len = pos - tkn;
196
197                         len -= 3;
198                         SAFE_FREE(arg->ip);
199                         arg->ip = SMB_XMALLOC_ARRAY(char, len);
200                         strlcpy(arg->ip, tkn + 4, len);
201                         retval |= DKD_HAVE_IP;
202                 } else if (strncmp(tkn, "pid=", 4) == 0) {
203                         errno = 0;
204                         arg->pid = strtol(tkn + 4, NULL, 0);
205                         if (errno != 0) {
206                                 syslog(LOG_ERR, "Invalid pid format: %s",
207                                        strerror(errno));
208                                 return 1;
209                         } else {
210                                 retval |= DKD_HAVE_PID;
211                         }
212                 } else if (strncmp(tkn, "sec=", 4) == 0) {
213                         if (strncmp(tkn + 4, "krb5", 4) == 0) {
214                                 retval |= DKD_HAVE_SEC;
215                                 arg->sec = KRB5;
216                         } else if (strncmp(tkn + 4, "mskrb5", 6) == 0) {
217                                 retval |= DKD_HAVE_SEC;
218                                 arg->sec = MS_KRB5;
219                         }
220                 } else if (strncmp(tkn, "uid=", 4) == 0) {
221                         errno = 0;
222                         arg->uid = strtol(tkn + 4, NULL, 16);
223                         if (errno != 0) {
224                                 syslog(LOG_ERR, "Invalid uid format: %s",
225                                        strerror(errno));
226                                 return 1;
227                         } else {
228                                 retval |= DKD_HAVE_UID;
229                         }
230                 } else if (strncmp(tkn, "ver=", 4) == 0) {      /* if version */
231                         errno = 0;
232                         arg->ver = strtol(tkn + 4, NULL, 16);
233                         if (errno != 0) {
234                                 syslog(LOG_ERR, "Invalid version format: %s",
235                                        strerror(errno));
236                                 return 1;
237                         } else {
238                                 retval |= DKD_HAVE_VERSION;
239                         }
240                 }
241                 if (pos == NULL)
242                         break;
243                 tkn = pos + 1;
244         } while (tkn);
245         return retval;
246 }
247
248 static int
249 cifs_resolver(const key_serial_t key, const char *key_descr)
250 {
251         int c;
252         struct addrinfo *addr;
253         char ip[INET6_ADDRSTRLEN];
254         void *p;
255         const char *keyend = key_descr;
256         /* skip next 4 ';' delimiters to get to description */
257         for (c = 1; c <= 4; c++) {
258                 keyend = index(keyend+1, ';');
259                 if (!keyend) {
260                         syslog(LOG_ERR, "invalid key description: %s",
261                                         key_descr);
262                         return 1;
263                 }
264         }
265         keyend++;
266
267         /* resolve name to ip */
268         c = getaddrinfo(keyend, NULL, NULL, &addr);
269         if (c) {
270                 syslog(LOG_ERR, "unable to resolve hostname: %s [%s]",
271                                 keyend, gai_strerror(c));
272                 return 1;
273         }
274
275         /* conver ip to string form */
276         if (addr->ai_family == AF_INET)
277                 p = &(((struct sockaddr_in *)addr->ai_addr)->sin_addr);
278         else
279                 p = &(((struct sockaddr_in6 *)addr->ai_addr)->sin6_addr);
280
281         if (!inet_ntop(addr->ai_family, p, ip, sizeof(ip))) {
282                 syslog(LOG_ERR, "%s: inet_ntop: %s", __func__, strerror(errno));
283                 freeaddrinfo(addr);
284                 return 1;
285         }
286
287         /* setup key */
288         c = keyctl_instantiate(key, ip, strlen(ip)+1, 0);
289         if (c == -1) {
290                 syslog(LOG_ERR, "%s: keyctl_instantiate: %s", __func__,
291                                 strerror(errno));
292                 freeaddrinfo(addr);
293                 return 1;
294         }
295
296         freeaddrinfo(addr);
297         return 0;
298 }
299
300 /*
301  * Older kernels sent IPv6 addresses without colons. Well, at least
302  * they're fixed-length strings. Convert these addresses to have colon
303  * delimiters to make getaddrinfo happy.
304  */
305 static void
306 convert_inet6_addr(const char *from, char *to)
307 {
308         int i = 1;
309
310         while (*from) {
311                 *to++ = *from++;
312                 if (!(i++ % 4) && *from)
313                         *to++ = ':';
314         }
315         *to = 0;
316 }
317
318 static int
319 ip_to_fqdn(const char *addrstr, char *host, size_t hostlen)
320 {
321         int rc;
322         struct addrinfo hints = { .ai_flags = AI_NUMERICHOST };
323         struct addrinfo *res;
324         const char *ipaddr = addrstr;
325         char converted[INET6_ADDRSTRLEN + 1];
326
327         if ((strlen(ipaddr) > INET_ADDRSTRLEN) && !strchr(ipaddr, ':')) {
328                 convert_inet6_addr(ipaddr, converted);
329                 ipaddr = converted;
330         }
331
332         rc = getaddrinfo(ipaddr, NULL, &hints, &res);
333         if (rc) {
334                 syslog(LOG_DEBUG, "%s: failed to resolve %s to "
335                         "ipaddr: %s", __func__, ipaddr,
336                 rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
337                 return rc;
338         }
339
340         rc = getnameinfo(res->ai_addr, res->ai_addrlen, host, hostlen,
341                          NULL, 0, NI_NAMEREQD);
342         freeaddrinfo(res);
343         if (rc) {
344                 syslog(LOG_DEBUG, "%s: failed to resolve %s to fqdn: %s",
345                         __func__, ipaddr,
346                         rc == EAI_SYSTEM ? strerror(errno) : gai_strerror(rc));
347                 return rc;
348         }
349
350         syslog(LOG_DEBUG, "%s: resolved %s to %s", __func__, ipaddr, host);
351         return 0;
352 }
353
354 static void
355 usage(void)
356 {
357         syslog(LOG_INFO, "Usage: %s [-t] [-v] key_serial", prog);
358         fprintf(stderr, "Usage: %s [-t] [-v] key_serial\n", prog);
359 }
360
361 const struct option long_options[] = {
362         { "trust-dns",  0, NULL, 't' },
363         { "version",    0, NULL, 'v' },
364         { NULL,         0, NULL, 0 }
365 };
366
367 int main(const int argc, char *const argv[])
368 {
369         struct cifs_spnego_msg *keydata = NULL;
370         DATA_BLOB secblob = data_blob_null;
371         DATA_BLOB sess_key = data_blob_null;
372         key_serial_t key = 0;
373         size_t datalen;
374         unsigned int have;
375         long rc = 1;
376         int c, try_dns = 0;
377         char *buf, *princ = NULL, *ccname = NULL;
378         char hostbuf[NI_MAXHOST], *host;
379         struct decoded_args arg = { };
380         const char *oid;
381
382         hostbuf[0] = '\0';
383
384         openlog(prog, 0, LOG_DAEMON);
385
386         while ((c = getopt_long(argc, argv, "ctv", long_options, NULL)) != -1) {
387                 switch (c) {
388                 case 'c':
389                         /* legacy option -- skip it */
390                         break;
391                 case 't':
392                         try_dns++;
393                         break;
394                 case 'v':
395                         printf("version: %s\n", CIFSSPNEGO_VERSION);
396                         goto out;
397                 default:
398                         syslog(LOG_ERR, "unknown option: %c", c);
399                         goto out;
400                 }
401         }
402
403         /* is there a key? */
404         if (argc <= optind) {
405                 usage();
406                 goto out;
407         }
408
409         /* get key and keyring values */
410         errno = 0;
411         key = strtol(argv[optind], NULL, 10);
412         if (errno != 0) {
413                 key = 0;
414                 syslog(LOG_ERR, "Invalid key format: %s", strerror(errno));
415                 goto out;
416         }
417
418         rc = keyctl_describe_alloc(key, &buf);
419         if (rc == -1) {
420                 syslog(LOG_ERR, "keyctl_describe_alloc failed: %s",
421                        strerror(errno));
422                 rc = 1;
423                 goto out;
424         }
425
426         syslog(LOG_DEBUG, "key description: %s", buf);
427
428         if ((strncmp(buf, "cifs.resolver", sizeof("cifs.resolver")-1) == 0) ||
429             (strncmp(buf, "dns_resolver", sizeof("dns_resolver")-1) == 0)) {
430                 rc = cifs_resolver(key, buf);
431                 goto out;
432         }
433
434         have = decode_key_description(buf, &arg);
435         SAFE_FREE(buf);
436         if ((have & DKD_MUSTHAVE_SET) != DKD_MUSTHAVE_SET) {
437                 syslog(LOG_ERR, "unable to get necessary params from key "
438                                 "description (0x%x)", have);
439                 rc = 1;
440                 goto out;
441         }
442
443         if (arg.ver > CIFS_SPNEGO_UPCALL_VERSION) {
444                 syslog(LOG_ERR, "incompatible kernel upcall version: 0x%x",
445                                 arg.ver);
446                 rc = 1;
447                 goto out;
448         }
449
450         if (have & DKD_HAVE_UID) {
451                 rc = setuid(arg.uid);
452                 if (rc == -1) {
453                         syslog(LOG_ERR, "setuid: %s", strerror(errno));
454                         goto out;
455                 }
456         }
457
458         if (have & DKD_HAVE_PID)
459                 ccname = get_krb5_ccname(arg.pid);
460
461         host = arg.hostname;
462
463         // do mech specific authorization
464         switch (arg.sec) {
465         case MS_KRB5:
466         case KRB5:
467 retry_new_hostname:
468                 /* for "cifs/" service name + terminating 0 */
469                 datalen = strlen(host) + 5 + 1;
470                 princ = SMB_XMALLOC_ARRAY(char, datalen);
471                 if (!princ) {
472                         rc = -ENOMEM;
473                         break;
474                 }
475
476                 if (arg.sec == MS_KRB5)
477                         oid = OID_KERBEROS5_OLD;
478                 else
479                         oid = OID_KERBEROS5;
480
481                 /*
482                  * try getting a cifs/ principal first and then fall back to
483                  * getting a host/ principal if that doesn't work.
484                  */
485                 strlcpy(princ, "cifs/", datalen);
486                 strlcpy(princ + 5, host, datalen - 5);
487                 rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
488                 if (!rc)
489                         break;
490
491                 memcpy(princ, "host/", 5);
492                 rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
493                 if (!rc)
494                         break;
495
496                 if (!try_dns || !(have & DKD_HAVE_IP))
497                         break;
498
499                 rc = ip_to_fqdn(arg.ip, hostbuf, sizeof(hostbuf));
500                 if (rc)
501                         break;
502
503                 SAFE_FREE(princ);
504                 try_dns = 0;
505                 host = hostbuf;
506                 goto retry_new_hostname;
507         default:
508                 syslog(LOG_ERR, "sectype: %d is not implemented", arg.sec);
509                 rc = 1;
510                 break;
511         }
512
513         SAFE_FREE(princ);
514
515         if (rc)
516                 goto out;
517
518         /* pack SecurityBLob and SessionKey into downcall packet */
519         datalen =
520             sizeof(struct cifs_spnego_msg) + secblob.length + sess_key.length;
521         keydata = (struct cifs_spnego_msg*)SMB_XMALLOC_ARRAY(char, datalen);
522         if (!keydata) {
523                 rc = 1;
524                 goto out;
525         }
526         keydata->version = arg.ver;
527         keydata->flags = 0;
528         keydata->sesskey_len = sess_key.length;
529         keydata->secblob_len = secblob.length;
530         memcpy(&(keydata->data), sess_key.data, sess_key.length);
531         memcpy(&(keydata->data) + keydata->sesskey_len,
532                secblob.data, secblob.length);
533
534         /* setup key */
535         rc = keyctl_instantiate(key, keydata, datalen, 0);
536         if (rc == -1) {
537                 syslog(LOG_ERR, "keyctl_instantiate: %s", strerror(errno));
538                 goto out;
539         }
540
541         /* BB: maybe we need use timeout for key: for example no more then
542          * ticket lifietime? */
543         /* keyctl_set_timeout( key, 60); */
544 out:
545         /*
546          * on error, negatively instantiate the key ourselves so that we can
547          * make sure the kernel doesn't hang it off of a searchable keyring
548          * and interfere with the next attempt to instantiate the key.
549          */
550         if (rc != 0  && key == 0)
551                 keyctl_negate(key, 1, KEY_REQKEY_DEFL_DEFAULT);
552         data_blob_free(&secblob);
553         data_blob_free(&sess_key);
554         SAFE_FREE(ccname);
555         SAFE_FREE(arg.hostname);
556         SAFE_FREE(arg.ip);
557         SAFE_FREE(keydata);
558         return rc;
559 }