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

Annotation of src/usr.bin/ssh/ssh-keygen.c, Revision 1.465

1.465   ! dtucker     1: /* $OpenBSD: ssh-keygen.c,v 1.464 2023/03/05 08:18:58 dtucker Exp $ */
1.1       deraadt     2: /*
1.13      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1994 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
                      6:  * Identity and host key generation and maintenance.
1.31      deraadt     7:  *
                      8:  * As far as I am concerned, the code I have written for this software
                      9:  * can be used freely for any purpose.  Any derived versions of this
                     10:  * software must be clearly marked as such, and if the derived work is
                     11:  * incompatible with the protocol description in the RFC file, it must be
                     12:  * called by a name other than "ssh" or "Secure Shell".
1.13      deraadt    13:  */
1.1       deraadt    14:
1.136     stevesk    15: #include <sys/types.h>
1.174     dtucker    16: #include <sys/socket.h>
1.136     stevesk    17: #include <sys/stat.h>
1.19      markus     18:
1.348     djm        19: #ifdef WITH_OPENSSL
1.19      markus     20: #include <openssl/evp.h>
                     21: #include <openssl/pem.h>
1.348     djm        22: #endif
1.145     stevesk    23:
1.347     djm        24: #include <stdint.h>
1.148     stevesk    25: #include <errno.h>
1.147     stevesk    26: #include <fcntl.h>
1.248     djm        27: #include <netdb.h>
1.145     stevesk    28: #include <pwd.h>
1.430     dtucker    29: #include <stdarg.h>
1.153     stevesk    30: #include <stdio.h>
1.152     stevesk    31: #include <stdlib.h>
1.150     stevesk    32: #include <string.h>
1.149     stevesk    33: #include <unistd.h>
1.253     deraadt    34: #include <limits.h>
1.294     djm        35: #include <locale.h>
1.1       deraadt    36:
                     37: #include "xmalloc.h"
1.252     djm        38: #include "sshkey.h"
1.19      markus     39: #include "authfile.h"
1.252     djm        40: #include "sshbuf.h"
1.40      markus     41: #include "pathnames.h"
1.41      markus     42: #include "log.h"
1.114     djm        43: #include "misc.h"
1.119     djm        44: #include "match.h"
                     45: #include "hostfile.h"
1.146     stevesk    46: #include "dns.h"
1.223     djm        47: #include "ssh.h"
1.179     djm        48: #include "ssh2.h"
1.252     djm        49: #include "ssherr.h"
1.223     djm        50: #include "atomicio.h"
                     51: #include "krl.h"
1.251     djm        52: #include "digest.h"
1.294     djm        53: #include "utf8.h"
1.305     djm        54: #include "authfd.h"
1.344     djm        55: #include "sshsig.h"
1.357     djm        56: #include "ssh-sk.h"
                     57: #include "sk-api.h" /* XXX for SSH_SK_USER_PRESENCE_REQD; remove */
1.426     dtucker    58: #include "cipher.h"
1.32      markus     59:
1.177     markus     60: #ifdef ENABLE_PKCS11
                     61: #include "ssh-pkcs11.h"
1.106     djm        62: #endif
1.66      markus     63:
1.273     djm        64: #ifdef WITH_OPENSSL
                     65: # define DEFAULT_KEY_TYPE_NAME "rsa"
                     66: #else
                     67: # define DEFAULT_KEY_TYPE_NAME "ed25519"
                     68: #endif
                     69:
1.328     dtucker    70: /*
1.329     dtucker    71:  * Default number of bits in the RSA, DSA and ECDSA keys.  These value can be
                     72:  * overridden on the command line.
                     73:  *
                     74:  * These values, with the exception of DSA, provide security equivalent to at
                     75:  * least 128 bits of security according to NIST Special Publication 800-57:
                     76:  * Recommendation for Key Management Part 1 rev 4 section 5.6.1.
                     77:  * For DSA it (and FIPS-186-4 section 4.2) specifies that the only size for
                     78:  * which a 160bit hash is acceptable is 1kbit, and since ssh-dss specifies only
                     79:  * SHA1 we limit the DSA key size 1k bits.
1.328     dtucker    80:  */
                     81: #define DEFAULT_BITS           3072
1.130     markus     82: #define DEFAULT_BITS_DSA       1024
1.203     naddy      83: #define DEFAULT_BITS_ECDSA     256
1.1       deraadt    84:
1.325     djm        85: static int quiet = 0;
1.182     djm        86:
1.8       markus     87: /* Flag indicating that we just want to see the key fingerprint */
1.325     djm        88: static int print_fingerprint = 0;
                     89: static int print_bubblebabble = 0;
1.8       markus     90:
1.251     djm        91: /* Hash algorithm to use for fingerprints. */
1.325     djm        92: static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
1.251     djm        93:
1.10      markus     94: /* The identity file name, given on the command line or entered by the user. */
1.351     deraadt    95: static char identity_file[PATH_MAX];
1.325     djm        96: static int have_identity = 0;
1.1       deraadt    97:
                     98: /* This is set to the passphrase if given on the command line. */
1.325     djm        99: static char *identity_passphrase = NULL;
1.1       deraadt   100:
                    101: /* This is set to the new passphrase if given on the command line. */
1.325     djm       102: static char *identity_new_passphrase = NULL;
1.186     djm       103:
1.179     djm       104: /* Key type when certifying */
1.325     djm       105: static u_int cert_key_type = SSH2_CERT_TYPE_USER;
1.179     djm       106:
                    107: /* "key ID" of signed key */
1.325     djm       108: static char *cert_key_id = NULL;
1.179     djm       109:
                    110: /* Comma-separated list of principal names for certifying keys */
1.325     djm       111: static char *cert_principals = NULL;
1.179     djm       112:
                    113: /* Validity period for certificates */
1.325     djm       114: static u_int64_t cert_valid_from = 0;
                    115: static u_int64_t cert_valid_to = ~0ULL;
1.179     djm       116:
1.186     djm       117: /* Certificate options */
1.371     djm       118: #define CERTOPT_X_FWD                          (1)
                    119: #define CERTOPT_AGENT_FWD                      (1<<1)
                    120: #define CERTOPT_PORT_FWD                       (1<<2)
                    121: #define CERTOPT_PTY                            (1<<3)
                    122: #define CERTOPT_USER_RC                                (1<<4)
                    123: #define CERTOPT_NO_REQUIRE_USER_PRESENCE       (1<<5)
1.453     naddy     124: #define CERTOPT_REQUIRE_VERIFY                 (1<<6)
1.190     djm       125: #define CERTOPT_DEFAULT        (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
                    126:                         CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
1.325     djm       127: static u_int32_t certflags_flags = CERTOPT_DEFAULT;
                    128: static char *certflags_command = NULL;
                    129: static char *certflags_src_addr = NULL;
1.179     djm       130:
1.300     djm       131: /* Arbitrary extensions specified by user */
1.415     djm       132: struct cert_ext {
1.300     djm       133:        char *key;
                    134:        char *val;
                    135:        int crit;
                    136: };
1.415     djm       137: static struct cert_ext *cert_ext;
                    138: static size_t ncert_ext;
1.300     djm       139:
1.193     djm       140: /* Conversion to/from various formats */
                    141: enum {
                    142:        FMT_RFC4716,
                    143:        FMT_PKCS8,
                    144:        FMT_PEM
                    145: } convert_format = FMT_RFC4716;
1.33      markus    146:
1.325     djm       147: static char *key_type_name = NULL;
1.19      markus    148:
1.197     djm       149: /* Load key from this PKCS#11 provider */
1.325     djm       150: static char *pkcs11provider = NULL;
1.193     djm       151:
1.357     djm       152: /* FIDO/U2F provider to use */
                    153: static char *sk_provider = NULL;
                    154:
1.336     djm       155: /* Format for writing private keys */
                    156: static int private_key_format = SSHKEY_PRIVATE_OPENSSH;
1.237     markus    157:
                    158: /* Cipher for new-format private keys */
1.336     djm       159: static char *openssh_format_cipher = NULL;
1.237     markus    160:
1.376     djm       161: /* Number of KDF rounds to derive new format keys. */
1.325     djm       162: static int rounds = 0;
1.237     markus    163:
1.10      markus    164: /* argv0 */
                    165: extern char *__progname;
1.1       deraadt   166:
1.325     djm       167: static char hostname[NI_MAXHOST];
1.19      markus    168:
1.274     djm       169: #ifdef WITH_OPENSSL
1.115     djm       170: /* moduli.c */
1.124     avsm      171: int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
1.215     dtucker   172: int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long,
                    173:     unsigned long);
1.274     djm       174: #endif
1.115     djm       175:
1.63      itojun    176: static void
1.255     djm       177: type_bits_valid(int type, const char *name, u_int32_t *bitsp)
1.206     stevesk   178: {
1.269     djm       179:        if (type == KEY_UNSPEC)
                    180:                fatal("unknown key type %s", key_type_name);
1.209     djm       181:        if (*bitsp == 0) {
1.271     djm       182: #ifdef WITH_OPENSSL
1.423     djm       183:                int nid;
1.339     naddy     184:
                    185:                switch(type) {
                    186:                case KEY_DSA:
1.209     djm       187:                        *bitsp = DEFAULT_BITS_DSA;
1.339     naddy     188:                        break;
                    189:                case KEY_ECDSA:
1.255     djm       190:                        if (name != NULL &&
                    191:                            (nid = sshkey_ecdsa_nid_from_name(name)) > 0)
                    192:                                *bitsp = sshkey_curve_nid_to_bits(nid);
                    193:                        if (*bitsp == 0)
                    194:                                *bitsp = DEFAULT_BITS_ECDSA;
1.339     naddy     195:                        break;
                    196:                case KEY_RSA:
                    197:                        *bitsp = DEFAULT_BITS;
                    198:                        break;
                    199:                }
1.271     djm       200: #endif
1.206     stevesk   201:        }
1.271     djm       202: #ifdef WITH_OPENSSL
1.303     djm       203:        switch (type) {
                    204:        case KEY_DSA:
                    205:                if (*bitsp != 1024)
                    206:                        fatal("Invalid DSA key length: must be 1024 bits");
                    207:                break;
                    208:        case KEY_RSA:
                    209:                if (*bitsp < SSH_RSA_MINIMUM_MODULUS_SIZE)
                    210:                        fatal("Invalid RSA key length: minimum is %d bits",
                    211:                            SSH_RSA_MINIMUM_MODULUS_SIZE);
1.339     naddy     212:                else if (*bitsp > OPENSSL_RSA_MAX_MODULUS_BITS)
                    213:                        fatal("Invalid RSA key length: maximum is %d bits",
                    214:                            OPENSSL_RSA_MAX_MODULUS_BITS);
1.303     djm       215:                break;
                    216:        case KEY_ECDSA:
                    217:                if (sshkey_ecdsa_bits_to_nid(*bitsp) == -1)
                    218:                        fatal("Invalid ECDSA key length: valid lengths are "
                    219:                            "256, 384 or 521 bits");
                    220:        }
1.246     markus    221: #endif
1.206     stevesk   222: }
                    223:
1.343     djm       224: /*
                    225:  * Checks whether a file exists and, if so, asks the user whether they wish
                    226:  * to overwrite it.
                    227:  * Returns nonzero if the file does not already exist or if the user agrees to
                    228:  * overwrite, or zero otherwise.
                    229:  */
                    230: static int
                    231: confirm_overwrite(const char *filename)
                    232: {
                    233:        char yesno[3];
                    234:        struct stat st;
                    235:
                    236:        if (stat(filename, &st) != 0)
                    237:                return 1;
                    238:        printf("%s already exists.\n", filename);
                    239:        printf("Overwrite (y/n)? ");
                    240:        fflush(stdout);
                    241:        if (fgets(yesno, sizeof(yesno), stdin) == NULL)
                    242:                return 0;
                    243:        if (yesno[0] != 'y' && yesno[0] != 'Y')
                    244:                return 0;
                    245:        return 1;
                    246: }
                    247:
1.206     stevesk   248: static void
1.10      markus    249: ask_filename(struct passwd *pw, const char *prompt)
1.1       deraadt   250: {
1.12      markus    251:        char buf[1024];
1.35      markus    252:        char *name = NULL;
                    253:
1.92      stevesk   254:        if (key_type_name == NULL)
1.40      markus    255:                name = _PATH_SSH_CLIENT_ID_RSA;
1.140     deraadt   256:        else {
1.252     djm       257:                switch (sshkey_type_from_name(key_type_name)) {
1.186     djm       258:                case KEY_DSA_CERT:
1.92      stevesk   259:                case KEY_DSA:
                    260:                        name = _PATH_SSH_CLIENT_ID_DSA;
                    261:                        break;
1.200     djm       262:                case KEY_ECDSA_CERT:
                    263:                case KEY_ECDSA:
                    264:                        name = _PATH_SSH_CLIENT_ID_ECDSA;
                    265:                        break;
1.357     djm       266:                case KEY_ECDSA_SK_CERT:
                    267:                case KEY_ECDSA_SK:
                    268:                        name = _PATH_SSH_CLIENT_ID_ECDSA_SK;
                    269:                        break;
1.186     djm       270:                case KEY_RSA_CERT:
1.92      stevesk   271:                case KEY_RSA:
                    272:                        name = _PATH_SSH_CLIENT_ID_RSA;
                    273:                        break;
1.238     markus    274:                case KEY_ED25519:
                    275:                case KEY_ED25519_CERT:
                    276:                        name = _PATH_SSH_CLIENT_ID_ED25519;
                    277:                        break;
1.362     markus    278:                case KEY_ED25519_SK:
                    279:                case KEY_ED25519_SK_CERT:
                    280:                        name = _PATH_SSH_CLIENT_ID_ED25519_SK;
                    281:                        break;
1.313     markus    282:                case KEY_XMSS:
                    283:                case KEY_XMSS_CERT:
                    284:                        name = _PATH_SSH_CLIENT_ID_XMSS;
                    285:                        break;
1.92      stevesk   286:                default:
1.269     djm       287:                        fatal("bad key type");
1.92      stevesk   288:                }
1.140     deraadt   289:        }
1.269     djm       290:        snprintf(identity_file, sizeof(identity_file),
                    291:            "%s/%s", pw->pw_dir, name);
                    292:        printf("%s (%s): ", prompt, identity_file);
                    293:        fflush(stdout);
1.12      markus    294:        if (fgets(buf, sizeof(buf), stdin) == NULL)
                    295:                exit(1);
1.162     gilles    296:        buf[strcspn(buf, "\n")] = '\0';
1.12      markus    297:        if (strcmp(buf, "") != 0)
                    298:                strlcpy(identity_file, buf, sizeof(identity_file));
                    299:        have_identity = 1;
1.7       markus    300: }
                    301:
1.252     djm       302: static struct sshkey *
1.342     djm       303: load_identity(const char *filename, char **commentp)
1.19      markus    304: {
1.52      markus    305:        char *pass;
1.252     djm       306:        struct sshkey *prv;
                    307:        int r;
1.52      markus    308:
1.341     djm       309:        if (commentp != NULL)
                    310:                *commentp = NULL;
                    311:        if ((r = sshkey_load_private(filename, "", &prv, commentp)) == 0)
1.252     djm       312:                return prv;
                    313:        if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1.421     djm       314:                fatal_r(r, "Load key \"%s\"", filename);
1.252     djm       315:        if (identity_passphrase)
                    316:                pass = xstrdup(identity_passphrase);
                    317:        else
                    318:                pass = read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN);
1.341     djm       319:        r = sshkey_load_private(filename, pass, &prv, commentp);
1.399     jsg       320:        freezero(pass, strlen(pass));
1.252     djm       321:        if (r != 0)
1.421     djm       322:                fatal_r(r, "Load key \"%s\"", filename);
1.52      markus    323:        return prv;
1.19      markus    324: }
                    325:
1.32      markus    326: #define SSH_COM_PUBLIC_BEGIN           "---- BEGIN SSH2 PUBLIC KEY ----"
1.100     deraadt   327: #define SSH_COM_PUBLIC_END             "---- END SSH2 PUBLIC KEY ----"
1.32      markus    328: #define SSH_COM_PRIVATE_BEGIN          "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
1.42      stevesk   329: #define        SSH_COM_PRIVATE_KEY_MAGIC       0x3f6ff9eb
1.19      markus    330:
1.246     markus    331: #ifdef WITH_OPENSSL
1.63      itojun    332: static void
1.252     djm       333: do_convert_to_ssh2(struct passwd *pw, struct sshkey *k)
1.19      markus    334: {
1.337     djm       335:        struct sshbuf *b;
                    336:        char comment[61], *b64;
1.252     djm       337:        int r;
1.19      markus    338:
1.337     djm       339:        if ((b = sshbuf_new()) == NULL)
1.421     djm       340:                fatal_f("sshbuf_new failed");
1.337     djm       341:        if ((r = sshkey_putb(k, b)) != 0)
1.421     djm       342:                fatal_fr(r, "put key");
1.337     djm       343:        if ((b64 = sshbuf_dtob64_string(b, 1)) == NULL)
1.421     djm       344:                fatal_f("sshbuf_dtob64_string failed");
1.337     djm       345:
1.176     djm       346:        /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
                    347:        snprintf(comment, sizeof(comment),
                    348:            "%u-bit %s, converted by %s@%s from OpenSSH",
1.252     djm       349:            sshkey_size(k), sshkey_type(k),
1.19      markus    350:            pw->pw_name, hostname);
1.176     djm       351:
1.337     djm       352:        sshkey_free(k);
                    353:        sshbuf_free(b);
                    354:
1.176     djm       355:        fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
1.337     djm       356:        fprintf(stdout, "Comment: \"%s\"\n%s", comment, b64);
1.32      markus    357:        fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
1.337     djm       358:        free(b64);
1.19      markus    359:        exit(0);
                    360: }
                    361:
1.63      itojun    362: static void
1.252     djm       363: do_convert_to_pkcs8(struct sshkey *k)
1.193     djm       364: {
1.252     djm       365:        switch (sshkey_type_plain(k->type)) {
1.193     djm       366:        case KEY_RSA:
                    367:                if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
                    368:                        fatal("PEM_write_RSA_PUBKEY failed");
                    369:                break;
                    370:        case KEY_DSA:
                    371:                if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
                    372:                        fatal("PEM_write_DSA_PUBKEY failed");
                    373:                break;
1.200     djm       374:        case KEY_ECDSA:
                    375:                if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
                    376:                        fatal("PEM_write_EC_PUBKEY failed");
                    377:                break;
1.193     djm       378:        default:
1.421     djm       379:                fatal_f("unsupported key type %s", sshkey_type(k));
1.193     djm       380:        }
                    381:        exit(0);
                    382: }
                    383:
                    384: static void
1.252     djm       385: do_convert_to_pem(struct sshkey *k)
1.193     djm       386: {
1.252     djm       387:        switch (sshkey_type_plain(k->type)) {
1.193     djm       388:        case KEY_RSA:
                    389:                if (!PEM_write_RSAPublicKey(stdout, k->rsa))
                    390:                        fatal("PEM_write_RSAPublicKey failed");
1.389     djm       391:                break;
                    392:        case KEY_DSA:
                    393:                if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
                    394:                        fatal("PEM_write_DSA_PUBKEY failed");
                    395:                break;
                    396:        case KEY_ECDSA:
                    397:                if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
                    398:                        fatal("PEM_write_EC_PUBKEY failed");
1.193     djm       399:                break;
                    400:        default:
1.421     djm       401:                fatal_f("unsupported key type %s", sshkey_type(k));
1.193     djm       402:        }
                    403:        exit(0);
                    404: }
                    405:
                    406: static void
                    407: do_convert_to(struct passwd *pw)
                    408: {
1.252     djm       409:        struct sshkey *k;
1.193     djm       410:        struct stat st;
1.252     djm       411:        int r;
1.193     djm       412:
                    413:        if (!have_identity)
                    414:                ask_filename(pw, "Enter file in which the key is");
1.333     deraadt   415:        if (stat(identity_file, &st) == -1)
1.193     djm       416:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
1.252     djm       417:        if ((r = sshkey_load_public(identity_file, &k, NULL)) != 0)
1.341     djm       418:                k = load_identity(identity_file, NULL);
1.193     djm       419:        switch (convert_format) {
                    420:        case FMT_RFC4716:
                    421:                do_convert_to_ssh2(pw, k);
                    422:                break;
                    423:        case FMT_PKCS8:
                    424:                do_convert_to_pkcs8(k);
                    425:                break;
                    426:        case FMT_PEM:
                    427:                do_convert_to_pem(k);
                    428:                break;
                    429:        default:
1.421     djm       430:                fatal_f("unknown key format %d", convert_format);
1.193     djm       431:        }
                    432:        exit(0);
                    433: }
                    434:
1.252     djm       435: /*
                    436:  * This is almost exactly the bignum1 encoding, but with 32 bit for length
                    437:  * instead of 16.
                    438:  */
1.193     djm       439: static void
1.252     djm       440: buffer_get_bignum_bits(struct sshbuf *b, BIGNUM *value)
1.32      markus    441: {
1.252     djm       442:        u_int bytes, bignum_bits;
                    443:        int r;
1.53      markus    444:
1.252     djm       445:        if ((r = sshbuf_get_u32(b, &bignum_bits)) != 0)
1.421     djm       446:                fatal_fr(r, "parse");
1.252     djm       447:        bytes = (bignum_bits + 7) / 8;
                    448:        if (sshbuf_len(b) < bytes)
1.421     djm       449:                fatal_f("input buffer too small: need %d have %zu",
                    450:                    bytes, sshbuf_len(b));
1.252     djm       451:        if (BN_bin2bn(sshbuf_ptr(b), bytes, value) == NULL)
1.421     djm       452:                fatal_f("BN_bin2bn failed");
1.252     djm       453:        if ((r = sshbuf_consume(b, bytes)) != 0)
1.421     djm       454:                fatal_fr(r, "consume");
1.32      markus    455: }
                    456:
1.252     djm       457: static struct sshkey *
1.337     djm       458: do_convert_private_ssh2(struct sshbuf *b)
1.32      markus    459: {
1.252     djm       460:        struct sshkey *key = NULL;
1.64      markus    461:        char *type, *cipher;
1.252     djm       462:        u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345";
                    463:        int r, rlen, ktype;
                    464:        u_int magic, i1, i2, i3, i4;
                    465:        size_t slen;
1.62      markus    466:        u_long e;
1.321     djm       467:        BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
                    468:        BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
                    469:        BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
                    470:        BIGNUM *rsa_p = NULL, *rsa_q = NULL, *rsa_iqmp = NULL;
1.337     djm       471:
1.252     djm       472:        if ((r = sshbuf_get_u32(b, &magic)) != 0)
1.421     djm       473:                fatal_fr(r, "parse magic");
1.32      markus    474:
                    475:        if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
1.252     djm       476:                error("bad magic 0x%x != 0x%x", magic,
                    477:                    SSH_COM_PRIVATE_KEY_MAGIC);
1.32      markus    478:                return NULL;
                    479:        }
1.252     djm       480:        if ((r = sshbuf_get_u32(b, &i1)) != 0 ||
                    481:            (r = sshbuf_get_cstring(b, &type, NULL)) != 0 ||
                    482:            (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 ||
                    483:            (r = sshbuf_get_u32(b, &i2)) != 0 ||
                    484:            (r = sshbuf_get_u32(b, &i3)) != 0 ||
                    485:            (r = sshbuf_get_u32(b, &i4)) != 0)
1.421     djm       486:                fatal_fr(r, "parse");
1.158     stevesk   487:        debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
1.32      markus    488:        if (strcmp(cipher, "none") != 0) {
                    489:                error("unsupported cipher %s", cipher);
1.227     djm       490:                free(cipher);
                    491:                free(type);
1.32      markus    492:                return NULL;
                    493:        }
1.227     djm       494:        free(cipher);
1.32      markus    495:
1.53      markus    496:        if (strstr(type, "dsa")) {
                    497:                ktype = KEY_DSA;
                    498:        } else if (strstr(type, "rsa")) {
                    499:                ktype = KEY_RSA;
                    500:        } else {
1.227     djm       501:                free(type);
1.32      markus    502:                return NULL;
                    503:        }
1.322     djm       504:        if ((key = sshkey_new(ktype)) == NULL)
                    505:                fatal("sshkey_new failed");
1.227     djm       506:        free(type);
1.53      markus    507:
                    508:        switch (key->type) {
                    509:        case KEY_DSA:
1.321     djm       510:                if ((dsa_p = BN_new()) == NULL ||
                    511:                    (dsa_q = BN_new()) == NULL ||
                    512:                    (dsa_g = BN_new()) == NULL ||
                    513:                    (dsa_pub_key = BN_new()) == NULL ||
                    514:                    (dsa_priv_key = BN_new()) == NULL)
1.421     djm       515:                        fatal_f("BN_new");
1.321     djm       516:                buffer_get_bignum_bits(b, dsa_p);
                    517:                buffer_get_bignum_bits(b, dsa_g);
                    518:                buffer_get_bignum_bits(b, dsa_q);
                    519:                buffer_get_bignum_bits(b, dsa_pub_key);
                    520:                buffer_get_bignum_bits(b, dsa_priv_key);
                    521:                if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g))
