[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.416

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