cifs.upcall: clean up flag handling
[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
31 #include "cifs_spnego.h"
32
33 const char *CIFSSPNEGO_VERSION = "1.3";
34 static const char *prog = "cifs.upcall";
35 typedef enum _sectype {
36         NONE = 0,
37         KRB5,
38         MS_KRB5
39 } sectype_t;
40
41 /*
42  * given a process ID, get the value of the KRB5CCNAME environment variable
43  * in the context of that process. On error, just return NULL.
44  */
45 static char *
46 get_krb5_ccname(pid_t pid)
47 {
48         int fd;
49         ssize_t len, left;
50
51         /*
52          * FIXME: sysconf for ARG_MAX instead? Kernel seems to be limited to a
53          * page however, so it may not matter.
54          */
55         char buf[4096];
56         char *p, *value = NULL;
57         
58         buf[4095] = '\0';
59         snprintf(buf, 4095, "/proc/%d/environ", pid);
60         fd = open(buf, O_RDONLY);
61         if (fd < 0) {
62                 syslog(LOG_DEBUG, "%s: unable to open %s: %d", __func__, buf,
63                         errno);
64                 return NULL;
65         }
66
67         /* FIXME: don't assume that we get it all in the first read? */
68         len = read(fd, buf, 4096);
69         close(fd);
70         if (len < 0) {
71                 syslog(LOG_DEBUG, "%s: unable to read from /proc/%d/environ: "
72                                   "%d", __func__, pid, errno);
73                 return NULL;
74         }
75
76         left = len;
77         p = buf;
78
79         /* can't have valid KRB5CCNAME if there are < 13 bytes left */
80         while (left > 12) {
81                 if (strncmp("KRB5CCNAME=", p, 11)) {
82                         p += strnlen(p, left);
83                         ++p;
84                         left = buf + len - p;
85                         continue;
86                 }
87                 p += 11;
88                 left -= 11;
89                 value = SMB_STRNDUP(p, left);
90                 break;
91         }
92         syslog(LOG_DEBUG, "%s: KRB5CCNAME=%s", __func__,
93                                 value ? value : "(null)");
94         return value;
95 }
96
97 /*
98  * Prepares AP-REQ data for mechToken and gets session key
99  * Uses credentials from cache. It will not ask for password
100  * you should receive credentials for yuor name manually using
101  * kinit or whatever you wish.
102  *
103  * in:
104  *      oid -           string with OID/ Could be OID_KERBEROS5
105  *                      or OID_KERBEROS5_OLD
106  *      principal -     Service name.
107  *                      Could be "cifs/FQDN" for KRB5 OID
108  *                      or for MS_KRB5 OID style server principal
109  *                      like "pdc$@YOUR.REALM.NAME"
110  *
111  * out:
112  *      secblob -       pointer for spnego wrapped AP-REQ data to be stored
113  *      sess_key-       pointer for SessionKey data to be stored
114  *
115  * ret: 0 - success, others - failure
116  */
117 static int
118 handle_krb5_mech(const char *oid, const char *principal, DATA_BLOB *secblob,
119                  DATA_BLOB *sess_key, const char *ccname)
120 {
121         int retval;
122         DATA_BLOB tkt, tkt_wrapped;
123
124         syslog(LOG_DEBUG, "%s: getting service ticket for %s", __func__,
125                           principal);
126
127         /* get a kerberos ticket for the service and extract the session key */
128         retval = cli_krb5_get_ticket(principal, 0, &tkt, sess_key, 0, ccname,
129                                      NULL);
130
131         if (retval) {
132                 syslog(LOG_DEBUG, "%s: failed to obtain service ticket (%d)",
133                                   __func__, retval);
134                 return retval;
135         }
136
137         syslog(LOG_DEBUG, "%s: obtained service ticket", __func__);
138
139         /* wrap that up in a nice GSS-API wrapping */
140         tkt_wrapped = spnego_gen_krb5_wrap(tkt, TOK_ID_KRB_AP_REQ);
141
142         /* and wrap that in a shiny SPNEGO wrapper */
143         *secblob = gen_negTokenInit(oid, tkt_wrapped);
144
145         data_blob_free(&tkt_wrapped);
146         data_blob_free(&tkt);
147         return retval;
148 }
149
150 #define DKD_HAVE_HOSTNAME       0x1
151 #define DKD_HAVE_VERSION        0x2
152 #define DKD_HAVE_SEC            0x4
153 #define DKD_HAVE_IPV4           0x8
154 #define DKD_HAVE_IPV6           0x10
155 #define DKD_HAVE_UID            0x20
156 #define DKD_HAVE_PID            0x40
157 #define DKD_MUSTHAVE_SET (DKD_HAVE_HOSTNAME|DKD_HAVE_VERSION|DKD_HAVE_SEC)
158
159 static struct decoded_args {
160         int             ver;
161         char            *hostname;
162         uid_t           uid;
163         pid_t           pid;
164         sectype_t       sec;
165 };
166
167 static unsigned int
168 decode_key_description(const char *desc, struct decoded_args *arg)
169 {
170         int retval = 0;
171         char *pos;
172         const char *tkn = desc;
173
174         do {
175                 pos = index(tkn, ';');
176                 if (strncmp(tkn, "host=", 5) == 0) {
177                         int len;
178
179                         if (pos == NULL)
180                                 len = strlen(tkn);
181                         else
182                                 len = pos - tkn;
183
184                         len -= 4;
185                         SAFE_FREE(arg->hostname);
186                         arg->hostname = SMB_XMALLOC_ARRAY(char, len);
187                         strlcpy(arg->hostname, tkn + 5, len);
188                         retval |= DKD_HAVE_HOSTNAME;
189                 } else if (strncmp(tkn, "ipv4=", 5) == 0) {
190                         /* BB: do we need it if we have hostname already? */
191                 } else if (strncmp(tkn, "ipv6=", 5) == 0) {
192                         /* BB: do we need it if we have hostname already? */
193                 } else if (strncmp(tkn, "pid=", 4) == 0) {
194                         errno = 0;
195                         arg->pid = strtol(tkn + 4, NULL, 0);
196                         if (errno != 0) {
197                                 syslog(LOG_ERR, "Invalid pid format: %s",
198                                        strerror(errno));
199                                 return 1;
200                         } else {
201                                 retval |= DKD_HAVE_PID;
202                         }
203                 } else if (strncmp(tkn, "sec=", 4) == 0) {
204                         if (strncmp(tkn + 4, "krb5", 4) == 0) {
205                                 retval |= DKD_HAVE_SEC;
206                                 arg->sec = KRB5;
207                         } else if (strncmp(tkn + 4, "mskrb5", 6) == 0) {
208                                 retval |= DKD_HAVE_SEC;
209                                 arg->sec = MS_KRB5;
210                         }
211                 } else if (strncmp(tkn, "uid=", 4) == 0) {
212                         errno = 0;
213                         arg->uid = strtol(tkn + 4, NULL, 16);
214                         if (errno != 0) {
215                                 syslog(LOG_ERR, "Invalid uid format: %s",
216                                        strerror(errno));
217                                 return 1;
218                         } else {
219                                 retval |= DKD_HAVE_UID;
220                         }
221                 } else if (strncmp(tkn, "ver=", 4) == 0) {      /* if version */
222                         errno = 0;
223                         arg->ver = strtol(tkn + 4, NULL, 16);
224                         if (errno != 0) {
225                                 syslog(LOG_ERR, "Invalid version format: %s",
226                                        strerror(errno));
227                                 return 1;
228                         } else {
229                                 retval |= DKD_HAVE_VERSION;
230                         }
231                 }
232                 if (pos == NULL)
233                         break;
234                 tkn = pos + 1;
235         } while (tkn);
236         return retval;
237 }
238
239 static int
240 cifs_resolver(const key_serial_t key, const char *key_descr)
241 {
242         int c;
243         struct addrinfo *addr;
244         char ip[INET6_ADDRSTRLEN];
245         void *p;
246         const char *keyend = key_descr;
247         /* skip next 4 ';' delimiters to get to description */
248         for (c = 1; c <= 4; c++) {
249                 keyend = index(keyend+1, ';');
250                 if (!keyend) {
251                         syslog(LOG_ERR, "invalid key description: %s",
252                                         key_descr);
253                         return 1;
254                 }
255         }
256         keyend++;
257
258         /* resolve name to ip */
259         c = getaddrinfo(keyend, NULL, NULL, &addr);
260         if (c) {
261                 syslog(LOG_ERR, "unable to resolve hostname: %s [%s]",
262                                 keyend, gai_strerror(c));
263                 return 1;
264         }
265
266         /* conver ip to string form */
267         if (addr->ai_family == AF_INET)
268                 p = &(((struct sockaddr_in *)addr->ai_addr)->sin_addr);
269         else
270                 p = &(((struct sockaddr_in6 *)addr->ai_addr)->sin6_addr);
271
272         if (!inet_ntop(addr->ai_family, p, ip, sizeof(ip))) {
273                 syslog(LOG_ERR, "%s: inet_ntop: %s", __func__, strerror(errno));
274                 freeaddrinfo(addr);
275                 return 1;
276         }
277
278         /* setup key */
279         c = keyctl_instantiate(key, ip, strlen(ip)+1, 0);
280         if (c == -1) {
281                 syslog(LOG_ERR, "%s: keyctl_instantiate: %s", __func__,
282                                 strerror(errno));
283                 freeaddrinfo(addr);
284                 return 1;
285         }
286
287         freeaddrinfo(addr);
288         return 0;
289 }
290
291 static void
292 usage(void)
293 {
294         syslog(LOG_INFO, "Usage: %s [-v] key_serial", prog);
295         fprintf(stderr, "Usage: %s [-v] key_serial\n", prog);
296 }
297
298 int main(const int argc, char *const argv[])
299 {
300         struct cifs_spnego_msg *keydata = NULL;
301         DATA_BLOB secblob = data_blob_null;
302         DATA_BLOB sess_key = data_blob_null;
303         key_serial_t key = 0;
304         size_t datalen;
305         unsigned int have;
306         long rc = 1;
307         int c;
308         char *buf, *princ, *ccname = NULL;
309         struct decoded_args arg = { };
310         const char *oid;
311
312         openlog(prog, 0, LOG_DAEMON);
313
314         while ((c = getopt(argc, argv, "cv")) != -1) {
315                 switch (c) {
316                 case 'c':
317                         /* legacy option -- skip it */
318                         break;
319                 case 'v':
320                         printf("version: %s\n", CIFSSPNEGO_VERSION);
321                         goto out;
322                 default:
323                         syslog(LOG_ERR, "unknown option: %c", c);
324                         goto out;
325                 }
326         }
327
328         /* is there a key? */
329         if (argc <= optind) {
330                 usage();
331                 goto out;
332         }
333
334         /* get key and keyring values */
335         errno = 0;
336         key = strtol(argv[optind], NULL, 10);
337         if (errno != 0) {
338                 key = 0;
339                 syslog(LOG_ERR, "Invalid key format: %s", strerror(errno));
340                 goto out;
341         }
342
343         rc = keyctl_describe_alloc(key, &buf);
344         if (rc == -1) {
345                 syslog(LOG_ERR, "keyctl_describe_alloc failed: %s",
346                        strerror(errno));
347                 rc = 1;
348                 goto out;
349         }
350
351         syslog(LOG_DEBUG, "key description: %s", buf);
352
353         if ((strncmp(buf, "cifs.resolver", sizeof("cifs.resolver")-1) == 0) ||
354             (strncmp(buf, "dns_resolver", sizeof("dns_resolver")-1) == 0)) {
355                 rc = cifs_resolver(key, buf);
356                 goto out;
357         }
358
359         have = decode_key_description(buf, &arg);
360         SAFE_FREE(buf);
361         if ((have & DKD_MUSTHAVE_SET) != DKD_MUSTHAVE_SET) {
362                 syslog(LOG_ERR, "unable to get necessary params from key "
363                                 "description (0x%x)", have);
364                 rc = 1;
365                 goto out;
366         }
367
368         if (arg.ver > CIFS_SPNEGO_UPCALL_VERSION) {
369                 syslog(LOG_ERR, "incompatible kernel upcall version: 0x%x",
370                                 arg.ver);
371                 rc = 1;
372                 goto out;
373         }
374
375         if (have & DKD_HAVE_UID) {
376                 rc = setuid(arg.uid);
377                 if (rc == -1) {
378                         syslog(LOG_ERR, "setuid: %s", strerror(errno));
379                         goto out;
380                 }
381         }
382
383         if (have & DKD_HAVE_PID)
384                 ccname = get_krb5_ccname(arg.pid);
385
386         // do mech specific authorization
387         switch (arg.sec) {
388         case MS_KRB5:
389         case KRB5:
390                 /* for "cifs/" service name + terminating 0 */
391                 datalen = strlen(arg.hostname) + 5 + 1;
392                 princ = SMB_XMALLOC_ARRAY(char, datalen);
393                 if (!princ) {
394                         rc = 1;
395                         break;
396                 }
397
398                 if (arg.sec == MS_KRB5)
399                         oid = OID_KERBEROS5_OLD;
400                 else
401                         oid = OID_KERBEROS5;
402
403                 /*
404                  * try getting a cifs/ principal first and then fall back to
405                  * getting a host/ principal if that doesn't work.
406                  */
407                 strlcpy(princ, "cifs/", datalen);
408                 strlcpy(princ + 5, arg.hostname, datalen - 5);
409                 rc = handle_krb5_mech(oid, princ, &secblob, &sess_key, ccname);
410                 if (rc) {
411                         memcpy(princ, "host/", 5);
412                         rc = handle_krb5_mech(oid, princ, &secblob, &sess_key,
413                                                 ccname);
414                 }
415                 SAFE_FREE(princ);
416                 break;
417         default:
418                 syslog(LOG_ERR, "sectype: %d is not implemented", arg.sec);
419                 rc = 1;
420                 break;
421         }
422
423         if (rc)
424                 goto out;
425
426         /* pack SecurityBLob and SessionKey into downcall packet */
427         datalen =
428             sizeof(struct cifs_spnego_msg) + secblob.length + sess_key.length;
429         keydata = (struct cifs_spnego_msg*)SMB_XMALLOC_ARRAY(char, datalen);
430         if (!keydata) {
431                 rc = 1;
432                 goto out;
433         }
434         keydata->version = arg.ver;
435         keydata->flags = 0;
436         keydata->sesskey_len = sess_key.length;
437         keydata->secblob_len = secblob.length;
438         memcpy(&(keydata->data), sess_key.data, sess_key.length);
439         memcpy(&(keydata->data) + keydata->sesskey_len,
440                secblob.data, secblob.length);
441
442         /* setup key */
443         rc = keyctl_instantiate(key, keydata, datalen, 0);
444         if (rc == -1) {
445                 syslog(LOG_ERR, "keyctl_instantiate: %s", strerror(errno));
446                 goto out;
447         }
448
449         /* BB: maybe we need use timeout for key: for example no more then
450          * ticket lifietime? */
451         /* keyctl_set_timeout( key, 60); */
452 out:
453         /*
454          * on error, negatively instantiate the key ourselves so that we can
455          * make sure the kernel doesn't hang it off of a searchable keyring
456          * and interfere with the next attempt to instantiate the key.
457          */
458         if (rc != 0  && key == 0)
459                 keyctl_negate(key, 1, KEY_REQKEY_DEFL_DEFAULT);
460         data_blob_free(&secblob);
461         data_blob_free(&sess_key);
462         SAFE_FREE(ccname);
463         SAFE_FREE(arg.hostname);
464         SAFE_FREE(keydata);
465         return rc;
466 }