1.421     djm       522:                        fatal_f("DSA_set0_pqg failed");
1.321     djm       523:                dsa_p = dsa_q = dsa_g = NULL; /* transferred */
                    524:                if (!DSA_set0_key(key->dsa, dsa_pub_key, dsa_priv_key))
1.421     djm       525:                        fatal_f("DSA_set0_key failed");
1.321     djm       526:                dsa_pub_key = dsa_priv_key = NULL; /* transferred */
1.53      markus    527:                break;
                    528:        case KEY_RSA:
1.252     djm       529:                if ((r = sshbuf_get_u8(b, &e1)) != 0 ||
                    530:                    (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) ||
                    531:                    (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0))
1.421     djm       532:                        fatal_fr(r, "parse RSA");
1.252     djm       533:                e = e1;
1.62      markus    534:                debug("e %lx", e);
                    535:                if (e < 30) {
                    536:                        e <<= 8;
1.252     djm       537:                        e += e2;
1.62      markus    538:                        debug("e %lx", e);
                    539:                        e <<= 8;
1.252     djm       540:                        e += e3;
1.62      markus    541:                        debug("e %lx", e);
                    542:                }
1.321     djm       543:                if ((rsa_e = BN_new()) == NULL)
1.421     djm       544:                        fatal_f("BN_new");
1.321     djm       545:                if (!BN_set_word(rsa_e, e)) {
                    546:                        BN_clear_free(rsa_e);
1.252     djm       547:                        sshkey_free(key);
1.53      markus    548:                        return NULL;
                    549:                }
1.321     djm       550:                if ((rsa_n = BN_new()) == NULL ||
                    551:                    (rsa_d = BN_new()) == NULL ||
                    552:                    (rsa_p = BN_new()) == NULL ||
                    553:                    (rsa_q = BN_new()) == NULL ||
                    554:                    (rsa_iqmp = BN_new()) == NULL)
1.421     djm       555:                        fatal_f("BN_new");
1.321     djm       556:                buffer_get_bignum_bits(b, rsa_d);
                    557:                buffer_get_bignum_bits(b, rsa_n);
                    558:                buffer_get_bignum_bits(b, rsa_iqmp);
                    559:                buffer_get_bignum_bits(b, rsa_q);
                    560:                buffer_get_bignum_bits(b, rsa_p);
                    561:                if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, rsa_d))
1.421     djm       562:                        fatal_f("RSA_set0_key failed");
1.321     djm       563:                rsa_n = rsa_e = rsa_d = NULL; /* transferred */
                    564:                if (!RSA_set0_factors(key->rsa, rsa_p, rsa_q))
1.421     djm       565:                        fatal_f("RSA_set0_factors failed");
1.321     djm       566:                rsa_p = rsa_q = NULL; /* transferred */
                    567:                if ((r = ssh_rsa_complete_crt_parameters(key, rsa_iqmp)) != 0)
1.421     djm       568:                        fatal_fr(r, "generate RSA parameters");
1.321     djm       569:                BN_clear_free(rsa_iqmp);
1.53      markus    570:                break;
                    571:        }
1.252     djm       572:        rlen = sshbuf_len(b);
1.85      deraadt   573:        if (rlen != 0)
1.421     djm       574:                error_f("remaining bytes in key blob %d", rlen);
1.64      markus    575:
                    576:        /* try the key */
1.455     djm       577:        if ((r = sshkey_sign(key, &sig, &slen, data, sizeof(data),
                    578:            NULL, NULL, NULL, 0)) != 0)
                    579:                error_fr(r, "signing with converted key failed");
                    580:        else if ((r = sshkey_verify(key, sig, slen, data, sizeof(data),
                    581:            NULL, 0, NULL)) != 0)
                    582:                error_fr(r, "verification with converted key failed");
                    583:        if (r != 0) {
1.252     djm       584:                sshkey_free(key);
                    585:                free(sig);
                    586:                return NULL;
                    587:        }
1.227     djm       588:        free(sig);
1.32      markus    589:        return key;
                    590: }
                    591:
1.137     dtucker   592: static int
                    593: get_line(FILE *fp, char *line, size_t len)
                    594: {
                    595:        int c;
                    596:        size_t pos = 0;
                    597:
                    598:        line[0] = '\0';
                    599:        while ((c = fgetc(fp)) != EOF) {
1.269     djm       600:                if (pos >= len - 1)
                    601:                        fatal("input line too long.");
1.140     deraadt   602:                switch (c) {
1.137     dtucker   603:                case '\r':
                    604:                        c = fgetc(fp);
1.269     djm       605:                        if (c != EOF && c != '\n' && ungetc(c, fp) == EOF)
                    606:                                fatal("unget: %s", strerror(errno));
1.137     dtucker   607:                        return pos;
                    608:                case '\n':
                    609:                        return pos;
                    610:                }
                    611:                line[pos++] = c;
                    612:                line[pos] = '\0';
                    613:        }
1.157     stevesk   614:        /* We reached EOF */
                    615:        return -1;
1.137     dtucker   616: }
                    617:
1.63      itojun    618: static void
1.252     djm       619: do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private)
1.19      markus    620: {
1.252     djm       621:        int r, blen, escaped = 0;
1.98      markus    622:        u_int len;
1.137     dtucker   623:        char line[1024];
1.337     djm       624:        struct sshbuf *buf;
1.19      markus    625:        char encoded[8096];
                    626:        FILE *fp;
                    627:
1.337     djm       628:        if ((buf = sshbuf_new()) == NULL)
                    629:                fatal("sshbuf_new failed");
1.191     djm       630:        if ((fp = fopen(identity_file, "r")) == NULL)
                    631:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
1.19      markus    632:        encoded[0] = '\0';
1.137     dtucker   633:        while ((blen = get_line(fp, line, sizeof(line))) != -1) {
1.228     djm       634:                if (blen > 0 && line[blen - 1] == '\\')
1.25      markus    635:                        escaped++;
1.19      markus    636:                if (strncmp(line, "----", 4) == 0 ||
                    637:                    strstr(line, ": ") != NULL) {
1.32      markus    638:                        if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
1.193     djm       639:                                *private = 1;
1.64      markus    640:                        if (strstr(line, " END ") != NULL) {
                    641:                                break;
                    642:                        }
1.60      markus    643:                        /* fprintf(stderr, "ignore: %s", line); */
1.19      markus    644:                        continue;
                    645:                }
1.25      markus    646:                if (escaped) {
                    647:                        escaped--;
1.60      markus    648:                        /* fprintf(stderr, "escaped: %s", line); */
1.25      markus    649:                        continue;
1.19      markus    650:                }
                    651:                strlcat(encoded, line, sizeof(encoded));
                    652:        }
1.98      markus    653:        len = strlen(encoded);
                    654:        if (((len % 4) == 3) &&
                    655:            (encoded[len-1] == '=') &&
                    656:            (encoded[len-2] == '=') &&
                    657:            (encoded[len-3] == '='))
                    658:                encoded[len-3] = '\0';
1.337     djm       659:        if ((r = sshbuf_b64tod(buf, encoded)) != 0)
1.421     djm       660:                fatal_fr(r, "base64 decode");
1.408     djm       661:        if (*private) {
                    662:                if ((*k = do_convert_private_ssh2(buf)) == NULL)
1.421     djm       663:                        fatal_f("private key conversion failed");
1.408     djm       664:        } else if ((r = sshkey_fromb(buf, k)) != 0)
1.421     djm       665:                fatal_fr(r, "parse key");
1.356     djm       666:        sshbuf_free(buf);
1.193     djm       667:        fclose(fp);
                    668: }
                    669:
                    670: static void
1.252     djm       671: do_convert_from_pkcs8(struct sshkey **k, int *private)
1.193     djm       672: {
                    673:        EVP_PKEY *pubkey;
                    674:        FILE *fp;
                    675:
                    676:        if ((fp = fopen(identity_file, "r")) == NULL)
                    677:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
                    678:        if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
1.421     djm       679:                fatal_f("%s is not a recognised public key format",
1.193     djm       680:                    identity_file);
                    681:        }
                    682:        fclose(fp);
1.321     djm       683:        switch (EVP_PKEY_base_id(pubkey)) {
1.193     djm       684:        case EVP_PKEY_RSA:
1.252     djm       685:                if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
                    686:                        fatal("sshkey_new failed");
1.193     djm       687:                (*k)->type = KEY_RSA;
                    688:                (*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
                    689:                break;
                    690:        case EVP_PKEY_DSA:
1.252     djm       691:                if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
                    692:                        fatal("sshkey_new failed");
1.193     djm       693:                (*k)->type = KEY_DSA;
                    694:                (*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
                    695:                break;
1.200     djm       696:        case EVP_PKEY_EC:
1.252     djm       697:                if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
                    698:                        fatal("sshkey_new failed");
1.200     djm       699:                (*k)->type = KEY_ECDSA;
                    700:                (*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
1.252     djm       701:                (*k)->ecdsa_nid = sshkey_ecdsa_key_to_nid((*k)->ecdsa);
1.200     djm       702:                break;
1.193     djm       703:        default:
1.421     djm       704:                fatal_f("unsupported pubkey type %d",
1.321     djm       705:                    EVP_PKEY_base_id(pubkey));
1.193     djm       706:        }
                    707:        EVP_PKEY_free(pubkey);
                    708:        return;
                    709: }
                    710:
                    711: static void
1.252     djm       712: do_convert_from_pem(struct sshkey **k, int *private)
1.193     djm       713: {
                    714:        FILE *fp;
                    715:        RSA *rsa;
                    716:
                    717:        if ((fp = fopen(identity_file, "r")) == NULL)
                    718:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
                    719:        if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
1.252     djm       720:                if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
                    721:                        fatal("sshkey_new failed");
1.193     djm       722:                (*k)->type = KEY_RSA;
                    723:                (*k)->rsa = rsa;
                    724:                fclose(fp);
                    725:                return;
                    726:        }
1.421     djm       727:        fatal_f("unrecognised raw private key format");
1.193     djm       728: }
                    729:
                    730: static void
                    731: do_convert_from(struct passwd *pw)
                    732: {
1.252     djm       733:        struct sshkey *k = NULL;
                    734:        int r, private = 0, ok = 0;
1.193     djm       735:        struct stat st;
                    736:
                    737:        if (!have_identity)
                    738:                ask_filename(pw, "Enter file in which the key is");
1.333     deraadt   739:        if (stat(identity_file, &st) == -1)
1.193     djm       740:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
                    741:
                    742:        switch (convert_format) {
                    743:        case FMT_RFC4716:
                    744:                do_convert_from_ssh2(pw, &k, &private);
                    745:                break;
                    746:        case FMT_PKCS8:
                    747:                do_convert_from_pkcs8(&k, &private);
                    748:                break;
                    749:        case FMT_PEM:
                    750:                do_convert_from_pem(&k, &private);
                    751:                break;
                    752:        default:
1.421     djm       753:                fatal_f("unknown key format %d", convert_format);
1.193     djm       754:        }
                    755:
1.260     djm       756:        if (!private) {
1.252     djm       757:                if ((r = sshkey_write(k, stdout)) == 0)
                    758:                        ok = 1;
1.193     djm       759:                if (ok)
                    760:                        fprintf(stdout, "\n");
1.260     djm       761:        } else {
1.193     djm       762:                switch (k->type) {
                    763:                case KEY_DSA:
                    764:                        ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
                    765:                            NULL, 0, NULL, NULL);
                    766:                        break;
1.200     djm       767:                case KEY_ECDSA:
                    768:                        ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
                    769:                            NULL, 0, NULL, NULL);
                    770:                        break;
1.193     djm       771:                case KEY_RSA:
                    772:                        ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
                    773:                            NULL, 0, NULL, NULL);
                    774:                        break;
                    775:                default:
1.421     djm       776:                        fatal_f("unsupported key type %s", sshkey_type(k));
1.193     djm       777:                }
                    778:        }
                    779:
1.269     djm       780:        if (!ok)
                    781:                fatal("key write failed");
1.252     djm       782:        sshkey_free(k);
1.19      markus    783:        exit(0);
                    784: }
1.246     markus    785: #endif
1.19      markus    786:
1.63      itojun    787: static void
1.19      markus    788: do_print_public(struct passwd *pw)
                    789: {
1.252     djm       790:        struct sshkey *prv;
1.19      markus    791:        struct stat st;
1.252     djm       792:        int r;
1.341     djm       793:        char *comment = NULL;
1.19      markus    794:
                    795:        if (!have_identity)
                    796:                ask_filename(pw, "Enter file in which the key is");
1.333     deraadt   797:        if (stat(identity_file, &st) == -1)
1.269     djm       798:                fatal("%s: %s", identity_file, strerror(errno));
1.341     djm       799:        prv = load_identity(identity_file, &comment);
1.252     djm       800:        if ((r = sshkey_write(prv, stdout)) != 0)
1.421     djm       801:                fatal_fr(r, "write key");
1.341     djm       802:        if (comment != NULL && *comment != '\0')
                    803:                fprintf(stdout, " %s", comment);
1.19      markus    804:        fprintf(stdout, "\n");
1.419     djm       805:        if (sshkey_is_sk(prv)) {
                    806:                debug("sk_application: \"%s\", sk_flags 0x%02x",
                    807:                        prv->sk_application, prv->sk_flags);
                    808:        }
                    809:        sshkey_free(prv);
1.341     djm       810:        free(comment);
1.19      markus    811:        exit(0);
                    812: }
                    813:
1.66      markus    814: static void
1.197     djm       815: do_download(struct passwd *pw)
1.75      markus    816: {
1.177     markus    817: #ifdef ENABLE_PKCS11
1.252     djm       818:        struct sshkey **keys = NULL;
1.177     markus    819:        int i, nkeys;
1.252     djm       820:        enum sshkey_fp_rep rep;
1.251     djm       821:        int fptype;
1.392     djm       822:        char *fp, *ra, **comments = NULL;
1.222     djm       823:
1.251     djm       824:        fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
                    825:        rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1.75      markus    826:
1.327     benno     827:        pkcs11_init(1);
1.392     djm       828:        nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys, &comments);
1.177     markus    829:        if (nkeys <= 0)
                    830:                fatal("cannot read public key from pkcs11");
                    831:        for (i = 0; i < nkeys; i++) {
1.221     djm       832:                if (print_fingerprint) {
1.252     djm       833:                        fp = sshkey_fingerprint(keys[i], fptype, rep);
                    834:                        ra = sshkey_fingerprint(keys[i], fingerprint_hash,
1.221     djm       835:                            SSH_FP_RANDOMART);
1.259     djm       836:                        if (fp == NULL || ra == NULL)
1.421     djm       837:                                fatal_f("sshkey_fingerprint fail");
1.252     djm       838:                        printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
                    839:                            fp, sshkey_type(keys[i]));
1.325     djm       840:                        if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
1.221     djm       841:                                printf("%s\n", ra);
1.227     djm       842:                        free(ra);
                    843:                        free(fp);
1.221     djm       844:                } else {
1.252     djm       845:                        (void) sshkey_write(keys[i], stdout); /* XXX check */
1.392     djm       846:                        fprintf(stdout, "%s%s\n",
                    847:                            *(comments[i]) == '\0' ? "" : " ", comments[i]);
1.221     djm       848:                }
1.392     djm       849:                free(comments[i]);
1.252     djm       850:                sshkey_free(keys[i]);
1.97      markus    851:        }
1.392     djm       852:        free(comments);
1.227     djm       853:        free(keys);
1.177     markus    854:        pkcs11_terminate();
1.75      markus    855:        exit(0);
1.177     markus    856: #else
                    857:        fatal("no pkcs11 support");
                    858: #endif /* ENABLE_PKCS11 */
1.75      markus    859: }
1.66      markus    860:
1.279     djm       861: static struct sshkey *
                    862: try_read_key(char **cpp)
                    863: {
                    864:        struct sshkey *ret;
                    865:        int r;
                    866:
                    867:        if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
                    868:                fatal("sshkey_new failed");
                    869:        if ((r = sshkey_read(ret, cpp)) == 0)
                    870:                return ret;
                    871:        /* Not a key */
                    872:        sshkey_free(ret);
                    873:        return NULL;
                    874: }
                    875:
1.63      itojun    876: static void
1.279     djm       877: fingerprint_one_key(const struct sshkey *public, const char *comment)
1.8       markus    878: {
1.279     djm       879:        char *fp = NULL, *ra = NULL;
1.252     djm       880:        enum sshkey_fp_rep rep;
1.251     djm       881:        int fptype;
1.12      markus    882:
1.251     djm       883:        fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
                    884:        rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1.279     djm       885:        fp = sshkey_fingerprint(public, fptype, rep);
                    886:        ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
                    887:        if (fp == NULL || ra == NULL)
1.421     djm       888:                fatal_f("sshkey_fingerprint failed");
1.294     djm       889:        mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
1.279     djm       890:            comment ? comment : "no comment", sshkey_type(public));
1.325     djm       891:        if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
1.279     djm       892:                printf("%s\n", ra);
                    893:        free(ra);
                    894:        free(fp);
                    895: }
                    896:
                    897: static void
                    898: fingerprint_private(const char *path)
                    899: {
                    900:        struct stat st;
                    901:        char *comment = NULL;
1.407     djm       902:        struct sshkey *privkey = NULL, *pubkey = NULL;
1.279     djm       903:        int r;
                    904:
1.333     deraadt   905:        if (stat(identity_file, &st) == -1)
1.279     djm       906:                fatal("%s: %s", path, strerror(errno));
1.407     djm       907:        if ((r = sshkey_load_public(path, &pubkey, &comment)) != 0)
1.421     djm       908:                debug_r(r, "load public \"%s\"", path);
1.407     djm       909:        if (pubkey == NULL || comment == NULL || *comment == '\0') {
                    910:                free(comment);
                    911:                if ((r = sshkey_load_private(path, NULL,
                    912:                    &privkey, &comment)) != 0)
1.421     djm       913:                        debug_r(r, "load private \"%s\"", path);
1.407     djm       914:        }
                    915:        if (pubkey == NULL && privkey == NULL)
                    916:                fatal("%s is not a key file.", path);
                    917:
                    918:        fingerprint_one_key(pubkey == NULL ? privkey : pubkey, comment);
                    919:        sshkey_free(pubkey);
                    920:        sshkey_free(privkey);
1.279     djm       921:        free(comment);
                    922: }
                    923:
                    924: static void
                    925: do_fingerprint(struct passwd *pw)
                    926: {
                    927:        FILE *f;
                    928:        struct sshkey *public = NULL;
1.317     markus    929:        char *comment = NULL, *cp, *ep, *line = NULL;
                    930:        size_t linesize = 0;
1.279     djm       931:        int i, invalid = 1;
                    932:        const char *path;
1.289     djm       933:        u_long lnum = 0;
1.279     djm       934:
1.12      markus    935:        if (!have_identity)
                    936:                ask_filename(pw, "Enter file in which the key is");
1.279     djm       937:        path = identity_file;
1.15      markus    938:
1.279     djm       939:        if (strcmp(identity_file, "-") == 0) {
                    940:                f = stdin;
                    941:                path = "(stdin)";
                    942:        } else if ((f = fopen(path, "r")) == NULL)
                    943:                fatal("%s: %s: %s", __progname, path, strerror(errno));
                    944:
1.317     markus    945:        while (getline(&line, &linesize, f) != -1) {
                    946:                lnum++;
1.279     djm       947:                cp = line;
                    948:                cp[strcspn(cp, "\n")] = '\0';
                    949:                /* Trim leading space and comments */
                    950:                cp = line + strspn(line, " \t");
                    951:                if (*cp == '#' || *cp == '\0')
                    952:                        continue;
1.191     djm       953:
1.279     djm       954:                /*
                    955:                 * Input may be plain keys, private keys, authorized_keys
                    956:                 * or known_hosts.
                    957:                 */
                    958:
                    959:                /*
                    960:                 * Try private keys first. Assume a key is private if
                    961:                 * "SSH PRIVATE KEY" appears on the first line and we're
                    962:                 * not reading from stdin (XXX support private keys on stdin).
                    963:                 */
                    964:                if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
1.280     djm       965:                    strstr(cp, "PRIVATE KEY") != NULL) {
1.317     markus    966:                        free(line);
1.279     djm       967:                        fclose(f);
                    968:                        fingerprint_private(path);
                    969:                        exit(0);
                    970:                }
                    971:
                    972:                /*
                    973:                 * If it's not a private key, then this must be prepared to
                    974:                 * accept a public key prefixed with a hostname or options.
                    975:                 * Try a bare key first, otherwise skip the leading stuff.
                    976:                 */
                    977:                if ((public = try_read_key(&cp)) == NULL) {
                    978:                        i = strtol(cp, &ep, 10);
                    979:                        if (i == 0 || ep == NULL ||
                    980:                            (*ep != ' ' && *ep != '\t')) {
                    981:                                int quoted = 0;
                    982:
                    983:                                comment = cp;
                    984:                                for (; *cp && (quoted || (*cp != ' ' &&
                    985:                                    *cp != '\t')); cp++) {
                    986:                                        if (*cp == '\\' && cp[1] == '"')
                    987:                                                cp++;   /* Skip both */
                    988:                                        else if (*cp == '"')
                    989:                                                quoted = !quoted;
                    990:                                }
                    991:                                if (!*cp)
                    992:                                        continue;
                    993:                                *cp++ = '\0';
                    994:                        }
1.191     djm       995:                }
1.279     djm       996:                /* Retry after parsing leading hostname/key options */
                    997:                if (public == NULL && (public = try_read_key(&cp)) == NULL) {
1.289     djm       998:                        debug("%s:%lu: not a public key", path, lnum);
1.191     djm       999:                        continue;
                   1000:                }
                   1001:
1.279     djm      1002:                /* Find trailing comment, if any */
                   1003:                for (; *cp == ' ' || *cp == '\t'; cp++)
1.191     djm      1004:                        ;
1.279     djm      1005:                if (*cp != '\0' && *cp != '#')
1.191     djm      1006:                        comment = cp;
1.279     djm      1007:
                   1008:                fingerprint_one_key(public, comment);
1.252     djm      1009:                sshkey_free(public);
1.279     djm      1010:                invalid = 0; /* One good key in the file is sufficient */
1.15      markus   1011:        }
1.191     djm      1012:        fclose(f);
1.317     markus   1013:        free(line);
1.191     djm      1014:
1.269     djm      1015:        if (invalid)
1.279     djm      1016:                fatal("%s is not a public key file.", path);
1.12      markus   1017:        exit(0);
1.8       markus   1018: }
                   1019:
