[BACK]Return to auth2-pubkey.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/auth2-pubkey.c, Revision 1.67

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