Annotation of src/usr.bin/ssh/auth2-pubkey.c, Revision 1.58
1.58 ! djm 1: /* $OpenBSD: auth2-pubkey.c,v 1.57 2016/09/14 20:11:26 djm Exp $ */
1.1 markus 2: /*
3: * Copyright (c) 2000 Markus Friedl. All rights reserved.
4: *
5: * Redistribution and use in source and binary forms, with or without
6: * modification, are permitted provided that the following conditions
7: * are met:
8: * 1. Redistributions of source code must retain the above copyright
9: * notice, this list of conditions and the following disclaimer.
10: * 2. Redistributions in binary form must reproduce the above copyright
11: * notice, this list of conditions and the following disclaimer in the
12: * documentation and/or other materials provided with the distribution.
13: *
14: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15: * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17: * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18: * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19: * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23: * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24: */
25:
1.10 stevesk 26:
27: #include <sys/types.h>
28: #include <sys/stat.h>
1.31 djm 29: #include <sys/wait.h>
1.13 stevesk 30:
1.31 djm 31: #include <errno.h>
1.16 djm 32: #include <fcntl.h>
1.31 djm 33: #include <paths.h>
1.13 stevesk 34: #include <pwd.h>
1.31 djm 35: #include <signal.h>
1.14 stevesk 36: #include <stdio.h>
1.15 deraadt 37: #include <stdarg.h>
1.20 djm 38: #include <string.h>
39: #include <time.h>
1.17 dtucker 40: #include <unistd.h>
1.44 djm 41: #include <limits.h>
1.1 markus 42:
1.15 deraadt 43: #include "xmalloc.h"
1.8 dtucker 44: #include "ssh.h"
1.1 markus 45: #include "ssh2.h"
46: #include "packet.h"
47: #include "buffer.h"
48: #include "log.h"
1.41 millert 49: #include "misc.h"
1.1 markus 50: #include "servconf.h"
51: #include "compat.h"
1.15 deraadt 52: #include "key.h"
53: #include "hostfile.h"
1.1 markus 54: #include "auth.h"
55: #include "pathnames.h"
56: #include "uidswap.h"
57: #include "auth-options.h"
58: #include "canohost.h"
1.15 deraadt 59: #ifdef GSSAPI
60: #include "ssh-gss.h"
61: #endif
1.1 markus 62: #include "monitor_wrap.h"
1.21 djm 63: #include "authfile.h"
1.24 djm 64: #include "match.h"
1.50 djm 65: #include "ssherr.h"
66: #include "channels.h" /* XXX for session.h */
67: #include "session.h" /* XXX for child_set_env(); refactor? */
1.1 markus 68:
69: /* import */
70: extern ServerOptions options;
71: extern u_char *session_id2;
1.4 markus 72: extern u_int session_id2_len;
1.1 markus 73:
1.2 markus 74: static int
1.1 markus 75: userauth_pubkey(Authctxt *authctxt)
76: {
77: Buffer b;
78: Key *key = NULL;
1.55 djm 79: char *pkalg, *userstyle, *fp = NULL;
1.1 markus 80: u_char *pkblob, *sig;
81: u_int alen, blen, slen;
82: int have_sig, pktype;
83: int authenticated = 0;
84:
85: if (!authctxt->valid) {
1.55 djm 86: debug2("%s: disabled because of invalid user", __func__);
1.1 markus 87: return 0;
88: }
89: have_sig = packet_get_char();
90: if (datafellows & SSH_BUG_PKAUTH) {
1.55 djm 91: debug2("%s: SSH_BUG_PKAUTH", __func__);
1.1 markus 92: /* no explicit pkalg given */
93: pkblob = packet_get_string(&blen);
94: buffer_init(&b);
95: buffer_append(&b, pkblob, blen);
96: /* so we have to extract the pkalg from the pkblob */
97: pkalg = buffer_get_string(&b, &alen);
98: buffer_free(&b);
99: } else {
100: pkalg = packet_get_string(&alen);
101: pkblob = packet_get_string(&blen);
102: }
103: pktype = key_type_from_name(pkalg);
104: if (pktype == KEY_UNSPEC) {
105: /* this is perfectly legal */
1.55 djm 106: logit("%s: unsupported public key algorithm: %s",
107: __func__, pkalg);
1.1 markus 108: goto done;
109: }
110: key = key_from_blob(pkblob, blen);
111: if (key == NULL) {
1.55 djm 112: error("%s: cannot decode key: %s", __func__, pkalg);
1.1 markus 113: goto done;
114: }
115: if (key->type != pktype) {
1.55 djm 116: error("%s: type mismatch for decoded key "
117: "(received %d, expected %d)", __func__, key->type, pktype);
1.39 djm 118: goto done;
119: }
120: if (key_type_plain(key->type) == KEY_RSA &&
121: (datafellows & SSH_BUG_RSASIGMD5) != 0) {
122: logit("Refusing RSA key because client uses unsafe "
123: "signature scheme");
1.1 markus 124: goto done;
125: }
1.55 djm 126: fp = sshkey_fingerprint(key, options.fingerprint_hash, SSH_FP_DEFAULT);
1.44 djm 127: if (auth2_userkey_already_used(authctxt, key)) {
128: logit("refusing previously-used %s key", key_type(key));
129: goto done;
130: }
1.49 djm 131: if (match_pattern_list(sshkey_ssh_name(key),
132: options.pubkey_key_types, 0) != 1) {
1.45 djm 133: logit("%s: key type %s not in PubkeyAcceptedKeyTypes",
134: __func__, sshkey_ssh_name(key));
135: goto done;
136: }
137:
1.1 markus 138: if (have_sig) {
1.55 djm 139: debug3("%s: have signature for %s %s",
140: __func__, sshkey_type(key), fp);
1.1 markus 141: sig = packet_get_string(&slen);
142: packet_check_eom();
143: buffer_init(&b);
144: if (datafellows & SSH_OLD_SESSIONID) {
145: buffer_append(&b, session_id2, session_id2_len);
146: } else {
147: buffer_put_string(&b, session_id2, session_id2_len);
148: }
149: /* reconstruct packet */
150: buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1.35 djm 151: xasprintf(&userstyle, "%s%s%s", authctxt->user,
152: authctxt->style ? ":" : "",
153: authctxt->style ? authctxt->style : "");
154: buffer_put_cstring(&b, userstyle);
155: free(userstyle);
1.1 markus 156: buffer_put_cstring(&b,
157: datafellows & SSH_BUG_PKSERVICE ?
158: "ssh-userauth" :
159: authctxt->service);
160: if (datafellows & SSH_BUG_PKAUTH) {
161: buffer_put_char(&b, have_sig);
162: } else {
163: buffer_put_cstring(&b, "publickey");
164: buffer_put_char(&b, have_sig);
165: buffer_put_cstring(&b, pkalg);
166: }
167: buffer_put_string(&b, pkblob, blen);
168: #ifdef DEBUG_PK
169: buffer_dump(&b);
170: #endif
1.38 djm 171: pubkey_auth_info(authctxt, key, NULL);
1.37 djm 172:
1.1 markus 173: /* test for correct signature */
174: authenticated = 0;
1.48 djm 175: if (PRIVSEP(user_key_allowed(authctxt->pw, key, 1)) &&
1.1 markus 176: PRIVSEP(key_verify(key, sig, slen, buffer_ptr(&b),
1.44 djm 177: buffer_len(&b))) == 1) {
1.1 markus 178: authenticated = 1;
1.44 djm 179: /* Record the successful key to prevent reuse */
180: auth2_record_userkey(authctxt, key);
181: key = NULL; /* Don't free below */
182: }
1.6 markus 183: buffer_free(&b);
1.36 djm 184: free(sig);
1.1 markus 185: } else {
1.55 djm 186: debug("%s: test whether pkalg/pkblob are acceptable for %s %s",
187: __func__, sshkey_type(key), fp);
1.1 markus 188: packet_check_eom();
189:
190: /* XXX fake reply and always send PK_OK ? */
191: /*
192: * XXX this allows testing whether a user is allowed
193: * to login: if you happen to have a valid pubkey this
194: * message is sent. the message is NEVER sent at all
195: * if a user is not allowed to login. is this an
196: * issue? -markus
197: */
1.48 djm 198: if (PRIVSEP(user_key_allowed(authctxt->pw, key, 0))) {
1.1 markus 199: packet_start(SSH2_MSG_USERAUTH_PK_OK);
200: packet_put_string(pkalg, alen);
201: packet_put_string(pkblob, blen);
202: packet_send();
203: packet_write_wait();
204: authctxt->postponed = 1;
205: }
206: }
207: if (authenticated != 1)
208: auth_clear_options();
209: done:
1.55 djm 210: debug2("%s: authenticated %d pkalg %s", __func__, authenticated, pkalg);
1.1 markus 211: if (key != NULL)
212: key_free(key);
1.36 djm 213: free(pkalg);
214: free(pkblob);
1.55 djm 215: free(fp);
1.1 markus 216: return authenticated;
217: }
218:
1.37 djm 219: void
1.38 djm 220: pubkey_auth_info(Authctxt *authctxt, const Key *key, const char *fmt, ...)
1.37 djm 221: {
1.38 djm 222: char *fp, *extra;
223: va_list ap;
224: int i;
225:
226: extra = NULL;
227: if (fmt != NULL) {
228: va_start(ap, fmt);
229: i = vasprintf(&extra, fmt, ap);
230: va_end(ap);
231: if (i < 0 || extra == NULL)
232: fatal("%s: vasprintf failed", __func__);
233: }
1.37 djm 234:
235: if (key_is_cert(key)) {
1.46 djm 236: fp = sshkey_fingerprint(key->cert->signature_key,
1.43 djm 237: options.fingerprint_hash, SSH_FP_DEFAULT);
1.38 djm 238: auth_info(authctxt, "%s ID %s (serial %llu) CA %s %s%s%s",
1.37 djm 239: key_type(key), key->cert->key_id,
240: (unsigned long long)key->cert->serial,
1.46 djm 241: key_type(key->cert->signature_key),
1.47 djm 242: fp == NULL ? "(null)" : fp,
1.38 djm 243: extra == NULL ? "" : ", ", extra == NULL ? "" : extra);
1.37 djm 244: free(fp);
245: } else {
1.46 djm 246: fp = sshkey_fingerprint(key, options.fingerprint_hash,
1.43 djm 247: SSH_FP_DEFAULT);
1.46 djm 248: auth_info(authctxt, "%s %s%s%s", key_type(key),
1.47 djm 249: fp == NULL ? "(null)" : fp,
1.38 djm 250: extra == NULL ? "" : ", ", extra == NULL ? "" : extra);
1.37 djm 251: free(fp);
252: }
1.38 djm 253: free(extra);
1.37 djm 254: }
255:
1.50 djm 256: /*
257: * Splits 's' into an argument vector. Handles quoted string and basic
258: * escape characters (\\, \", \'). Caller must free the argument vector
259: * and its members.
260: */
261: static int
262: split_argv(const char *s, int *argcp, char ***argvp)
263: {
264: int r = SSH_ERR_INTERNAL_ERROR;
265: int argc = 0, quote, i, j;
266: char *arg, **argv = xcalloc(1, sizeof(*argv));
267:
268: *argvp = NULL;
269: *argcp = 0;
270:
271: for (i = 0; s[i] != '\0'; i++) {
272: /* Skip leading whitespace */
273: if (s[i] == ' ' || s[i] == '\t')
274: continue;
275:
276: /* Start of a token */
277: quote = 0;
278: if (s[i] == '\\' &&
279: (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
280: i++;
281: else if (s[i] == '\'' || s[i] == '"')
282: quote = s[i++];
283:
284: argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
285: arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
286: argv[argc] = NULL;
287:
288: /* Copy the token in, removing escapes */
289: for (j = 0; s[i] != '\0'; i++) {
290: if (s[i] == '\\') {
291: if (s[i + 1] == '\'' ||
292: s[i + 1] == '\"' ||
293: s[i + 1] == '\\') {
294: i++; /* Skip '\' */
295: arg[j++] = s[i];
296: } else {
297: /* Unrecognised escape */
298: arg[j++] = s[i];
299: }
300: } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
301: break; /* done */
302: else if (quote != 0 && s[i] == quote)
303: break; /* done */
304: else
305: arg[j++] = s[i];
306: }
307: if (s[i] == '\0') {
308: if (quote != 0) {
309: /* Ran out of string looking for close quote */
310: r = SSH_ERR_INVALID_FORMAT;
311: goto out;
312: }
313: break;
314: }
315: }
316: /* Success */
317: *argcp = argc;
318: *argvp = argv;
319: argc = 0;
320: argv = NULL;
321: r = 0;
322: out:
323: if (argc != 0 && argv != NULL) {
324: for (i = 0; i < argc; i++)
325: free(argv[i]);
326: free(argv);
327: }
328: return r;
329: }
330:
331: /*
332: * Reassemble an argument vector into a string, quoting and escaping as
333: * necessary. Caller must free returned string.
334: */
335: static char *
336: assemble_argv(int argc, char **argv)
337: {
338: int i, j, ws, r;
339: char c, *ret;
340: struct sshbuf *buf, *arg;
341:
342: if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
343: fatal("%s: sshbuf_new failed", __func__);
344:
345: for (i = 0; i < argc; i++) {
346: ws = 0;
347: sshbuf_reset(arg);
348: for (j = 0; argv[i][j] != '\0'; j++) {
349: r = 0;
350: c = argv[i][j];
351: switch (c) {
352: case ' ':
353: case '\t':
354: ws = 1;
355: r = sshbuf_put_u8(arg, c);
356: break;
357: case '\\':
358: case '\'':
359: case '"':
360: if ((r = sshbuf_put_u8(arg, '\\')) != 0)
361: break;
362: /* FALLTHROUGH */
363: default:
364: r = sshbuf_put_u8(arg, c);
365: break;
366: }
367: if (r != 0)
368: fatal("%s: sshbuf_put_u8: %s",
369: __func__, ssh_err(r));
370: }
371: if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
372: (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
373: (r = sshbuf_putb(buf, arg)) != 0 ||
374: (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
375: fatal("%s: buffer error: %s", __func__, ssh_err(r));
376: }
377: if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
378: fatal("%s: malloc failed", __func__);
379: memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
380: ret[sshbuf_len(buf)] = '\0';
381: sshbuf_free(buf);
382: sshbuf_free(arg);
383: return ret;
384: }
385:
386: /*
387: * Runs command in a subprocess. Returns pid on success and a FILE* to the
388: * subprocess' stdout or 0 on failure.
389: * NB. "command" is only used for logging.
390: */
391: static pid_t
392: subprocess(const char *tag, struct passwd *pw, const char *command,
393: int ac, char **av, FILE **child)
394: {
395: FILE *f;
396: struct stat st;
397: int devnull, p[2], i;
398: pid_t pid;
399: char *cp, errmsg[512];
400: u_int envsize;
401: char **child_env;
402:
403: *child = NULL;
404:
405: debug3("%s: %s command \"%s\" running as %s", __func__,
406: tag, command, pw->pw_name);
407:
408: /* Verify the path exists and is safe-ish to execute */
409: if (*av[0] != '/') {
410: error("%s path is not absolute", tag);
411: return 0;
412: }
413: temporarily_use_uid(pw);
414: if (stat(av[0], &st) < 0) {
415: error("Could not stat %s \"%s\": %s", tag,
416: av[0], strerror(errno));
417: restore_uid();
418: return 0;
419: }
420: if (auth_secure_path(av[0], &st, NULL, 0,
421: errmsg, sizeof(errmsg)) != 0) {
422: error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
423: restore_uid();
424: return 0;
425: }
426:
427: /*
428: * Run the command; stderr is left in place, stdout is the
429: * authorized_keys output.
430: */
431: if (pipe(p) != 0) {
432: error("%s: pipe: %s", tag, strerror(errno));
433: restore_uid();
434: return 0;
435: }
436:
437: /*
438: * Don't want to call this in the child, where it can fatal() and
439: * run cleanup_exit() code.
440: */
441: restore_uid();
442:
443: switch ((pid = fork())) {
444: case -1: /* error */
445: error("%s: fork: %s", tag, strerror(errno));
446: close(p[0]);
447: close(p[1]);
448: return 0;
449: case 0: /* child */
450: /* Prepare a minimal environment for the child. */
451: envsize = 5;
452: child_env = xcalloc(sizeof(*child_env), envsize);
453: child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH);
454: child_set_env(&child_env, &envsize, "USER", pw->pw_name);
455: child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name);
456: child_set_env(&child_env, &envsize, "HOME", pw->pw_dir);
457: if ((cp = getenv("LANG")) != NULL)
458: child_set_env(&child_env, &envsize, "LANG", cp);
459:
460: for (i = 0; i < NSIG; i++)
461: signal(i, SIG_DFL);
462:
463: if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
464: error("%s: open %s: %s", tag, _PATH_DEVNULL,
465: strerror(errno));
466: _exit(1);
467: }
468: /* Keep stderr around a while longer to catch errors */
469: if (dup2(devnull, STDIN_FILENO) == -1 ||
470: dup2(p[1], STDOUT_FILENO) == -1) {
471: error("%s: dup2: %s", tag, strerror(errno));
472: _exit(1);
473: }
474: closefrom(STDERR_FILENO + 1);
475:
476: /* Don't use permanently_set_uid() here to avoid fatal() */
477: if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0) {
478: error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
479: strerror(errno));
480: _exit(1);
481: }
482: if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0) {
483: error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
484: strerror(errno));
485: _exit(1);
486: }
487: /* stdin is pointed to /dev/null at this point */
488: if (dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
489: error("%s: dup2: %s", tag, strerror(errno));
490: _exit(1);
491: }
492:
493: execve(av[0], av, child_env);
494: error("%s exec \"%s\": %s", tag, command, strerror(errno));
495: _exit(127);
496: default: /* parent */
497: break;
498: }
499:
500: close(p[1]);
501: if ((f = fdopen(p[0], "r")) == NULL) {
502: error("%s: fdopen: %s", tag, strerror(errno));
503: close(p[0]);
504: /* Don't leave zombie child */
505: kill(pid, SIGTERM);
506: while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
507: ;
508: return 0;
509: }
510: /* Success */
511: debug3("%s: %s pid %ld", __func__, tag, (long)pid);
512: *child = f;
513: return pid;
514: }
515:
516: /* Returns 0 if pid exited cleanly, non-zero otherwise */
517: static int
518: exited_cleanly(pid_t pid, const char *tag, const char *cmd)
519: {
520: int status;
521:
522: while (waitpid(pid, &status, 0) == -1) {
523: if (errno != EINTR) {
524: error("%s: waitpid: %s", tag, strerror(errno));
525: return -1;
526: }
527: }
528: if (WIFSIGNALED(status)) {
529: error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
530: return -1;
531: } else if (WEXITSTATUS(status) != 0) {
532: error("%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
533: return -1;
534: }
535: return 0;
536: }
537:
1.24 djm 538: static int
1.40 djm 539: match_principals_option(const char *principal_list, struct sshkey_cert *cert)
1.24 djm 540: {
541: char *result;
542: u_int i;
543:
544: /* XXX percent_expand() sequences for authorized_principals? */
545:
546: for (i = 0; i < cert->nprincipals; i++) {
547: if ((result = match_list(cert->principals[i],
548: principal_list, NULL)) != NULL) {
549: debug3("matched principal from key options \"%.100s\"",
550: result);
1.36 djm 551: free(result);
1.24 djm 552: return 1;
553: }
554: }
555: return 0;
556: }
557:
558: static int
1.51 djm 559: process_principals(FILE *f, char *file, struct passwd *pw,
1.56 djm 560: const struct sshkey_cert *cert)
1.24 djm 561: {
1.26 djm 562: char line[SSH_MAX_PUBKEY_BYTES], *cp, *ep, *line_opts;
1.24 djm 563: u_long linenum = 0;
564: u_int i;
565:
566: while (read_keyfile_line(f, file, line, sizeof(line), &linenum) != -1) {
1.26 djm 567: /* Skip leading whitespace. */
1.24 djm 568: for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
569: ;
1.26 djm 570: /* Skip blank and comment lines. */
571: if ((ep = strchr(cp, '#')) != NULL)
572: *ep = '\0';
573: if (!*cp || *cp == '\n')
1.24 djm 574: continue;
1.26 djm 575: /* Trim trailing whitespace. */
576: ep = cp + strlen(cp) - 1;
577: while (ep > cp && (*ep == '\n' || *ep == ' ' || *ep == '\t'))
578: *ep-- = '\0';
579: /*
580: * If the line has internal whitespace then assume it has
581: * key options.
582: */
583: line_opts = NULL;
584: if ((ep = strrchr(cp, ' ')) != NULL ||
585: (ep = strrchr(cp, '\t')) != NULL) {
586: for (; *ep == ' ' || *ep == '\t'; ep++)
1.27 deraadt 587: ;
1.26 djm 588: line_opts = cp;
589: cp = ep;
590: }
1.24 djm 591: for (i = 0; i < cert->nprincipals; i++) {
592: if (strcmp(cp, cert->principals[i]) == 0) {
1.51 djm 593: debug3("%s:%lu: matched principal \"%.100s\"",
594: file == NULL ? "(command)" : file,
595: linenum, cert->principals[i]);
1.26 djm 596: if (auth_parse_options(pw, line_opts,
597: file, linenum) != 1)
598: continue;
1.24 djm 599: return 1;
600: }
601: }
602: }
1.51 djm 603: return 0;
604: }
605:
606: static int
607: match_principals_file(char *file, struct passwd *pw, struct sshkey_cert *cert)
608: {
609: FILE *f;
610: int success;
611:
612: temporarily_use_uid(pw);
613: debug("trying authorized principals file %s", file);
614: if ((f = auth_openprincipals(file, pw, options.strict_modes)) == NULL) {
615: restore_uid();
616: return 0;
617: }
618: success = process_principals(f, file, pw, cert);
1.24 djm 619: fclose(f);
620: restore_uid();
1.51 djm 621: return success;
1.31 djm 622: }
1.24 djm 623:
1.31 djm 624: /*
1.51 djm 625: * Checks whether principal is allowed in output of command.
626: * returns 1 if the principal is allowed or 0 otherwise.
627: */
628: static int
1.56 djm 629: match_principals_command(struct passwd *user_pw, const struct sshkey *key)
1.51 djm 630: {
1.56 djm 631: const struct sshkey_cert *cert = key->cert;
1.51 djm 632: FILE *f = NULL;
1.56 djm 633: int r, ok, found_principal = 0;
1.51 djm 634: struct passwd *pw;
635: int i, ac = 0, uid_swapped = 0;
636: pid_t pid;
637: char *tmp, *username = NULL, *command = NULL, **av = NULL;
1.56 djm 638: char *ca_fp = NULL, *key_fp = NULL, *catext = NULL, *keytext = NULL;
1.58 ! djm 639: char serial_s[16];
1.51 djm 640: void (*osigchld)(int);
641:
642: if (options.authorized_principals_command == NULL)
643: return 0;
644: if (options.authorized_principals_command_user == NULL) {
645: error("No user for AuthorizedPrincipalsCommand specified, "
646: "skipping");
647: return 0;
648: }
649:
650: /*
651: * NB. all returns later this function should go via "out" to
652: * ensure the original SIGCHLD handler is restored properly.
653: */
654: osigchld = signal(SIGCHLD, SIG_DFL);
655:
656: /* Prepare and verify the user for the command */
657: username = percent_expand(options.authorized_principals_command_user,
658: "u", user_pw->pw_name, (char *)NULL);
659: pw = getpwnam(username);
660: if (pw == NULL) {
661: error("AuthorizedPrincipalsCommandUser \"%s\" not found: %s",
662: username, strerror(errno));
663: goto out;
664: }
665:
666: /* Turn the command into an argument vector */
667: if (split_argv(options.authorized_principals_command, &ac, &av) != 0) {
668: error("AuthorizedPrincipalsCommand \"%s\" contains "
669: "invalid quotes", command);
670: goto out;
671: }
672: if (ac == 0) {
673: error("AuthorizedPrincipalsCommand \"%s\" yielded no arguments",
674: command);
675: goto out;
676: }
1.56 djm 677: if ((ca_fp = sshkey_fingerprint(cert->signature_key,
678: options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
679: error("%s: sshkey_fingerprint failed", __func__);
680: goto out;
681: }
1.57 djm 682: if ((key_fp = sshkey_fingerprint(key,
1.56 djm 683: options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
684: error("%s: sshkey_fingerprint failed", __func__);
685: goto out;
686: }
687: if ((r = sshkey_to_base64(cert->signature_key, &catext)) != 0) {
688: error("%s: sshkey_to_base64 failed: %s", __func__, ssh_err(r));
689: goto out;
690: }
691: if ((r = sshkey_to_base64(key, &keytext)) != 0) {
692: error("%s: sshkey_to_base64 failed: %s", __func__, ssh_err(r));
693: goto out;
694: }
1.58 ! djm 695: snprintf(serial_s, sizeof(serial_s), "%llu", cert->serial);
1.51 djm 696: for (i = 1; i < ac; i++) {
697: tmp = percent_expand(av[i],
698: "u", user_pw->pw_name,
699: "h", user_pw->pw_dir,
1.56 djm 700: "t", sshkey_ssh_name(key),
701: "T", sshkey_ssh_name(cert->signature_key),
702: "f", key_fp,
703: "F", ca_fp,
704: "k", keytext,
705: "K", catext,
1.58 ! djm 706: "i", cert->key_id,
! 707: "s", serial_s,
1.51 djm 708: (char *)NULL);
709: if (tmp == NULL)
710: fatal("%s: percent_expand failed", __func__);
711: free(av[i]);
712: av[i] = tmp;
713: }
714: /* Prepare a printable command for logs, etc. */
715: command = assemble_argv(ac, av);
716:
717: if ((pid = subprocess("AuthorizedPrincipalsCommand", pw, command,
718: ac, av, &f)) == 0)
719: goto out;
720:
721: uid_swapped = 1;
722: temporarily_use_uid(pw);
723:
1.52 jsing 724: ok = process_principals(f, NULL, pw, cert);
1.51 djm 725:
726: if (exited_cleanly(pid, "AuthorizedPrincipalsCommand", command) != 0)
727: goto out;
728:
729: /* Read completed successfully */
730: found_principal = ok;
731: out:
732: if (f != NULL)
733: fclose(f);
734: signal(SIGCHLD, osigchld);
735: for (i = 0; i < ac; i++)
736: free(av[i]);
737: free(av);
738: if (uid_swapped)
739: restore_uid();
740: free(command);
741: free(username);
1.56 djm 742: free(ca_fp);
743: free(key_fp);
744: free(catext);
745: free(keytext);
1.51 djm 746: return found_principal;
747: }
748: /*
1.31 djm 749: * Checks whether key is allowed in authorized_keys-format file,
750: * returns 1 if the key is allowed or 0 otherwise.
751: */
1.1 markus 752: static int
1.31 djm 753: check_authkeys_file(FILE *f, char *file, Key* key, struct passwd *pw)
1.1 markus 754: {
1.8 dtucker 755: char line[SSH_MAX_PUBKEY_BYTES];
1.20 djm 756: const char *reason;
1.18 dtucker 757: int found_key = 0;
1.1 markus 758: u_long linenum = 0;
759: Key *found;
760: char *fp;
761:
762: found_key = 0;
763:
1.37 djm 764: found = NULL;
1.8 dtucker 765: while (read_keyfile_line(f, file, line, sizeof(line), &linenum) != -1) {
1.7 avsm 766: char *cp, *key_options = NULL;
1.37 djm 767: if (found != NULL)
768: key_free(found);
769: found = key_new(key_is_cert(key) ? KEY_UNSPEC : key->type);
1.20 djm 770: auth_clear_options();
771:
1.1 markus 772: /* Skip leading whitespace, empty and comment lines. */
773: for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
774: ;
775: if (!*cp || *cp == '\n' || *cp == '#')
776: continue;
777:
778: if (key_read(found, &cp) != 1) {
779: /* no key? check if there are options for this key */
780: int quoted = 0;
781: debug2("user_key_allowed: check options: '%s'", cp);
1.7 avsm 782: key_options = cp;
1.1 markus 783: for (; *cp && (quoted || (*cp != ' ' && *cp != '\t')); cp++) {
784: if (*cp == '\\' && cp[1] == '"')
785: cp++; /* Skip both */
786: else if (*cp == '"')
787: quoted = !quoted;
788: }
789: /* Skip remaining whitespace. */
790: for (; *cp == ' ' || *cp == '\t'; cp++)
791: ;
792: if (key_read(found, &cp) != 1) {
793: debug2("user_key_allowed: advance: '%s'", cp);
794: /* still no key? advance to next line*/
795: continue;
796: }
797: }
1.23 djm 798: if (key_is_cert(key)) {
1.25 djm 799: if (!key_equal(found, key->cert->signature_key))
800: continue;
801: if (auth_parse_options(pw, key_options, file,
802: linenum) != 1)
803: continue;
1.20 djm 804: if (!key_is_cert_authority)
805: continue;
1.46 djm 806: if ((fp = sshkey_fingerprint(found,
807: options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
808: continue;
1.22 djm 809: debug("matching CA found: file %s, line %lu, %s %s",
810: file, linenum, key_type(found), fp);
1.24 djm 811: /*
812: * If the user has specified a list of principals as
813: * a key option, then prefer that list to matching
814: * their username in the certificate principals list.
815: */
816: if (authorized_principals != NULL &&
817: !match_principals_option(authorized_principals,
818: key->cert)) {
819: reason = "Certificate does not contain an "
820: "authorized principal";
821: fail_reason:
1.36 djm 822: free(fp);
1.20 djm 823: error("%s", reason);
824: auth_debug_add("%s", reason);
825: continue;
826: }
1.24 djm 827: if (key_cert_check_authority(key, 0, 0,
828: authorized_principals == NULL ? pw->pw_name : NULL,
829: &reason) != 0)
830: goto fail_reason;
1.23 djm 831: if (auth_cert_options(key, pw) != 0) {
1.36 djm 832: free(fp);
1.20 djm 833: continue;
1.22 djm 834: }
1.54 djm 835: verbose("Accepted certificate ID \"%s\" (serial %llu) "
1.22 djm 836: "signed by %s CA %s via %s", key->cert->key_id,
1.54 djm 837: (unsigned long long)key->cert->serial,
1.22 djm 838: key_type(found), fp, file);
1.36 djm 839: free(fp);
1.20 djm 840: found_key = 1;
841: break;
1.25 djm 842: } else if (key_equal(found, key)) {
843: if (auth_parse_options(pw, key_options, file,
844: linenum) != 1)
845: continue;
846: if (key_is_cert_authority)
847: continue;
1.46 djm 848: if ((fp = sshkey_fingerprint(found,
849: options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
850: continue;
1.37 djm 851: debug("matching key found: file %s, line %lu %s %s",
852: file, linenum, key_type(found), fp);
1.36 djm 853: free(fp);
1.46 djm 854: found_key = 1;
1.1 markus 855: break;
856: }
857: }
1.37 djm 858: if (found != NULL)
859: key_free(found);
1.1 markus 860: if (!found_key)
861: debug2("key not found");
862: return found_key;
863: }
864:
1.21 djm 865: /* Authenticate a certificate key against TrustedUserCAKeys */
866: static int
867: user_cert_trusted_ca(struct passwd *pw, Key *key)
868: {
1.24 djm 869: char *ca_fp, *principals_file = NULL;
1.21 djm 870: const char *reason;
1.53 jsing 871: int ret = 0, found_principal = 0, use_authorized_principals;
1.21 djm 872:
873: if (!key_is_cert(key) || options.trusted_user_ca_keys == NULL)
874: return 0;
875:
1.46 djm 876: if ((ca_fp = sshkey_fingerprint(key->cert->signature_key,
877: options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
878: return 0;
1.21 djm 879:
1.42 djm 880: if (sshkey_in_file(key->cert->signature_key,
881: options.trusted_user_ca_keys, 1, 0) != 0) {
1.21 djm 882: debug2("%s: CA %s %s is not listed in %s", __func__,
883: key_type(key->cert->signature_key), ca_fp,
884: options.trusted_user_ca_keys);
885: goto out;
886: }
1.24 djm 887: /*
888: * If AuthorizedPrincipals is in use, then compare the certificate
889: * principals against the names in that file rather than matching
890: * against the username.
891: */
892: if ((principals_file = authorized_principals_file(pw)) != NULL) {
1.51 djm 893: if (match_principals_file(principals_file, pw, key->cert))
894: found_principal = 1;
895: }
896: /* Try querying command if specified */
1.56 djm 897: if (!found_principal && match_principals_command(pw, key))
1.51 djm 898: found_principal = 1;
1.53 jsing 899: /* If principals file or command is specified, then require a match */
900: use_authorized_principals = principals_file != NULL ||
901: options.authorized_principals_command != NULL;
902: if (!found_principal && use_authorized_principals) {
1.51 djm 903: reason = "Certificate does not contain an authorized principal";
1.24 djm 904: fail_reason:
1.51 djm 905: error("%s", reason);
906: auth_debug_add("%s", reason);
907: goto out;
1.21 djm 908: }
1.24 djm 909: if (key_cert_check_authority(key, 0, 1,
1.53 jsing 910: use_authorized_principals ? NULL : pw->pw_name, &reason) != 0)
1.24 djm 911: goto fail_reason;
1.23 djm 912: if (auth_cert_options(key, pw) != 0)
1.21 djm 913: goto out;
914:
1.54 djm 915: verbose("Accepted certificate ID \"%s\" (serial %llu) signed by "
916: "%s CA %s via %s", key->cert->key_id,
917: (unsigned long long)key->cert->serial,
918: key_type(key->cert->signature_key), ca_fp,
1.22 djm 919: options.trusted_user_ca_keys);
1.21 djm 920: ret = 1;
921:
922: out:
1.36 djm 923: free(principals_file);
924: free(ca_fp);
1.21 djm 925: return ret;
926: }
927:
1.31 djm 928: /*
929: * Checks whether key is allowed in file.
930: * returns 1 if the key is allowed or 0 otherwise.
931: */
932: static int
933: user_key_allowed2(struct passwd *pw, Key *key, char *file)
934: {
935: FILE *f;
936: int found_key = 0;
937:
938: /* Temporarily use the user's uid. */
939: temporarily_use_uid(pw);
940:
941: debug("trying public key file %s", file);
942: if ((f = auth_openkeyfile(file, pw, options.strict_modes)) != NULL) {
943: found_key = check_authkeys_file(f, file, key, pw);
944: fclose(f);
945: }
946:
947: restore_uid();
948: return found_key;
949: }
950:
951: /*
952: * Checks whether key is allowed in output of command.
953: * returns 1 if the key is allowed or 0 otherwise.
954: */
955: static int
956: user_key_command_allowed2(struct passwd *user_pw, Key *key)
957: {
1.50 djm 958: FILE *f = NULL;
959: int r, ok, found_key = 0;
1.31 djm 960: struct passwd *pw;
1.50 djm 961: int i, uid_swapped = 0, ac = 0;
1.31 djm 962: pid_t pid;
1.50 djm 963: char *username = NULL, *key_fp = NULL, *keytext = NULL;
964: char *tmp, *command = NULL, **av = NULL;
965: void (*osigchld)(int);
1.31 djm 966:
1.50 djm 967: if (options.authorized_keys_command == NULL)
1.31 djm 968: return 0;
1.32 djm 969: if (options.authorized_keys_command_user == NULL) {
970: error("No user for AuthorizedKeysCommand specified, skipping");
971: return 0;
972: }
973:
1.50 djm 974: /*
975: * NB. all returns later this function should go via "out" to
976: * ensure the original SIGCHLD handler is restored properly.
977: */
978: osigchld = signal(SIGCHLD, SIG_DFL);
979:
980: /* Prepare and verify the user for the command */
1.32 djm 981: username = percent_expand(options.authorized_keys_command_user,
982: "u", user_pw->pw_name, (char *)NULL);
983: pw = getpwnam(username);
984: if (pw == NULL) {
1.34 djm 985: error("AuthorizedKeysCommandUser \"%s\" not found: %s",
986: username, strerror(errno));
1.50 djm 987: goto out;
1.31 djm 988: }
989:
1.50 djm 990: /* Prepare AuthorizedKeysCommand */
991: if ((key_fp = sshkey_fingerprint(key, options.fingerprint_hash,
992: SSH_FP_DEFAULT)) == NULL) {
993: error("%s: sshkey_fingerprint failed", __func__);
1.31 djm 994: goto out;
995: }
1.50 djm 996: if ((r = sshkey_to_base64(key, &keytext)) != 0) {
997: error("%s: sshkey_to_base64 failed: %s", __func__, ssh_err(r));
1.31 djm 998: goto out;
999: }
1000:
1.50 djm 1001: /* Turn the command into an argument vector */
1002: if (split_argv(options.authorized_keys_command, &ac, &av) != 0) {
1003: error("AuthorizedKeysCommand \"%s\" contains invalid quotes",
1004: command);
1005: goto out;
1006: }
1007: if (ac == 0) {
1008: error("AuthorizedKeysCommand \"%s\" yielded no arguments",
1009: command);
1.31 djm 1010: goto out;
1011: }
1.50 djm 1012: for (i = 1; i < ac; i++) {
1013: tmp = percent_expand(av[i],
1014: "u", user_pw->pw_name,
1015: "h", user_pw->pw_dir,
1016: "t", sshkey_ssh_name(key),
1017: "f", key_fp,
1018: "k", keytext,
1019: (char *)NULL);
1020: if (tmp == NULL)
1021: fatal("%s: percent_expand failed", __func__);
1022: free(av[i]);
1023: av[i] = tmp;
1024: }
1025: /* Prepare a printable command for logs, etc. */
1026: command = assemble_argv(ac, av);
1.31 djm 1027:
1028: /*
1.50 djm 1029: * If AuthorizedKeysCommand was run without arguments
1030: * then fall back to the old behaviour of passing the
1031: * target username as a single argument.
1.31 djm 1032: */
1.50 djm 1033: if (ac == 1) {
1034: av = xreallocarray(av, ac + 2, sizeof(*av));
1035: av[1] = xstrdup(user_pw->pw_name);
1036: av[2] = NULL;
1037: /* Fix up command too, since it is used in log messages */
1038: free(command);
1039: xasprintf(&command, "%s %s", av[0], av[1]);
1040: }
1.31 djm 1041:
1.50 djm 1042: if ((pid = subprocess("AuthorizedKeysCommand", pw, command,
1043: ac, av, &f)) == 0)
1044: goto out;
1.31 djm 1045:
1.50 djm 1046: uid_swapped = 1;
1.31 djm 1047: temporarily_use_uid(pw);
1048:
1049: ok = check_authkeys_file(f, options.authorized_keys_command, key, pw);
1050:
1.50 djm 1051: if (exited_cleanly(pid, "AuthorizedKeysCommand", command) != 0)
1.31 djm 1052: goto out;
1.50 djm 1053:
1054: /* Read completed successfully */
1.31 djm 1055: found_key = ok;
1056: out:
1.50 djm 1057: if (f != NULL)
1058: fclose(f);
1059: signal(SIGCHLD, osigchld);
1060: for (i = 0; i < ac; i++)
1061: free(av[i]);
1062: free(av);
1063: if (uid_swapped)
1064: restore_uid();
1065: free(command);
1066: free(username);
1067: free(key_fp);
1068: free(keytext);
1.31 djm 1069: return found_key;
1070: }
1071:
1072: /*
1073: * Check whether key authenticates and authorises the user.
1074: */
1.1 markus 1075: int
1.48 djm 1076: user_key_allowed(struct passwd *pw, Key *key, int auth_attempt)
1.1 markus 1077: {
1.29 djm 1078: u_int success, i;
1.1 markus 1079: char *file;
1.21 djm 1080:
1081: if (auth_key_is_revoked(key))
1082: return 0;
1083: if (key_is_cert(key) && auth_key_is_revoked(key->cert->signature_key))
1084: return 0;
1085:
1086: success = user_cert_trusted_ca(pw, key);
1087: if (success)
1088: return success;
1.1 markus 1089:
1.31 djm 1090: success = user_key_command_allowed2(pw, key);
1091: if (success > 0)
1092: return success;
1093:
1.29 djm 1094: for (i = 0; !success && i < options.num_authkeys_files; i++) {
1.31 djm 1095:
1096: if (strcasecmp(options.authorized_keys_files[i], "none") == 0)
1097: continue;
1.29 djm 1098: file = expand_authorized_keys(
1099: options.authorized_keys_files[i], pw);
1.31 djm 1100:
1.29 djm 1101: success = user_key_allowed2(pw, key, file);
1.36 djm 1102: free(file);
1.29 djm 1103: }
1.1 markus 1104:
1105: return success;
1.44 djm 1106: }
1107:
1108: /* Records a public key in the list of previously-successful keys */
1109: void
1110: auth2_record_userkey(Authctxt *authctxt, struct sshkey *key)
1111: {
1112: struct sshkey **tmp;
1113:
1114: if (authctxt->nprev_userkeys >= INT_MAX ||
1115: (tmp = reallocarray(authctxt->prev_userkeys,
1116: authctxt->nprev_userkeys + 1, sizeof(*tmp))) == NULL)
1117: fatal("%s: reallocarray failed", __func__);
1118: authctxt->prev_userkeys = tmp;
1119: authctxt->prev_userkeys[authctxt->nprev_userkeys] = key;
1120: authctxt->nprev_userkeys++;
1121: }
1122:
1123: /* Checks whether a key has already been used successfully for authentication */
1124: int
1125: auth2_userkey_already_used(Authctxt *authctxt, struct sshkey *key)
1126: {
1127: u_int i;
1128:
1129: for (i = 0; i < authctxt->nprev_userkeys; i++) {
1130: if (sshkey_equal_public(key, authctxt->prev_userkeys[i])) {
1131: return 1;
1132: }
1133: }
1134: return 0;
1.1 markus 1135: }
1.2 markus 1136:
1137: Authmethod method_pubkey = {
1138: "publickey",
1139: userauth_pubkey,
1140: &options.pubkey_authentication
1141: };