1.119     djm      1020: static void
1.206     stevesk  1021: do_gen_all_hostkeys(struct passwd *pw)
                   1022: {
                   1023:        struct {
                   1024:                char *key_type;
                   1025:                char *key_type_display;
                   1026:                char *path;
                   1027:        } key_types[] = {
1.267     djm      1028: #ifdef WITH_OPENSSL
1.206     stevesk  1029:                { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
                   1030:                { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
1.267     djm      1031: #endif /* WITH_OPENSSL */
1.238     markus   1032:                { "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
1.313     markus   1033: #ifdef WITH_XMSS
                   1034:                { "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
                   1035: #endif /* WITH_XMSS */
1.206     stevesk  1036:                { NULL, NULL, NULL }
                   1037:        };
                   1038:
1.340     dtucker  1039:        u_int32_t bits = 0;
1.206     stevesk  1040:        int first = 0;
                   1041:        struct stat st;
1.252     djm      1042:        struct sshkey *private, *public;
1.307     djm      1043:        char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
1.252     djm      1044:        int i, type, fd, r;
1.206     stevesk  1045:
                   1046:        for (i = 0; key_types[i].key_type; i++) {
1.307     djm      1047:                public = private = NULL;
                   1048:                prv_tmp = pub_tmp = prv_file = pub_file = NULL;
                   1049:
                   1050:                xasprintf(&prv_file, "%s%s",
                   1051:                    identity_file, key_types[i].path);
                   1052:
                   1053:                /* Check whether private key exists and is not zero-length */
                   1054:                if (stat(prv_file, &st) == 0) {
                   1055:                        if (st.st_size != 0)
                   1056:                                goto next;
                   1057:                } else if (errno != ENOENT) {
1.269     djm      1058:                        error("Could not stat %s: %s", key_types[i].path,
1.206     stevesk  1059:                            strerror(errno));
1.307     djm      1060:                        goto failnext;
1.206     stevesk  1061:                }
                   1062:
1.307     djm      1063:                /*
                   1064:                 * Private key doesn't exist or is invalid; proceed with
                   1065:                 * key generation.
                   1066:                 */
                   1067:                xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
                   1068:                    identity_file, key_types[i].path);
                   1069:                xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
                   1070:                    identity_file, key_types[i].path);
                   1071:                xasprintf(&pub_file, "%s%s.pub",
                   1072:                    identity_file, key_types[i].path);
                   1073:
1.206     stevesk  1074:                if (first == 0) {
                   1075:                        first = 1;
                   1076:                        printf("%s: generating new host keys: ", __progname);
                   1077:                }
                   1078:                printf("%s ", key_types[i].key_type_display);
                   1079:                fflush(stdout);
1.252     djm      1080:                type = sshkey_type_from_name(key_types[i].key_type);
1.307     djm      1081:                if ((fd = mkstemp(prv_tmp)) == -1) {
1.409     djm      1082:                        error("Could not save your private key in %s: %s",
1.307     djm      1083:                            prv_tmp, strerror(errno));
                   1084:                        goto failnext;
                   1085:                }
1.409     djm      1086:                (void)close(fd); /* just using mkstemp() to reserve a name */
1.206     stevesk  1087:                bits = 0;
1.255     djm      1088:                type_bits_valid(type, NULL, &bits);
1.252     djm      1089:                if ((r = sshkey_generate(type, bits, &private)) != 0) {
1.421     djm      1090:                        error_r(r, "sshkey_generate failed");
1.307     djm      1091:                        goto failnext;
1.206     stevesk  1092:                }
1.252     djm      1093:                if ((r = sshkey_from_private(private, &public)) != 0)
1.421     djm      1094:                        fatal_fr(r, "sshkey_from_private");
1.206     stevesk  1095:                snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
                   1096:                    hostname);
1.307     djm      1097:                if ((r = sshkey_save_private(private, prv_tmp, "",
1.336     djm      1098:                    comment, private_key_format, openssh_format_cipher,
                   1099:                    rounds)) != 0) {
1.421     djm      1100:                        error_r(r, "Saving key \"%s\" failed", prv_tmp);
1.307     djm      1101:                        goto failnext;
1.206     stevesk  1102:                }
1.307     djm      1103:                if ((fd = mkstemp(pub_tmp)) == -1) {
                   1104:                        error("Could not save your public key in %s: %s",
                   1105:                            pub_tmp, strerror(errno));
                   1106:                        goto failnext;
1.206     stevesk  1107:                }
1.307     djm      1108:                (void)fchmod(fd, 0644);
1.409     djm      1109:                (void)close(fd);
                   1110:                if ((r = sshkey_save_public(public, pub_tmp, comment)) != 0) {
1.421     djm      1111:                        error_r(r, "Unable to save public key to %s",
                   1112:                            identity_file);
1.307     djm      1113:                        goto failnext;
                   1114:                }
                   1115:
                   1116:                /* Rename temporary files to their permanent locations. */
                   1117:                if (rename(pub_tmp, pub_file) != 0) {
                   1118:                        error("Unable to move %s into position: %s",
                   1119:                            pub_file, strerror(errno));
                   1120:                        goto failnext;
                   1121:                }
                   1122:                if (rename(prv_tmp, prv_file) != 0) {
                   1123:                        error("Unable to move %s into position: %s",
                   1124:                            key_types[i].path, strerror(errno));
                   1125:  failnext:
1.206     stevesk  1126:                        first = 0;
1.307     djm      1127:                        goto next;
1.206     stevesk  1128:                }
1.307     djm      1129:  next:
                   1130:                sshkey_free(private);
1.252     djm      1131:                sshkey_free(public);
1.307     djm      1132:                free(prv_tmp);
                   1133:                free(pub_tmp);
                   1134:                free(prv_file);
                   1135:                free(pub_file);
1.206     stevesk  1136:        }
                   1137:        if (first != 0)
                   1138:                printf("\n");
                   1139: }
                   1140:
1.256     djm      1141: struct known_hosts_ctx {
1.257     djm      1142:        const char *host;       /* Hostname searched for in find/delete case */
                   1143:        FILE *out;              /* Output file, stdout for find_hosts case */
                   1144:        int has_unhashed;       /* When hashing, original had unhashed hosts */
                   1145:        int found_key;          /* For find/delete, host was found */
                   1146:        int invalid;            /* File contained invalid items; don't delete */
1.325     djm      1147:        int hash_hosts;         /* Hash hostnames as we go */
                   1148:        int find_host;          /* Search for specific hostname */
                   1149:        int delete_host;        /* Delete host from known_hosts */
1.256     djm      1150: };
                   1151:
                   1152: static int
                   1153: known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1.119     djm      1154: {
1.256     djm      1155:        struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
                   1156:        char *hashed, *cp, *hosts, *ohosts;
                   1157:        int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
1.298     dtucker  1158:        int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
1.256     djm      1159:
1.262     djm      1160:        switch (l->status) {
                   1161:        case HKF_STATUS_OK:
                   1162:        case HKF_STATUS_MATCHED:
                   1163:                /*
                   1164:                 * Don't hash hosts already already hashed, with wildcard
                   1165:                 * characters or a CA/revocation marker.
                   1166:                 */
1.296     djm      1167:                if (was_hashed || has_wild || l->marker != MRK_NONE) {
1.262     djm      1168:                        fprintf(ctx->out, "%s\n", l->line);
1.325     djm      1169:                        if (has_wild && !ctx->find_host) {
1.297     dtucker  1170:                                logit("%s:%lu: ignoring host name "
1.269     djm      1171:                                    "with wildcard: %.64s", l->path,
1.262     djm      1172:                                    l->linenum, l->hosts);
                   1173:                        }
                   1174:                        return 0;
                   1175:                }
                   1176:                /*
                   1177:                 * Split any comma-separated hostnames from the host list,
                   1178:                 * hash and store separately.
                   1179:                 */
                   1180:                ohosts = hosts = xstrdup(l->hosts);
                   1181:                while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
1.299     djm      1182:                        lowercase(cp);
1.262     djm      1183:                        if ((hashed = host_hash(cp, NULL, 0)) == NULL)
                   1184:                                fatal("hash_host failed");
                   1185:                        fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
1.438     dtucker  1186:                        free(hashed);
1.262     djm      1187:                        ctx->has_unhashed = 1;
                   1188:                }
                   1189:                free(ohosts);
                   1190:                return 0;
                   1191:        case HKF_STATUS_INVALID:
                   1192:                /* Retain invalid lines, but mark file as invalid. */
1.256     djm      1193:                ctx->invalid = 1;
1.297     dtucker  1194:                logit("%s:%lu: invalid line", l->path, l->linenum);
1.262     djm      1195:                /* FALLTHROUGH */
                   1196:        default:
1.256     djm      1197:                fprintf(ctx->out, "%s\n", l->line);
                   1198:                return 0;
                   1199:        }
1.262     djm      1200:        /* NOTREACHED */
                   1201:        return -1;
1.256     djm      1202: }
                   1203:
                   1204: static int
                   1205: known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
                   1206: {
                   1207:        struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1.272     djm      1208:        enum sshkey_fp_rep rep;
                   1209:        int fptype;
1.338     djm      1210:        char *fp = NULL, *ra = NULL;
1.272     djm      1211:
                   1212:        fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
                   1213:        rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1.256     djm      1214:
1.262     djm      1215:        if (l->status == HKF_STATUS_MATCHED) {
1.325     djm      1216:                if (ctx->delete_host) {
1.256     djm      1217:                        if (l->marker != MRK_NONE) {
                   1218:                                /* Don't remove CA and revocation lines */
                   1219:                                fprintf(ctx->out, "%s\n", l->line);
                   1220:                        } else {
                   1221:                                /*
                   1222:                                 * Hostname matches and has no CA/revoke
                   1223:                                 * marker, delete it by *not* writing the
                   1224:                                 * line to ctx->out.
                   1225:                                 */
                   1226:                                ctx->found_key = 1;
                   1227:                                if (!quiet)
1.297     dtucker  1228:                                        printf("# Host %s found: line %lu\n",
1.256     djm      1229:                                            ctx->host, l->linenum);
                   1230:                        }
                   1231:                        return 0;
1.325     djm      1232:                } else if (ctx->find_host) {
1.256     djm      1233:                        ctx->found_key = 1;
                   1234:                        if (!quiet) {
1.297     dtucker  1235:                                printf("# Host %s found: line %lu %s\n",
1.256     djm      1236:                                    ctx->host,
                   1237:                                    l->linenum, l->marker == MRK_CA ? "CA" :
                   1238:                                    (l->marker == MRK_REVOKE ? "REVOKED" : ""));
                   1239:                        }
1.325     djm      1240:                        if (ctx->hash_hosts)
1.256     djm      1241:                                known_hosts_hash(l, ctx);
1.272     djm      1242:                        else if (print_fingerprint) {
                   1243:                                fp = sshkey_fingerprint(l->key, fptype, rep);
1.338     djm      1244:                                ra = sshkey_fingerprint(l->key,
                   1245:                                    fingerprint_hash, SSH_FP_RANDOMART);
                   1246:                                if (fp == NULL || ra == NULL)
1.421     djm      1247:                                        fatal_f("sshkey_fingerprint failed");
1.385     claudio  1248:                                mprintf("%s %s %s%s%s\n", ctx->host,
                   1249:                                    sshkey_type(l->key), fp,
                   1250:                                    l->comment[0] ? " " : "",
                   1251:                                    l->comment);
1.338     djm      1252:                                if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
                   1253:                                        printf("%s\n", ra);
                   1254:                                free(ra);
1.272     djm      1255:                                free(fp);
                   1256:                        } else
1.256     djm      1257:                                fprintf(ctx->out, "%s\n", l->line);
                   1258:                        return 0;
                   1259:                }
1.325     djm      1260:        } else if (ctx->delete_host) {
1.256     djm      1261:                /* Retain non-matching hosts when deleting */
                   1262:                if (l->status == HKF_STATUS_INVALID) {
                   1263:                        ctx->invalid = 1;
1.297     dtucker  1264:                        logit("%s:%lu: invalid line", l->path, l->linenum);
1.256     djm      1265:                }
                   1266:                fprintf(ctx->out, "%s\n", l->line);
1.166     djm      1267:        }
1.256     djm      1268:        return 0;
1.119     djm      1269: }
                   1270:
                   1271: static void
1.325     djm      1272: do_known_hosts(struct passwd *pw, const char *name, int find_host,
                   1273:     int delete_host, int hash_hosts)
1.119     djm      1274: {
1.258     deraadt  1275:        char *cp, tmp[PATH_MAX], old[PATH_MAX];
1.257     djm      1276:        int r, fd, oerrno, inplace = 0;
1.256     djm      1277:        struct known_hosts_ctx ctx;
1.272     djm      1278:        u_int foreach_options;
1.410     djm      1279:        struct stat sb;
1.119     djm      1280:
                   1281:        if (!have_identity) {
                   1282:                cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
                   1283:                if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
                   1284:                    sizeof(identity_file))
                   1285:                        fatal("Specified known hosts path too long");
1.227     djm      1286:                free(cp);
1.119     djm      1287:                have_identity = 1;
                   1288:        }
1.410     djm      1289:        if (stat(identity_file, &sb) != 0)
                   1290:                fatal("Cannot stat %s: %s", identity_file, strerror(errno));
1.119     djm      1291:
1.256     djm      1292:        memset(&ctx, 0, sizeof(ctx));
                   1293:        ctx.out = stdout;
                   1294:        ctx.host = name;
1.325     djm      1295:        ctx.hash_hosts = hash_hosts;
                   1296:        ctx.find_host = find_host;
                   1297:        ctx.delete_host = delete_host;
1.256     djm      1298:
1.119     djm      1299:        /*
                   1300:         * Find hosts goes to stdout, hash and deletions happen in-place
                   1301:         * A corner case is ssh-keygen -HF foo, which should go to stdout
                   1302:         */
                   1303:        if (!find_host && (hash_hosts || delete_host)) {
                   1304:                if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
                   1305:                    strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
                   1306:                    strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
                   1307:                    strlcat(old, ".old", sizeof(old)) >= sizeof(old))
                   1308:                        fatal("known_hosts path too long");
                   1309:                umask(077);
1.256     djm      1310:                if ((fd = mkstemp(tmp)) == -1)
1.119     djm      1311:                        fatal("mkstemp: %s", strerror(errno));
1.256     djm      1312:                if ((ctx.out = fdopen(fd, "w")) == NULL) {
                   1313:                        oerrno = errno;
1.119     djm      1314:                        unlink(tmp);
1.256     djm      1315:                        fatal("fdopen: %s", strerror(oerrno));
1.119     djm      1316:                }
1.463     dtucker  1317:                (void)fchmod(fd, sb.st_mode & 0644);
1.257     djm      1318:                inplace = 1;
1.119     djm      1319:        }
1.256     djm      1320:        /* XXX support identity_file == "-" for stdin */
1.272     djm      1321:        foreach_options = find_host ? HKF_WANT_MATCH : 0;
                   1322:        foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1.316     djm      1323:        if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ?
1.315     djm      1324:            known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL,
1.427     djm      1325:            foreach_options, 0)) != 0) {
1.284     deraadt  1326:                if (inplace)
                   1327:                        unlink(tmp);
1.421     djm      1328:                fatal_fr(r, "hostkeys_foreach");
1.284     deraadt  1329:        }
1.119     djm      1330:
1.257     djm      1331:        if (inplace)
1.256     djm      1332:                fclose(ctx.out);
1.119     djm      1333:
1.256     djm      1334:        if (ctx.invalid) {
1.269     djm      1335:                error("%s is not a valid known_hosts file.", identity_file);
1.257     djm      1336:                if (inplace) {
1.269     djm      1337:                        error("Not replacing existing known_hosts "
                   1338:                            "file because of errors");
1.119     djm      1339:                        unlink(tmp);
                   1340:                }
                   1341:                exit(1);
1.256     djm      1342:        } else if (delete_host && !ctx.found_key) {
1.269     djm      1343:                logit("Host %s not found in %s", name, identity_file);
1.277     djm      1344:                if (inplace)
                   1345:                        unlink(tmp);
1.257     djm      1346:        } else if (inplace) {
1.119     djm      1347:                /* Backup existing file */
                   1348:                if (unlink(old) == -1 && errno != ENOENT)
                   1349:                        fatal("unlink %.100s: %s", old, strerror(errno));
                   1350:                if (link(identity_file, old) == -1)
                   1351:                        fatal("link %.100s to %.100s: %s", identity_file, old,
                   1352:                            strerror(errno));
                   1353:                /* Move new one into place */
                   1354:                if (rename(tmp, identity_file) == -1) {
                   1355:                        error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
                   1356:                            strerror(errno));
                   1357:                        unlink(tmp);
                   1358:                        unlink(old);
                   1359:                        exit(1);
                   1360:                }
                   1361:
1.269     djm      1362:                printf("%s updated.\n", identity_file);
                   1363:                printf("Original contents retained as %s\n", old);
1.256     djm      1364:                if (ctx.has_unhashed) {
1.269     djm      1365:                        logit("WARNING: %s contains unhashed entries", old);
                   1366:                        logit("Delete this file to ensure privacy "
                   1367:                            "of hostnames");
1.119     djm      1368:                }
                   1369:        }
                   1370:
1.256     djm      1371:        exit (find_host && !ctx.found_key);
1.119     djm      1372: }
                   1373:
1.13      deraadt  1374: /*
                   1375:  * Perform changing a passphrase.  The argument is the passwd structure
                   1376:  * for the current user.
                   1377:  */
1.63      itojun   1378: static void
1.7       markus   1379: do_change_passphrase(struct passwd *pw)
                   1380: {
1.12      markus   1381:        char *comment;
                   1382:        char *old_passphrase, *passphrase1, *passphrase2;
                   1383:        struct stat st;
1.252     djm      1384:        struct sshkey *private;
                   1385:        int r;
1.12      markus   1386:
                   1387:        if (!have_identity)
                   1388:                ask_filename(pw, "Enter file in which the key is");
1.333     deraadt  1389:        if (stat(identity_file, &st) == -1)
1.269     djm      1390:                fatal("%s: %s", identity_file, strerror(errno));
1.12      markus   1391:        /* Try to load the file with empty passphrase. */
1.252     djm      1392:        r = sshkey_load_private(identity_file, "", &private, &comment);
                   1393:        if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1.12      markus   1394:                if (identity_passphrase)
                   1395:                        old_passphrase = xstrdup(identity_passphrase);
                   1396:                else
1.65      markus   1397:                        old_passphrase =
                   1398:                            read_passphrase("Enter old passphrase: ",
                   1399:                            RP_ALLOW_STDIN);
1.252     djm      1400:                r = sshkey_load_private(identity_file, old_passphrase,
                   1401:                    &private, &comment);
1.399     jsg      1402:                freezero(old_passphrase, strlen(old_passphrase));
1.252     djm      1403:                if (r != 0)
                   1404:                        goto badkey;
                   1405:        } else if (r != 0) {
                   1406:  badkey:
1.421     djm      1407:                fatal_r(r, "Failed to load key %s", identity_file);
1.12      markus   1408:        }
1.266     djm      1409:        if (comment)
1.294     djm      1410:                mprintf("Key has comment '%s'\n", comment);
1.12      markus   1411:
                   1412:        /* Ask the new passphrase (twice). */
                   1413:        if (identity_new_passphrase) {
                   1414:                passphrase1 = xstrdup(identity_new_passphrase);
                   1415:                passphrase2 = NULL;
                   1416:        } else {
                   1417:                passphrase1 =
1.65      markus   1418:                        read_passphrase("Enter new passphrase (empty for no "
                   1419:                            "passphrase): ", RP_ALLOW_STDIN);
                   1420:                passphrase2 = read_passphrase("Enter same passphrase again: ",
1.86      deraadt  1421:                    RP_ALLOW_STDIN);
1.12      markus   1422:
                   1423:                /* Verify that they are the same. */
                   1424:                if (strcmp(passphrase1, passphrase2) != 0) {
1.240     djm      1425:                        explicit_bzero(passphrase1, strlen(passphrase1));
                   1426:                        explicit_bzero(passphrase2, strlen(passphrase2));
1.227     djm      1427:                        free(passphrase1);
                   1428:                        free(passphrase2);
1.12      markus   1429:                        printf("Pass phrases do not match.  Try again.\n");
                   1430:                        exit(1);
                   1431:                }
                   1432:                /* Destroy the other copy. */
1.399     jsg      1433:                freezero(passphrase2, strlen(passphrase2));
1.12      markus   1434:        }
                   1435:
                   1436:        /* Save the file using the new passphrase. */
1.252     djm      1437:        if ((r = sshkey_save_private(private, identity_file, passphrase1,
1.336     djm      1438:            comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
1.421     djm      1439:                error_r(r, "Saving key \"%s\" failed", identity_file);
1.399     jsg      1440:                freezero(passphrase1, strlen(passphrase1));
1.252     djm      1441:                sshkey_free(private);
1.227     djm      1442:                free(comment);
1.12      markus   1443:                exit(1);
                   1444:        }
                   1445:        /* Destroy the passphrase and the copy of the key in memory. */
1.399     jsg      1446:        freezero(passphrase1, strlen(passphrase1));
1.252     djm      1447:        sshkey_free(private);            /* Destroys contents */
1.227     djm      1448:        free(comment);
1.1       deraadt  1449:
1.12      markus   1450:        printf("Your identification has been saved with the new passphrase.\n");
                   1451:        exit(0);
1.1       deraadt  1452: }
                   1453:
1.105     jakob    1454: /*
                   1455:  * Print the SSHFP RR.
                   1456:  */
1.138     jakob    1457: static int
1.325     djm      1458: do_print_resource_record(struct passwd *pw, char *fname, char *hname,
1.462     djm      1459:     int print_generic, char * const *opts, size_t nopts)
1.105     jakob    1460: {
1.252     djm      1461:        struct sshkey *public;
1.105     jakob    1462:        char *comment = NULL;
                   1463:        struct stat st;
1.462     djm      1464:        int r, hash = -1;
                   1465:        size_t i;
1.105     jakob    1466:
1.462     djm      1467:        for (i = 0; i < nopts; i++) {
                   1468:                if (strncasecmp(opts[i], "hashalg=", 8) == 0) {
                   1469:                        if ((hash = ssh_digest_alg_by_name(opts[i] + 8)) == -1)
                   1470:                                fatal("Unsupported hash algorithm");
                   1471:                } else {
                   1472:                        error("Invalid option \"%s\"", opts[i]);
                   1473:                        return SSH_ERR_INVALID_ARGUMENT;
                   1474:                }
                   1475:        }
1.138     jakob    1476:        if (fname == NULL)
1.421     djm      1477:                fatal_f("no filename");
1.333     deraadt  1478:        if (stat(fname, &st) == -1) {
1.138     jakob    1479:                if (errno == ENOENT)
                   1480:                        return 0;
1.269     djm      1481:                fatal("%s: %s", fname, strerror(errno));
1.105     jakob    1482:        }
1.269     djm      1483:        if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
1.421     djm      1484:                fatal_r(r, "Failed to read v2 public key from \"%s\"", fname);
1.462     djm      1485:        export_dns_rr(hname, public, stdout, print_generic, hash);
1.252     djm      1486:        sshkey_free(public);
                   1487:        free(comment);
                   1488:        return 1;
1.105     jakob    1489: }
                   1490:
1.13      deraadt  1491: /*
                   1492:  * Change the comment of a private key file.
                   1493:  */
1.63      itojun   1494: static void
1.325     djm      1495: do_change_comment(struct passwd *pw, const char *identity_comment)
1.1       deraadt  1496: {
1.46      deraadt  1497:        char new_comment[1024], *comment, *passphrase;
1.252     djm      1498:        struct sshkey *private;
                   1499:        struct sshkey *public;
1.12      markus   1500:        struct stat st;
1.409     djm      1501:        int r;
1.12      markus   1502:
                   1503:        if (!have_identity)
                   1504:                ask_filename(pw, "Enter file in which the key is");
1.333     deraadt  1505:        if (stat(identity_file, &st) == -1)
1.269     djm      1506:                fatal("%s: %s", identity_file, strerror(errno));
1.252     djm      1507:        if ((r = sshkey_load_private(identity_file, "",
                   1508:            &private, &comment)) == 0)
                   1509:                passphrase = xstrdup("");
1.269     djm      1510:        else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1.421     djm      1511:                fatal_r(r, "Cannot load private key \"%s\"", identity_file);
1.269     djm      1512:        else {
1.12      markus   1513:                if (identity_passphrase)
                   1514:                        passphrase = xstrdup(identity_passphrase);
                   1515:                else if (identity_new_passphrase)
                   1516:                        passphrase = xstrdup(identity_new_passphrase);
                   1517:                else
1.65      markus   1518:                        passphrase = read_passphrase("Enter passphrase: ",
                   1519:                            RP_ALLOW_STDIN);
1.12      markus   1520:                /* Try to load using the passphrase. */
1.252     djm      1521:                if ((r = sshkey_load_private(identity_file, passphrase,
                   1522:                    &private, &comment)) != 0) {
1.399     jsg      1523:                        freezero(passphrase, strlen(passphrase));
1.421     djm      1524:                        fatal_r(r, "Cannot load private key \"%s\"",
                   1525:                            identity_file);
1.12      markus   1526:                }
                   1527:        }
1.283     halex    1528:
1.313     markus   1529:        if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
1.336     djm      1530:            private_key_format != SSHKEY_PRIVATE_OPENSSH) {
1.302     djm      1531:                error("Comments are only supported for keys stored in "
1.283     halex    1532:                    "the new format (-o).");
1.268     tobias   1533:                explicit_bzero(passphrase, strlen(passphrase));
1.252     djm      1534:                sshkey_free(private);
1.52      markus   1535:                exit(1);
1.86      deraadt  1536:        }
1.293     millert  1537:        if (comment)
1.330     lum      1538:                printf("Old comment: %s\n", comment);
1.293     millert  1539:        else
1.330     lum      1540:                printf("No existing comment\n");
1.12      markus   1541:
                   1542:        if (identity_comment) {
                   1543:                strlcpy(new_comment, identity_comment, sizeof(new_comment));
                   1544:        } else {
1.330     lum      1545:                printf("New comment: ");
1.12      markus   1546:                fflush(stdout);
                   1547:                if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1.240     djm      1548:                        explicit_bzero(passphrase, strlen(passphrase));
1.252     djm      1549:                        sshkey_free(private);
1.12      markus   1550:                        exit(1);
                   1551:                }
1.162     gilles   1552:                new_comment[strcspn(new_comment, "\n")] = '\0';
1.12      markus   1553:        }
1.330     lum      1554:        if (comment != NULL && strcmp(comment, new_comment) == 0) {
                   1555:                printf("No change to comment\n");
                   1556:                free(passphrase);
                   1557:                sshkey_free(private);
                   1558:                free(comment);
                   1559:                exit(0);
                   1560:        }
1.12      markus   1561:
                   1562:        /* Save the file using the new passphrase. */
1.252     djm      1563:        if ((r = sshkey_save_private(private, identity_file, passphrase,
1.336     djm      1564:            new_comment, private_key_format, openssh_format_cipher,
                   1565:            rounds)) != 0) {
1.421     djm      1566:                error_r(r, "Saving key \"%s\" failed", identity_file);
1.399     jsg      1567:                freezero(passphrase, strlen(passphrase));
1.252     djm      1568:                sshkey_free(private);
1.227     djm      1569:                free(comment);
1.12      markus   1570:                exit(1);
                   1571:        }
1.399     jsg      1572:        freezero(passphrase, strlen(passphrase));
1.252     djm      1573:        if ((r = sshkey_from_private(private, &public)) != 0)
1.421     djm      1574:                fatal_fr(r, "sshkey_from_private");
1.252     djm      1575:        sshkey_free(private);
1.12      markus   1576:
                   1577:        strlcat(identity_file, ".pub", sizeof(identity_file));
1.421     djm      1578:        if ((r = sshkey_save_public(public, identity_file, new_comment)) != 0)
                   1579:                fatal_r(r, "Unable to save public key to %s", identity_file);
1.252     djm      1580:        sshkey_free(public);
1.227     djm      1581:        free(comment);
1.1       deraadt  1582:
1.330     lum      1583:        if (strlen(new_comment) > 0)
                   1584:                printf("Comment '%s' applied\n", new_comment);
                   1585:        else
                   1586:                printf("Comment removed\n");
                   1587:
1.12      markus   1588:        exit(0);
1.1       deraadt  1589: }
                   1590:
1.179     djm      1591: static void
1.415     djm      1592: cert_ext_add(const char *key, const char *value, int iscrit)
1.179     djm      1593: {
1.415     djm      1594:        cert_ext = xreallocarray(cert_ext, ncert_ext + 1, sizeof(*cert_ext));
                   1595:        cert_ext[ncert_ext].key = xstrdup(key);
                   1596:        cert_ext[ncert_ext].val = value == NULL ? NULL : xstrdup(value);
                   1597:        cert_ext[ncert_ext].crit = iscrit;
                   1598:        ncert_ext++;
1.179     djm      1599: }
                   1600:
1.415     djm      1601: /* qsort(3) comparison function for certificate extensions */
                   1602: static int
                   1603: cert_ext_cmp(const void *_a, const void *_b)
1.179     djm      1604: {
1.415     djm      1605:        const struct cert_ext *a = (const struct cert_ext *)_a;
                   1606:        const struct cert_ext *b = (const struct cert_ext *)_b;
1.252     djm      1607:        int r;
1.179     djm      1608:
1.415     djm      1609:        if (a->crit != b->crit)
                   1610:                return (a->crit < b->crit) ? -1 : 1;
                   1611:        if ((r = strcmp(a->key, b->key)) != 0)
                   1612:                return r;
                   1613:        if ((a->val == NULL) != (b->val == NULL))
                   1614:                return (a->val == NULL) ? -1 : 1;
                   1615:        if (a->val != NULL && (r = strcmp(a->val, b->val)) != 0)
                   1616:                return r;
                   1617:        return 0;
1.179     djm      1618: }
                   1619:
1.190     djm      1620: #define OPTIONS_CRITICAL       1
                   1621: #define OPTIONS_EXTENSIONS     2
1.179     djm      1622: static void
1.252     djm      1623: prepare_options_buf(struct sshbuf *c, int which)
1.179     djm      1624: {
1.415     djm      1625:        struct sshbuf *b;
1.300     djm      1626:        size_t i;
1.415     djm      1627:        int r;
                   1628:        const struct cert_ext *ext;
1.300     djm      1629:
1.415     djm      1630:        if ((b = sshbuf_new()) == NULL)
1.421     djm      1631:                fatal_f("sshbuf_new failed");
1.252     djm      1632:        sshbuf_reset(c);
1.415     djm      1633:        for (i = 0; i < ncert_ext; i++) {
                   1634:                ext = &cert_ext[i];
                   1635:                if ((ext->crit && (which & OPTIONS_EXTENSIONS)) ||
                   1636:                    (!ext->crit && (which & OPTIONS_CRITICAL)))
1.300     djm      1637:                        continue;
1.415     djm      1638:                if (ext->val == NULL) {
                   1639:                        /* flag option */
1.421     djm      1640:                        debug3_f("%s", ext->key);
1.415     djm      1641:                        if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
                   1642:                            (r = sshbuf_put_string(c, NULL, 0)) != 0)
1.421     djm      1643:                                fatal_fr(r, "prepare flag");
1.415     djm      1644:                } else {
                   1645:                        /* key/value option */
1.421     djm      1646:                        debug3_f("%s=%s", ext->key, ext->val);
1.415     djm      1647:                        sshbuf_reset(b);
                   1648:                        if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
                   1649:                            (r = sshbuf_put_cstring(b, ext->val)) != 0 ||
                   1650:                            (r = sshbuf_put_stringb(c, b)) != 0)
1.421     djm      1651:                                fatal_fr(r, "prepare k/v");
1.300     djm      1652:                }
                   1653:        }
1.415     djm      1654:        sshbuf_free(b);
                   1655: }
                   1656:
                   1657: static void
                   1658: finalise_cert_exts(void)
                   1659: {
                   1660:        /* critical options */
                   1661:        if (certflags_command != NULL)
                   1662:                cert_ext_add("force-command", certflags_command, 1);
                   1663:        if (certflags_src_addr != NULL)
                   1664:                cert_ext_add("source-address", certflags_src_addr, 1);
1.453     naddy    1665:        if ((certflags_flags & CERTOPT_REQUIRE_VERIFY) != 0)
                   1666:                cert_ext_add("verify-required", NULL, 1);
1.415     djm      1667:        /* extensions */
                   1668:        if ((certflags_flags & CERTOPT_X_FWD) != 0)
                   1669:                cert_ext_add("permit-X11-forwarding", NULL, 0);
                   1670:        if ((certflags_flags & CERTOPT_AGENT_FWD) != 0)
                   1671:                cert_ext_add("permit-agent-forwarding", NULL, 0);
                   1672:        if ((certflags_flags & CERTOPT_PORT_FWD) != 0)
                   1673:                cert_ext_add("permit-port-forwarding", NULL, 0);
                   1674:        if ((certflags_flags & CERTOPT_PTY) != 0)
                   1675:                cert_ext_add("permit-pty", NULL, 0);
                   1676:        if ((certflags_flags & CERTOPT_USER_RC) != 0)
                   1677:                cert_ext_add("permit-user-rc", NULL, 0);
                   1678:        if ((certflags_flags & CERTOPT_NO_REQUIRE_USER_PRESENCE) != 0)
                   1679:                cert_ext_add("no-touch-required", NULL, 0);
                   1680:        /* order lexically by key */
                   1681:        if (ncert_ext > 0)
                   1682:                qsort(cert_ext, ncert_ext, sizeof(*cert_ext), cert_ext_cmp);
1.179     djm      1683: }
                   1684:
1.252     djm      1685: static struct sshkey *
1.197     djm      1686: load_pkcs11_key(char *path)
                   1687: {
                   1688: #ifdef ENABLE_PKCS11
1.252     djm      1689:        struct sshkey **keys = NULL, *public, *private = NULL;
                   1690:        int r, i, nkeys;
1.197     djm      1691:
1.252     djm      1692:        if ((r = sshkey_load_public(path, &public, NULL)) != 0)
1.421     djm      1693:                fatal_r(r, "Couldn't load CA public key \"%s\"", path);
1.197     djm      1694:
1.392     djm      1695:        nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase,
                   1696:            &keys, NULL);
1.421     djm      1697:        debug3_f("%d keys", nkeys);
1.197     djm      1698:        if (nkeys <= 0)
                   1699:                fatal("cannot read public key from pkcs11");
                   1700:        for (i = 0; i < nkeys; i++) {
1.252     djm      1701:                if (sshkey_equal_public(public, keys[i])) {
1.197     djm      1702:                        private = keys[i];
                   1703:                        continue;
                   1704:                }
1.252     djm      1705:                sshkey_free(keys[i]);
1.197     djm      1706:        }
1.227     djm      1707:        free(keys);
1.252     djm      1708:        sshkey_free(public);
1.197     djm      1709:        return private;
                   1710: #else
                   1711:        fatal("no pkcs11 support");
                   1712: #endif /* ENABLE_PKCS11 */
                   1713: }
                   1714:
1.305     djm      1715: /* Signer for sshkey_certify_custom that uses the agent */
                   1716: static int
1.332     djm      1717: agent_signer(struct sshkey *key, u_char **sigp, size_t *lenp,
1.305     djm      1718:     const u_char *data, size_t datalen,
1.416     djm      1719:     const char *alg, const char *provider, const char *pin,
                   1720:     u_int compat, void *ctx)
1.305     djm      1721: {
                   1722:        int *agent_fdp = (int *)ctx;
                   1723:
                   1724:        return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
                   1725:            data, datalen, alg, compat);
                   1726: }
                   1727:
1.179     djm      1728: static void
1.325     djm      1729: do_ca_sign(struct passwd *pw, const char *ca_key_path, int prefer_agent,
1.326     djm      1730:     unsigned long long cert_serial, int cert_serial_autoinc,
                   1731:     int argc, char **argv)
1.179     djm      1732: {
1.409     djm      1733:        int r, i, found, agent_fd = -1;
1.179     djm      1734:        u_int n;
1.252     djm      1735:        struct sshkey *ca, *public;
1.374     djm      1736:        char valid[64], *otmp, *tmp, *cp, *out, *comment;
1.416     djm      1737:        char *ca_fp = NULL, **plist = NULL, *pin = NULL;
1.305     djm      1738:        struct ssh_identitylist *agent_ids;
                   1739:        size_t j;
1.374     djm      1740:        struct notifier_ctx *notifier = NULL;
1.186     djm      1741:
1.246     markus   1742: #ifdef ENABLE_PKCS11
1.197     djm      1743:        pkcs11_init(1);
1.246     markus   1744: #endif
1.197     djm      1745:        tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
                   1746:        if (pkcs11provider != NULL) {
1.305     djm      1747:                /* If a PKCS#11 token was specified then try to use it */
1.197     djm      1748:                if ((ca = load_pkcs11_key(tmp)) == NULL)
                   1749:                        fatal("No PKCS#11 key matching %s found", ca_key_path);
1.305     djm      1750:        } else if (prefer_agent) {
                   1751:                /*
                   1752:                 * Agent signature requested. Try to use agent after making
                   1753:                 * sure the public key specified is actually present in the
                   1754:                 * agent.
                   1755:                 */
                   1756:                if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
1.421     djm      1757:                        fatal_r(r, "Cannot load CA public key %s", tmp);
1.305     djm      1758:                if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
1.421     djm      1759:                        fatal_r(r, "Cannot use public key for CA signature");
1.305     djm      1760:                if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
1.421     djm      1761:                        fatal_r(r, "Retrieve agent key list");
1.305     djm      1762:                found = 0;
                   1763:                for (j = 0; j < agent_ids->nkeys; j++) {
                   1764:                        if (sshkey_equal(ca, agent_ids->keys[j])) {
                   1765:                                found = 1;
                   1766:                                break;
                   1767:                        }
                   1768:                }
                   1769:                if (!found)
                   1770:                        fatal("CA key %s not found in agent", tmp);
                   1771:                ssh_free_identitylist(agent_ids);
                   1772:                ca->flags |= SSHKEY_FLAG_EXT;
                   1773:        } else {
                   1774:                /* CA key is assumed to be a private key on the filesystem */
1.341     djm      1775:                ca = load_identity(tmp, NULL);
1.416     djm      1776:                if (sshkey_is_sk(ca) &&
                   1777:                    (ca->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
                   1778:                        if ((pin = read_passphrase("Enter PIN for CA key: ",
                   1779:                            RP_ALLOW_STDIN)) == NULL)
1.421     djm      1780:                                fatal_f("couldn't read PIN");
1.416     djm      1781:                }
1.305     djm      1782:        }
1.227     djm      1783:        free(tmp);
1.197     djm      1784:
1.390     djm      1785:        if (key_type_name != NULL) {
                   1786:                if (sshkey_type_from_name(key_type_name) != ca->type) {
                   1787:                        fatal("CA key type %s doesn't match specified %s",
                   1788:                            sshkey_ssh_name(ca), key_type_name);
                   1789:                }
                   1790:        } else if (ca->type == KEY_RSA) {
                   1791:                /* Default to a good signature algorithm */
                   1792:                key_type_name = "rsa-sha2-512";
1.290     djm      1793:        }
1.374     djm      1794:        ca_fp = sshkey_fingerprint(ca, fingerprint_hash, SSH_FP_DEFAULT);
1.290     djm      1795:
1.415     djm      1796:        finalise_cert_exts();
1.179     djm      1797:        for (i = 0; i < argc; i++) {
                   1798:                /* Split list of principals */
                   1799:                n = 0;
                   1800:                if (cert_principals != NULL) {
                   1801:                        otmp = tmp = xstrdup(cert_principals);
                   1802:                        plist = NULL;
                   1803:                        for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1.270     deraadt  1804:                                plist = xreallocarray(plist, n + 1, sizeof(*plist));
1.179     djm      1805:                                if (*(plist[n] = xstrdup(cp)) == '\0')
                   1806:                                        fatal("Empty principal name");
                   1807:                        }
1.227     djm      1808:                        free(otmp);
1.179     djm      1809:                }
1.312     djm      1810:                if (n > SSHKEY_CERT_MAX_PRINCIPALS)
                   1811:                        fatal("Too many certificate principals specified");
1.337     djm      1812:
1.179     djm      1813:                tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1.252     djm      1814:                if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
1.421     djm      1815:                        fatal_r(r, "load pubkey \"%s\"", tmp);
1.366     djm      1816:                if (sshkey_is_cert(public))
1.421     djm      1817:                        fatal_f("key \"%s\" type %s cannot be certified",
                   1818:                            tmp, sshkey_type(public));
1.179     djm      1819:
                   1820:                /* Prepare certificate to sign */
1.275     djm      1821:                if ((r = sshkey_to_certified(public)) != 0)
1.421     djm      1822:                        fatal_r(r, "Could not upgrade key %s to certificate", tmp);
1.179     djm      1823:                public->cert->type = cert_key_type;
1.186     djm      1824:                public->cert->serial = (u_int64_t)cert_serial;
1.179     djm      1825:                public->cert->key_id = xstrdup(cert_key_id);
                   1826:                public->cert->nprincipals = n;
                   1827:                public->cert->principals = plist;
                   1828:                public->cert->valid_after = cert_valid_from;
                   1829:                public->cert->valid_before = cert_valid_to;
1.275     djm      1830:                prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
                   1831:                prepare_options_buf(public->cert->extensions,
                   1832:                    OPTIONS_EXTENSIONS);
1.252     djm      1833:                if ((r = sshkey_from_private(ca,
                   1834:                    &public->cert->signature_key)) != 0)
1.421     djm      1835:                        fatal_r(r, "sshkey_from_private (ca key)");
1.179     djm      1836:
1.305     djm      1837:                if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
                   1838:                        if ((r = sshkey_certify_custom(public, ca,
1.416     djm      1839:                            key_type_name, sk_provider, NULL, agent_signer,
1.358     djm      1840:                            &agent_fd)) != 0)
1.421     djm      1841:                                fatal_r(r, "Couldn't certify %s via agent", tmp);
1.305     djm      1842:                } else {
1.374     djm      1843:                        if (sshkey_is_sk(ca) &&
                   1844:                            (ca->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
                   1845:                                notifier = notify_start(0,
                   1846:                                    "Confirm user presence for key %s %s",
                   1847:                                    sshkey_type(ca), ca_fp);
                   1848:                        }
                   1849:                        r = sshkey_certify(public, ca, key_type_name,
1.416     djm      1850:                            sk_provider, pin);
1.424     djm      1851:                        notify_complete(notifier, "User presence confirmed");
1.374     djm      1852:                        if (r != 0)
1.421     djm      1853:                                fatal_r(r, "Couldn't certify key %s", tmp);
1.305     djm      1854:                }
1.179     djm      1855:
                   1856:                if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
                   1857:                        *cp = '\0';
                   1858:                xasprintf(&out, "%s-cert.pub", tmp);
1.227     djm      1859:                free(tmp);
1.179     djm      1860:
1.409     djm      1861:                if ((r = sshkey_save_public(public, out, comment)) != 0) {
1.421     djm      1862:                        fatal_r(r, "Unable to save public key to %s",
                   1863:                            identity_file);
1.409     djm      1864:                }
1.179     djm      1865:
1.186     djm      1866:                if (!quiet) {
1.282     djm      1867:                        sshkey_format_cert_validity(public->cert,
1.281     djm      1868:                            valid, sizeof(valid));
1.186     djm      1869:                        logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1.282     djm      1870:                            "valid %s", sshkey_cert_type(public),
1.205     djm      1871:                            out, public->cert->key_id,
                   1872:                            (unsigned long long)public->cert->serial,
1.179     djm      1873:                            cert_principals != NULL ? " for " : "",
                   1874:                            cert_principals != NULL ? cert_principals : "",
1.281     djm      1875:                            valid);
1.186     djm      1876:                }
1.179     djm      1877:
1.252     djm      1878:                sshkey_free(public);
1.227     djm      1879:                free(out);
1.326     djm      1880:                if (cert_serial_autoinc)
                   1881:                        cert_serial++;
1.179     djm      1882:        }
1.416     djm      1883:        if (pin != NULL)
                   1884:                freezero(pin, strlen(pin));
1.374     djm      1885:        free(ca_fp);
1.246     markus   1886: #ifdef ENABLE_PKCS11
1.197     djm      1887:        pkcs11_terminate();
1.246     markus   1888: #endif
1.179     djm      1889:        exit(0);
                   1890: }
                   1891:
                   1892: static u_int64_t
                   1893: parse_relative_time(const char *s, time_t now)
                   1894: {
                   1895:        int64_t mul, secs;
                   1896:
                   1897:        mul = *s == '-' ? -1 : 1;
                   1898:
                   1899:        if ((secs = convtime(s + 1)) == -1)
                   1900:                fatal("Invalid relative certificate time %s", s);
                   1901:        if (mul == -1 && secs > now)
                   1902:                fatal("Certificate time %s cannot be represented", s);
                   1903:        return now + (u_int64_t)(secs * mul);
                   1904: }
                   1905:
                   1906: static void
1.459     djm      1907: parse_hex_u64(const char *s, uint64_t *up)
                   1908: {
                   1909:        char *ep;
                   1910:        unsigned long long ull;
                   1911:
                   1912:        errno = 0;
                   1913:        ull = strtoull(s, &ep, 16);
                   1914:        if (*s == '\0' || *ep != '\0')
                   1915:                fatal("Invalid certificate time: not a number");
                   1916:        if (errno == ERANGE && ull == ULONG_MAX)
                   1917:                fatal_fr(SSH_ERR_SYSTEM_ERROR, "Invalid certificate time");
                   1918:        *up = (uint64_t)ull;
                   1919: }
                   1920:
                   1921: static void
1.179     djm      1922: parse_cert_times(char *timespec)
                   1923: {
                   1924:        char *from, *to;
                   1925:        time_t now = time(NULL);
                   1926:        int64_t secs;
                   1927:
                   1928:        /* +timespec relative to now */
                   1929:        if (*timespec == '+' && strchr(timespec, ':') == NULL) {
                   1930:                if ((secs = convtime(timespec + 1)) == -1)
                   1931:                        fatal("Invalid relative certificate life %s", timespec);
                   1932:                cert_valid_to = now + secs;
                   1933:                /*
                   1934:                 * Backdate certificate one minute to avoid problems on hosts
                   1935:                 * with poorly-synchronised clocks.
                   1936:                 */
                   1937:                cert_valid_from = ((now - 59)/ 60) * 60;
                   1938:                return;
                   1939:        }
                   1940:
                   1941:        /*
                   1942:         * from:to, where
1.459     djm      1943:         * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "always"
                   1944:         *   to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "forever"
1.179     djm      1945:         */
                   1946:        from = xstrdup(timespec);
                   1947:        to = strchr(from, ':');
                   1948:        if (to == NULL || from == to || *(to + 1) == '\0')
1.181     djm      1949:                fatal("Invalid certificate life specification %s", timespec);
1.179     djm      1950:        *to++ = '\0';
                   1951:
                   1952:        if (*from == '-' || *from == '+')
                   1953:                cert_valid_from = parse_relative_time(from, now);
1.308     djm      1954:        else if (strcmp(from, "always") == 0)
                   1955:                cert_valid_from = 0;
1.459     djm      1956:        else if (strncmp(from, "0x", 2) == 0)
                   1957:                parse_hex_u64(from, &cert_valid_from);
1.314     djm      1958:        else if (parse_absolute_time(from, &cert_valid_from) != 0)
                   1959:                fatal("Invalid from time \"%s\"", from);
1.179     djm      1960:
                   1961:        if (*to == '-' || *to == '+')
1.235     djm      1962:                cert_valid_to = parse_relative_time(to, now);
1.308     djm      1963:        else if (strcmp(to, "forever") == 0)
                   1964:                cert_valid_to = ~(u_int64_t)0;
1.460     djm      1965:        else if (strncmp(to, "0x", 2) == 0)
1.459     djm      1966:                parse_hex_u64(to, &cert_valid_to);
1.314     djm      1967:        else if (parse_absolute_time(to, &cert_valid_to) != 0)
                   1968:                fatal("Invalid to time \"%s\"", to);
1.179     djm      1969:
                   1970:        if (cert_valid_to <= cert_valid_from)
                   1971:                fatal("Empty certificate validity interval");
1.227     djm      1972:        free(from);
1.179     djm      1973: }
                   1974:
                   1975: static void
1.186     djm      1976: add_cert_option(char *opt)
1.179     djm      1977: {
1.300     djm      1978:        char *val, *cp;
                   1979:        int iscrit = 0;
1.179     djm      1980:
1.208     stevesk  1981:        if (strcasecmp(opt, "clear") == 0)
1.190     djm      1982:                certflags_flags = 0;
1.179     djm      1983:        else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1.190     djm      1984:                certflags_flags &= ~CERTOPT_X_FWD;
1.179     djm      1985:        else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1.190     djm      1986:                certflags_flags |= CERTOPT_X_FWD;
1.179     djm      1987:        else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1.190     djm      1988:                certflags_flags &= ~CERTOPT_AGENT_FWD;
1.179     djm      1989:        else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1.190     djm      1990:                certflags_flags |= CERTOPT_AGENT_FWD;
1.179     djm      1991:        else if (strcasecmp(opt, "no-port-forwarding") == 0)
1.190     djm      1992:                certflags_flags &= ~CERTOPT_PORT_FWD;
1.179     djm      1993:        else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1.190     djm      1994:                certflags_flags |= CERTOPT_PORT_FWD;
1.179     djm      1995:        else if (strcasecmp(opt, "no-pty") == 0)
1.190     djm      1996:                certflags_flags &= ~CERTOPT_PTY;
1.179     djm      1997:        else if (strcasecmp(opt, "permit-pty") == 0)
1.190     djm      1998:                certflags_flags |= CERTOPT_PTY;
1.179     djm      1999:        else if (strcasecmp(opt, "no-user-rc") == 0)
1.190     djm      2000:                certflags_flags &= ~CERTOPT_USER_RC;
1.179     djm      2001:        else if (strcasecmp(opt, "permit-user-rc") == 0)
1.190     djm      2002:                certflags_flags |= CERTOPT_USER_RC;
1.371     djm      2003:        else if (strcasecmp(opt, "touch-required") == 0)
                   2004:                certflags_flags &= ~CERTOPT_NO_REQUIRE_USER_PRESENCE;
                   2005:        else if (strcasecmp(opt, "no-touch-required") == 0)
                   2006:                certflags_flags |= CERTOPT_NO_REQUIRE_USER_PRESENCE;
1.453     naddy    2007:        else if (strcasecmp(opt, "no-verify-required") == 0)
                   2008:                certflags_flags &= ~CERTOPT_REQUIRE_VERIFY;
                   2009:        else if (strcasecmp(opt, "verify-required") == 0)
                   2010:                certflags_flags |= CERTOPT_REQUIRE_VERIFY;
1.179     djm      2011:        else if (strncasecmp(opt, "force-command=", 14) == 0) {
                   2012:                val = opt + 14;
                   2013:                if (*val == '\0')
1.186     djm      2014:                        fatal("Empty force-command option");
1.190     djm      2015:                if (certflags_command != NULL)
1.179     djm      2016:                        fatal("force-command already specified");
1.190     djm      2017:                certflags_command = xstrdup(val);
1.179     djm      2018:        } else if (strncasecmp(opt, "source-address=", 15) == 0) {
                   2019:                val = opt + 15;
                   2020:                if (*val == '\0')
1.186     djm      2021:                        fatal("Empty source-address option");
1.190     djm      2022:                if (certflags_src_addr != NULL)
1.179     djm      2023:                        fatal("source-address already specified");
                   2024:                if (addr_match_cidr_list(NULL, val) != 0)
                   2025:                        fatal("Invalid source-address list");
1.190     djm      2026:                certflags_src_addr = xstrdup(val);
1.300     djm      2027:        } else if (strncasecmp(opt, "extension:", 10) == 0 ||
1.429     djm      2028:                    (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
1.300     djm      2029:                val = xstrdup(strchr(opt, ':') + 1);
                   2030:                if ((cp = strchr(val, '=')) != NULL)
                   2031:                        *cp++ = '\0';
1.415     djm      2032:                cert_ext_add(val, cp, iscrit);
                   2033:                free(val);
1.179     djm      2034:        } else
1.186     djm      2035:                fatal("Unsupported certificate option \"%s\"", opt);
1.179     djm      2036: }
                   2037:
1.63      itojun   2038: static void
1.275     djm      2039: show_options(struct sshbuf *optbuf, int in_critical)
1.192     djm      2040: {
1.415     djm      2041:        char *name, *arg, *hex;
1.252     djm      2042:        struct sshbuf *options, *option = NULL;
                   2043:        int r;
                   2044:
                   2045:        if ((options = sshbuf_fromb(optbuf)) == NULL)
1.421     djm      2046:                fatal_f("sshbuf_fromb failed");
1.252     djm      2047:        while (sshbuf_len(options) != 0) {
                   2048:                sshbuf_free(option);
                   2049:                option = NULL;
                   2050:                if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
                   2051:                    (r = sshbuf_froms(options, &option)) != 0)
1.421     djm      2052:                        fatal_fr(r, "parse option");
1.192     djm      2053:                printf("                %s", name);
1.275     djm      2054:                if (!in_critical &&
1.192     djm      2055:                    (strcmp(name, "permit-X11-forwarding") == 0 ||
                   2056:                    strcmp(name, "permit-agent-forwarding") == 0 ||
                   2057:                    strcmp(name, "permit-port-forwarding") == 0 ||
                   2058:                    strcmp(name, "permit-pty") == 0 ||
1.371     djm      2059:                    strcmp(name, "permit-user-rc") == 0 ||
                   2060:                    strcmp(name, "no-touch-required") == 0)) {
1.192     djm      2061:                        printf("\n");
1.371     djm      2062:                } else if (in_critical &&
1.192     djm      2063:                    (strcmp(name, "force-command") == 0 ||
                   2064:                    strcmp(name, "source-address") == 0)) {
1.252     djm      2065:                        if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
1.421     djm      2066:                                fatal_fr(r, "parse critical");
1.245     djm      2067:                        printf(" %s\n", arg);
                   2068:                        free(arg);
1.453     naddy    2069:                } else if (in_critical &&
                   2070:                    strcmp(name, "verify-required") == 0) {
                   2071:                        printf("\n");
1.415     djm      2072:                } else if (sshbuf_len(option) > 0) {
                   2073:                        hex = sshbuf_dtob16(option);
                   2074:                        printf(" UNKNOWN OPTION: %s (len %zu)\n",
                   2075:                            hex, sshbuf_len(option));
1.252     djm      2076:                        sshbuf_reset(option);
1.415     djm      2077:                        free(hex);
                   2078:                } else
                   2079:                        printf(" UNKNOWN FLAG OPTION\n");
1.227     djm      2080:                free(name);
1.252     djm      2081:                if (sshbuf_len(option) != 0)
1.192     djm      2082:                        fatal("Option corrupt: extra data at end");
                   2083:        }
1.252     djm      2084:        sshbuf_free(option);
                   2085:        sshbuf_free(options);
1.192     djm      2086: }
                   2087:
                   2088: static void
1.278     djm      2089: print_cert(struct sshkey *key)
1.182     djm      2090: {
1.281     djm      2091:        char valid[64], *key_fp, *ca_fp;
1.275     djm      2092:        u_int i;
1.186     djm      2093:
1.252     djm      2094:        key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
                   2095:        ca_fp = sshkey_fingerprint(key->cert->signature_key,
1.251     djm      2096:            fingerprint_hash, SSH_FP_DEFAULT);
1.259     djm      2097:        if (key_fp == NULL || ca_fp == NULL)
1.421     djm      2098:                fatal_f("sshkey_fingerprint fail");
1.281     djm      2099:        sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
1.182     djm      2100:
1.252     djm      2101:        printf("        Type: %s %s certificate\n", sshkey_ssh_name(key),
                   2102:            sshkey_cert_type(key));
                   2103:        printf("        Public key: %s %s\n", sshkey_type(key), key_fp);
1.323     djm      2104:        printf("        Signing CA: %s %s (using %s)\n",
                   2105:            sshkey_type(key->cert->signature_key), ca_fp,
                   2106:            key->cert->signature_type);
1.186     djm      2107:        printf("        Key ID: \"%s\"\n", key->cert->key_id);
1.275     djm      2108:        printf("        Serial: %llu\n", (unsigned long long)key->cert->serial);
1.281     djm      2109:        printf("        Valid: %s\n", valid);
1.182     djm      2110:        printf("        Principals: ");
                   2111:        if (key->cert->nprincipals == 0)
                   2112:                printf("(none)\n");
                   2113:        else {
                   2114:                for (i = 0; i < key->cert->nprincipals; i++)
                   2115:                        printf("\n                %s",
                   2116:                            key->cert->principals[i]);
                   2117:                printf("\n");
                   2118:        }
1.186     djm      2119:        printf("        Critical Options: ");
1.252     djm      2120:        if (sshbuf_len(key->cert->critical) == 0)
1.182     djm      2121:                printf("(none)\n");
                   2122:        else {
                   2123:                printf("\n");
1.275     djm      2124:                show_options(key->cert->critical, 1);
1.186     djm      2125:        }
1.275     djm      2126:        printf("        Extensions: ");
                   2127:        if (sshbuf_len(key->cert->extensions) == 0)
                   2128:                printf("(none)\n");
                   2129:        else {
                   2130:                printf("\n");
                   2131:                show_options(key->cert->extensions, 0);
1.182     djm      2132:        }
1.278     djm      2133: }
                   2134:
                   2135: static void
                   2136: do_show_cert(struct passwd *pw)
                   2137: {
                   2138:        struct sshkey *key = NULL;
                   2139:        struct stat st;
                   2140:        int r, is_stdin = 0, ok = 0;
                   2141:        FILE *f;
1.317     markus   2142:        char *cp, *line = NULL;
1.278     djm      2143:        const char *path;
1.317     markus   2144:        size_t linesize = 0;
1.289     djm      2145:        u_long lnum = 0;
1.278     djm      2146:
                   2147:        if (!have_identity)
                   2148:                ask_filename(pw, "Enter file in which the key is");
1.333     deraadt  2149:        if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) == -1)
1.278     djm      2150:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
                   2151:
                   2152:        path = identity_file;
                   2153:        if (strcmp(path, "-") == 0) {
                   2154:                f = stdin;
                   2155:                path = "(stdin)";
                   2156:                is_stdin = 1;
                   2157:        } else if ((f = fopen(identity_file, "r")) == NULL)
                   2158:                fatal("fopen %s: %s", identity_file, strerror(errno));
                   2159:
1.317     markus   2160:        while (getline(&line, &linesize, f) != -1) {
                   2161:                lnum++;
1.278     djm      2162:                sshkey_free(key);
                   2163:                key = NULL;
                   2164:                /* Trim leading space and comments */
                   2165:                cp = line + strspn(line, " \t");
                   2166:                if (*cp == '#' || *cp == '\0')
                   2167:                        continue;
                   2168:                if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
1.304     markus   2169:                        fatal("sshkey_new");
1.278     djm      2170:                if ((r = sshkey_read(key, &cp)) != 0) {
1.421     djm      2171:                        error_r(r, "%s:%lu: invalid key", path, lnum);
1.278     djm      2172:                        continue;
                   2173:                }
                   2174:                if (!sshkey_is_cert(key)) {
                   2175:                        error("%s:%lu is not a certificate", path, lnum);
                   2176:                        continue;
                   2177:                }
                   2178:                ok = 1;
                   2179:                if (!is_stdin && lnum == 1)
                   2180:                        printf("%s:\n", path);
                   2181:                else
                   2182:                        printf("%s:%lu:\n", path, lnum);
                   2183:                print_cert(key);
                   2184:        }
1.317     markus   2185:        free(line);
1.278     djm      2186:        sshkey_free(key);
                   2187:        fclose(f);
                   2188:        exit(ok ? 0 : 1);
1.182     djm      2189: }
                   2190:
                   2191: static void
1.223     djm      2192: load_krl(const char *path, struct ssh_krl **krlp)
                   2193: {
1.252     djm      2194:        struct sshbuf *krlbuf;
1.393     djm      2195:        int r;
1.223     djm      2196:
1.393     djm      2197:        if ((r = sshbuf_load_file(path, &krlbuf)) != 0)
1.421     djm      2198:                fatal_r(r, "Unable to load KRL %s", path);
1.223     djm      2199:        /* XXX check sigs */
1.252     djm      2200:        if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
1.223     djm      2201:            *krlp == NULL)
1.421     djm      2202:                fatal_r(r, "Invalid KRL file %s", path);
1.252     djm      2203:        sshbuf_free(krlbuf);
1.223     djm      2204: }
                   2205:
                   2206: static void
1.320     djm      2207: hash_to_blob(const char *cp, u_char **blobp, size_t *lenp,
                   2208:     const char *file, u_long lnum)
                   2209: {
                   2210:        char *tmp;
                   2211:        size_t tlen;
                   2212:        struct sshbuf *b;
                   2213:        int r;
                   2214:
                   2215:        if (strncmp(cp, "SHA256:", 7) != 0)
                   2216:                fatal("%s:%lu: unsupported hash algorithm", file, lnum);
                   2217:        cp += 7;
                   2218:
                   2219:        /*
                   2220:         * OpenSSH base64 hashes omit trailing '='
                   2221:         * characters; put them back for decode.
                   2222:         */
                   2223:        tlen = strlen(cp);
                   2224:        tmp = xmalloc(tlen + 4 + 1);
                   2225:        strlcpy(tmp, cp, tlen + 1);
                   2226:        while ((tlen % 4) != 0) {
                   2227:                tmp[tlen++] = '=';
                   2228:                tmp[tlen] = '\0';
                   2229:        }
                   2230:        if ((b = sshbuf_new()) == NULL)
1.421     djm      2231:                fatal_f("sshbuf_new failed");
1.320     djm      2232:        if ((r = sshbuf_b64tod(b, tmp)) != 0)
1.421     djm      2233:                fatal_r(r, "%s:%lu: decode hash failed", file, lnum);
1.320     djm      2234:        free(tmp);
                   2235:        *lenp = sshbuf_len(b);
                   2236:        *blobp = xmalloc(*lenp);
                   2237:        memcpy(*blobp, sshbuf_ptr(b), *lenp);
                   2238:        sshbuf_free(b);
                   2239: }
                   2240:
                   2241: static void
1.261     djm      2242: update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
1.252     djm      2243:     const struct sshkey *ca, struct ssh_krl *krl)
1.223     djm      2244: {
1.252     djm      2245:        struct sshkey *key = NULL;
1.223     djm      2246:        u_long lnum = 0;
1.317     markus   2247:        char *path, *cp, *ep, *line = NULL;
1.320     djm      2248:        u_char *blob = NULL;
                   2249:        size_t blen = 0, linesize = 0;
1.223     djm      2250:        unsigned long long serial, serial2;
1.320     djm      2251:        int i, was_explicit_key, was_sha1, was_sha256, was_hash, r;
1.223     djm      2252:        FILE *krl_spec;
                   2253:
                   2254:        path = tilde_expand_filename(file, pw->pw_uid);
                   2255:        if (strcmp(path, "-") == 0) {
                   2256:                krl_spec = stdin;
                   2257:                free(path);
                   2258:                path = xstrdup("(standard input)");
                   2259:        } else if ((krl_spec = fopen(path, "r")) == NULL)
                   2260:                fatal("fopen %s: %s", path, strerror(errno));
                   2261:
                   2262:        if (!quiet)
                   2263:                printf("Revoking from %s\n", path);
1.317     markus   2264:        while (getline(&line, &linesize, krl_spec) != -1) {
                   2265:                lnum++;
1.320     djm      2266:                was_explicit_key = was_sha1 = was_sha256 = was_hash = 0;
1.223     djm      2267:                cp = line + strspn(line, " \t");
                   2268:                /* Trim trailing space, comments and strip \n */
                   2269:                for (i = 0, r = -1; cp[i] != '\0'; i++) {
                   2270:                        if (cp[i] == '#' || cp[i] == '\n') {
                   2271:                                cp[i] = '\0';
                   2272:                                break;
                   2273:                        }
                   2274:                        if (cp[i] == ' ' || cp[i] == '\t') {
                   2275:                                /* Remember the start of a span of whitespace */
                   2276:                                if (r == -1)
                   2277:                                        r = i;
                   2278:                        } else
                   2279:                                r = -1;
                   2280:                }
                   2281:                if (r != -1)
                   2282:                        cp[r] = '\0';
                   2283:                if (*cp == '\0')
                   2284:                        continue;
                   2285:                if (strncasecmp(cp, "serial:", 7) == 0) {
1.261     djm      2286:                        if (ca == NULL && !wild_ca) {
1.231     djm      2287:                                fatal("revoking certificates by serial number "
1.223     djm      2288:                                    "requires specification of a CA key");
                   2289:                        }
                   2290:                        cp += 7;
                   2291:                        cp = cp + strspn(cp, " \t");
                   2292:                        errno = 0;
                   2293:                        serial = strtoull(cp, &ep, 0);
                   2294:                        if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
                   2295:                                fatal("%s:%lu: invalid serial \"%s\"",
                   2296:                                    path, lnum, cp);
                   2297:                        if (errno == ERANGE && serial == ULLONG_MAX)
                   2298:                                fatal("%s:%lu: serial out of range",
                   2299:                                    path, lnum);
                   2300:                        serial2 = serial;
                   2301:                        if (*ep == '-') {
                   2302:                                cp = ep + 1;
                   2303:                                errno = 0;
                   2304:                                serial2 = strtoull(cp, &ep, 0);
                   2305:                                if (*cp == '\0' || *ep != '\0')
                   2306:                                        fatal("%s:%lu: invalid serial \"%s\"",
                   2307:                                            path, lnum, cp);
                   2308:                                if (errno == ERANGE && serial2 == ULLONG_MAX)
                   2309:                                        fatal("%s:%lu: serial out of range",
                   2310:                                            path, lnum);
                   2311:                                if (serial2 <= serial)
                   2312:                                        fatal("%s:%lu: invalid serial range "
                   2313:                                            "%llu:%llu", path, lnum,
                   2314:                                            (unsigned long long)serial,
                   2315:                                            (unsigned long long)serial2);
                   2316:                        }
                   2317:                        if (ssh_krl_revoke_cert_by_serial_range(krl,
                   2318:                            ca, serial, serial2) != 0) {
1.421     djm      2319:                                fatal_f("revoke serial failed");
1.223     djm      2320:                        }
                   2321:                } else if (strncasecmp(cp, "id:", 3) == 0) {
1.261     djm      2322:                        if (ca == NULL && !wild_ca) {
1.232     djm      2323:                                fatal("revoking certificates by key ID "
1.223     djm      2324:                                    "requires specification of a CA key");
                   2325:                        }
                   2326:                        cp += 3;
                   2327:                        cp = cp + strspn(cp, " \t");
                   2328:                        if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
1.421     djm      2329:                                fatal_f("revoke key ID failed");
1.320     djm      2330:                } else if (strncasecmp(cp, "hash:", 5) == 0) {
                   2331:                        cp += 5;
                   2332:                        cp = cp + strspn(cp, " \t");
                   2333:                        hash_to_blob(cp, &blob, &blen, file, lnum);
                   2334:                        r = ssh_krl_revoke_key_sha256(krl, blob, blen);
1.401     markus   2335:                        if (r != 0)
1.421     djm      2336:                                fatal_fr(r, "revoke key failed");
1.223     djm      2337:                } else {
                   2338:                        if (strncasecmp(cp, "key:", 4) == 0) {
                   2339:                                cp += 4;
                   2340:                                cp = cp + strspn(cp, " \t");
                   2341:                                was_explicit_key = 1;
                   2342:                        } else if (strncasecmp(cp, "sha1:", 5) == 0) {
                   2343:                                cp += 5;
                   2344:                                cp = cp + strspn(cp, " \t");
                   2345:                                was_sha1 = 1;
1.320     djm      2346:                        } else if (strncasecmp(cp, "sha256:", 7) == 0) {
                   2347:                                cp += 7;
                   2348:                                cp = cp + strspn(cp, " \t");
                   2349:                                was_sha256 = 1;
1.223     djm      2350:                                /*
                   2351:                                 * Just try to process the line as a key.
                   2352:                                 * Parsing will fail if it isn't.
                   2353:                                 */
                   2354:                        }
1.252     djm      2355:                        if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
1.304     markus   2356:                                fatal("sshkey_new");
1.252     djm      2357:                        if ((r = sshkey_read(key, &cp)) != 0)
1.421     djm      2358:                                fatal_r(r, "%s:%lu: invalid key", path, lnum);
1.223     djm      2359:                        if (was_explicit_key)
                   2360:                                r = ssh_krl_revoke_key_explicit(krl, key);
1.320     djm      2361:                        else if (was_sha1) {
                   2362:                                if (sshkey_fingerprint_raw(key,
                   2363:                                    SSH_DIGEST_SHA1, &blob, &blen) != 0) {
                   2364:                                        fatal("%s:%lu: fingerprint failed",
                   2365:                                            file, lnum);
                   2366:                                }
                   2367:                                r = ssh_krl_revoke_key_sha1(krl, blob, blen);
                   2368:                        } else if (was_sha256) {
                   2369:                                if (sshkey_fingerprint_raw(key,
                   2370:                                    SSH_DIGEST_SHA256, &blob, &blen) != 0) {
                   2371:                                        fatal("%s:%lu: fingerprint failed",
                   2372:                                            file, lnum);
                   2373:                                }
                   2374:                                r = ssh_krl_revoke_key_sha256(krl, blob, blen);
                   2375:                        } else
1.223     djm      2376:                                r = ssh_krl_revoke_key(krl, key);
                   2377:                        if (r != 0)
1.421     djm      2378:                                fatal_fr(r, "revoke key failed");
1.320     djm      2379:                        freezero(blob, blen);
                   2380:                        blob = NULL;
                   2381:                        blen = 0;
1.252     djm      2382:                        sshkey_free(key);
1.223     djm      2383:                }
                   2384:        }
                   2385:        if (strcmp(path, "-") != 0)
                   2386:                fclose(krl_spec);
1.317     markus   2387:        free(line);
1.226     djm      2388:        free(path);
1.223     djm      2389: }
                   2390:
                   2391: static void
1.325     djm      2392: do_gen_krl(struct passwd *pw, int updating, const char *ca_key_path,
                   2393:     unsigned long long krl_version, const char *krl_comment,
                   2394:     int argc, char **argv)
1.223     djm      2395: {
                   2396:        struct ssh_krl *krl;
                   2397:        struct stat sb;
1.252     djm      2398:        struct sshkey *ca = NULL;
1.393     djm      2399:        int i, r, wild_ca = 0;
1.223     djm      2400:        char *tmp;
1.252     djm      2401:        struct sshbuf *kbuf;
1.223     djm      2402:
                   2403:        if (*identity_file == '\0')
                   2404:                fatal("KRL generation requires an output file");
                   2405:        if (stat(identity_file, &sb) == -1) {
                   2406:                if (errno != ENOENT)
                   2407:                        fatal("Cannot access KRL \"%s\": %s",
                   2408:                            identity_file, strerror(errno));
                   2409:                if (updating)
                   2410:                        fatal("KRL \"%s\" does not exist", identity_file);
                   2411:        }
                   2412:        if (ca_key_path != NULL) {
1.261     djm      2413:                if (strcasecmp(ca_key_path, "none") == 0)
                   2414:                        wild_ca = 1;
                   2415:                else {
                   2416:                        tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
                   2417:                        if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
1.421     djm      2418:                                fatal_r(r, "Cannot load CA public key %s", tmp);
1.261     djm      2419:                        free(tmp);
                   2420:                }
1.223     djm      2421:        }
                   2422:
                   2423:        if (updating)
                   2424:                load_krl(identity_file, &krl);
                   2425:        else if ((krl = ssh_krl_init()) == NULL)
                   2426:                fatal("couldn't create KRL");
                   2427:
1.325     djm      2428:        if (krl_version != 0)
                   2429:                ssh_krl_set_version(krl, krl_version);
                   2430:        if (krl_comment != NULL)
                   2431:                ssh_krl_set_comment(krl, krl_comment);
1.223     djm      2432:
                   2433:        for (i = 0; i < argc; i++)
1.261     djm      2434:                update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
1.223     djm      2435:
1.252     djm      2436:        if ((kbuf = sshbuf_new()) == NULL)
                   2437:                fatal("sshbuf_new failed");
                   2438:        if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
1.223     djm      2439:                fatal("Couldn't generate KRL");
1.393     djm      2440:        if ((r = sshbuf_write_file(identity_file, kbuf)) != 0)
1.223     djm      2441:                fatal("write %s: %s", identity_file, strerror(errno));
1.252     djm      2442:        sshbuf_free(kbuf);
1.223     djm      2443:        ssh_krl_free(krl);
1.286     mmcc     2444:        sshkey_free(ca);
1.223     djm      2445: }
                   2446:
                   2447: static void
1.405     djm      2448: do_check_krl(struct passwd *pw, int print_krl, int argc, char **argv)
1.223     djm      2449: {
                   2450:        int i, r, ret = 0;
                   2451:        char *comment;
                   2452:        struct ssh_krl *krl;
1.252     djm      2453:        struct sshkey *k;
1.223     djm      2454:
                   2455:        if (*identity_file == '\0')
                   2456:                fatal("KRL checking requires an input file");
                   2457:        load_krl(identity_file, &krl);
1.405     djm      2458:        if (print_krl)
                   2459:                krl_dump(krl, stdout);
1.223     djm      2460:        for (i = 0; i < argc; i++) {
1.252     djm      2461:                if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
1.421     djm      2462:                        fatal_r(r, "Cannot load public key %s", argv[i]);
1.223     djm      2463:                r = ssh_krl_check_key(krl, k);
                   2464:                printf("%s%s%s%s: %s\n", argv[i],
                   2465:                    *comment ? " (" : "", comment, *comment ? ")" : "",
                   2466:                    r == 0 ? "ok" : "REVOKED");
                   2467:                if (r != 0)
                   2468:                        ret = 1;
1.252     djm      2469:                sshkey_free(k);
1.223     djm      2470:                free(comment);
                   2471:        }
                   2472:        ssh_krl_free(krl);
                   2473:        exit(ret);
                   2474: }
                   2475:
1.344     djm      2476: static struct sshkey *
                   2477: load_sign_key(const char *keypath, const struct sshkey *pubkey)
                   2478: {
                   2479:        size_t i, slen, plen = strlen(keypath);
                   2480:        char *privpath = xstrdup(keypath);
1.448     djm      2481:        static const char * const suffixes[] = { "-cert.pub", ".pub", NULL };
1.344     djm      2482:        struct sshkey *ret = NULL, *privkey = NULL;
1.451     djm      2483:        int r, waspub = 0;
                   2484:        struct stat st;
1.344     djm      2485:
                   2486:        /*
1.404     djm      2487:         * If passed a public key filename, then try to locate the corresponding
1.344     djm      2488:         * private key. This lets us specify certificates on the command-line
                   2489:         * and have ssh-keygen find the appropriate private key.
                   2490:         */
                   2491:        for (i = 0; suffixes[i]; i++) {
                   2492:                slen = strlen(suffixes[i]);
                   2493:                if (plen <= slen ||
                   2494:                    strcmp(privpath + plen - slen, suffixes[i]) != 0)
                   2495:                        continue;
                   2496:                privpath[plen - slen] = '\0';
1.421     djm      2497:                debug_f("%s looks like a public key, using private key "
                   2498:                    "path %s instead", keypath, privpath);
1.451     djm      2499:                waspub = 1;
1.344     djm      2500:        }
1.451     djm      2501:        if (waspub && stat(privpath, &st) != 0 && errno == ENOENT)
                   2502:                fatal("No private key found for public key \"%s\"", keypath);
                   2503:        if ((r = sshkey_load_private(privpath, "", &privkey, NULL)) != 0 &&
                   2504:            (r != SSH_ERR_KEY_WRONG_PASSPHRASE)) {
                   2505:                debug_fr(r, "load private key \"%s\"", privpath);
                   2506:                fatal("No private key found for \"%s\"", privpath);
                   2507:        } else if (privkey == NULL)
                   2508:                privkey = load_identity(privpath, NULL);
                   2509:
1.344     djm      2510:        if (!sshkey_equal_public(pubkey, privkey)) {
                   2511:                error("Public key %s doesn't match private %s",
                   2512:                    keypath, privpath);
                   2513:                goto done;
                   2514:        }
                   2515:        if (sshkey_is_cert(pubkey) && !sshkey_is_cert(privkey)) {
                   2516:                /*
                   2517:                 * Graft the certificate onto the private key to make
                   2518:                 * it capable of signing.
                   2519:                 */
                   2520:                if ((r = sshkey_to_certified(privkey)) != 0) {
1.421     djm      2521:                        error_fr(r, "sshkey_to_certified");
1.344     djm      2522:                        goto done;
                   2523:                }
                   2524:                if ((r = sshkey_cert_copy(pubkey, privkey)) != 0) {
1.421     djm      2525:                        error_fr(r, "sshkey_cert_copy");
1.344     djm      2526:                        goto done;
                   2527:                }
                   2528:        }
                   2529:        /* success */
                   2530:        ret = privkey;
                   2531:        privkey = NULL;
                   2532:  done:
                   2533:        sshkey_free(privkey);
                   2534:        free(privpath);
                   2535:        return ret;
                   2536: }
                   2537:
                   2538: static int
                   2539: sign_one(struct sshkey *signkey, const char *filename, int fd,
1.445     djm      2540:     const char *sig_namespace, const char *hashalg, sshsig_signer *signer,
                   2541:     void *signer_ctx)
1.344     djm      2542: {
                   2543:        struct sshbuf *sigbuf = NULL, *abuf = NULL;
                   2544:        int r = SSH_ERR_INTERNAL_ERROR, wfd = -1, oerrno;
1.363     djm      2545:        char *wfile = NULL, *asig = NULL, *fp = NULL;
1.416     djm      2546:        char *pin = NULL, *prompt = NULL;
1.344     djm      2547:
                   2548:        if (!quiet) {
                   2549:                if (fd == STDIN_FILENO)
                   2550:                        fprintf(stderr, "Signing data on standard input\n");
                   2551:                else
                   2552:                        fprintf(stderr, "Signing file %s\n", filename);
1.363     djm      2553:        }
1.416     djm      2554:        if (signer == NULL && sshkey_is_sk(signkey)) {
                   2555:                if ((signkey->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
                   2556:                        xasprintf(&prompt, "Enter PIN for %s key: ",
                   2557:                            sshkey_type(signkey));
                   2558:                        if ((pin = read_passphrase(prompt,
                   2559:                            RP_ALLOW_STDIN)) == NULL)
1.421     djm      2560:                                fatal_f("couldn't read PIN");
1.416     djm      2561:                }
                   2562:                if ((signkey->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
                   2563:                        if ((fp = sshkey_fingerprint(signkey, fingerprint_hash,
                   2564:                            SSH_FP_DEFAULT)) == NULL)
1.421     djm      2565:                                fatal_f("fingerprint failed");
1.416     djm      2566:                        fprintf(stderr, "Confirm user presence for key %s %s\n",
                   2567:                            sshkey_type(signkey), fp);
                   2568:                        free(fp);
                   2569:                }
1.344     djm      2570:        }
1.445     djm      2571:        if ((r = sshsig_sign_fd(signkey, hashalg, sk_provider, pin,
1.416     djm      2572:            fd, sig_namespace, &sigbuf, signer, signer_ctx)) != 0) {
1.421     djm      2573:                error_r(r, "Signing %s failed", filename);
1.344     djm      2574:                goto out;
                   2575:        }
                   2576:        if ((r = sshsig_armor(sigbuf, &abuf)) != 0) {
1.421     djm      2577:                error_fr(r, "sshsig_armor");
1.344     djm      2578:                goto out;
                   2579:        }
                   2580:        if ((asig = sshbuf_dup_string(abuf)) == NULL) {
1.421     djm      2581:                error_f("buffer error");
1.344     djm      2582:                r = SSH_ERR_ALLOC_FAIL;
                   2583:                goto out;
                   2584:        }
                   2585:
                   2586:        if (fd == STDIN_FILENO) {
                   2587:                fputs(asig, stdout);
                   2588:                fflush(stdout);
                   2589:        } else {
                   2590:                xasprintf(&wfile, "%s.sig", filename);
                   2591:                if (confirm_overwrite(wfile)) {
                   2592:                        if ((wfd = open(wfile, O_WRONLY|O_CREAT|O_TRUNC,
                   2593:                            0666)) == -1) {
                   2594:                                oerrno = errno;
                   2595:                                error("Cannot open %s: %s",
                   2596:                                    wfile, strerror(errno));
                   2597:                                errno = oerrno;
                   2598:                                r = SSH_ERR_SYSTEM_ERROR;
                   2599:                                goto out;
                   2600:                        }
                   2601:                        if (atomicio(vwrite, wfd, asig,
                   2602:                            strlen(asig)) != strlen(asig)) {
                   2603:                                oerrno = errno;
                   2604:                                error("Cannot write to %s: %s",
                   2605:                                    wfile, strerror(errno));
                   2606:                                errno = oerrno;
                   2607:                                r = SSH_ERR_SYSTEM_ERROR;
                   2608:                                goto out;
                   2609:                        }
                   2610:                        if (!quiet) {
                   2611:                                fprintf(stderr, "Write signature to %s\n",
                   2612:                                    wfile);
                   2613:                        }
                   2614:                }
                   2615:        }
                   2616:        /* success */
                   2617:        r = 0;
                   2618:  out:
                   2619:        free(wfile);
1.416     djm      2620:        free(prompt);
1.344     djm      2621:        free(asig);
1.416     djm      2622:        if (pin != NULL)
                   2623:                freezero(pin, strlen(pin));
1.344     djm      2624:        sshbuf_free(abuf);
                   2625:        sshbuf_free(sigbuf);
                   2626:        if (wfd != -1)
                   2627:                close(wfd);
                   2628:        return r;
                   2629: }
                   2630:
                   2631: static int
1.445     djm      2632: sig_process_opts(char * const *opts, size_t nopts, char **hashalgp,
                   2633:     uint64_t *verify_timep, int *print_pubkey)
1.443     djm      2634: {
                   2635:        size_t i;
                   2636:        time_t now;
                   2637:
                   2638:        if (verify_timep != NULL)
                   2639:                *verify_timep = 0;
                   2640:        if (print_pubkey != NULL)
                   2641:                *print_pubkey = 0;
1.445     djm      2642:        if (hashalgp != NULL)
                   2643:                *hashalgp = NULL;
1.443     djm      2644:        for (i = 0; i < nopts; i++) {
1.445     djm      2645:                if (hashalgp != NULL &&
                   2646:                    strncasecmp(opts[i], "hashalg=", 8) == 0) {
                   2647:                        *hashalgp = xstrdup(opts[i] + 8);
                   2648:                } else if (verify_timep &&
1.443     djm      2649:                    strncasecmp(opts[i], "verify-time=", 12) == 0) {
                   2650:                        if (parse_absolute_time(opts[i] + 12,
                   2651:                            verify_timep) != 0 || *verify_timep == 0) {
                   2652:                                error("Invalid \"verify-time\" option");
                   2653:                                return SSH_ERR_INVALID_ARGUMENT;
                   2654:                        }
                   2655:                } else if (print_pubkey &&
                   2656:                    strcasecmp(opts[i], "print-pubkey") == 0) {
                   2657:                        *print_pubkey = 1;
                   2658:                } else {
                   2659:                        error("Invalid option \"%s\"", opts[i]);
                   2660:                        return SSH_ERR_INVALID_ARGUMENT;
                   2661:                }
                   2662:        }
                   2663:        if (verify_timep && *verify_timep == 0) {
                   2664:                if ((now = time(NULL)) < 0) {
                   2665:                        error("Time is before epoch");
                   2666:                        return SSH_ERR_INVALID_ARGUMENT;
                   2667:                }
                   2668:                *verify_timep = (uint64_t)now;
                   2669:        }
                   2670:        return 0;
                   2671: }
                   2672:
                   2673:
                   2674: static int
1.452     djm      2675: sig_sign(const char *keypath, const char *sig_namespace, int require_agent,
                   2676:     int argc, char **argv, char * const *opts, size_t nopts)
1.344     djm      2677: {
                   2678:        int i, fd = -1, r, ret = -1;
                   2679:        int agent_fd = -1;
                   2680:        struct sshkey *pubkey = NULL, *privkey = NULL, *signkey = NULL;
                   2681:        sshsig_signer *signer = NULL;
1.445     djm      2682:        char *hashalg = NULL;
1.344     djm      2683:
                   2684:        /* Check file arguments. */
                   2685:        for (i = 0; i < argc; i++) {
                   2686:                if (strcmp(argv[i], "-") != 0)
                   2687:                        continue;
                   2688:                if (i > 0 || argc > 1)
                   2689:                        fatal("Cannot sign mix of paths and standard input");
                   2690:        }
                   2691:
1.445     djm      2692:        if (sig_process_opts(opts, nopts, &hashalg, NULL, NULL) != 0)
                   2693:                goto done; /* error already logged */
                   2694:
1.344     djm      2695:        if ((r = sshkey_load_public(keypath, &pubkey, NULL)) != 0) {
1.421     djm      2696:                error_r(r, "Couldn't load public key %s", keypath);
1.344     djm      2697:                goto done;
                   2698:        }
                   2699:
1.452     djm      2700:        if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
                   2701:                if (require_agent)
                   2702:                        fatal("Couldn't get agent socket");
1.421     djm      2703:                debug_r(r, "Couldn't get agent socket");
1.452     djm      2704:        } else {
1.344     djm      2705:                if ((r = ssh_agent_has_key(agent_fd, pubkey)) == 0)
                   2706:                        signer = agent_signer;
1.452     djm      2707:                else {
                   2708:                        if (require_agent)
                   2709:                                fatal("Couldn't find key in agent");
1.421     djm      2710:                        debug_r(r, "Couldn't find key in agent");
1.452     djm      2711:                }
1.344     djm      2712:        }
                   2713:
                   2714:        if (signer == NULL) {
                   2715:                /* Not using agent - try to load private key */
                   2716:                if ((privkey = load_sign_key(keypath, pubkey)) == NULL)
                   2717:                        goto done;
                   2718:                signkey = privkey;
                   2719:        } else {
                   2720:                /* Will use key in agent */
                   2721:                signkey = pubkey;
                   2722:        }
                   2723:
                   2724:        if (argc == 0) {
                   2725:                if ((r = sign_one(signkey, "(stdin)", STDIN_FILENO,
1.445     djm      2726:                    sig_namespace, hashalg, signer, &agent_fd)) != 0)
1.344     djm      2727:                        goto done;
                   2728:        } else {
                   2729:                for (i = 0; i < argc; i++) {
                   2730:                        if (strcmp(argv[i], "-") == 0)
                   2731:                                fd = STDIN_FILENO;
                   2732:                        else if ((fd = open(argv[i], O_RDONLY)) == -1) {
                   2733:                                error("Cannot open %s for signing: %s",
                   2734:                                    argv[i], strerror(errno));
                   2735:                                goto done;
                   2736:                        }
                   2737:                        if ((r = sign_one(signkey, argv[i], fd, sig_namespace,
1.445     djm      2738:                            hashalg, signer, &agent_fd)) != 0)
1.344     djm      2739:                                goto done;
                   2740:                        if (fd != STDIN_FILENO)
                   2741:                                close(fd);
                   2742:                        fd = -1;
                   2743:                }
                   2744:        }
                   2745:
                   2746:        ret = 0;
                   2747: done:
                   2748:        if (fd != -1 && fd != STDIN_FILENO)
                   2749:                close(fd);
                   2750:        sshkey_free(pubkey);
                   2751:        sshkey_free(privkey);
1.445     djm      2752:        free(hashalg);
1.344     djm      2753:        return ret;
1.432     djm      2754: }
                   2755:
                   2756: static int
1.386     djm      2757: sig_verify(const char *signature, const char *sig_namespace,
1.432     djm      2758:     const char *principal, const char *allowed_keys, const char *revoked_keys,
                   2759:     char * const *opts, size_t nopts)
1.344     djm      2760: {
1.393     djm      2761:        int r, ret = -1;
1.435     djm      2762:        int print_pubkey = 0;
1.344     djm      2763:        struct sshbuf *sigbuf = NULL, *abuf = NULL;
                   2764:        struct sshkey *sign_key = NULL;
                   2765:        char *fp = NULL;
1.370     djm      2766:        struct sshkey_sig_details *sig_details = NULL;
1.432     djm      2767:        uint64_t verify_time = 0;
                   2768:
1.445     djm      2769:        if (sig_process_opts(opts, nopts, NULL, &verify_time,
                   2770:            &print_pubkey) != 0)
1.432     djm      2771:                goto done; /* error already logged */
1.344     djm      2772:
1.370     djm      2773:        memset(&sig_details, 0, sizeof(sig_details));
1.393     djm      2774:        if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
1.421     djm      2775:                error_r(r, "Couldn't read signature file");
1.344     djm      2776:                goto done;
                   2777:        }
                   2778:
                   2779:        if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
1.421     djm      2780:                error_fr(r, "sshsig_armor");
1.386     djm      2781:                goto done;
1.344     djm      2782:        }
                   2783:        if ((r = sshsig_verify_fd(sigbuf, STDIN_FILENO, sig_namespace,
1.370     djm      2784:            &sign_key, &sig_details)) != 0)
1.344     djm      2785:                goto done; /* sshsig_verify() prints error */
                   2786:
                   2787:        if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
                   2788:            SSH_FP_DEFAULT)) == NULL)
1.421     djm      2789:                fatal_f("sshkey_fingerprint failed");
1.344     djm      2790:        debug("Valid (unverified) signature from key %s", fp);
1.370     djm      2791:        if (sig_details != NULL) {
1.421     djm      2792:                debug2_f("signature details: counter = %u, flags = 0x%02x",
                   2793:                    sig_details->sk_counter, sig_details->sk_flags);
1.370     djm      2794:        }
1.344     djm      2795:        free(fp);
                   2796:        fp = NULL;
                   2797:
                   2798:        if (revoked_keys != NULL) {
1.345     djm      2799:                if ((r = sshkey_check_revoked(sign_key, revoked_keys)) != 0) {
1.421     djm      2800:                        debug3_fr(r, "sshkey_check_revoked");
1.345     djm      2801:                        goto done;
                   2802:                }
1.344     djm      2803:        }
                   2804:
1.421     djm      2805:        if (allowed_keys != NULL && (r = sshsig_check_allowed_keys(allowed_keys,
1.432     djm      2806:            sign_key, principal, sig_namespace, verify_time)) != 0) {
1.421     djm      2807:                debug3_fr(r, "sshsig_check_allowed_keys");
1.344     djm      2808:                goto done;
                   2809:        }
                   2810:        /* success */
                   2811:        ret = 0;
                   2812: done:
                   2813:        if (!quiet) {
                   2814:                if (ret == 0) {
                   2815:                        if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
1.421     djm      2816:                            SSH_FP_DEFAULT)) == NULL)
                   2817:                                fatal_f("sshkey_fingerprint failed");
1.350     djm      2818:                        if (principal == NULL) {
                   2819:                                printf("Good \"%s\" signature with %s key %s\n",
1.429     djm      2820:                                    sig_namespace, sshkey_type(sign_key), fp);
1.350     djm      2821:
                   2822:                        } else {
                   2823:                                printf("Good \"%s\" signature for %s with %s key %s\n",
1.429     djm      2824:                                    sig_namespace, principal,
                   2825:                                    sshkey_type(sign_key), fp);
1.350     djm      2826:                        }
1.344     djm      2827:                } else {
                   2828:                        printf("Could not verify signature.\n");
                   2829:                }
                   2830:        }
1.435     djm      2831:        /* Print the signature key if requested */
                   2832:        if (ret == 0 && print_pubkey && sign_key != NULL) {
                   2833:                if ((r = sshkey_write(sign_key, stdout)) == 0)
                   2834:                        fputc('\n', stdout);
                   2835:                else {
                   2836:                        error_r(r, "Could not print public key.\n");
                   2837:                        ret = -1;
                   2838:                }
                   2839:        }
1.344     djm      2840:        sshbuf_free(sigbuf);
                   2841:        sshbuf_free(abuf);
                   2842:        sshkey_free(sign_key);
1.370     djm      2843:        sshkey_sig_details_free(sig_details);
1.344     djm      2844:        free(fp);
                   2845:        return ret;
                   2846: }
                   2847:
1.386     djm      2848: static int
1.432     djm      2849: sig_find_principals(const char *signature, const char *allowed_keys,
                   2850:     char * const *opts, size_t nopts)
                   2851: {
1.393     djm      2852:        int r, ret = -1;
1.386     djm      2853:        struct sshbuf *sigbuf = NULL, *abuf = NULL;
                   2854:        struct sshkey *sign_key = NULL;
1.391     djm      2855:        char *principals = NULL, *cp, *tmp;
1.432     djm      2856:        uint64_t verify_time = 0;
                   2857:
1.445     djm      2858:        if (sig_process_opts(opts, nopts, NULL, &verify_time, NULL) != 0)
1.432     djm      2859:                goto done; /* error already logged */
1.386     djm      2860:
1.393     djm      2861:        if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
1.421     djm      2862:                error_r(r, "Couldn't read signature file");
1.386     djm      2863:                goto done;
                   2864:        }
                   2865:        if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
1.421     djm      2866:                error_fr(r, "sshsig_armor");
1.386     djm      2867:                goto done;
                   2868:        }
                   2869:        if ((r = sshsig_get_pubkey(sigbuf, &sign_key)) != 0) {
1.421     djm      2870:                error_fr(r, "sshsig_get_pubkey");
1.386     djm      2871:                goto done;
                   2872:        }
1.388     djm      2873:        if ((r = sshsig_find_principals(allowed_keys, sign_key,
1.432     djm      2874:            verify_time, &principals)) != 0) {
1.431     djm      2875:                if (r != SSH_ERR_KEY_NOT_FOUND)
                   2876:                        error_fr(r, "sshsig_find_principal");
1.386     djm      2877:                goto done;
                   2878:        }
                   2879:        ret = 0;
                   2880: done:
                   2881:        if (ret == 0 ) {
1.391     djm      2882:                /* Emit matching principals one per line */
                   2883:                tmp = principals;
                   2884:                while ((cp = strsep(&tmp, ",")) != NULL && *cp != '\0')
                   2885:                        puts(cp);
1.386     djm      2886:        } else {
1.391     djm      2887:                fprintf(stderr, "No principal matched.\n");
1.386     djm      2888:        }
                   2889:        sshbuf_free(sigbuf);
                   2890:        sshbuf_free(abuf);
                   2891:        sshkey_free(sign_key);
1.388     djm      2892:        free(principals);
1.386     djm      2893:        return ret;
                   2894: }
                   2895:
1.441     djm      2896: static int
                   2897: sig_match_principals(const char *allowed_keys, char *principal,
                   2898:        char * const *opts, size_t nopts)
                   2899: {
                   2900:        int r;
                   2901:        char **principals = NULL;
                   2902:        size_t i, nprincipals = 0;
                   2903:
1.445     djm      2904:        if ((r = sig_process_opts(opts, nopts, NULL, NULL, NULL)) != 0)
1.441     djm      2905:                return r; /* error already logged */
                   2906:
                   2907:        if ((r = sshsig_match_principals(allowed_keys, principal,
                   2908:            &principals, &nprincipals)) != 0) {
                   2909:                debug_f("match: %s", ssh_err(r));
                   2910:                fprintf(stderr, "No principal matched.\n");
                   2911:                return r;
                   2912:        }
                   2913:        for (i = 0; i < nprincipals; i++) {
                   2914:                printf("%s\n", principals[i]);
                   2915:                free(principals[i]);
                   2916:        }
                   2917:        free(principals);
                   2918:
                   2919:        return 0;
                   2920: }
                   2921:
1.223     djm      2922: static void
1.376     djm      2923: do_moduli_gen(const char *out_file, char **opts, size_t nopts)
                   2924: {
                   2925: #ifdef WITH_OPENSSL
                   2926:        /* Moduli generation/screening */
                   2927:        u_int32_t memory = 0;
                   2928:        BIGNUM *start = NULL;
                   2929:        int moduli_bits = 0;
                   2930:        FILE *out;
                   2931:        size_t i;
                   2932:        const char *errstr;
                   2933:
                   2934:        /* Parse options */
                   2935:        for (i = 0; i < nopts; i++) {
                   2936:                if (strncmp(opts[i], "memory=", 7) == 0) {
                   2937:                        memory = (u_int32_t)strtonum(opts[i]+7, 1,
                   2938:                            UINT_MAX, &errstr);
                   2939:                        if (errstr) {
                   2940:                                fatal("Memory limit is %s: %s",
                   2941:                                    errstr, opts[i]+7);
                   2942:                        }
                   2943:                } else if (strncmp(opts[i], "start=", 6) == 0) {
                   2944:                        /* XXX - also compare length against bits */
                   2945:                        if (BN_hex2bn(&start, opts[i]+6) == 0)
                   2946:                                fatal("Invalid start point.");
                   2947:                } else if (strncmp(opts[i], "bits=", 5) == 0) {
                   2948:                        moduli_bits = (int)strtonum(opts[i]+5, 1,
                   2949:                            INT_MAX, &errstr);
                   2950:                        if (errstr) {
                   2951:                                fatal("Invalid number: %s (%s)",
                   2952:                                        opts[i]+12, errstr);
                   2953:                        }
                   2954:                } else {
                   2955:                        fatal("Option \"%s\" is unsupported for moduli "
                   2956:                            "generation", opts[i]);
                   2957:                }
                   2958:        }
                   2959:
                   2960:        if ((out = fopen(out_file, "w")) == NULL) {
                   2961:                fatal("Couldn't open modulus candidate file \"%s\": %s",
                   2962:                    out_file, strerror(errno));
                   2963:        }
                   2964:        setvbuf(out, NULL, _IOLBF, 0);
                   2965:
                   2966:        if (moduli_bits == 0)
                   2967:                moduli_bits = DEFAULT_BITS;
                   2968:        if (gen_candidates(out, memory, moduli_bits, start) != 0)
                   2969:                fatal("modulus candidate generation failed");
                   2970: #else /* WITH_OPENSSL */
                   2971:        fatal("Moduli generation is not supported");
                   2972: #endif /* WITH_OPENSSL */
                   2973: }
                   2974:
                   2975: static void
                   2976: do_moduli_screen(const char *out_file, char **opts, size_t nopts)
                   2977: {
                   2978: #ifdef WITH_OPENSSL
                   2979:        /* Moduli generation/screening */
                   2980:        char *checkpoint = NULL;
                   2981:        u_int32_t generator_wanted = 0;
                   2982:        unsigned long start_lineno = 0, lines_to_process = 0;
                   2983:        int prime_tests = 0;
                   2984:        FILE *out, *in = stdin;
                   2985:        size_t i;
                   2986:        const char *errstr;
                   2987:
                   2988:        /* Parse options */
                   2989:        for (i = 0; i < nopts; i++) {
                   2990:                if (strncmp(opts[i], "lines=", 6) == 0) {
                   2991:                        lines_to_process = strtoul(opts[i]+6, NULL, 10);
                   2992:                } else if (strncmp(opts[i], "start-line=", 11) == 0) {
                   2993:                        start_lineno = strtoul(opts[i]+11, NULL, 10);
                   2994:                } else if (strncmp(opts[i], "checkpoint=", 11) == 0) {
1.465   ! dtucker  2995:                        free(checkpoint);
1.376     djm      2996:                        checkpoint = xstrdup(opts[i]+11);
                   2997:                } else if (strncmp(opts[i], "generator=", 10) == 0) {
                   2998:                        generator_wanted = (u_int32_t)strtonum(
                   2999:                            opts[i]+10, 1, UINT_MAX, &errstr);
                   3000:                        if (errstr != NULL) {
                   3001:                                fatal("Generator invalid: %s (%s)",
                   3002:                                    opts[i]+10, errstr);
                   3003:                        }
                   3004:                } else if (strncmp(opts[i], "prime-tests=", 12) == 0) {
                   3005:                        prime_tests = (int)strtonum(opts[i]+12, 1,
                   3006:                            INT_MAX, &errstr);
                   3007:                        if (errstr) {
                   3008:                                fatal("Invalid number: %s (%s)",
                   3009:                                        opts[i]+12, errstr);
                   3010:                        }
                   3011:                } else {
                   3012:                        fatal("Option \"%s\" is unsupported for moduli "
                   3013:                            "screening", opts[i]);
                   3014:                }
                   3015:        }
                   3016:
                   3017:        if (have_identity && strcmp(identity_file, "-") != 0) {
                   3018:                if ((in = fopen(identity_file, "r")) == NULL) {
                   3019:                        fatal("Couldn't open modulus candidate "
                   3020:                            "file \"%s\": %s", identity_file,
                   3021:                            strerror(errno));
                   3022:                }
                   3023:        }
                   3024:
                   3025:        if ((out = fopen(out_file, "a")) == NULL) {
                   3026:                fatal("Couldn't open moduli file \"%s\": %s",
                   3027:                    out_file, strerror(errno));
                   3028:        }
                   3029:        setvbuf(out, NULL, _IOLBF, 0);
                   3030:        if (prime_test(in, out, prime_tests == 0 ? 100 : prime_tests,
                   3031:            generator_wanted, checkpoint,
                   3032:            start_lineno, lines_to_process) != 0)
                   3033:                fatal("modulus screening failed");
1.465   ! dtucker  3034:        if (in != stdin)
        !          3035:                (void)fclose(in);
1.464     dtucker  3036:        free(checkpoint);
1.376     djm      3037: #else /* WITH_OPENSSL */
                   3038:        fatal("Moduli screening is not supported");
                   3039: #endif /* WITH_OPENSSL */
                   3040: }
                   3041:
1.455     djm      3042: /* Read and confirm a passphrase */
1.381     djm      3043: static char *
1.455     djm      3044: read_check_passphrase(const char *prompt1, const char *prompt2,
                   3045:     const char *retry_prompt)
1.381     djm      3046: {
                   3047:        char *passphrase1, *passphrase2;
                   3048:
1.455     djm      3049:        for (;;) {
                   3050:                passphrase1 = read_passphrase(prompt1, RP_ALLOW_STDIN);
                   3051:                passphrase2 = read_passphrase(prompt2, RP_ALLOW_STDIN);
                   3052:                if (strcmp(passphrase1, passphrase2) == 0) {
1.381     djm      3053:                        freezero(passphrase2, strlen(passphrase2));
1.455     djm      3054:                        return passphrase1;
1.381     djm      3055:                }
1.455     djm      3056:                /* The passphrases do not match. Clear them and retry. */
                   3057:                freezero(passphrase1, strlen(passphrase1));
1.381     djm      3058:                freezero(passphrase2, strlen(passphrase2));
1.455     djm      3059:                fputs(retry_prompt, stdout);
                   3060:                fputc('\n', stdout);
                   3061:                fflush(stdout);
1.381     djm      3062:        }
1.455     djm      3063:        /* NOTREACHED */
                   3064:        return NULL;
                   3065: }
                   3066:
                   3067: static char *
                   3068: private_key_passphrase(void)
                   3069: {
                   3070:        if (identity_passphrase)
                   3071:                return xstrdup(identity_passphrase);
                   3072:        if (identity_new_passphrase)
                   3073:                return xstrdup(identity_new_passphrase);
                   3074:
                   3075:        return read_check_passphrase(
                   3076:            "Enter passphrase (empty for no passphrase): ",
                   3077:            "Enter same passphrase again: ",
                   3078:            "Passphrases do not match.  Try again.");
1.381     djm      3079: }
                   3080:
1.439     djm      3081: static char *
                   3082: sk_suffix(const char *application, const uint8_t *user, size_t userlen)
1.381     djm      3083: {
1.439     djm      3084:        char *ret, *cp;
                   3085:        size_t slen, i;
                   3086:
                   3087:        /* Trim off URL-like preamble */
                   3088:        if (strncmp(application, "ssh://", 6) == 0)
                   3089:                ret =  xstrdup(application + 6);
                   3090:        else if (strncmp(application, "ssh:", 4) == 0)
                   3091:                ret =  xstrdup(application + 4);
                   3092:        else
                   3093:                ret = xstrdup(application);
                   3094:
                   3095:        /* Count trailing zeros in user */
                   3096:        for (i = 0; i < userlen; i++) {
                   3097:                if (user[userlen - i - 1] != 0)
                   3098:                        break;
                   3099:        }
                   3100:        if (i >= userlen)
                   3101:                return ret; /* user-id was default all-zeros */
                   3102:
                   3103:        /* Append user-id, escaping non-UTF-8 characters */
                   3104:        slen = userlen - i;
                   3105:        if (asmprintf(&cp, INT_MAX, NULL, "%.*s", (int)slen, user) == -1)
                   3106:                fatal_f("asmprintf failed");
                   3107:        /* Don't emit a user-id that contains path or control characters */
                   3108:        if (strchr(cp, '/') != NULL || strstr(cp, "..") != NULL ||
                   3109:            strchr(cp, '\\') != NULL) {
                   3110:                free(cp);
                   3111:                cp = tohex(user, slen);
                   3112:        }
                   3113:        xextendf(&ret, "_", "%s", cp);
                   3114:        free(cp);
                   3115:        return ret;
1.381     djm      3116: }
                   3117:
                   3118: static int
1.382     djm      3119: do_download_sk(const char *skprovider, const char *device)
1.381     djm      3120: {
1.439     djm      3121:        struct sshsk_resident_key **srks;
                   3122:        size_t nsrks, i;
1.412     djm      3123:        int r, ret = -1;
1.403     djm      3124:        char *fp, *pin = NULL, *pass = NULL, *path, *pubpath;
1.381     djm      3125:        const char *ext;
1.439     djm      3126:        struct sshkey *key;
1.381     djm      3127:
                   3128:        if (skprovider == NULL)
                   3129:                fatal("Cannot download keys without provider");
                   3130:
1.418     djm      3131:        pin = read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN);
                   3132:        if (!quiet) {
                   3133:                printf("You may need to touch your authenticator "
                   3134:                    "to authorize key download.\n");
                   3135:        }
1.439     djm      3136:        if ((r = sshsk_load_resident(skprovider, device, pin, 0,
                   3137:            &srks, &nsrks)) != 0) {
1.418     djm      3138:                if (pin != NULL)
                   3139:                        freezero(pin, strlen(pin));
1.421     djm      3140:                error_r(r, "Unable to load resident keys");
1.418     djm      3141:                return -1;
1.381     djm      3142:        }
1.439     djm      3143:        if (nsrks == 0)
1.381     djm      3144:                logit("No keys to download");
1.411     djm      3145:        if (pin != NULL)
                   3146:                freezero(pin, strlen(pin));
1.381     djm      3147:
1.439     djm      3148:        for (i = 0; i < nsrks; i++) {
                   3149:                key = srks[i]->key;
                   3150:                if (key->type != KEY_ECDSA_SK && key->type != KEY_ED25519_SK) {
1.381     djm      3151:                        error("Unsupported key type %s (%d)",
1.439     djm      3152:                            sshkey_type(key), key->type);
1.381     djm      3153:                        continue;
                   3154:                }
1.439     djm      3155:                if ((fp = sshkey_fingerprint(key, fingerprint_hash,
                   3156:                    SSH_FP_DEFAULT)) == NULL)
1.421     djm      3157:                        fatal_f("sshkey_fingerprint failed");
                   3158:                debug_f("key %zu: %s %s %s (flags 0x%02x)", i,
1.439     djm      3159:                    sshkey_type(key), fp, key->sk_application, key->sk_flags);
                   3160:                ext = sk_suffix(key->sk_application,
                   3161:                    srks[i]->user_id, srks[i]->user_id_len);
1.381     djm      3162:                xasprintf(&path, "id_%s_rk%s%s",
1.439     djm      3163:                    key->type == KEY_ECDSA_SK ? "ecdsa_sk" : "ed25519_sk",
1.381     djm      3164:                    *ext == '\0' ? "" : "_", ext);
                   3165:
                   3166:                /* If the file already exists, ask the user to confirm. */
                   3167:                if (!confirm_overwrite(path)) {
                   3168:                        free(path);
                   3169:                        break;
                   3170:                }
                   3171:
                   3172:                /* Save the key with the application string as the comment */
                   3173:                if (pass == NULL)
                   3174:                        pass = private_key_passphrase();
1.439     djm      3175:                if ((r = sshkey_save_private(key, path, pass,
                   3176:                    key->sk_application, private_key_format,
1.381     djm      3177:                    openssh_format_cipher, rounds)) != 0) {
1.421     djm      3178:                        error_r(r, "Saving key \"%s\" failed", path);
1.381     djm      3179:                        free(path);
                   3180:                        break;
                   3181:                }
                   3182:                if (!quiet) {
1.439     djm      3183:                        printf("Saved %s key%s%s to %s\n", sshkey_type(key),
1.381     djm      3184:                            *ext != '\0' ? " " : "",
1.439     djm      3185:                            *ext != '\0' ? key->sk_application : "",
1.381     djm      3186:                            path);
                   3187:                }
                   3188:
                   3189:                /* Save public key too */
                   3190:                xasprintf(&pubpath, "%s.pub", path);
                   3191:                free(path);
1.439     djm      3192:                if ((r = sshkey_save_public(key, pubpath,
                   3193:                    key->sk_application)) != 0) {
1.421     djm      3194:                        error_r(r, "Saving public key \"%s\" failed", pubpath);
1.402     markus   3195:                        free(pubpath);
1.381     djm      3196:                        break;
                   3197:                }
                   3198:                free(pubpath);
                   3199:        }
                   3200:
1.439     djm      3201:        if (i >= nsrks)
1.412     djm      3202:                ret = 0; /* success */
1.381     djm      3203:        if (pass != NULL)
                   3204:                freezero(pass, strlen(pass));
1.439     djm      3205:        sshsk_free_resident_keys(srks, nsrks);
1.412     djm      3206:        return ret;
1.381     djm      3207: }
                   3208:
1.376     djm      3209: static void
1.420     djm      3210: save_attestation(struct sshbuf *attest, const char *path)
                   3211: {
                   3212:        mode_t omask;
                   3213:        int r;
                   3214:
                   3215:        if (path == NULL)
                   3216:                return; /* nothing to do */
                   3217:        if (attest == NULL || sshbuf_len(attest) == 0)
                   3218:                fatal("Enrollment did not return attestation data");
                   3219:        omask = umask(077);
                   3220:        r = sshbuf_write_file(path, attest);
                   3221:        umask(omask);
                   3222:        if (r != 0)
1.421     djm      3223:                fatal_r(r, "Unable to write attestation data \"%s\"", path);
1.420     djm      3224:        if (!quiet)
                   3225:                printf("Your FIDO attestation certificate has been saved in "
                   3226:                    "%s\n", path);
                   3227: }
                   3228:
1.456     djm      3229: static int
                   3230: confirm_sk_overwrite(const char *application, const char *user)
                   3231: {
                   3232:        char yesno[3];
                   3233:
                   3234:        printf("A resident key scoped to '%s' with user id '%s' already "
                   3235:            "exists.\n", application == NULL ? "ssh:" : application,
                   3236:            user == NULL ? "null" : user);
                   3237:        printf("Overwrite key in token (y/n)? ");
                   3238:        fflush(stdout);
                   3239:        if (fgets(yesno, sizeof(yesno), stdin) == NULL)
                   3240:                return 0;
                   3241:        if (yesno[0] != 'y' && yesno[0] != 'Y')
                   3242:                return 0;
                   3243:        return 1;
                   3244: }
                   3245:
1.420     djm      3246: static void
1.10      markus   3247: usage(void)
                   3248: {
1.243     deraadt  3249:        fprintf(stderr,
1.414     solene   3250:            "usage: ssh-keygen [-q] [-a rounds] [-b bits] [-C comment] [-f output_keyfile]\n"
                   3251:            "                  [-m format] [-N new_passphrase] [-O option]\n"
1.369     naddy    3252:            "                  [-t dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa]\n"
1.425     dtucker  3253:            "                  [-w provider] [-Z cipher]\n"
1.414     solene   3254:            "       ssh-keygen -p [-a rounds] [-f keyfile] [-m format] [-N new_passphrase]\n"
1.425     dtucker  3255:            "                   [-P old_passphrase] [-Z cipher]\n"
1.433     dtucker  3256: #ifdef WITH_OPENSSL
1.355     jmc      3257:            "       ssh-keygen -i [-f input_keyfile] [-m key_format]\n"
                   3258:            "       ssh-keygen -e [-f input_keyfile] [-m key_format]\n"
1.434     dtucker  3259: #endif
1.243     deraadt  3260:            "       ssh-keygen -y [-f input_keyfile]\n"
1.414     solene   3261:            "       ssh-keygen -c [-a rounds] [-C comment] [-f keyfile] [-P passphrase]\n"
1.265     naddy    3262:            "       ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
1.302     djm      3263:            "       ssh-keygen -B [-f input_keyfile]\n");
1.177     markus   3264: #ifdef ENABLE_PKCS11
1.243     deraadt  3265:        fprintf(stderr,
                   3266:            "       ssh-keygen -D pkcs11\n");
1.177     markus   3267: #endif
1.243     deraadt  3268:        fprintf(stderr,
1.352     jmc      3269:            "       ssh-keygen -F hostname [-lv] [-f known_hosts_file]\n"
1.243     deraadt  3270:            "       ssh-keygen -H [-f known_hosts_file]\n"
1.414     solene   3271:            "       ssh-keygen -K [-a rounds] [-w provider]\n"
1.243     deraadt  3272:            "       ssh-keygen -R hostname [-f known_hosts_file]\n"
1.352     jmc      3273:            "       ssh-keygen -r hostname [-g] [-f input_keyfile]\n"
1.274     djm      3274: #ifdef WITH_OPENSSL
1.383     naddy    3275:            "       ssh-keygen -M generate [-O option] output_file\n"
                   3276:            "       ssh-keygen -M screen [-f input_file] [-O option] output_file\n"
1.274     djm      3277: #endif
1.355     jmc      3278:            "       ssh-keygen -I certificate_identity -s ca_key [-hU] [-D pkcs11_provider]\n"
                   3279:            "                  [-n principals] [-O option] [-V validity_interval]\n"
                   3280:            "                  [-z serial_number] file ...\n"
1.243     deraadt  3281:            "       ssh-keygen -L [-f input_keyfile]\n"
1.414     solene   3282:            "       ssh-keygen -A [-a rounds] [-f prefix_path]\n"
1.243     deraadt  3283:            "       ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
                   3284:            "                  file ...\n"
1.405     djm      3285:            "       ssh-keygen -Q [-l] -f krl_file [file ...]\n"
1.388     djm      3286:            "       ssh-keygen -Y find-principals -s signature_file -f allowed_signers_file\n"
1.442     djm      3287:            "       ssh-keygen -Y match-principals -I signer_identity -f allowed_signers_file\n"
1.355     jmc      3288:            "       ssh-keygen -Y check-novalidate -n namespace -s signature_file\n"
1.445     djm      3289:            "       ssh-keygen -Y sign -f key_file -n namespace file [-O option] ...\n"
1.355     jmc      3290:            "       ssh-keygen -Y verify -f allowed_signers_file -I signer_identity\n"
1.445     djm      3291:            "                  -n namespace -s signature_file [-r krl_file] [-O option]\n");
1.12      markus   3292:        exit(1);
1.10      markus   3293: }
                   3294:
1.13      deraadt  3295: /*
                   3296:  * Main program for key management.
                   3297:  */
1.2       provos   3298: int
1.156     deraadt  3299: main(int argc, char **argv)
1.1       deraadt  3300: {
1.458     djm      3301:        char comment[1024], *passphrase = NULL;
1.274     djm      3302:        char *rr_hostname = NULL, *ep, *fp, *ra;
1.252     djm      3303:        struct sshkey *private, *public;
1.12      markus   3304:        struct passwd *pw;
1.381     djm      3305:        int r, opt, type;
1.325     djm      3306:        int change_passphrase = 0, change_comment = 0, show_cert = 0;
                   3307:        int find_host = 0, delete_host = 0, hash_hosts = 0;
1.274     djm      3308:        int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
1.325     djm      3309:        int prefer_agent = 0, convert_to = 0, convert_from = 0;
1.326     djm      3310:        int print_public = 0, print_generic = 0, cert_serial_autoinc = 0;
1.381     djm      3311:        int do_gen_candidates = 0, do_screen_candidates = 0, download_sk = 0;
1.380     djm      3312:        unsigned long long cert_serial = 0;
1.375     djm      3313:        char *identity_comment = NULL, *ca_key_path = NULL, **opts = NULL;
1.382     djm      3314:        char *sk_application = NULL, *sk_device = NULL, *sk_user = NULL;
1.420     djm      3315:        char *sk_attestation_path = NULL;
1.395     djm      3316:        struct sshbuf *challenge = NULL, *attest = NULL;
1.375     djm      3317:        size_t i, nopts = 0;
1.340     dtucker  3318:        u_int32_t bits = 0;
1.357     djm      3319:        uint8_t sk_flags = SSH_SK_USER_PRESENCE_REQD;
1.274     djm      3320:        const char *errstr;
1.325     djm      3321:        int log_level = SYSLOG_LEVEL_INFO;
1.344     djm      3322:        char *sign_op = NULL;
1.33      markus   3323:
1.12      markus   3324:        extern int optind;
                   3325:        extern char *optarg;
1.129     djm      3326:
                   3327:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                   3328:        sanitise_stdfd();
1.12      markus   3329:
1.348     djm      3330: #ifdef WITH_OPENSSL
1.201     djm      3331:        OpenSSL_add_all_algorithms();
1.348     djm      3332: #endif
1.156     deraadt  3333:        log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
1.294     djm      3334:
                   3335:        setlocale(LC_CTYPE, "");
1.19      markus   3336:
1.14      markus   3337:        /* we need this for the home * directory.  */
1.12      markus   3338:        pw = getpwuid(getuid());
1.269     djm      3339:        if (!pw)
                   3340:                fatal("No user exists for uid %lu", (u_long)getuid());
1.428     djm      3341:        pw = pwcopy(pw);
1.333     deraadt  3342:        if (gethostname(hostname, sizeof(hostname)) == -1)
1.269     djm      3343:                fatal("gethostname: %s", strerror(errno));
1.14      markus   3344:
1.357     djm      3345:        sk_provider = getenv("SSH_SK_PROVIDER");
                   3346:
1.381     djm      3347:        /* Remaining characters: dGjJSTWx */
                   3348:        while ((opt = getopt(argc, argv, "ABHKLQUXceghiklopquvy"
1.376     djm      3349:            "C:D:E:F:I:M:N:O:P:R:V:Y:Z:"
1.380     djm      3350:            "a:b:f:g:m:n:r:s:t:w:z:")) != -1) {
1.12      markus   3351:                switch (opt) {
1.206     stevesk  3352:                case 'A':
                   3353:                        gen_all_hostkeys = 1;
                   3354:                        break;
1.12      markus   3355:                case 'b':
1.340     dtucker  3356:                        bits = (u_int32_t)strtonum(optarg, 1, UINT32_MAX,
                   3357:                            &errstr);
1.125     avsm     3358:                        if (errstr)
                   3359:                                fatal("Bits has bad value %s (%s)",
                   3360:                                        optarg, errstr);
1.12      markus   3361:                        break;
1.251     djm      3362:                case 'E':
                   3363:                        fingerprint_hash = ssh_digest_alg_by_name(optarg);
                   3364:                        if (fingerprint_hash == -1)
                   3365:                                fatal("Invalid hash algorithm \"%s\"", optarg);
                   3366:                        break;
1.119     djm      3367:                case 'F':
                   3368:                        find_host = 1;
                   3369:                        rr_hostname = optarg;
                   3370:                        break;
                   3371:                case 'H':
                   3372:                        hash_hosts = 1;
                   3373:                        break;
1.179     djm      3374:                case 'I':
                   3375:                        cert_key_id = optarg;
                   3376:                        break;
1.119     djm      3377:                case 'R':
                   3378:                        delete_host = 1;
                   3379:                        rr_hostname = optarg;
                   3380:                        break;
1.182     djm      3381:                case 'L':
                   3382:                        show_cert = 1;
                   3383:                        break;
1.12      markus   3384:                case 'l':
                   3385:                        print_fingerprint = 1;
                   3386:                        break;
1.49      markus   3387:                case 'B':
                   3388:                        print_bubblebabble = 1;
                   3389:                        break;
1.193     djm      3390:                case 'm':
                   3391:                        if (strcasecmp(optarg, "RFC4716") == 0 ||
                   3392:                            strcasecmp(optarg, "ssh2") == 0) {
                   3393:                                convert_format = FMT_RFC4716;
                   3394:                                break;
                   3395:                        }
                   3396:                        if (strcasecmp(optarg, "PKCS8") == 0) {
                   3397:                                convert_format = FMT_PKCS8;
1.336     djm      3398:                                private_key_format = SSHKEY_PRIVATE_PKCS8;
1.193     djm      3399:                                break;
                   3400:                        }
                   3401:                        if (strcasecmp(optarg, "PEM") == 0) {
                   3402:                                convert_format = FMT_PEM;
1.336     djm      3403:                                private_key_format = SSHKEY_PRIVATE_PEM;
1.193     djm      3404:                                break;
                   3405:                        }
                   3406:                        fatal("Unsupported conversion format \"%s\"", optarg);
1.179     djm      3407:                case 'n':
                   3408:                        cert_principals = optarg;
                   3409:                        break;
1.237     markus   3410:                case 'o':
1.319     djm      3411:                        /* no-op; new format is already the default */
1.237     markus   3412:                        break;
1.12      markus   3413:                case 'p':
                   3414:                        change_passphrase = 1;
                   3415:                        break;
                   3416:                case 'c':
                   3417:                        change_comment = 1;
                   3418:                        break;
                   3419:                case 'f':
1.274     djm      3420:                        if (strlcpy(identity_file, optarg,
                   3421:                            sizeof(identity_file)) >= sizeof(identity_file))
1.124     avsm     3422:                                fatal("Identity filename too long");
1.12      markus   3423:                        have_identity = 1;
                   3424:                        break;
1.105     jakob    3425:                case 'g':
                   3426:                        print_generic = 1;
                   3427:                        break;
1.381     djm      3428:                case 'K':
                   3429:                        download_sk = 1;
                   3430:                        break;
1.12      markus   3431:                case 'P':
                   3432:                        identity_passphrase = optarg;
                   3433:                        break;
                   3434:                case 'N':
                   3435:                        identity_new_passphrase = optarg;
                   3436:                        break;
1.223     djm      3437:                case 'Q':
                   3438:                        check_krl = 1;
                   3439:                        break;
1.179     djm      3440:                case 'O':
1.375     djm      3441:                        opts = xrecallocarray(opts, nopts, nopts + 1,
                   3442:                            sizeof(*opts));
                   3443:                        opts[nopts++] = xstrdup(optarg);
1.179     djm      3444:                        break;
1.237     markus   3445:                case 'Z':
1.336     djm      3446:                        openssh_format_cipher = optarg;
1.425     dtucker  3447:                        if (cipher_by_name(openssh_format_cipher) == NULL)
                   3448:                                fatal("Invalid OpenSSH-format cipher '%s'",
                   3449:                                    openssh_format_cipher);
1.237     markus   3450:                        break;
1.12      markus   3451:                case 'C':
                   3452:                        identity_comment = optarg;
                   3453:                        break;
                   3454:                case 'q':
                   3455:                        quiet = 1;
1.20      deraadt  3456:                        break;
1.57      markus   3457:                case 'e':
                   3458:                        /* export key */
1.193     djm      3459:                        convert_to = 1;
1.19      markus   3460:                        break;
1.179     djm      3461:                case 'h':
                   3462:                        cert_key_type = SSH2_CERT_TYPE_HOST;
1.190     djm      3463:                        certflags_flags = 0;
1.179     djm      3464:                        break;
1.223     djm      3465:                case 'k':
                   3466:                        gen_krl = 1;
                   3467:                        break;
1.57      markus   3468:                case 'i':
1.19      markus   3469:                case 'X':
1.57      markus   3470:                        /* import key */
1.193     djm      3471:                        convert_from = 1;
1.19      markus   3472:                        break;
                   3473:                case 'y':
                   3474:                        print_public = 1;
                   3475:                        break;
1.179     djm      3476:                case 's':
                   3477:                        ca_key_path = optarg;
                   3478:                        break;
1.33      markus   3479:                case 't':
                   3480:                        key_type_name = optarg;
                   3481:                        break;
1.75      markus   3482:                case 'D':
1.177     markus   3483:                        pkcs11provider = optarg;
1.305     djm      3484:                        break;
                   3485:                case 'U':
                   3486:                        prefer_agent = 1;
1.66      markus   3487:                        break;
1.223     djm      3488:                case 'u':
                   3489:                        update_krl = 1;
                   3490:                        break;
1.113     djm      3491:                case 'v':
                   3492:                        if (log_level == SYSLOG_LEVEL_INFO)
                   3493:                                log_level = SYSLOG_LEVEL_DEBUG1;
                   3494:                        else {
1.117     deraadt  3495:                                if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
1.113     djm      3496:                                    log_level < SYSLOG_LEVEL_DEBUG3)
                   3497:                                        log_level++;
                   3498:                        }
                   3499:                        break;
1.105     jakob    3500:                case 'r':
1.119     djm      3501:                        rr_hostname = optarg;
1.105     jakob    3502:                        break;
1.107     djm      3503:                case 'a':
1.237     markus   3504:                        rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
1.124     avsm     3505:                        if (errstr)
1.237     markus   3506:                                fatal("Invalid number: %s (%s)",
1.124     avsm     3507:                                        optarg, errstr);
1.107     djm      3508:                        break;
1.274     djm      3509:                case 'V':
                   3510:                        parse_cert_times(optarg);
                   3511:                        break;
1.344     djm      3512:                case 'Y':
                   3513:                        sign_op = optarg;
1.365     djm      3514:                        break;
1.357     djm      3515:                case 'w':
                   3516:                        sk_provider = optarg;
                   3517:                        break;
1.274     djm      3518:                case 'z':
                   3519:                        errno = 0;
1.326     djm      3520:                        if (*optarg == '+') {
                   3521:                                cert_serial_autoinc = 1;
                   3522:                                optarg++;
                   3523:                        }
1.274     djm      3524:                        cert_serial = strtoull(optarg, &ep, 10);
                   3525:                        if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
                   3526:                            (errno == ERANGE && cert_serial == ULLONG_MAX))
                   3527:                                fatal("Invalid serial number \"%s\"", optarg);
1.107     djm      3528:                        break;
1.274     djm      3529:                case 'M':
1.376     djm      3530:                        if (strcmp(optarg, "generate") == 0)
                   3531:                                do_gen_candidates = 1;
                   3532:                        else if (strcmp(optarg, "screen") == 0)
                   3533:                                do_screen_candidates = 1;
                   3534:                        else
                   3535:                                fatal("Unsupported moduli option %s", optarg);
1.179     djm      3536:                        break;
1.12      markus   3537:                default:
                   3538:                        usage();
                   3539:                }
                   3540:        }
1.364     djm      3541:
                   3542:        if (sk_provider == NULL)
                   3543:                sk_provider = "internal";
1.113     djm      3544:
                   3545:        /* reinit */
1.156     deraadt  3546:        log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
1.113     djm      3547:
1.179     djm      3548:        argv += optind;
                   3549:        argc -= optind;
1.344     djm      3550:
                   3551:        if (sign_op != NULL) {
1.388     djm      3552:                if (strncmp(sign_op, "find-principals", 15) == 0) {
1.386     djm      3553:                        if (ca_key_path == NULL) {
1.388     djm      3554:                                error("Too few arguments for find-principals:"
1.429     djm      3555:                                    "missing signature file");
1.386     djm      3556:                                exit(1);
                   3557:                        }
                   3558:                        if (!have_identity) {
1.388     djm      3559:                                error("Too few arguments for find-principals:"
1.429     djm      3560:                                    "missing allowed keys file");
1.386     djm      3561:                                exit(1);
                   3562:                        }
1.432     djm      3563:                        return sig_find_principals(ca_key_path, identity_file,
1.441     djm      3564:                            opts, nopts);
                   3565:                } else if (strncmp(sign_op, "match-principals", 16) == 0) {
                   3566:                        if (!have_identity) {
                   3567:                                error("Too few arguments for match-principals:"
                   3568:                                    "missing allowed keys file");
                   3569:                                exit(1);
                   3570:                        }
                   3571:                        if (cert_key_id == NULL) {
                   3572:                                error("Too few arguments for match-principals: "
                   3573:                                    "missing principal ID");
                   3574:                                exit(1);
                   3575:                        }
                   3576:                        return sig_match_principals(identity_file, cert_key_id,
1.432     djm      3577:                            opts, nopts);
1.391     djm      3578:                } else if (strncmp(sign_op, "sign", 4) == 0) {
1.447     djm      3579:                        /* NB. cert_principals is actually namespace, via -n */
1.391     djm      3580:                        if (cert_principals == NULL ||
                   3581:                            *cert_principals == '\0') {
                   3582:                                error("Too few arguments for sign: "
                   3583:                                    "missing namespace");
                   3584:                                exit(1);
                   3585:                        }
1.344     djm      3586:                        if (!have_identity) {
                   3587:                                error("Too few arguments for sign: "
                   3588:                                    "missing key");
                   3589:                                exit(1);
                   3590:                        }
1.386     djm      3591:                        return sig_sign(identity_file, cert_principals,
1.452     djm      3592:                            prefer_agent, argc, argv, opts, nopts);
1.350     djm      3593:                } else if (strncmp(sign_op, "check-novalidate", 16) == 0) {
1.450     djm      3594:                        /* NB. cert_principals is actually namespace, via -n */
1.449     djm      3595:                        if (cert_principals == NULL ||
                   3596:                            *cert_principals == '\0') {
                   3597:                                error("Too few arguments for check-novalidate: "
                   3598:                                    "missing namespace");
                   3599:                                exit(1);
                   3600:                        }
1.350     djm      3601:                        if (ca_key_path == NULL) {
                   3602:                                error("Too few arguments for check-novalidate: "
1.429     djm      3603:                                    "missing signature file");
1.350     djm      3604:                                exit(1);
                   3605:                        }
1.386     djm      3606:                        return sig_verify(ca_key_path, cert_principals,
1.432     djm      3607:                            NULL, NULL, NULL, opts, nopts);
1.344     djm      3608:                } else if (strncmp(sign_op, "verify", 6) == 0) {
1.447     djm      3609:                        /* NB. cert_principals is actually namespace, via -n */
1.391     djm      3610:                        if (cert_principals == NULL ||
                   3611:                            *cert_principals == '\0') {
                   3612:                                error("Too few arguments for verify: "
1.447     djm      3613:                                    "missing namespace");
1.391     djm      3614:                                exit(1);
                   3615:                        }
1.344     djm      3616:                        if (ca_key_path == NULL) {
                   3617:                                error("Too few arguments for verify: "
                   3618:                                    "missing signature file");
                   3619:                                exit(1);
                   3620:                        }
                   3621:                        if (!have_identity) {
                   3622:                                error("Too few arguments for sign: "
                   3623:                                    "missing allowed keys file");
                   3624:                                exit(1);
                   3625:                        }
                   3626:                        if (cert_key_id == NULL) {
                   3627:                                error("Too few arguments for verify: "
1.447     djm      3628:                                    "missing principal identity");
1.344     djm      3629:                                exit(1);
                   3630:                        }
1.386     djm      3631:                        return sig_verify(ca_key_path, cert_principals,
1.432     djm      3632:                            cert_key_id, identity_file, rr_hostname,
                   3633:                            opts, nopts);
1.344     djm      3634:                }
1.391     djm      3635:                error("Unsupported operation for -Y: \"%s\"", sign_op);
1.344     djm      3636:                usage();
                   3637:                /* NOTREACHED */
                   3638:        }
1.179     djm      3639:
                   3640:        if (ca_key_path != NULL) {
1.223     djm      3641:                if (argc < 1 && !gen_krl) {
1.269     djm      3642:                        error("Too few arguments.");
1.179     djm      3643:                        usage();
                   3644:                }
1.376     djm      3645:        } else if (argc > 0 && !gen_krl && !check_krl &&
                   3646:            !do_gen_candidates && !do_screen_candidates) {
1.269     djm      3647:                error("Too many arguments.");
1.87      djm      3648:                usage();
                   3649:        }
1.12      markus   3650:        if (change_passphrase && change_comment) {
1.269     djm      3651:                error("Can only have one of -p and -c.");
1.166     djm      3652:                usage();
                   3653:        }
                   3654:        if (print_fingerprint && (delete_host || hash_hosts)) {
1.269     djm      3655:                error("Cannot use -l with -H or -R.");
1.12      markus   3656:                usage();
1.223     djm      3657:        }
1.376     djm      3658:        if (gen_krl) {
1.325     djm      3659:                do_gen_krl(pw, update_krl, ca_key_path,
                   3660:                    cert_serial, identity_comment, argc, argv);
1.223     djm      3661:                return (0);
                   3662:        }
                   3663:        if (check_krl) {
1.405     djm      3664:                do_check_krl(pw, print_fingerprint, argc, argv);
1.223     djm      3665:                return (0);
1.179     djm      3666:        }
                   3667:        if (ca_key_path != NULL) {
                   3668:                if (cert_key_id == NULL)
                   3669:                        fatal("Must specify key id (-I) when certifying");
1.375     djm      3670:                for (i = 0; i < nopts; i++)
                   3671:                        add_cert_option(opts[i]);
1.326     djm      3672:                do_ca_sign(pw, ca_key_path, prefer_agent,
                   3673:                    cert_serial, cert_serial_autoinc, argc, argv);
1.12      markus   3674:        }
1.182     djm      3675:        if (show_cert)
                   3676:                do_show_cert(pw);
1.325     djm      3677:        if (delete_host || hash_hosts || find_host) {
                   3678:                do_known_hosts(pw, rr_hostname, find_host,
                   3679:                    delete_host, hash_hosts);
                   3680:        }
1.221     djm      3681:        if (pkcs11provider != NULL)
                   3682:                do_download(pw);
1.382     djm      3683:        if (download_sk) {
                   3684:                for (i = 0; i < nopts; i++) {
                   3685:                        if (strncasecmp(opts[i], "device=", 7) == 0) {
                   3686:                                sk_device = xstrdup(opts[i] + 7);
                   3687:                        } else {
                   3688:                                fatal("Option \"%s\" is unsupported for "
                   3689:                                    "FIDO authenticator download", opts[i]);
                   3690:                        }
                   3691:                }
                   3692:                return do_download_sk(sk_provider, sk_device);
                   3693:        }
1.49      markus   3694:        if (print_fingerprint || print_bubblebabble)
1.12      markus   3695:                do_fingerprint(pw);
                   3696:        if (change_passphrase)
                   3697:                do_change_passphrase(pw);
                   3698:        if (change_comment)
1.325     djm      3699:                do_change_comment(pw, identity_comment);
1.246     markus   3700: #ifdef WITH_OPENSSL
1.193     djm      3701:        if (convert_to)
                   3702:                do_convert_to(pw);
                   3703:        if (convert_from)
                   3704:                do_convert_from(pw);
1.349     djm      3705: #else /* WITH_OPENSSL */
                   3706:        if (convert_to || convert_from)
                   3707:                fatal("key conversion disabled at compile time");
                   3708: #endif /* WITH_OPENSSL */
1.19      markus   3709:        if (print_public)
                   3710:                do_print_public(pw);
1.119     djm      3711:        if (rr_hostname != NULL) {
1.138     jakob    3712:                unsigned int n = 0;
                   3713:
                   3714:                if (have_identity) {
1.325     djm      3715:                        n = do_print_resource_record(pw, identity_file,
1.462     djm      3716:                            rr_hostname, print_generic, opts, nopts);
1.269     djm      3717:                        if (n == 0)
                   3718:                                fatal("%s: %s", identity_file, strerror(errno));
1.138     jakob    3719:                        exit(0);
                   3720:                } else {
                   3721:
                   3722:                        n += do_print_resource_record(pw,
1.325     djm      3723:                            _PATH_HOST_RSA_KEY_FILE, rr_hostname,
1.462     djm      3724:                            print_generic, opts, nopts);
1.138     jakob    3725:                        n += do_print_resource_record(pw,
1.325     djm      3726:                            _PATH_HOST_DSA_KEY_FILE, rr_hostname,
1.462     djm      3727:                            print_generic, opts, nopts);
1.214     djm      3728:                        n += do_print_resource_record(pw,
1.325     djm      3729:                            _PATH_HOST_ECDSA_KEY_FILE, rr_hostname,
1.462     djm      3730:                            print_generic, opts, nopts);
1.244     logan    3731:                        n += do_print_resource_record(pw,
1.325     djm      3732:                            _PATH_HOST_ED25519_KEY_FILE, rr_hostname,
1.462     djm      3733:                            print_generic, opts, nopts);
1.313     markus   3734:                        n += do_print_resource_record(pw,
1.325     djm      3735:                            _PATH_HOST_XMSS_KEY_FILE, rr_hostname,
1.462     djm      3736:                            print_generic, opts, nopts);
1.138     jakob    3737:                        if (n == 0)
                   3738:                                fatal("no keys found.");
                   3739:                        exit(0);
                   3740:                }
1.105     jakob    3741:        }
1.107     djm      3742:
1.376     djm      3743:        if (do_gen_candidates || do_screen_candidates) {
                   3744:                if (argc <= 0)
                   3745:                        fatal("No output file specified");
                   3746:                else if (argc > 1)
                   3747:                        fatal("Too many output files specified");
                   3748:        }
1.107     djm      3749:        if (do_gen_candidates) {
1.376     djm      3750:                do_moduli_gen(argv[0], opts, nopts);
                   3751:                return 0;
1.107     djm      3752:        }
                   3753:        if (do_screen_candidates) {
1.376     djm      3754:                do_moduli_screen(argv[0], opts, nopts);
                   3755:                return 0;
1.75      markus   3756:        }
1.12      markus   3757:
1.206     stevesk  3758:        if (gen_all_hostkeys) {
                   3759:                do_gen_all_hostkeys(pw);
                   3760:                return (0);
                   3761:        }
                   3762:
1.133     djm      3763:        if (key_type_name == NULL)
1.273     djm      3764:                key_type_name = DEFAULT_KEY_TYPE_NAME;
1.133     djm      3765:
1.252     djm      3766:        type = sshkey_type_from_name(key_type_name);
1.255     djm      3767:        type_bits_valid(type, key_type_name, &bits);
1.206     stevesk  3768:
1.33      markus   3769:        if (!quiet)
1.252     djm      3770:                printf("Generating public/private %s key pair.\n",
                   3771:                    key_type_name);
1.362     markus   3772:        switch (type) {
                   3773:        case KEY_ECDSA_SK:
                   3774:        case KEY_ED25519_SK:
1.380     djm      3775:                for (i = 0; i < nopts; i++) {
                   3776:                        if (strcasecmp(opts[i], "no-touch-required") == 0) {
                   3777:                                sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
1.416     djm      3778:                        } else if (strcasecmp(opts[i], "verify-required") == 0) {
                   3779:                                sk_flags |= SSH_SK_USER_VERIFICATION_REQD;
1.380     djm      3780:                        } else if (strcasecmp(opts[i], "resident") == 0) {
                   3781:                                sk_flags |= SSH_SK_RESIDENT_KEY;
1.382     djm      3782:                        } else if (strncasecmp(opts[i], "device=", 7) == 0) {
                   3783:                                sk_device = xstrdup(opts[i] + 7);
                   3784:                        } else if (strncasecmp(opts[i], "user=", 5) == 0) {
                   3785:                                sk_user = xstrdup(opts[i] + 5);
1.395     djm      3786:                        } else if (strncasecmp(opts[i], "challenge=", 10) == 0) {
                   3787:                                if ((r = sshbuf_load_file(opts[i] + 10,
                   3788:                                    &challenge)) != 0) {
1.421     djm      3789:                                        fatal_r(r, "Unable to load FIDO "
                   3790:                                            "enrollment challenge \"%s\"",
                   3791:                                            opts[i] + 10);
1.395     djm      3792:                                }
                   3793:                        } else if (strncasecmp(opts[i],
                   3794:                            "write-attestation=", 18) == 0) {
1.420     djm      3795:                                sk_attestation_path = opts[i] + 18;
1.382     djm      3796:                        } else if (strncasecmp(opts[i],
                   3797:                            "application=", 12) == 0) {
                   3798:                                sk_application = xstrdup(opts[i] + 12);
1.396     djm      3799:                                if (strncmp(sk_application, "ssh:", 4) != 0) {
                   3800:                                        fatal("FIDO application string must "
                   3801:                                            "begin with \"ssh:\"");
                   3802:                                }
1.380     djm      3803:                        } else {
                   3804:                                fatal("Option \"%s\" is unsupported for "
                   3805:                                    "FIDO authenticator enrollment", opts[i]);
                   3806:                        }
                   3807:                }
1.395     djm      3808:                if ((attest = sshbuf_new()) == NULL)
                   3809:                        fatal("sshbuf_new failed");
1.457     djm      3810:                r = 0;
                   3811:                for (i = 0 ;;) {
                   3812:                        if (!quiet) {
                   3813:                                printf("You may need to touch your "
                   3814:                                    "authenticator%s to authorize key "
                   3815:                                    "generation.\n",
                   3816:                                    r == 0 ? "" : " again");
                   3817:                        }
1.379     djm      3818:                        fflush(stdout);
1.382     djm      3819:                        r = sshsk_enroll(type, sk_provider, sk_device,
                   3820:                            sk_application == NULL ? "ssh:" : sk_application,
1.395     djm      3821:                            sk_user, sk_flags, passphrase, challenge,
                   3822:                            &private, attest);
1.379     djm      3823:                        if (r == 0)
                   3824:                                break;
1.456     djm      3825:                        if (r == SSH_ERR_KEY_BAD_PERMISSIONS &&
                   3826:                            (sk_flags & SSH_SK_RESIDENT_KEY) != 0 &&
                   3827:                            (sk_flags & SSH_SK_FORCE_OPERATION) == 0 &&
                   3828:                            confirm_sk_overwrite(sk_application, sk_user)) {
                   3829:                                sk_flags |= SSH_SK_FORCE_OPERATION;
                   3830:                                continue;
                   3831:                        }
1.379     djm      3832:                        if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1.421     djm      3833:                                fatal_r(r, "Key enrollment failed");
1.418     djm      3834:                        else if (passphrase != NULL) {
1.398     djm      3835:                                error("PIN incorrect");
1.381     djm      3836:                                freezero(passphrase, strlen(passphrase));
1.398     djm      3837:                                passphrase = NULL;
                   3838:                        }
1.457     djm      3839:                        if (++i >= 3)
1.398     djm      3840:                                fatal("Too many incorrect PINs");
1.397     naddy    3841:                        passphrase = read_passphrase("Enter PIN for "
                   3842:                            "authenticator: ", RP_ALLOW_STDIN);
1.373     djm      3843:                }
1.398     djm      3844:                if (passphrase != NULL) {
1.381     djm      3845:                        freezero(passphrase, strlen(passphrase));
1.398     djm      3846:                        passphrase = NULL;
                   3847:                }
1.362     markus   3848:                break;
                   3849:        default:
                   3850:                if ((r = sshkey_generate(type, bits, &private)) != 0)
                   3851:                        fatal("sshkey_generate failed");
                   3852:                break;
                   3853:        }
1.269     djm      3854:        if ((r = sshkey_from_private(private, &public)) != 0)
1.421     djm      3855:                fatal_r(r, "sshkey_from_private");
1.12      markus   3856:
                   3857:        if (!have_identity)
                   3858:                ask_filename(pw, "Enter file in which to save the key");
                   3859:
1.132     djm      3860:        /* Create ~/.ssh directory if it doesn't already exist. */
1.413     dtucker  3861:        hostfile_create_user_ssh_dir(identity_file, !quiet);
                   3862:
1.12      markus   3863:        /* If the file already exists, ask the user to confirm. */
1.343     djm      3864:        if (!confirm_overwrite(identity_file))
                   3865:                exit(1);
1.12      markus   3866:
1.381     djm      3867:        /* Determine the passphrase for the private key */
                   3868:        passphrase = private_key_passphrase();
1.12      markus   3869:        if (identity_comment) {
                   3870:                strlcpy(comment, identity_comment, sizeof(comment));
                   3871:        } else {
1.172     stevesk  3872:                /* Create default comment field for the passphrase. */
1.12      markus   3873:                snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
                   3874:        }
                   3875:
                   3876:        /* Save the key with the given passphrase and comment. */
1.381     djm      3877:        if ((r = sshkey_save_private(private, identity_file, passphrase,
1.336     djm      3878:            comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
1.421     djm      3879:                error_r(r, "Saving key \"%s\" failed", identity_file);
1.381     djm      3880:                freezero(passphrase, strlen(passphrase));
1.12      markus   3881:                exit(1);
                   3882:        }
1.381     djm      3883:        freezero(passphrase, strlen(passphrase));
1.252     djm      3884:        sshkey_free(private);
1.12      markus   3885:
1.381     djm      3886:        if (!quiet) {
1.387     djm      3887:                printf("Your identification has been saved in %s\n",
1.381     djm      3888:                    identity_file);
                   3889:        }
1.12      markus   3890:
                   3891:        strlcat(identity_file, ".pub", sizeof(identity_file));
1.421     djm      3892:        if ((r = sshkey_save_public(public, identity_file, comment)) != 0)
                   3893:                fatal_r(r, "Unable to save public key to %s", identity_file);
1.12      markus   3894:
                   3895:        if (!quiet) {
1.259     djm      3896:                fp = sshkey_fingerprint(public, fingerprint_hash,
1.251     djm      3897:                    SSH_FP_DEFAULT);
1.259     djm      3898:                ra = sshkey_fingerprint(public, fingerprint_hash,
1.167     grunk    3899:                    SSH_FP_RANDOMART);
1.259     djm      3900:                if (fp == NULL || ra == NULL)
                   3901:                        fatal("sshkey_fingerprint failed");
1.387     djm      3902:                printf("Your public key has been saved in %s\n",
1.19      markus   3903:                    identity_file);
1.12      markus   3904:                printf("The key fingerprint is:\n");
1.50      markus   3905:                printf("%s %s\n", fp, comment);
1.167     grunk    3906:                printf("The key's randomart image is:\n");
                   3907:                printf("%s\n", ra);
1.227     djm      3908:                free(ra);
                   3909:                free(fp);
1.12      markus   3910:        }
1.19      markus   3911:
1.420     djm      3912:        if (sk_attestation_path != NULL)
                   3913:                save_attestation(attest, sk_attestation_path);
                   3914:
1.395     djm      3915:        sshbuf_free(attest);
1.252     djm      3916:        sshkey_free(public);
1.395     djm      3917:
1.12      markus   3918:        exit(0);
1.1       deraadt  3919: }