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

1.293   ! millert     1: /* $OpenBSD: ssh-keygen.c,v 1.292 2016/09/12 03:29:16 dtucker Exp $ */
1.1       deraadt     2: /*
1.13      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1994 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
                      6:  * Identity and host key generation and maintenance.
1.31      deraadt     7:  *
                      8:  * As far as I am concerned, the code I have written for this software
                      9:  * can be used freely for any purpose.  Any derived versions of this
                     10:  * software must be clearly marked as such, and if the derived work is
                     11:  * incompatible with the protocol description in the RFC file, it must be
                     12:  * called by a name other than "ssh" or "Secure Shell".
1.13      deraadt    13:  */
1.1       deraadt    14:
1.136     stevesk    15: #include <sys/types.h>
1.174     dtucker    16: #include <sys/socket.h>
1.136     stevesk    17: #include <sys/stat.h>
1.19      markus     18:
                     19: #include <openssl/evp.h>
                     20: #include <openssl/pem.h>
1.145     stevesk    21:
1.148     stevesk    22: #include <errno.h>
1.147     stevesk    23: #include <fcntl.h>
1.248     djm        24: #include <netdb.h>
1.145     stevesk    25: #include <pwd.h>
1.153     stevesk    26: #include <stdio.h>
1.152     stevesk    27: #include <stdlib.h>
1.150     stevesk    28: #include <string.h>
1.149     stevesk    29: #include <unistd.h>
1.253     deraadt    30: #include <limits.h>
1.1       deraadt    31:
                     32: #include "xmalloc.h"
1.252     djm        33: #include "sshkey.h"
1.53      markus     34: #include "rsa.h"
1.19      markus     35: #include "authfile.h"
                     36: #include "uuencode.h"
1.252     djm        37: #include "sshbuf.h"
1.40      markus     38: #include "pathnames.h"
1.41      markus     39: #include "log.h"
1.114     djm        40: #include "misc.h"
1.119     djm        41: #include "match.h"
                     42: #include "hostfile.h"
1.146     stevesk    43: #include "dns.h"
1.223     djm        44: #include "ssh.h"
1.179     djm        45: #include "ssh2.h"
1.252     djm        46: #include "ssherr.h"
1.223     djm        47: #include "atomicio.h"
                     48: #include "krl.h"
1.251     djm        49: #include "digest.h"
1.32      markus     50:
1.177     markus     51: #ifdef ENABLE_PKCS11
                     52: #include "ssh-pkcs11.h"
1.106     djm        53: #endif
1.66      markus     54:
1.273     djm        55: #ifdef WITH_OPENSSL
                     56: # define DEFAULT_KEY_TYPE_NAME "rsa"
                     57: #else
                     58: # define DEFAULT_KEY_TYPE_NAME "ed25519"
                     59: #endif
                     60:
1.130     markus     61: /* Number of bits in the RSA/DSA key.  This value can be set on the command line. */
                     62: #define DEFAULT_BITS           2048
                     63: #define DEFAULT_BITS_DSA       1024
1.203     naddy      64: #define DEFAULT_BITS_ECDSA     256
1.130     markus     65: u_int32_t bits = 0;
1.1       deraadt    66:
1.14      markus     67: /*
                     68:  * Flag indicating that we just want to change the passphrase.  This can be
                     69:  * set on the command line.
                     70:  */
1.1       deraadt    71: int change_passphrase = 0;
                     72:
1.14      markus     73: /*
                     74:  * Flag indicating that we just want to change the comment.  This can be set
                     75:  * on the command line.
                     76:  */
1.1       deraadt    77: int change_comment = 0;
                     78:
1.2       provos     79: int quiet = 0;
                     80:
1.169     grunk      81: int log_level = SYSLOG_LEVEL_INFO;
                     82:
1.119     djm        83: /* Flag indicating that we want to hash a known_hosts file */
                     84: int hash_hosts = 0;
                     85: /* Flag indicating that we want lookup a host in known_hosts file */
                     86: int find_host = 0;
                     87: /* Flag indicating that we want to delete a host from a known_hosts file */
                     88: int delete_host = 0;
                     89:
1.182     djm        90: /* Flag indicating that we want to show the contents of a certificate */
                     91: int show_cert = 0;
                     92:
1.8       markus     93: /* Flag indicating that we just want to see the key fingerprint */
                     94: int print_fingerprint = 0;
1.49      markus     95: int print_bubblebabble = 0;
1.8       markus     96:
1.251     djm        97: /* Hash algorithm to use for fingerprints. */
                     98: int fingerprint_hash = SSH_FP_HASH_DEFAULT;
                     99:
1.10      markus    100: /* The identity file name, given on the command line or entered by the user. */
                    101: char identity_file[1024];
                    102: int have_identity = 0;
1.1       deraadt   103:
                    104: /* This is set to the passphrase if given on the command line. */
                    105: char *identity_passphrase = NULL;
                    106:
                    107: /* This is set to the new passphrase if given on the command line. */
                    108: char *identity_new_passphrase = NULL;
                    109:
                    110: /* This is set to the new comment if given on the command line. */
                    111: char *identity_comment = NULL;
                    112:
1.179     djm       113: /* Path to CA key when certifying keys. */
                    114: char *ca_key_path = NULL;
                    115:
1.186     djm       116: /* Certificate serial number */
1.220     djm       117: unsigned long long cert_serial = 0;
1.186     djm       118:
1.179     djm       119: /* Key type when certifying */
                    120: u_int cert_key_type = SSH2_CERT_TYPE_USER;
                    121:
                    122: /* "key ID" of signed key */
                    123: char *cert_key_id = NULL;
                    124:
                    125: /* Comma-separated list of principal names for certifying keys */
                    126: char *cert_principals = NULL;
                    127:
                    128: /* Validity period for certificates */
                    129: u_int64_t cert_valid_from = 0;
                    130: u_int64_t cert_valid_to = ~0ULL;
                    131:
1.186     djm       132: /* Certificate options */
1.190     djm       133: #define CERTOPT_X_FWD  (1)
                    134: #define CERTOPT_AGENT_FWD      (1<<1)
                    135: #define CERTOPT_PORT_FWD       (1<<2)
                    136: #define CERTOPT_PTY            (1<<3)
                    137: #define CERTOPT_USER_RC        (1<<4)
                    138: #define CERTOPT_DEFAULT        (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
                    139:                         CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
                    140: u_int32_t certflags_flags = CERTOPT_DEFAULT;
                    141: char *certflags_command = NULL;
                    142: char *certflags_src_addr = NULL;
1.179     djm       143:
1.193     djm       144: /* Conversion to/from various formats */
                    145: int convert_to = 0;
                    146: int convert_from = 0;
                    147: enum {
                    148:        FMT_RFC4716,
                    149:        FMT_PKCS8,
                    150:        FMT_PEM
                    151: } convert_format = FMT_RFC4716;
1.19      markus    152: int print_public = 0;
1.105     jakob     153: int print_generic = 0;
1.33      markus    154:
1.87      djm       155: char *key_type_name = NULL;
1.19      markus    156:
1.197     djm       157: /* Load key from this PKCS#11 provider */
                    158: char *pkcs11provider = NULL;
1.193     djm       159:
1.237     markus    160: /* Use new OpenSSH private key format when writing SSH2 keys instead of PEM */
                    161: int use_new_format = 0;
                    162:
                    163: /* Cipher for new-format private keys */
                    164: char *new_format_cipher = NULL;
                    165:
                    166: /*
                    167:  * Number of KDF rounds to derive new format keys /
                    168:  * number of primality trials when screening moduli.
                    169:  */
                    170: int rounds = 0;
                    171:
1.10      markus    172: /* argv0 */
                    173: extern char *__progname;
1.1       deraadt   174:
1.248     djm       175: char hostname[NI_MAXHOST];
1.19      markus    176:
1.274     djm       177: #ifdef WITH_OPENSSL
1.115     djm       178: /* moduli.c */
1.124     avsm      179: int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
1.215     dtucker   180: int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long,
                    181:     unsigned long);
1.274     djm       182: #endif
1.115     djm       183:
1.63      itojun    184: static void
1.255     djm       185: type_bits_valid(int type, const char *name, u_int32_t *bitsp)
1.206     stevesk   186: {
1.271     djm       187: #ifdef WITH_OPENSSL
1.255     djm       188:        u_int maxbits, nid;
1.271     djm       189: #endif
1.206     stevesk   190:
1.269     djm       191:        if (type == KEY_UNSPEC)
                    192:                fatal("unknown key type %s", key_type_name);
1.209     djm       193:        if (*bitsp == 0) {
1.271     djm       194: #ifdef WITH_OPENSSL
1.206     stevesk   195:                if (type == KEY_DSA)
1.209     djm       196:                        *bitsp = DEFAULT_BITS_DSA;
1.255     djm       197:                else if (type == KEY_ECDSA) {
                    198:                        if (name != NULL &&
                    199:                            (nid = sshkey_ecdsa_nid_from_name(name)) > 0)
                    200:                                *bitsp = sshkey_curve_nid_to_bits(nid);
                    201:                        if (*bitsp == 0)
                    202:                                *bitsp = DEFAULT_BITS_ECDSA;
1.291     dtucker   203:                } else
1.271     djm       204: #endif
1.209     djm       205:                        *bitsp = DEFAULT_BITS;
1.206     stevesk   206:        }
1.271     djm       207: #ifdef WITH_OPENSSL
1.206     stevesk   208:        maxbits = (type == KEY_DSA) ?
                    209:            OPENSSL_DSA_MAX_MODULUS_BITS : OPENSSL_RSA_MAX_MODULUS_BITS;
1.269     djm       210:        if (*bitsp > maxbits)
                    211:                fatal("key bits exceeds maximum %d", maxbits);
1.209     djm       212:        if (type == KEY_DSA && *bitsp != 1024)
1.206     stevesk   213:                fatal("DSA keys must be 1024 bits");
1.276     djm       214:        else if (type != KEY_ECDSA && type != KEY_ED25519 && *bitsp < 1024)
                    215:                fatal("Key must at least be 1024 bits");
1.252     djm       216:        else if (type == KEY_ECDSA && sshkey_ecdsa_bits_to_nid(*bitsp) == -1)
1.206     stevesk   217:                fatal("Invalid ECDSA key length - valid lengths are "
                    218:                    "256, 384 or 521 bits");
1.246     markus    219: #endif
1.206     stevesk   220: }
                    221:
                    222: static void
1.10      markus    223: ask_filename(struct passwd *pw, const char *prompt)
1.1       deraadt   224: {
1.12      markus    225:        char buf[1024];
1.35      markus    226:        char *name = NULL;
                    227:
1.92      stevesk   228:        if (key_type_name == NULL)
1.40      markus    229:                name = _PATH_SSH_CLIENT_ID_RSA;
1.140     deraadt   230:        else {
1.252     djm       231:                switch (sshkey_type_from_name(key_type_name)) {
1.92      stevesk   232:                case KEY_RSA1:
                    233:                        name = _PATH_SSH_CLIENT_IDENTITY;
                    234:                        break;
1.186     djm       235:                case KEY_DSA_CERT:
1.92      stevesk   236:                case KEY_DSA:
                    237:                        name = _PATH_SSH_CLIENT_ID_DSA;
                    238:                        break;
1.200     djm       239:                case KEY_ECDSA_CERT:
                    240:                case KEY_ECDSA:
                    241:                        name = _PATH_SSH_CLIENT_ID_ECDSA;
                    242:                        break;
1.186     djm       243:                case KEY_RSA_CERT:
1.92      stevesk   244:                case KEY_RSA:
                    245:                        name = _PATH_SSH_CLIENT_ID_RSA;
                    246:                        break;
1.238     markus    247:                case KEY_ED25519:
                    248:                case KEY_ED25519_CERT:
                    249:                        name = _PATH_SSH_CLIENT_ID_ED25519;
                    250:                        break;
1.92      stevesk   251:                default:
1.269     djm       252:                        fatal("bad key type");
1.92      stevesk   253:                }
1.140     deraadt   254:        }
1.269     djm       255:        snprintf(identity_file, sizeof(identity_file),
                    256:            "%s/%s", pw->pw_dir, name);
                    257:        printf("%s (%s): ", prompt, identity_file);
                    258:        fflush(stdout);
1.12      markus    259:        if (fgets(buf, sizeof(buf), stdin) == NULL)
                    260:                exit(1);
1.162     gilles    261:        buf[strcspn(buf, "\n")] = '\0';
1.12      markus    262:        if (strcmp(buf, "") != 0)
                    263:                strlcpy(identity_file, buf, sizeof(identity_file));
                    264:        have_identity = 1;
1.7       markus    265: }
                    266:
1.252     djm       267: static struct sshkey *
1.61      markus    268: load_identity(char *filename)
1.19      markus    269: {
1.52      markus    270:        char *pass;
1.252     djm       271:        struct sshkey *prv;
                    272:        int r;
1.52      markus    273:
1.252     djm       274:        if ((r = sshkey_load_private(filename, "", &prv, NULL)) == 0)
                    275:                return prv;
                    276:        if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
                    277:                fatal("Load key \"%s\": %s", filename, ssh_err(r));
                    278:        if (identity_passphrase)
                    279:                pass = xstrdup(identity_passphrase);
                    280:        else
                    281:                pass = read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN);
                    282:        r = sshkey_load_private(filename, pass, &prv, NULL);
                    283:        explicit_bzero(pass, strlen(pass));
                    284:        free(pass);
                    285:        if (r != 0)
                    286:                fatal("Load key \"%s\": %s", filename, ssh_err(r));
1.52      markus    287:        return prv;
1.19      markus    288: }
                    289:
1.32      markus    290: #define SSH_COM_PUBLIC_BEGIN           "---- BEGIN SSH2 PUBLIC KEY ----"
1.100     deraadt   291: #define SSH_COM_PUBLIC_END             "---- END SSH2 PUBLIC KEY ----"
1.32      markus    292: #define SSH_COM_PRIVATE_BEGIN          "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
1.42      stevesk   293: #define        SSH_COM_PRIVATE_KEY_MAGIC       0x3f6ff9eb
1.19      markus    294:
1.246     markus    295: #ifdef WITH_OPENSSL
1.63      itojun    296: static void
1.252     djm       297: do_convert_to_ssh2(struct passwd *pw, struct sshkey *k)
1.19      markus    298: {
1.252     djm       299:        size_t len;
1.36      markus    300:        u_char *blob;
1.176     djm       301:        char comment[61];
1.252     djm       302:        int r;
1.19      markus    303:
1.269     djm       304:        if (k->type == KEY_RSA1)
                    305:                fatal("version 1 keys are not supported");
                    306:        if ((r = sshkey_to_blob(k, &blob, &len)) != 0)
                    307:                fatal("key_to_blob failed: %s", ssh_err(r));
1.176     djm       308:        /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
                    309:        snprintf(comment, sizeof(comment),
                    310:            "%u-bit %s, converted by %s@%s from OpenSSH",
1.252     djm       311:            sshkey_size(k), sshkey_type(k),
1.19      markus    312:            pw->pw_name, hostname);
1.176     djm       313:
                    314:        fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
                    315:        fprintf(stdout, "Comment: \"%s\"\n", comment);
1.19      markus    316:        dump_base64(stdout, blob, len);
1.32      markus    317:        fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
1.252     djm       318:        sshkey_free(k);
1.227     djm       319:        free(blob);
1.19      markus    320:        exit(0);
                    321: }
                    322:
1.63      itojun    323: static void
1.252     djm       324: do_convert_to_pkcs8(struct sshkey *k)
1.193     djm       325: {
1.252     djm       326:        switch (sshkey_type_plain(k->type)) {
1.213     djm       327:        case KEY_RSA1:
1.193     djm       328:        case KEY_RSA:
                    329:                if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
                    330:                        fatal("PEM_write_RSA_PUBKEY failed");
                    331:                break;
                    332:        case KEY_DSA:
                    333:                if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
                    334:                        fatal("PEM_write_DSA_PUBKEY failed");
                    335:                break;
1.200     djm       336:        case KEY_ECDSA:
                    337:                if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
                    338:                        fatal("PEM_write_EC_PUBKEY failed");
                    339:                break;
1.193     djm       340:        default:
1.252     djm       341:                fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
1.193     djm       342:        }
                    343:        exit(0);
                    344: }
                    345:
                    346: static void
1.252     djm       347: do_convert_to_pem(struct sshkey *k)
1.193     djm       348: {
1.252     djm       349:        switch (sshkey_type_plain(k->type)) {
1.213     djm       350:        case KEY_RSA1:
1.193     djm       351:        case KEY_RSA:
                    352:                if (!PEM_write_RSAPublicKey(stdout, k->rsa))
                    353:                        fatal("PEM_write_RSAPublicKey failed");
                    354:                break;
                    355: #if notyet /* OpenSSH 0.9.8 lacks this function */
                    356:        case KEY_DSA:
                    357:                if (!PEM_write_DSAPublicKey(stdout, k->dsa))
                    358:                        fatal("PEM_write_DSAPublicKey failed");
                    359:                break;
                    360: #endif
1.200     djm       361:        /* XXX ECDSA? */
1.193     djm       362:        default:
1.252     djm       363:                fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
1.193     djm       364:        }
                    365:        exit(0);
                    366: }
                    367:
                    368: static void
                    369: do_convert_to(struct passwd *pw)
                    370: {
1.252     djm       371:        struct sshkey *k;
1.193     djm       372:        struct stat st;
1.252     djm       373:        int r;
1.193     djm       374:
                    375:        if (!have_identity)
                    376:                ask_filename(pw, "Enter file in which the key is");
                    377:        if (stat(identity_file, &st) < 0)
                    378:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
1.252     djm       379:        if ((r = sshkey_load_public(identity_file, &k, NULL)) != 0)
                    380:                k = load_identity(identity_file);
1.193     djm       381:        switch (convert_format) {
                    382:        case FMT_RFC4716:
                    383:                do_convert_to_ssh2(pw, k);
                    384:                break;
                    385:        case FMT_PKCS8:
                    386:                do_convert_to_pkcs8(k);
                    387:                break;
                    388:        case FMT_PEM:
                    389:                do_convert_to_pem(k);
                    390:                break;
                    391:        default:
                    392:                fatal("%s: unknown key format %d", __func__, convert_format);
                    393:        }
                    394:        exit(0);
                    395: }
                    396:
1.252     djm       397: /*
                    398:  * This is almost exactly the bignum1 encoding, but with 32 bit for length
                    399:  * instead of 16.
                    400:  */
1.193     djm       401: static void
1.252     djm       402: buffer_get_bignum_bits(struct sshbuf *b, BIGNUM *value)
1.32      markus    403: {
1.252     djm       404:        u_int bytes, bignum_bits;
                    405:        int r;
1.53      markus    406:
1.252     djm       407:        if ((r = sshbuf_get_u32(b, &bignum_bits)) != 0)
                    408:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    409:        bytes = (bignum_bits + 7) / 8;
                    410:        if (sshbuf_len(b) < bytes)
                    411:                fatal("%s: input buffer too small: need %d have %zu",
                    412:                    __func__, bytes, sshbuf_len(b));
                    413:        if (BN_bin2bn(sshbuf_ptr(b), bytes, value) == NULL)
                    414:                fatal("%s: BN_bin2bn failed", __func__);
                    415:        if ((r = sshbuf_consume(b, bytes)) != 0)
                    416:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.32      markus    417: }
                    418:
1.252     djm       419: static struct sshkey *
1.93      markus    420: do_convert_private_ssh2_from_blob(u_char *blob, u_int blen)
1.32      markus    421: {
1.252     djm       422:        struct sshbuf *b;
                    423:        struct sshkey *key = NULL;
1.64      markus    424:        char *type, *cipher;
1.252     djm       425:        u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345";
                    426:        int r, rlen, ktype;
                    427:        u_int magic, i1, i2, i3, i4;
                    428:        size_t slen;
1.62      markus    429:        u_long e;
1.32      markus    430:
1.252     djm       431:        if ((b = sshbuf_from(blob, blen)) == NULL)
                    432:                fatal("%s: sshbuf_from failed", __func__);
                    433:        if ((r = sshbuf_get_u32(b, &magic)) != 0)
                    434:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.32      markus    435:
                    436:        if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
1.252     djm       437:                error("bad magic 0x%x != 0x%x", magic,
                    438:                    SSH_COM_PRIVATE_KEY_MAGIC);
                    439:                sshbuf_free(b);
1.32      markus    440:                return NULL;
                    441:        }
1.252     djm       442:        if ((r = sshbuf_get_u32(b, &i1)) != 0 ||
                    443:            (r = sshbuf_get_cstring(b, &type, NULL)) != 0 ||
                    444:            (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 ||
                    445:            (r = sshbuf_get_u32(b, &i2)) != 0 ||
                    446:            (r = sshbuf_get_u32(b, &i3)) != 0 ||
                    447:            (r = sshbuf_get_u32(b, &i4)) != 0)
                    448:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.158     stevesk   449:        debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
1.32      markus    450:        if (strcmp(cipher, "none") != 0) {
                    451:                error("unsupported cipher %s", cipher);
1.227     djm       452:                free(cipher);
1.252     djm       453:                sshbuf_free(b);
1.227     djm       454:                free(type);
1.32      markus    455:                return NULL;
                    456:        }
1.227     djm       457:        free(cipher);
1.32      markus    458:
1.53      markus    459:        if (strstr(type, "dsa")) {
                    460:                ktype = KEY_DSA;
                    461:        } else if (strstr(type, "rsa")) {
                    462:                ktype = KEY_RSA;
                    463:        } else {
1.252     djm       464:                sshbuf_free(b);
1.227     djm       465:                free(type);
1.32      markus    466:                return NULL;
                    467:        }
1.252     djm       468:        if ((key = sshkey_new_private(ktype)) == NULL)
                    469:                fatal("key_new_private failed");
1.227     djm       470:        free(type);
1.53      markus    471:
                    472:        switch (key->type) {
                    473:        case KEY_DSA:
1.252     djm       474:                buffer_get_bignum_bits(b, key->dsa->p);
                    475:                buffer_get_bignum_bits(b, key->dsa->g);
                    476:                buffer_get_bignum_bits(b, key->dsa->q);
                    477:                buffer_get_bignum_bits(b, key->dsa->pub_key);
                    478:                buffer_get_bignum_bits(b, key->dsa->priv_key);
1.53      markus    479:                break;
                    480:        case KEY_RSA:
1.252     djm       481:                if ((r = sshbuf_get_u8(b, &e1)) != 0 ||
                    482:                    (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) ||
                    483:                    (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0))
                    484:                        fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    485:                e = e1;
1.62      markus    486:                debug("e %lx", e);
                    487:                if (e < 30) {
                    488:                        e <<= 8;
1.252     djm       489:                        e += e2;
1.62      markus    490:                        debug("e %lx", e);
                    491:                        e <<= 8;
1.252     djm       492:                        e += e3;
1.62      markus    493:                        debug("e %lx", e);
                    494:                }
                    495:                if (!BN_set_word(key->rsa->e, e)) {
1.252     djm       496:                        sshbuf_free(b);
                    497:                        sshkey_free(key);
1.53      markus    498:                        return NULL;
                    499:                }
1.252     djm       500:                buffer_get_bignum_bits(b, key->rsa->d);
                    501:                buffer_get_bignum_bits(b, key->rsa->n);
                    502:                buffer_get_bignum_bits(b, key->rsa->iqmp);
                    503:                buffer_get_bignum_bits(b, key->rsa->q);
                    504:                buffer_get_bignum_bits(b, key->rsa->p);
                    505:                if ((r = rsa_generate_additional_parameters(key->rsa)) != 0)
                    506:                        fatal("generate RSA parameters failed: %s", ssh_err(r));
1.53      markus    507:                break;
                    508:        }
1.252     djm       509:        rlen = sshbuf_len(b);
1.85      deraadt   510:        if (rlen != 0)
1.53      markus    511:                error("do_convert_private_ssh2_from_blob: "
                    512:                    "remaining bytes in key blob %d", rlen);
1.252     djm       513:        sshbuf_free(b);
1.64      markus    514:
                    515:        /* try the key */
1.285     markus    516:        if (sshkey_sign(key, &sig, &slen, data, sizeof(data), NULL, 0) != 0 ||
1.252     djm       517:            sshkey_verify(key, sig, slen, data, sizeof(data), 0) != 0) {
                    518:                sshkey_free(key);
                    519:                free(sig);
                    520:                return NULL;
                    521:        }
1.227     djm       522:        free(sig);
1.32      markus    523:        return key;
                    524: }
                    525:
1.137     dtucker   526: static int
                    527: get_line(FILE *fp, char *line, size_t len)
                    528: {
                    529:        int c;
                    530:        size_t pos = 0;
                    531:
                    532:        line[0] = '\0';
                    533:        while ((c = fgetc(fp)) != EOF) {
1.269     djm       534:                if (pos >= len - 1)
                    535:                        fatal("input line too long.");
1.140     deraadt   536:                switch (c) {
1.137     dtucker   537:                case '\r':
                    538:                        c = fgetc(fp);
1.269     djm       539:                        if (c != EOF && c != '\n' && ungetc(c, fp) == EOF)
                    540:                                fatal("unget: %s", strerror(errno));
1.137     dtucker   541:                        return pos;
                    542:                case '\n':
                    543:                        return pos;
                    544:                }
                    545:                line[pos++] = c;
                    546:                line[pos] = '\0';
                    547:        }
1.157     stevesk   548:        /* We reached EOF */
                    549:        return -1;
1.137     dtucker   550: }
                    551:
1.63      itojun    552: static void
1.252     djm       553: do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private)
1.19      markus    554: {
1.252     djm       555:        int r, blen, escaped = 0;
1.98      markus    556:        u_int len;
1.137     dtucker   557:        char line[1024];
1.80      stevesk   558:        u_char blob[8096];
1.19      markus    559:        char encoded[8096];
                    560:        FILE *fp;
                    561:
1.191     djm       562:        if ((fp = fopen(identity_file, "r")) == NULL)
                    563:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
1.19      markus    564:        encoded[0] = '\0';
1.137     dtucker   565:        while ((blen = get_line(fp, line, sizeof(line))) != -1) {
1.228     djm       566:                if (blen > 0 && line[blen - 1] == '\\')
1.25      markus    567:                        escaped++;
1.19      markus    568:                if (strncmp(line, "----", 4) == 0 ||
                    569:                    strstr(line, ": ") != NULL) {
1.32      markus    570:                        if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
1.193     djm       571:                                *private = 1;
1.64      markus    572:                        if (strstr(line, " END ") != NULL) {
                    573:                                break;
                    574:                        }
1.60      markus    575:                        /* fprintf(stderr, "ignore: %s", line); */
1.19      markus    576:                        continue;
                    577:                }
1.25      markus    578:                if (escaped) {
                    579:                        escaped--;
1.60      markus    580:                        /* fprintf(stderr, "escaped: %s", line); */
1.25      markus    581:                        continue;
1.19      markus    582:                }
                    583:                strlcat(encoded, line, sizeof(encoded));
                    584:        }
1.98      markus    585:        len = strlen(encoded);
                    586:        if (((len % 4) == 3) &&
                    587:            (encoded[len-1] == '=') &&
                    588:            (encoded[len-2] == '=') &&
                    589:            (encoded[len-3] == '='))
                    590:                encoded[len-3] = '\0';
1.91      stevesk   591:        blen = uudecode(encoded, blob, sizeof(blob));
1.269     djm       592:        if (blen < 0)
                    593:                fatal("uudecode failed.");
1.252     djm       594:        if (*private)
                    595:                *k = do_convert_private_ssh2_from_blob(blob, blen);
1.269     djm       596:        else if ((r = sshkey_from_blob(blob, blen, k)) != 0)
                    597:                fatal("decode blob failed: %s", ssh_err(r));
1.193     djm       598:        fclose(fp);
                    599: }
                    600:
                    601: static void
1.252     djm       602: do_convert_from_pkcs8(struct sshkey **k, int *private)
1.193     djm       603: {
                    604:        EVP_PKEY *pubkey;
                    605:        FILE *fp;
                    606:
                    607:        if ((fp = fopen(identity_file, "r")) == NULL)
                    608:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
                    609:        if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
                    610:                fatal("%s: %s is not a recognised public key format", __func__,
                    611:                    identity_file);
                    612:        }
                    613:        fclose(fp);
                    614:        switch (EVP_PKEY_type(pubkey->type)) {
                    615:        case EVP_PKEY_RSA:
1.252     djm       616:                if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
                    617:                        fatal("sshkey_new failed");
1.193     djm       618:                (*k)->type = KEY_RSA;
                    619:                (*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
                    620:                break;
                    621:        case EVP_PKEY_DSA:
1.252     djm       622:                if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
                    623:                        fatal("sshkey_new failed");
1.193     djm       624:                (*k)->type = KEY_DSA;
                    625:                (*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
                    626:                break;
1.200     djm       627:        case EVP_PKEY_EC:
1.252     djm       628:                if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
                    629:                        fatal("sshkey_new failed");
1.200     djm       630:                (*k)->type = KEY_ECDSA;
                    631:                (*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
1.252     djm       632:                (*k)->ecdsa_nid = sshkey_ecdsa_key_to_nid((*k)->ecdsa);
1.200     djm       633:                break;
1.193     djm       634:        default:
                    635:                fatal("%s: unsupported pubkey type %d", __func__,
                    636:                    EVP_PKEY_type(pubkey->type));
                    637:        }
                    638:        EVP_PKEY_free(pubkey);
                    639:        return;
                    640: }
                    641:
                    642: static void
1.252     djm       643: do_convert_from_pem(struct sshkey **k, int *private)
1.193     djm       644: {
                    645:        FILE *fp;
                    646:        RSA *rsa;
                    647: #ifdef notyet
                    648:        DSA *dsa;
                    649: #endif
                    650:
                    651:        if ((fp = fopen(identity_file, "r")) == NULL)
                    652:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
                    653:        if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
1.252     djm       654:                if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
                    655:                        fatal("sshkey_new failed");
1.193     djm       656:                (*k)->type = KEY_RSA;
                    657:                (*k)->rsa = rsa;
                    658:                fclose(fp);
                    659:                return;
                    660:        }
                    661: #if notyet /* OpenSSH 0.9.8 lacks this function */
                    662:        rewind(fp);
                    663:        if ((dsa = PEM_read_DSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
1.252     djm       664:                if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
                    665:                        fatal("sshkey_new failed");
1.193     djm       666:                (*k)->type = KEY_DSA;
                    667:                (*k)->dsa = dsa;
                    668:                fclose(fp);
                    669:                return;
                    670:        }
1.200     djm       671:        /* XXX ECDSA */
1.193     djm       672: #endif
                    673:        fatal("%s: unrecognised raw private key format", __func__);
                    674: }
                    675:
                    676: static void
                    677: do_convert_from(struct passwd *pw)
                    678: {
1.252     djm       679:        struct sshkey *k = NULL;
                    680:        int r, private = 0, ok = 0;
1.193     djm       681:        struct stat st;
                    682:
                    683:        if (!have_identity)
                    684:                ask_filename(pw, "Enter file in which the key is");
                    685:        if (stat(identity_file, &st) < 0)
                    686:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
                    687:
                    688:        switch (convert_format) {
                    689:        case FMT_RFC4716:
                    690:                do_convert_from_ssh2(pw, &k, &private);
                    691:                break;
                    692:        case FMT_PKCS8:
                    693:                do_convert_from_pkcs8(&k, &private);
                    694:                break;
                    695:        case FMT_PEM:
                    696:                do_convert_from_pem(&k, &private);
                    697:                break;
                    698:        default:
                    699:                fatal("%s: unknown key format %d", __func__, convert_format);
                    700:        }
                    701:
1.260     djm       702:        if (!private) {
1.252     djm       703:                if ((r = sshkey_write(k, stdout)) == 0)
                    704:                        ok = 1;
1.193     djm       705:                if (ok)
                    706:                        fprintf(stdout, "\n");
1.260     djm       707:        } else {
1.193     djm       708:                switch (k->type) {
                    709:                case KEY_DSA:
                    710:                        ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
                    711:                            NULL, 0, NULL, NULL);
                    712:                        break;
1.200     djm       713:                case KEY_ECDSA:
                    714:                        ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
                    715:                            NULL, 0, NULL, NULL);
                    716:                        break;
1.193     djm       717:                case KEY_RSA:
                    718:                        ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
                    719:                            NULL, 0, NULL, NULL);
                    720:                        break;
                    721:                default:
                    722:                        fatal("%s: unsupported key type %s", __func__,
1.252     djm       723:                            sshkey_type(k));
1.193     djm       724:                }
                    725:        }
                    726:
1.269     djm       727:        if (!ok)
                    728:                fatal("key write failed");
1.252     djm       729:        sshkey_free(k);
1.19      markus    730:        exit(0);
                    731: }
1.246     markus    732: #endif
1.19      markus    733:
1.63      itojun    734: static void
1.19      markus    735: do_print_public(struct passwd *pw)
                    736: {
1.252     djm       737:        struct sshkey *prv;
1.19      markus    738:        struct stat st;
1.252     djm       739:        int r;
1.19      markus    740:
                    741:        if (!have_identity)
                    742:                ask_filename(pw, "Enter file in which the key is");
1.269     djm       743:        if (stat(identity_file, &st) < 0)
                    744:                fatal("%s: %s", identity_file, strerror(errno));
1.61      markus    745:        prv = load_identity(identity_file);
1.252     djm       746:        if ((r = sshkey_write(prv, stdout)) != 0)
1.269     djm       747:                error("key_write failed: %s", ssh_err(r));
1.252     djm       748:        sshkey_free(prv);
1.19      markus    749:        fprintf(stdout, "\n");
                    750:        exit(0);
                    751: }
                    752:
1.66      markus    753: static void
1.197     djm       754: do_download(struct passwd *pw)
1.75      markus    755: {
1.177     markus    756: #ifdef ENABLE_PKCS11
1.252     djm       757:        struct sshkey **keys = NULL;
1.177     markus    758:        int i, nkeys;
1.252     djm       759:        enum sshkey_fp_rep rep;
1.251     djm       760:        int fptype;
1.221     djm       761:        char *fp, *ra;
1.222     djm       762:
1.251     djm       763:        fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
                    764:        rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1.75      markus    765:
1.177     markus    766:        pkcs11_init(0);
                    767:        nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys);
                    768:        if (nkeys <= 0)
                    769:                fatal("cannot read public key from pkcs11");
                    770:        for (i = 0; i < nkeys; i++) {
1.221     djm       771:                if (print_fingerprint) {
1.252     djm       772:                        fp = sshkey_fingerprint(keys[i], fptype, rep);
                    773:                        ra = sshkey_fingerprint(keys[i], fingerprint_hash,
1.221     djm       774:                            SSH_FP_RANDOMART);
1.259     djm       775:                        if (fp == NULL || ra == NULL)
                    776:                                fatal("%s: sshkey_fingerprint fail", __func__);
1.252     djm       777:                        printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
                    778:                            fp, sshkey_type(keys[i]));
1.221     djm       779:                        if (log_level >= SYSLOG_LEVEL_VERBOSE)
                    780:                                printf("%s\n", ra);
1.227     djm       781:                        free(ra);
                    782:                        free(fp);
1.221     djm       783:                } else {
1.252     djm       784:                        (void) sshkey_write(keys[i], stdout); /* XXX check */
1.221     djm       785:                        fprintf(stdout, "\n");
                    786:                }
1.252     djm       787:                sshkey_free(keys[i]);
1.97      markus    788:        }
1.227     djm       789:        free(keys);
1.177     markus    790:        pkcs11_terminate();
1.75      markus    791:        exit(0);
1.177     markus    792: #else
                    793:        fatal("no pkcs11 support");
                    794: #endif /* ENABLE_PKCS11 */
1.75      markus    795: }
1.66      markus    796:
1.279     djm       797: static struct sshkey *
                    798: try_read_key(char **cpp)
                    799: {
                    800:        struct sshkey *ret;
                    801:        int r;
                    802:
                    803:        if ((ret = sshkey_new(KEY_RSA1)) == NULL)
                    804:                fatal("sshkey_new failed");
                    805:        /* Try RSA1 */
                    806:        if ((r = sshkey_read(ret, cpp)) == 0)
                    807:                return ret;
                    808:        /* Try modern */
                    809:        sshkey_free(ret);
                    810:        if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
                    811:                fatal("sshkey_new failed");
                    812:        if ((r = sshkey_read(ret, cpp)) == 0)
                    813:                return ret;
                    814:        /* Not a key */
                    815:        sshkey_free(ret);
                    816:        return NULL;
                    817: }
                    818:
1.63      itojun    819: static void
1.279     djm       820: fingerprint_one_key(const struct sshkey *public, const char *comment)
1.8       markus    821: {
1.279     djm       822:        char *fp = NULL, *ra = NULL;
1.252     djm       823:        enum sshkey_fp_rep rep;
1.251     djm       824:        int fptype;
1.12      markus    825:
1.251     djm       826:        fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
                    827:        rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1.279     djm       828:        fp = sshkey_fingerprint(public, fptype, rep);
                    829:        ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
                    830:        if (fp == NULL || ra == NULL)
                    831:                fatal("%s: sshkey_fingerprint failed", __func__);
                    832:        printf("%u %s %s (%s)\n", sshkey_size(public), fp,
                    833:            comment ? comment : "no comment", sshkey_type(public));
                    834:        if (log_level >= SYSLOG_LEVEL_VERBOSE)
                    835:                printf("%s\n", ra);
                    836:        free(ra);
                    837:        free(fp);
                    838: }
                    839:
                    840: static void
                    841: fingerprint_private(const char *path)
                    842: {
                    843:        struct stat st;
                    844:        char *comment = NULL;
                    845:        struct sshkey *public = NULL;
                    846:        int r;
                    847:
                    848:        if (stat(identity_file, &st) < 0)
                    849:                fatal("%s: %s", path, strerror(errno));
1.280     djm       850:        if ((r = sshkey_load_public(path, &public, &comment)) != 0) {
                    851:                debug("load public \"%s\": %s", path, ssh_err(r));
                    852:                if ((r = sshkey_load_private(path, NULL,
                    853:                    &public, &comment)) != 0) {
                    854:                        debug("load private \"%s\": %s", path, ssh_err(r));
                    855:                        fatal("%s is not a key file.", path);
                    856:                }
                    857:        }
                    858:
1.279     djm       859:        fingerprint_one_key(public, comment);
                    860:        sshkey_free(public);
                    861:        free(comment);
                    862: }
                    863:
                    864: static void
                    865: do_fingerprint(struct passwd *pw)
                    866: {
                    867:        FILE *f;
                    868:        struct sshkey *public = NULL;
1.287     djm       869:        char *comment = NULL, *cp, *ep, line[SSH_MAX_PUBKEY_BYTES];
1.279     djm       870:        int i, invalid = 1;
                    871:        const char *path;
1.289     djm       872:        u_long lnum = 0;
1.279     djm       873:
1.12      markus    874:        if (!have_identity)
                    875:                ask_filename(pw, "Enter file in which the key is");
1.279     djm       876:        path = identity_file;
1.15      markus    877:
1.279     djm       878:        if (strcmp(identity_file, "-") == 0) {
                    879:                f = stdin;
                    880:                path = "(stdin)";
                    881:        } else if ((f = fopen(path, "r")) == NULL)
                    882:                fatal("%s: %s: %s", __progname, path, strerror(errno));
                    883:
                    884:        while (read_keyfile_line(f, path, line, sizeof(line), &lnum) == 0) {
                    885:                cp = line;
                    886:                cp[strcspn(cp, "\n")] = '\0';
                    887:                /* Trim leading space and comments */
                    888:                cp = line + strspn(line, " \t");
                    889:                if (*cp == '#' || *cp == '\0')
                    890:                        continue;
1.191     djm       891:
1.279     djm       892:                /*
                    893:                 * Input may be plain keys, private keys, authorized_keys
                    894:                 * or known_hosts.
                    895:                 */
                    896:
                    897:                /*
                    898:                 * Try private keys first. Assume a key is private if
                    899:                 * "SSH PRIVATE KEY" appears on the first line and we're
                    900:                 * not reading from stdin (XXX support private keys on stdin).
                    901:                 */
                    902:                if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
1.280     djm       903:                    strstr(cp, "PRIVATE KEY") != NULL) {
1.279     djm       904:                        fclose(f);
                    905:                        fingerprint_private(path);
                    906:                        exit(0);
                    907:                }
                    908:
                    909:                /*
                    910:                 * If it's not a private key, then this must be prepared to
                    911:                 * accept a public key prefixed with a hostname or options.
                    912:                 * Try a bare key first, otherwise skip the leading stuff.
                    913:                 */
                    914:                if ((public = try_read_key(&cp)) == NULL) {
                    915:                        i = strtol(cp, &ep, 10);
                    916:                        if (i == 0 || ep == NULL ||
                    917:                            (*ep != ' ' && *ep != '\t')) {
                    918:                                int quoted = 0;
                    919:
                    920:                                comment = cp;
                    921:                                for (; *cp && (quoted || (*cp != ' ' &&
                    922:                                    *cp != '\t')); cp++) {
                    923:                                        if (*cp == '\\' && cp[1] == '"')
                    924:                                                cp++;   /* Skip both */
                    925:                                        else if (*cp == '"')
                    926:                                                quoted = !quoted;
                    927:                                }
                    928:                                if (!*cp)
                    929:                                        continue;
                    930:                                *cp++ = '\0';
                    931:                        }
1.191     djm       932:                }
1.279     djm       933:                /* Retry after parsing leading hostname/key options */
                    934:                if (public == NULL && (public = try_read_key(&cp)) == NULL) {
1.289     djm       935:                        debug("%s:%lu: not a public key", path, lnum);
1.191     djm       936:                        continue;
                    937:                }
                    938:
1.279     djm       939:                /* Find trailing comment, if any */
                    940:                for (; *cp == ' ' || *cp == '\t'; cp++)
1.191     djm       941:                        ;
1.279     djm       942:                if (*cp != '\0' && *cp != '#')
1.191     djm       943:                        comment = cp;
1.279     djm       944:
                    945:                fingerprint_one_key(public, comment);
1.252     djm       946:                sshkey_free(public);
1.279     djm       947:                invalid = 0; /* One good key in the file is sufficient */
1.15      markus    948:        }
1.191     djm       949:        fclose(f);
                    950:
1.269     djm       951:        if (invalid)
1.279     djm       952:                fatal("%s is not a public key file.", path);
1.12      markus    953:        exit(0);
1.8       markus    954: }
                    955:
1.119     djm       956: static void
1.206     stevesk   957: do_gen_all_hostkeys(struct passwd *pw)
                    958: {
                    959:        struct {
                    960:                char *key_type;
                    961:                char *key_type_display;
                    962:                char *path;
                    963:        } key_types[] = {
1.267     djm       964: #ifdef WITH_OPENSSL
                    965: #ifdef WITH_SSH1
1.206     stevesk   966:                { "rsa1", "RSA1", _PATH_HOST_KEY_FILE },
1.267     djm       967: #endif /* WITH_SSH1 */
1.206     stevesk   968:                { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
                    969:                { "dsa", "DSA", _PATH_HOST_DSA_KEY_FILE },
                    970:                { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
1.267     djm       971: #endif /* WITH_OPENSSL */
1.238     markus    972:                { "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
1.206     stevesk   973:                { NULL, NULL, NULL }
                    974:        };
                    975:
                    976:        int first = 0;
                    977:        struct stat st;
1.252     djm       978:        struct sshkey *private, *public;
1.206     stevesk   979:        char comment[1024];
1.252     djm       980:        int i, type, fd, r;
1.206     stevesk   981:        FILE *f;
                    982:
                    983:        for (i = 0; key_types[i].key_type; i++) {
                    984:                if (stat(key_types[i].path, &st) == 0)
                    985:                        continue;
                    986:                if (errno != ENOENT) {
1.269     djm       987:                        error("Could not stat %s: %s", key_types[i].path,
1.206     stevesk   988:                            strerror(errno));
                    989:                        first = 0;
                    990:                        continue;
                    991:                }
                    992:
                    993:                if (first == 0) {
                    994:                        first = 1;
                    995:                        printf("%s: generating new host keys: ", __progname);
                    996:                }
                    997:                printf("%s ", key_types[i].key_type_display);
                    998:                fflush(stdout);
1.252     djm       999:                type = sshkey_type_from_name(key_types[i].key_type);
1.206     stevesk  1000:                strlcpy(identity_file, key_types[i].path, sizeof(identity_file));
                   1001:                bits = 0;
1.255     djm      1002:                type_bits_valid(type, NULL, &bits);
1.252     djm      1003:                if ((r = sshkey_generate(type, bits, &private)) != 0) {
1.269     djm      1004:                        error("key_generate failed: %s", ssh_err(r));
1.206     stevesk  1005:                        first = 0;
                   1006:                        continue;
                   1007:                }
1.252     djm      1008:                if ((r = sshkey_from_private(private, &public)) != 0)
                   1009:                        fatal("sshkey_from_private failed: %s", ssh_err(r));
1.206     stevesk  1010:                snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
                   1011:                    hostname);
1.252     djm      1012:                if ((r = sshkey_save_private(private, identity_file, "",
                   1013:                    comment, use_new_format, new_format_cipher, rounds)) != 0) {
1.269     djm      1014:                        error("Saving key \"%s\" failed: %s",
                   1015:                            identity_file, ssh_err(r));
1.252     djm      1016:                        sshkey_free(private);
                   1017:                        sshkey_free(public);
1.206     stevesk  1018:                        first = 0;
                   1019:                        continue;
                   1020:                }
1.252     djm      1021:                sshkey_free(private);
1.206     stevesk  1022:                strlcat(identity_file, ".pub", sizeof(identity_file));
                   1023:                fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
                   1024:                if (fd == -1) {
1.269     djm      1025:                        error("Could not save your public key in %s",
1.206     stevesk  1026:                            identity_file);
1.252     djm      1027:                        sshkey_free(public);
1.206     stevesk  1028:                        first = 0;
                   1029:                        continue;
                   1030:                }
                   1031:                f = fdopen(fd, "w");
                   1032:                if (f == NULL) {
1.269     djm      1033:                        error("fdopen %s failed", identity_file);
1.250     doug     1034:                        close(fd);
1.252     djm      1035:                        sshkey_free(public);
1.206     stevesk  1036:                        first = 0;
                   1037:                        continue;
                   1038:                }
1.254     djm      1039:                if ((r = sshkey_write(public, f)) != 0) {
1.269     djm      1040:                        error("write key failed: %s", ssh_err(r));
1.250     doug     1041:                        fclose(f);
1.252     djm      1042:                        sshkey_free(public);
1.206     stevesk  1043:                        first = 0;
                   1044:                        continue;
                   1045:                }
                   1046:                fprintf(f, " %s\n", comment);
                   1047:                fclose(f);
1.252     djm      1048:                sshkey_free(public);
1.206     stevesk  1049:
                   1050:        }
                   1051:        if (first != 0)
                   1052:                printf("\n");
                   1053: }
                   1054:
1.256     djm      1055: struct known_hosts_ctx {
1.257     djm      1056:        const char *host;       /* Hostname searched for in find/delete case */
                   1057:        FILE *out;              /* Output file, stdout for find_hosts case */
                   1058:        int has_unhashed;       /* When hashing, original had unhashed hosts */
                   1059:        int found_key;          /* For find/delete, host was found */
                   1060:        int invalid;            /* File contained invalid items; don't delete */
1.256     djm      1061: };
                   1062:
                   1063: static int
                   1064: known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1.119     djm      1065: {
1.256     djm      1066:        struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
                   1067:        char *hashed, *cp, *hosts, *ohosts;
                   1068:        int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
                   1069:
1.262     djm      1070:        switch (l->status) {
                   1071:        case HKF_STATUS_OK:
                   1072:        case HKF_STATUS_MATCHED:
                   1073:                /*
                   1074:                 * Don't hash hosts already already hashed, with wildcard
                   1075:                 * characters or a CA/revocation marker.
                   1076:                 */
                   1077:                if ((l->match & HKF_MATCH_HOST_HASHED) != 0 ||
                   1078:                    has_wild || l->marker != MRK_NONE) {
                   1079:                        fprintf(ctx->out, "%s\n", l->line);
                   1080:                        if (has_wild && !find_host) {
1.269     djm      1081:                                logit("%s:%ld: ignoring host name "
                   1082:                                    "with wildcard: %.64s", l->path,
1.262     djm      1083:                                    l->linenum, l->hosts);
                   1084:                        }
                   1085:                        return 0;
                   1086:                }
                   1087:                /*
                   1088:                 * Split any comma-separated hostnames from the host list,
                   1089:                 * hash and store separately.
                   1090:                 */
                   1091:                ohosts = hosts = xstrdup(l->hosts);
                   1092:                while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
                   1093:                        if ((hashed = host_hash(cp, NULL, 0)) == NULL)
                   1094:                                fatal("hash_host failed");
                   1095:                        fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
                   1096:                        ctx->has_unhashed = 1;
                   1097:                }
                   1098:                free(ohosts);
                   1099:                return 0;
                   1100:        case HKF_STATUS_INVALID:
                   1101:                /* Retain invalid lines, but mark file as invalid. */
1.256     djm      1102:                ctx->invalid = 1;
1.269     djm      1103:                logit("%s:%ld: invalid line", l->path, l->linenum);
1.262     djm      1104:                /* FALLTHROUGH */
                   1105:        default:
1.256     djm      1106:                fprintf(ctx->out, "%s\n", l->line);
                   1107:                return 0;
                   1108:        }
1.262     djm      1109:        /* NOTREACHED */
                   1110:        return -1;
1.256     djm      1111: }
                   1112:
                   1113: static int
                   1114: known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
                   1115: {
                   1116:        struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1.272     djm      1117:        enum sshkey_fp_rep rep;
                   1118:        int fptype;
                   1119:        char *fp;
                   1120:
                   1121:        fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
                   1122:        rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1.256     djm      1123:
1.262     djm      1124:        if (l->status == HKF_STATUS_MATCHED) {
1.256     djm      1125:                if (delete_host) {
                   1126:                        if (l->marker != MRK_NONE) {
                   1127:                                /* Don't remove CA and revocation lines */
                   1128:                                fprintf(ctx->out, "%s\n", l->line);
                   1129:                        } else {
                   1130:                                /*
                   1131:                                 * Hostname matches and has no CA/revoke
                   1132:                                 * marker, delete it by *not* writing the
                   1133:                                 * line to ctx->out.
                   1134:                                 */
                   1135:                                ctx->found_key = 1;
                   1136:                                if (!quiet)
                   1137:                                        printf("# Host %s found: line %ld\n",
                   1138:                                            ctx->host, l->linenum);
                   1139:                        }
                   1140:                        return 0;
                   1141:                } else if (find_host) {
                   1142:                        ctx->found_key = 1;
                   1143:                        if (!quiet) {
                   1144:                                printf("# Host %s found: line %ld %s\n",
                   1145:                                    ctx->host,
                   1146:                                    l->linenum, l->marker == MRK_CA ? "CA" :
                   1147:                                    (l->marker == MRK_REVOKE ? "REVOKED" : ""));
                   1148:                        }
                   1149:                        if (hash_hosts)
                   1150:                                known_hosts_hash(l, ctx);
1.272     djm      1151:                        else if (print_fingerprint) {
                   1152:                                fp = sshkey_fingerprint(l->key, fptype, rep);
                   1153:                                printf("%s %s %s %s\n", ctx->host,
                   1154:                                    sshkey_type(l->key), fp, l->comment);
                   1155:                                free(fp);
                   1156:                        } else
1.256     djm      1157:                                fprintf(ctx->out, "%s\n", l->line);
                   1158:                        return 0;
                   1159:                }
                   1160:        } else if (delete_host) {
                   1161:                /* Retain non-matching hosts when deleting */
                   1162:                if (l->status == HKF_STATUS_INVALID) {
                   1163:                        ctx->invalid = 1;
1.269     djm      1164:                        logit("%s:%ld: invalid line", l->path, l->linenum);
1.256     djm      1165:                }
                   1166:                fprintf(ctx->out, "%s\n", l->line);
1.166     djm      1167:        }
1.256     djm      1168:        return 0;
1.119     djm      1169: }
                   1170:
                   1171: static void
                   1172: do_known_hosts(struct passwd *pw, const char *name)
                   1173: {
1.258     deraadt  1174:        char *cp, tmp[PATH_MAX], old[PATH_MAX];
1.257     djm      1175:        int r, fd, oerrno, inplace = 0;
1.256     djm      1176:        struct known_hosts_ctx ctx;
1.272     djm      1177:        u_int foreach_options;
1.119     djm      1178:
                   1179:        if (!have_identity) {
                   1180:                cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
                   1181:                if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
                   1182:                    sizeof(identity_file))
                   1183:                        fatal("Specified known hosts path too long");
1.227     djm      1184:                free(cp);
1.119     djm      1185:                have_identity = 1;
                   1186:        }
                   1187:
1.256     djm      1188:        memset(&ctx, 0, sizeof(ctx));
                   1189:        ctx.out = stdout;
                   1190:        ctx.host = name;
                   1191:
1.119     djm      1192:        /*
                   1193:         * Find hosts goes to stdout, hash and deletions happen in-place
                   1194:         * A corner case is ssh-keygen -HF foo, which should go to stdout
                   1195:         */
                   1196:        if (!find_host && (hash_hosts || delete_host)) {
                   1197:                if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
                   1198:                    strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
                   1199:                    strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
                   1200:                    strlcat(old, ".old", sizeof(old)) >= sizeof(old))
                   1201:                        fatal("known_hosts path too long");
                   1202:                umask(077);
1.256     djm      1203:                if ((fd = mkstemp(tmp)) == -1)
1.119     djm      1204:                        fatal("mkstemp: %s", strerror(errno));
1.256     djm      1205:                if ((ctx.out = fdopen(fd, "w")) == NULL) {
                   1206:                        oerrno = errno;
1.119     djm      1207:                        unlink(tmp);
1.256     djm      1208:                        fatal("fdopen: %s", strerror(oerrno));
1.119     djm      1209:                }
1.257     djm      1210:                inplace = 1;
1.119     djm      1211:        }
                   1212:
1.256     djm      1213:        /* XXX support identity_file == "-" for stdin */
1.272     djm      1214:        foreach_options = find_host ? HKF_WANT_MATCH : 0;
                   1215:        foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1.256     djm      1216:        if ((r = hostkeys_foreach(identity_file,
                   1217:            hash_hosts ? known_hosts_hash : known_hosts_find_delete, &ctx,
1.284     deraadt  1218:            name, NULL, foreach_options)) != 0) {
                   1219:                if (inplace)
                   1220:                        unlink(tmp);
1.256     djm      1221:                fatal("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
1.284     deraadt  1222:        }
1.119     djm      1223:
1.257     djm      1224:        if (inplace)
1.256     djm      1225:                fclose(ctx.out);
1.119     djm      1226:
1.256     djm      1227:        if (ctx.invalid) {
1.269     djm      1228:                error("%s is not a valid known_hosts file.", identity_file);
1.257     djm      1229:                if (inplace) {
1.269     djm      1230:                        error("Not replacing existing known_hosts "
                   1231:                            "file because of errors");
1.119     djm      1232:                        unlink(tmp);
                   1233:                }
                   1234:                exit(1);
1.256     djm      1235:        } else if (delete_host && !ctx.found_key) {
1.269     djm      1236:                logit("Host %s not found in %s", name, identity_file);
1.277     djm      1237:                if (inplace)
                   1238:                        unlink(tmp);
1.257     djm      1239:        } else if (inplace) {
1.119     djm      1240:                /* Backup existing file */
                   1241:                if (unlink(old) == -1 && errno != ENOENT)
                   1242:                        fatal("unlink %.100s: %s", old, strerror(errno));
                   1243:                if (link(identity_file, old) == -1)
                   1244:                        fatal("link %.100s to %.100s: %s", identity_file, old,
                   1245:                            strerror(errno));
                   1246:                /* Move new one into place */
                   1247:                if (rename(tmp, identity_file) == -1) {
                   1248:                        error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
                   1249:                            strerror(errno));
                   1250:                        unlink(tmp);
                   1251:                        unlink(old);
                   1252:                        exit(1);
                   1253:                }
                   1254:
1.269     djm      1255:                printf("%s updated.\n", identity_file);
                   1256:                printf("Original contents retained as %s\n", old);
1.256     djm      1257:                if (ctx.has_unhashed) {
1.269     djm      1258:                        logit("WARNING: %s contains unhashed entries", old);
                   1259:                        logit("Delete this file to ensure privacy "
                   1260:                            "of hostnames");
1.119     djm      1261:                }
                   1262:        }
                   1263:
1.256     djm      1264:        exit (find_host && !ctx.found_key);
1.119     djm      1265: }
                   1266:
1.13      deraadt  1267: /*
                   1268:  * Perform changing a passphrase.  The argument is the passwd structure
                   1269:  * for the current user.
                   1270:  */
1.63      itojun   1271: static void
1.7       markus   1272: do_change_passphrase(struct passwd *pw)
                   1273: {
1.12      markus   1274:        char *comment;
                   1275:        char *old_passphrase, *passphrase1, *passphrase2;
                   1276:        struct stat st;
1.252     djm      1277:        struct sshkey *private;
                   1278:        int r;
1.12      markus   1279:
                   1280:        if (!have_identity)
                   1281:                ask_filename(pw, "Enter file in which the key is");
1.269     djm      1282:        if (stat(identity_file, &st) < 0)
                   1283:                fatal("%s: %s", identity_file, strerror(errno));
1.12      markus   1284:        /* Try to load the file with empty passphrase. */
1.252     djm      1285:        r = sshkey_load_private(identity_file, "", &private, &comment);
                   1286:        if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1.12      markus   1287:                if (identity_passphrase)
                   1288:                        old_passphrase = xstrdup(identity_passphrase);
                   1289:                else
1.65      markus   1290:                        old_passphrase =
                   1291:                            read_passphrase("Enter old passphrase: ",
                   1292:                            RP_ALLOW_STDIN);
1.252     djm      1293:                r = sshkey_load_private(identity_file, old_passphrase,
                   1294:                    &private, &comment);
1.240     djm      1295:                explicit_bzero(old_passphrase, strlen(old_passphrase));
1.227     djm      1296:                free(old_passphrase);
1.252     djm      1297:                if (r != 0)
                   1298:                        goto badkey;
                   1299:        } else if (r != 0) {
                   1300:  badkey:
1.269     djm      1301:                fatal("Failed to load key %s: %s", identity_file, ssh_err(r));
1.12      markus   1302:        }
1.266     djm      1303:        if (comment)
                   1304:                printf("Key has comment '%s'\n", comment);
1.12      markus   1305:
                   1306:        /* Ask the new passphrase (twice). */
                   1307:        if (identity_new_passphrase) {
                   1308:                passphrase1 = xstrdup(identity_new_passphrase);
                   1309:                passphrase2 = NULL;
                   1310:        } else {
                   1311:                passphrase1 =
1.65      markus   1312:                        read_passphrase("Enter new passphrase (empty for no "
                   1313:                            "passphrase): ", RP_ALLOW_STDIN);
                   1314:                passphrase2 = read_passphrase("Enter same passphrase again: ",
1.86      deraadt  1315:                    RP_ALLOW_STDIN);
1.12      markus   1316:
                   1317:                /* Verify that they are the same. */
                   1318:                if (strcmp(passphrase1, passphrase2) != 0) {
1.240     djm      1319:                        explicit_bzero(passphrase1, strlen(passphrase1));
                   1320:                        explicit_bzero(passphrase2, strlen(passphrase2));
1.227     djm      1321:                        free(passphrase1);
                   1322:                        free(passphrase2);
1.12      markus   1323:                        printf("Pass phrases do not match.  Try again.\n");
                   1324:                        exit(1);
                   1325:                }
                   1326:                /* Destroy the other copy. */
1.240     djm      1327:                explicit_bzero(passphrase2, strlen(passphrase2));
1.227     djm      1328:                free(passphrase2);
1.12      markus   1329:        }
                   1330:
                   1331:        /* Save the file using the new passphrase. */
1.252     djm      1332:        if ((r = sshkey_save_private(private, identity_file, passphrase1,
                   1333:            comment, use_new_format, new_format_cipher, rounds)) != 0) {
1.269     djm      1334:                error("Saving key \"%s\" failed: %s.",
1.252     djm      1335:                    identity_file, ssh_err(r));
1.240     djm      1336:                explicit_bzero(passphrase1, strlen(passphrase1));
1.227     djm      1337:                free(passphrase1);
1.252     djm      1338:                sshkey_free(private);
1.227     djm      1339:                free(comment);
1.12      markus   1340:                exit(1);
                   1341:        }
                   1342:        /* Destroy the passphrase and the copy of the key in memory. */
1.240     djm      1343:        explicit_bzero(passphrase1, strlen(passphrase1));
1.227     djm      1344:        free(passphrase1);
1.252     djm      1345:        sshkey_free(private);            /* Destroys contents */
1.227     djm      1346:        free(comment);
1.1       deraadt  1347:
1.12      markus   1348:        printf("Your identification has been saved with the new passphrase.\n");
                   1349:        exit(0);
1.1       deraadt  1350: }
                   1351:
1.105     jakob    1352: /*
                   1353:  * Print the SSHFP RR.
                   1354:  */
1.138     jakob    1355: static int
                   1356: do_print_resource_record(struct passwd *pw, char *fname, char *hname)
1.105     jakob    1357: {
1.252     djm      1358:        struct sshkey *public;
1.105     jakob    1359:        char *comment = NULL;
                   1360:        struct stat st;
1.252     djm      1361:        int r;
1.105     jakob    1362:
1.138     jakob    1363:        if (fname == NULL)
1.229     djm      1364:                fatal("%s: no filename", __func__);
1.138     jakob    1365:        if (stat(fname, &st) < 0) {
                   1366:                if (errno == ENOENT)
                   1367:                        return 0;
1.269     djm      1368:                fatal("%s: %s", fname, strerror(errno));
1.105     jakob    1369:        }
1.269     djm      1370:        if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
                   1371:                fatal("Failed to read v2 public key from \"%s\": %s.",
1.252     djm      1372:                    fname, ssh_err(r));
                   1373:        export_dns_rr(hname, public, stdout, print_generic);
                   1374:        sshkey_free(public);
                   1375:        free(comment);
                   1376:        return 1;
1.105     jakob    1377: }
                   1378:
1.13      deraadt  1379: /*
                   1380:  * Change the comment of a private key file.
                   1381:  */
1.63      itojun   1382: static void
1.2       provos   1383: do_change_comment(struct passwd *pw)
1.1       deraadt  1384: {
1.46      deraadt  1385:        char new_comment[1024], *comment, *passphrase;
1.252     djm      1386:        struct sshkey *private;
                   1387:        struct sshkey *public;
1.12      markus   1388:        struct stat st;
                   1389:        FILE *f;
1.252     djm      1390:        int r, fd;
1.12      markus   1391:
                   1392:        if (!have_identity)
                   1393:                ask_filename(pw, "Enter file in which the key is");
1.269     djm      1394:        if (stat(identity_file, &st) < 0)
                   1395:                fatal("%s: %s", identity_file, strerror(errno));
1.252     djm      1396:        if ((r = sshkey_load_private(identity_file, "",
                   1397:            &private, &comment)) == 0)
                   1398:                passphrase = xstrdup("");
1.269     djm      1399:        else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
                   1400:                fatal("Cannot load private key \"%s\": %s.",
1.252     djm      1401:                    identity_file, ssh_err(r));
1.269     djm      1402:        else {
1.12      markus   1403:                if (identity_passphrase)
                   1404:                        passphrase = xstrdup(identity_passphrase);
                   1405:                else if (identity_new_passphrase)
                   1406:                        passphrase = xstrdup(identity_new_passphrase);
                   1407:                else
1.65      markus   1408:                        passphrase = read_passphrase("Enter passphrase: ",
                   1409:                            RP_ALLOW_STDIN);
1.12      markus   1410:                /* Try to load using the passphrase. */
1.252     djm      1411:                if ((r = sshkey_load_private(identity_file, passphrase,
                   1412:                    &private, &comment)) != 0) {
1.240     djm      1413:                        explicit_bzero(passphrase, strlen(passphrase));
1.227     djm      1414:                        free(passphrase);
1.269     djm      1415:                        fatal("Cannot load private key \"%s\": %s.",
1.252     djm      1416:                            identity_file, ssh_err(r));
1.12      markus   1417:                }
                   1418:        }
1.283     halex    1419:
                   1420:        if (private->type != KEY_RSA1 && private->type != KEY_ED25519 &&
                   1421:            !use_new_format) {
                   1422:                error("Comments are only supported for RSA1 or keys stored in "
                   1423:                    "the new format (-o).");
1.268     tobias   1424:                explicit_bzero(passphrase, strlen(passphrase));
1.252     djm      1425:                sshkey_free(private);
1.52      markus   1426:                exit(1);
1.86      deraadt  1427:        }
1.293   ! millert  1428:        if (comment)
        !          1429:                printf("Key now has comment '%s'\n", comment);
        !          1430:        else
        !          1431:                printf("Key now has no comment\n");
1.12      markus   1432:
                   1433:        if (identity_comment) {
                   1434:                strlcpy(new_comment, identity_comment, sizeof(new_comment));
                   1435:        } else {
                   1436:                printf("Enter new comment: ");
                   1437:                fflush(stdout);
                   1438:                if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1.240     djm      1439:                        explicit_bzero(passphrase, strlen(passphrase));
1.252     djm      1440:                        sshkey_free(private);
1.12      markus   1441:                        exit(1);
                   1442:                }
1.162     gilles   1443:                new_comment[strcspn(new_comment, "\n")] = '\0';
1.12      markus   1444:        }
                   1445:
                   1446:        /* Save the file using the new passphrase. */
1.252     djm      1447:        if ((r = sshkey_save_private(private, identity_file, passphrase,
                   1448:            new_comment, use_new_format, new_format_cipher, rounds)) != 0) {
1.269     djm      1449:                error("Saving key \"%s\" failed: %s",
1.252     djm      1450:                    identity_file, ssh_err(r));
1.240     djm      1451:                explicit_bzero(passphrase, strlen(passphrase));
1.227     djm      1452:                free(passphrase);
1.252     djm      1453:                sshkey_free(private);
1.227     djm      1454:                free(comment);
1.12      markus   1455:                exit(1);
                   1456:        }
1.240     djm      1457:        explicit_bzero(passphrase, strlen(passphrase));
1.227     djm      1458:        free(passphrase);
1.252     djm      1459:        if ((r = sshkey_from_private(private, &public)) != 0)
                   1460:                fatal("key_from_private failed: %s", ssh_err(r));
                   1461:        sshkey_free(private);
1.12      markus   1462:
                   1463:        strlcat(identity_file, ".pub", sizeof(identity_file));
1.46      deraadt  1464:        fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1.269     djm      1465:        if (fd == -1)
                   1466:                fatal("Could not save your public key in %s", identity_file);
1.46      deraadt  1467:        f = fdopen(fd, "w");
1.269     djm      1468:        if (f == NULL)
                   1469:                fatal("fdopen %s failed: %s", identity_file, strerror(errno));
1.252     djm      1470:        if ((r = sshkey_write(public, f)) != 0)
1.269     djm      1471:                fatal("write key failed: %s", ssh_err(r));
1.252     djm      1472:        sshkey_free(public);
1.19      markus   1473:        fprintf(f, " %s\n", new_comment);
1.12      markus   1474:        fclose(f);
1.1       deraadt  1475:
1.227     djm      1476:        free(comment);
1.1       deraadt  1477:
1.12      markus   1478:        printf("The comment in your key file has been changed.\n");
                   1479:        exit(0);
1.1       deraadt  1480: }
                   1481:
1.179     djm      1482: static void
1.252     djm      1483: add_flag_option(struct sshbuf *c, const char *name)
1.179     djm      1484: {
1.252     djm      1485:        int r;
                   1486:
1.179     djm      1487:        debug3("%s: %s", __func__, name);
1.252     djm      1488:        if ((r = sshbuf_put_cstring(c, name)) != 0 ||
                   1489:            (r = sshbuf_put_string(c, NULL, 0)) != 0)
                   1490:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.179     djm      1491: }
                   1492:
                   1493: static void
1.252     djm      1494: add_string_option(struct sshbuf *c, const char *name, const char *value)
1.179     djm      1495: {
1.252     djm      1496:        struct sshbuf *b;
                   1497:        int r;
1.179     djm      1498:
                   1499:        debug3("%s: %s=%s", __func__, name, value);
1.252     djm      1500:        if ((b = sshbuf_new()) == NULL)
                   1501:                fatal("%s: sshbuf_new failed", __func__);
                   1502:        if ((r = sshbuf_put_cstring(b, value)) != 0 ||
                   1503:            (r = sshbuf_put_cstring(c, name)) != 0 ||
                   1504:            (r = sshbuf_put_stringb(c, b)) != 0)
                   1505:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.179     djm      1506:
1.252     djm      1507:        sshbuf_free(b);
1.179     djm      1508: }
                   1509:
1.190     djm      1510: #define OPTIONS_CRITICAL       1
                   1511: #define OPTIONS_EXTENSIONS     2
1.179     djm      1512: static void
1.252     djm      1513: prepare_options_buf(struct sshbuf *c, int which)
1.179     djm      1514: {
1.252     djm      1515:        sshbuf_reset(c);
1.196     djm      1516:        if ((which & OPTIONS_CRITICAL) != 0 &&
                   1517:            certflags_command != NULL)
                   1518:                add_string_option(c, "force-command", certflags_command);
1.190     djm      1519:        if ((which & OPTIONS_EXTENSIONS) != 0 &&
1.210     djm      1520:            (certflags_flags & CERTOPT_X_FWD) != 0)
                   1521:                add_flag_option(c, "permit-X11-forwarding");
                   1522:        if ((which & OPTIONS_EXTENSIONS) != 0 &&
1.190     djm      1523:            (certflags_flags & CERTOPT_AGENT_FWD) != 0)
1.186     djm      1524:                add_flag_option(c, "permit-agent-forwarding");
1.190     djm      1525:        if ((which & OPTIONS_EXTENSIONS) != 0 &&
                   1526:            (certflags_flags & CERTOPT_PORT_FWD) != 0)
1.186     djm      1527:                add_flag_option(c, "permit-port-forwarding");
1.190     djm      1528:        if ((which & OPTIONS_EXTENSIONS) != 0 &&
                   1529:            (certflags_flags & CERTOPT_PTY) != 0)
1.186     djm      1530:                add_flag_option(c, "permit-pty");
1.190     djm      1531:        if ((which & OPTIONS_EXTENSIONS) != 0 &&
                   1532:            (certflags_flags & CERTOPT_USER_RC) != 0)
1.186     djm      1533:                add_flag_option(c, "permit-user-rc");
1.190     djm      1534:        if ((which & OPTIONS_CRITICAL) != 0 &&
                   1535:            certflags_src_addr != NULL)
                   1536:                add_string_option(c, "source-address", certflags_src_addr);
1.179     djm      1537: }
                   1538:
1.252     djm      1539: static struct sshkey *
1.197     djm      1540: load_pkcs11_key(char *path)
                   1541: {
                   1542: #ifdef ENABLE_PKCS11
1.252     djm      1543:        struct sshkey **keys = NULL, *public, *private = NULL;
                   1544:        int r, i, nkeys;
1.197     djm      1545:
1.252     djm      1546:        if ((r = sshkey_load_public(path, &public, NULL)) != 0)
                   1547:                fatal("Couldn't load CA public key \"%s\": %s",
                   1548:                    path, ssh_err(r));
1.197     djm      1549:
                   1550:        nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase, &keys);
                   1551:        debug3("%s: %d keys", __func__, nkeys);
                   1552:        if (nkeys <= 0)
                   1553:                fatal("cannot read public key from pkcs11");
                   1554:        for (i = 0; i < nkeys; i++) {
1.252     djm      1555:                if (sshkey_equal_public(public, keys[i])) {
1.197     djm      1556:                        private = keys[i];
                   1557:                        continue;
                   1558:                }
1.252     djm      1559:                sshkey_free(keys[i]);
1.197     djm      1560:        }
1.227     djm      1561:        free(keys);
1.252     djm      1562:        sshkey_free(public);
1.197     djm      1563:        return private;
                   1564: #else
                   1565:        fatal("no pkcs11 support");
                   1566: #endif /* ENABLE_PKCS11 */
                   1567: }
                   1568:
1.179     djm      1569: static void
                   1570: do_ca_sign(struct passwd *pw, int argc, char **argv)
                   1571: {
1.252     djm      1572:        int r, i, fd;
1.179     djm      1573:        u_int n;
1.252     djm      1574:        struct sshkey *ca, *public;
1.281     djm      1575:        char valid[64], *otmp, *tmp, *cp, *out, *comment, **plist = NULL;
1.179     djm      1576:        FILE *f;
1.186     djm      1577:
1.246     markus   1578: #ifdef ENABLE_PKCS11
1.197     djm      1579:        pkcs11_init(1);
1.246     markus   1580: #endif
1.197     djm      1581:        tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
                   1582:        if (pkcs11provider != NULL) {
                   1583:                if ((ca = load_pkcs11_key(tmp)) == NULL)
                   1584:                        fatal("No PKCS#11 key matching %s found", ca_key_path);
1.252     djm      1585:        } else
                   1586:                ca = load_identity(tmp);
1.227     djm      1587:        free(tmp);
1.197     djm      1588:
1.290     djm      1589:        if (key_type_name != NULL &&
                   1590:            sshkey_type_from_name(key_type_name) != ca->type)  {
                   1591:                fatal("CA key type %s doesn't match specified %s",
                   1592:                    sshkey_ssh_name(ca), key_type_name);
                   1593:        }
                   1594:
1.179     djm      1595:        for (i = 0; i < argc; i++) {
                   1596:                /* Split list of principals */
                   1597:                n = 0;
                   1598:                if (cert_principals != NULL) {
                   1599:                        otmp = tmp = xstrdup(cert_principals);
                   1600:                        plist = NULL;
                   1601:                        for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1.270     deraadt  1602:                                plist = xreallocarray(plist, n + 1, sizeof(*plist));
1.179     djm      1603:                                if (*(plist[n] = xstrdup(cp)) == '\0')
                   1604:                                        fatal("Empty principal name");
                   1605:                        }
1.227     djm      1606:                        free(otmp);
1.179     djm      1607:                }
                   1608:
                   1609:                tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1.252     djm      1610:                if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
                   1611:                        fatal("%s: unable to open \"%s\": %s",
                   1612:                            __func__, tmp, ssh_err(r));
1.200     djm      1613:                if (public->type != KEY_RSA && public->type != KEY_DSA &&
1.238     markus   1614:                    public->type != KEY_ECDSA && public->type != KEY_ED25519)
1.179     djm      1615:                        fatal("%s: key \"%s\" type %s cannot be certified",
1.252     djm      1616:                            __func__, tmp, sshkey_type(public));
1.179     djm      1617:
                   1618:                /* Prepare certificate to sign */
1.275     djm      1619:                if ((r = sshkey_to_certified(public)) != 0)
1.252     djm      1620:                        fatal("Could not upgrade key %s to certificate: %s",
                   1621:                            tmp, ssh_err(r));
1.179     djm      1622:                public->cert->type = cert_key_type;
1.186     djm      1623:                public->cert->serial = (u_int64_t)cert_serial;
1.179     djm      1624:                public->cert->key_id = xstrdup(cert_key_id);
                   1625:                public->cert->nprincipals = n;
                   1626:                public->cert->principals = plist;
                   1627:                public->cert->valid_after = cert_valid_from;
                   1628:                public->cert->valid_before = cert_valid_to;
1.275     djm      1629:                prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
                   1630:                prepare_options_buf(public->cert->extensions,
                   1631:                    OPTIONS_EXTENSIONS);
1.252     djm      1632:                if ((r = sshkey_from_private(ca,
                   1633:                    &public->cert->signature_key)) != 0)
                   1634:                        fatal("key_from_private (ca key): %s", ssh_err(r));
1.179     djm      1635:
1.290     djm      1636:                if ((r = sshkey_certify(public, ca, key_type_name)) != 0)
                   1637:                        fatal("Couldn't certify key %s: %s", tmp, ssh_err(r));
1.179     djm      1638:
                   1639:                if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
                   1640:                        *cp = '\0';
                   1641:                xasprintf(&out, "%s-cert.pub", tmp);
1.227     djm      1642:                free(tmp);
1.179     djm      1643:
                   1644:                if ((fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
                   1645:                        fatal("Could not open \"%s\" for writing: %s", out,
                   1646:                            strerror(errno));
                   1647:                if ((f = fdopen(fd, "w")) == NULL)
                   1648:                        fatal("%s: fdopen: %s", __func__, strerror(errno));
1.252     djm      1649:                if ((r = sshkey_write(public, f)) != 0)
                   1650:                        fatal("Could not write certified key to %s: %s",
                   1651:                            out, ssh_err(r));
1.179     djm      1652:                fprintf(f, " %s\n", comment);
                   1653:                fclose(f);
                   1654:
1.186     djm      1655:                if (!quiet) {
1.282     djm      1656:                        sshkey_format_cert_validity(public->cert,
1.281     djm      1657:                            valid, sizeof(valid));
1.186     djm      1658:                        logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1.282     djm      1659:                            "valid %s", sshkey_cert_type(public),
1.205     djm      1660:                            out, public->cert->key_id,
                   1661:                            (unsigned long long)public->cert->serial,
1.179     djm      1662:                            cert_principals != NULL ? " for " : "",
                   1663:                            cert_principals != NULL ? cert_principals : "",
1.281     djm      1664:                            valid);
1.186     djm      1665:                }
1.179     djm      1666:
1.252     djm      1667:                sshkey_free(public);
1.227     djm      1668:                free(out);
1.179     djm      1669:        }
1.246     markus   1670: #ifdef ENABLE_PKCS11
1.197     djm      1671:        pkcs11_terminate();
1.246     markus   1672: #endif
1.179     djm      1673:        exit(0);
                   1674: }
                   1675:
                   1676: static u_int64_t
                   1677: parse_relative_time(const char *s, time_t now)
                   1678: {
                   1679:        int64_t mul, secs;
                   1680:
                   1681:        mul = *s == '-' ? -1 : 1;
                   1682:
                   1683:        if ((secs = convtime(s + 1)) == -1)
                   1684:                fatal("Invalid relative certificate time %s", s);
                   1685:        if (mul == -1 && secs > now)
                   1686:                fatal("Certificate time %s cannot be represented", s);
                   1687:        return now + (u_int64_t)(secs * mul);
                   1688: }
                   1689:
                   1690: static u_int64_t
                   1691: parse_absolute_time(const char *s)
                   1692: {
                   1693:        struct tm tm;
                   1694:        time_t tt;
1.180     djm      1695:        char buf[32], *fmt;
1.179     djm      1696:
1.180     djm      1697:        /*
1.282     djm      1698:         * POSIX strptime says "The application shall ensure that there
1.180     djm      1699:         * is white-space or other non-alphanumeric characters between
                   1700:         * any two conversion specifications" so arrange things this way.
                   1701:         */
                   1702:        switch (strlen(s)) {
                   1703:        case 8:
1.184     djm      1704:                fmt = "%Y-%m-%d";
                   1705:                snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
1.180     djm      1706:                break;
                   1707:        case 14:
1.184     djm      1708:                fmt = "%Y-%m-%dT%H:%M:%S";
                   1709:                snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
1.180     djm      1710:                    s, s + 4, s + 6, s + 8, s + 10, s + 12);
                   1711:                break;
                   1712:        default:
1.179     djm      1713:                fatal("Invalid certificate time format %s", s);
1.180     djm      1714:        }
1.179     djm      1715:
1.239     tedu     1716:        memset(&tm, 0, sizeof(tm));
1.180     djm      1717:        if (strptime(buf, fmt, &tm) == NULL)
1.179     djm      1718:                fatal("Invalid certificate time %s", s);
                   1719:        if ((tt = mktime(&tm)) < 0)
                   1720:                fatal("Certificate time %s cannot be represented", s);
                   1721:        return (u_int64_t)tt;
                   1722: }
                   1723:
                   1724: static void
                   1725: parse_cert_times(char *timespec)
                   1726: {
                   1727:        char *from, *to;
                   1728:        time_t now = time(NULL);
                   1729:        int64_t secs;
                   1730:
                   1731:        /* +timespec relative to now */
                   1732:        if (*timespec == '+' && strchr(timespec, ':') == NULL) {
                   1733:                if ((secs = convtime(timespec + 1)) == -1)
                   1734:                        fatal("Invalid relative certificate life %s", timespec);
                   1735:                cert_valid_to = now + secs;
                   1736:                /*
                   1737:                 * Backdate certificate one minute to avoid problems on hosts
                   1738:                 * with poorly-synchronised clocks.
                   1739:                 */
                   1740:                cert_valid_from = ((now - 59)/ 60) * 60;
                   1741:                return;
                   1742:        }
                   1743:
                   1744:        /*
                   1745:         * from:to, where
                   1746:         * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
                   1747:         *   to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
                   1748:         */
                   1749:        from = xstrdup(timespec);
                   1750:        to = strchr(from, ':');
                   1751:        if (to == NULL || from == to || *(to + 1) == '\0')
1.181     djm      1752:                fatal("Invalid certificate life specification %s", timespec);
1.179     djm      1753:        *to++ = '\0';
                   1754:
                   1755:        if (*from == '-' || *from == '+')
                   1756:                cert_valid_from = parse_relative_time(from, now);
                   1757:        else
                   1758:                cert_valid_from = parse_absolute_time(from);
                   1759:
                   1760:        if (*to == '-' || *to == '+')
1.235     djm      1761:                cert_valid_to = parse_relative_time(to, now);
1.179     djm      1762:        else
                   1763:                cert_valid_to = parse_absolute_time(to);
                   1764:
                   1765:        if (cert_valid_to <= cert_valid_from)
                   1766:                fatal("Empty certificate validity interval");
1.227     djm      1767:        free(from);
1.179     djm      1768: }
                   1769:
                   1770: static void
1.186     djm      1771: add_cert_option(char *opt)
1.179     djm      1772: {
                   1773:        char *val;
                   1774:
1.208     stevesk  1775:        if (strcasecmp(opt, "clear") == 0)
1.190     djm      1776:                certflags_flags = 0;
1.179     djm      1777:        else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1.190     djm      1778:                certflags_flags &= ~CERTOPT_X_FWD;
1.179     djm      1779:        else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1.190     djm      1780:                certflags_flags |= CERTOPT_X_FWD;
1.179     djm      1781:        else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1.190     djm      1782:                certflags_flags &= ~CERTOPT_AGENT_FWD;
1.179     djm      1783:        else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1.190     djm      1784:                certflags_flags |= CERTOPT_AGENT_FWD;
1.179     djm      1785:        else if (strcasecmp(opt, "no-port-forwarding") == 0)
1.190     djm      1786:                certflags_flags &= ~CERTOPT_PORT_FWD;
1.179     djm      1787:        else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1.190     djm      1788:                certflags_flags |= CERTOPT_PORT_FWD;
1.179     djm      1789:        else if (strcasecmp(opt, "no-pty") == 0)
1.190     djm      1790:                certflags_flags &= ~CERTOPT_PTY;
1.179     djm      1791:        else if (strcasecmp(opt, "permit-pty") == 0)
1.190     djm      1792:                certflags_flags |= CERTOPT_PTY;
1.179     djm      1793:        else if (strcasecmp(opt, "no-user-rc") == 0)
1.190     djm      1794:                certflags_flags &= ~CERTOPT_USER_RC;
1.179     djm      1795:        else if (strcasecmp(opt, "permit-user-rc") == 0)
1.190     djm      1796:                certflags_flags |= CERTOPT_USER_RC;
1.179     djm      1797:        else if (strncasecmp(opt, "force-command=", 14) == 0) {
                   1798:                val = opt + 14;
                   1799:                if (*val == '\0')
1.186     djm      1800:                        fatal("Empty force-command option");
1.190     djm      1801:                if (certflags_command != NULL)
1.179     djm      1802:                        fatal("force-command already specified");
1.190     djm      1803:                certflags_command = xstrdup(val);
1.179     djm      1804:        } else if (strncasecmp(opt, "source-address=", 15) == 0) {
                   1805:                val = opt + 15;
                   1806:                if (*val == '\0')
1.186     djm      1807:                        fatal("Empty source-address option");
1.190     djm      1808:                if (certflags_src_addr != NULL)
1.179     djm      1809:                        fatal("source-address already specified");
                   1810:                if (addr_match_cidr_list(NULL, val) != 0)
                   1811:                        fatal("Invalid source-address list");
1.190     djm      1812:                certflags_src_addr = xstrdup(val);
1.179     djm      1813:        } else
1.186     djm      1814:                fatal("Unsupported certificate option \"%s\"", opt);
1.179     djm      1815: }
                   1816:
1.63      itojun   1817: static void
1.275     djm      1818: show_options(struct sshbuf *optbuf, int in_critical)
1.192     djm      1819: {
1.245     djm      1820:        char *name, *arg;
1.252     djm      1821:        struct sshbuf *options, *option = NULL;
                   1822:        int r;
                   1823:
                   1824:        if ((options = sshbuf_fromb(optbuf)) == NULL)
                   1825:                fatal("%s: sshbuf_fromb failed", __func__);
                   1826:        while (sshbuf_len(options) != 0) {
                   1827:                sshbuf_free(option);
                   1828:                option = NULL;
                   1829:                if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
                   1830:                    (r = sshbuf_froms(options, &option)) != 0)
                   1831:                        fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.192     djm      1832:                printf("                %s", name);
1.275     djm      1833:                if (!in_critical &&
1.192     djm      1834:                    (strcmp(name, "permit-X11-forwarding") == 0 ||
                   1835:                    strcmp(name, "permit-agent-forwarding") == 0 ||
                   1836:                    strcmp(name, "permit-port-forwarding") == 0 ||
                   1837:                    strcmp(name, "permit-pty") == 0 ||
                   1838:                    strcmp(name, "permit-user-rc") == 0))
                   1839:                        printf("\n");
1.275     djm      1840:                else if (in_critical &&
1.192     djm      1841:                    (strcmp(name, "force-command") == 0 ||
                   1842:                    strcmp(name, "source-address") == 0)) {
1.252     djm      1843:                        if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
                   1844:                                fatal("%s: buffer error: %s",
                   1845:                                    __func__, ssh_err(r));
1.245     djm      1846:                        printf(" %s\n", arg);
                   1847:                        free(arg);
1.192     djm      1848:                } else {
1.252     djm      1849:                        printf(" UNKNOWN OPTION (len %zu)\n",
                   1850:                            sshbuf_len(option));
                   1851:                        sshbuf_reset(option);
1.192     djm      1852:                }
1.227     djm      1853:                free(name);
1.252     djm      1854:                if (sshbuf_len(option) != 0)
1.192     djm      1855:                        fatal("Option corrupt: extra data at end");
                   1856:        }
1.252     djm      1857:        sshbuf_free(option);
                   1858:        sshbuf_free(options);
1.192     djm      1859: }
                   1860:
                   1861: static void
1.278     djm      1862: print_cert(struct sshkey *key)
1.182     djm      1863: {
1.281     djm      1864:        char valid[64], *key_fp, *ca_fp;
1.275     djm      1865:        u_int i;
1.186     djm      1866:
1.252     djm      1867:        key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
                   1868:        ca_fp = sshkey_fingerprint(key->cert->signature_key,
1.251     djm      1869:            fingerprint_hash, SSH_FP_DEFAULT);
1.259     djm      1870:        if (key_fp == NULL || ca_fp == NULL)
                   1871:                fatal("%s: sshkey_fingerprint fail", __func__);
1.281     djm      1872:        sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
1.182     djm      1873:
1.252     djm      1874:        printf("        Type: %s %s certificate\n", sshkey_ssh_name(key),
                   1875:            sshkey_cert_type(key));
                   1876:        printf("        Public key: %s %s\n", sshkey_type(key), key_fp);
1.186     djm      1877:        printf("        Signing CA: %s %s\n",
1.252     djm      1878:            sshkey_type(key->cert->signature_key), ca_fp);
1.186     djm      1879:        printf("        Key ID: \"%s\"\n", key->cert->key_id);
1.275     djm      1880:        printf("        Serial: %llu\n", (unsigned long long)key->cert->serial);
1.281     djm      1881:        printf("        Valid: %s\n", valid);
1.182     djm      1882:        printf("        Principals: ");
                   1883:        if (key->cert->nprincipals == 0)
                   1884:                printf("(none)\n");
                   1885:        else {
                   1886:                for (i = 0; i < key->cert->nprincipals; i++)
                   1887:                        printf("\n                %s",
                   1888:                            key->cert->principals[i]);
                   1889:                printf("\n");
                   1890:        }
1.186     djm      1891:        printf("        Critical Options: ");
1.252     djm      1892:        if (sshbuf_len(key->cert->critical) == 0)
1.182     djm      1893:                printf("(none)\n");
                   1894:        else {
                   1895:                printf("\n");
1.275     djm      1896:                show_options(key->cert->critical, 1);
1.186     djm      1897:        }
1.275     djm      1898:        printf("        Extensions: ");
                   1899:        if (sshbuf_len(key->cert->extensions) == 0)
                   1900:                printf("(none)\n");
                   1901:        else {
                   1902:                printf("\n");
                   1903:                show_options(key->cert->extensions, 0);
1.182     djm      1904:        }
1.278     djm      1905: }
                   1906:
                   1907: static void
                   1908: do_show_cert(struct passwd *pw)
                   1909: {
                   1910:        struct sshkey *key = NULL;
                   1911:        struct stat st;
                   1912:        int r, is_stdin = 0, ok = 0;
                   1913:        FILE *f;
1.287     djm      1914:        char *cp, line[SSH_MAX_PUBKEY_BYTES];
1.278     djm      1915:        const char *path;
1.289     djm      1916:        u_long lnum = 0;
1.278     djm      1917:
                   1918:        if (!have_identity)
                   1919:                ask_filename(pw, "Enter file in which the key is");
                   1920:        if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) < 0)
                   1921:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
                   1922:
                   1923:        path = identity_file;
                   1924:        if (strcmp(path, "-") == 0) {
                   1925:                f = stdin;
                   1926:                path = "(stdin)";
                   1927:                is_stdin = 1;
                   1928:        } else if ((f = fopen(identity_file, "r")) == NULL)
                   1929:                fatal("fopen %s: %s", identity_file, strerror(errno));
                   1930:
                   1931:        while (read_keyfile_line(f, path, line, sizeof(line), &lnum) == 0) {
                   1932:                sshkey_free(key);
                   1933:                key = NULL;
                   1934:                /* Trim leading space and comments */
                   1935:                cp = line + strspn(line, " \t");
                   1936:                if (*cp == '#' || *cp == '\0')
                   1937:                        continue;
                   1938:                if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
                   1939:                        fatal("key_new");
                   1940:                if ((r = sshkey_read(key, &cp)) != 0) {
                   1941:                        error("%s:%lu: invalid key: %s", path,
                   1942:                            lnum, ssh_err(r));
                   1943:                        continue;
                   1944:                }
                   1945:                if (!sshkey_is_cert(key)) {
                   1946:                        error("%s:%lu is not a certificate", path, lnum);
                   1947:                        continue;
                   1948:                }
                   1949:                ok = 1;
                   1950:                if (!is_stdin && lnum == 1)
                   1951:                        printf("%s:\n", path);
                   1952:                else
                   1953:                        printf("%s:%lu:\n", path, lnum);
                   1954:                print_cert(key);
                   1955:        }
                   1956:        sshkey_free(key);
                   1957:        fclose(f);
                   1958:        exit(ok ? 0 : 1);
1.182     djm      1959: }
                   1960:
1.246     markus   1961: #ifdef WITH_OPENSSL
1.182     djm      1962: static void
1.223     djm      1963: load_krl(const char *path, struct ssh_krl **krlp)
                   1964: {
1.252     djm      1965:        struct sshbuf *krlbuf;
                   1966:        int r, fd;
1.223     djm      1967:
1.252     djm      1968:        if ((krlbuf = sshbuf_new()) == NULL)
                   1969:                fatal("sshbuf_new failed");
1.223     djm      1970:        if ((fd = open(path, O_RDONLY)) == -1)
                   1971:                fatal("open %s: %s", path, strerror(errno));
1.252     djm      1972:        if ((r = sshkey_load_file(fd, krlbuf)) != 0)
                   1973:                fatal("Unable to load KRL: %s", ssh_err(r));
1.223     djm      1974:        close(fd);
                   1975:        /* XXX check sigs */
1.252     djm      1976:        if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
1.223     djm      1977:            *krlp == NULL)
1.252     djm      1978:                fatal("Invalid KRL file: %s", ssh_err(r));
                   1979:        sshbuf_free(krlbuf);
1.223     djm      1980: }
                   1981:
                   1982: static void
1.261     djm      1983: update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
1.252     djm      1984:     const struct sshkey *ca, struct ssh_krl *krl)
1.223     djm      1985: {
1.252     djm      1986:        struct sshkey *key = NULL;
1.223     djm      1987:        u_long lnum = 0;
                   1988:        char *path, *cp, *ep, line[SSH_MAX_PUBKEY_BYTES];
                   1989:        unsigned long long serial, serial2;
                   1990:        int i, was_explicit_key, was_sha1, r;
                   1991:        FILE *krl_spec;
                   1992:
                   1993:        path = tilde_expand_filename(file, pw->pw_uid);
                   1994:        if (strcmp(path, "-") == 0) {
                   1995:                krl_spec = stdin;
                   1996:                free(path);
                   1997:                path = xstrdup("(standard input)");
                   1998:        } else if ((krl_spec = fopen(path, "r")) == NULL)
                   1999:                fatal("fopen %s: %s", path, strerror(errno));
                   2000:
                   2001:        if (!quiet)
                   2002:                printf("Revoking from %s\n", path);
                   2003:        while (read_keyfile_line(krl_spec, path, line, sizeof(line),
                   2004:            &lnum) == 0) {
                   2005:                was_explicit_key = was_sha1 = 0;
                   2006:                cp = line + strspn(line, " \t");
                   2007:                /* Trim trailing space, comments and strip \n */
                   2008:                for (i = 0, r = -1; cp[i] != '\0'; i++) {
                   2009:                        if (cp[i] == '#' || cp[i] == '\n') {
                   2010:                                cp[i] = '\0';
                   2011:                                break;
                   2012:                        }
                   2013:                        if (cp[i] == ' ' || cp[i] == '\t') {
                   2014:                                /* Remember the start of a span of whitespace */
                   2015:                                if (r == -1)
                   2016:                                        r = i;
                   2017:                        } else
                   2018:                                r = -1;
                   2019:                }
                   2020:                if (r != -1)
                   2021:                        cp[r] = '\0';
                   2022:                if (*cp == '\0')
                   2023:                        continue;
                   2024:                if (strncasecmp(cp, "serial:", 7) == 0) {
1.261     djm      2025:                        if (ca == NULL && !wild_ca) {
1.231     djm      2026:                                fatal("revoking certificates by serial number "
1.223     djm      2027:                                    "requires specification of a CA key");
                   2028:                        }
                   2029:                        cp += 7;
                   2030:                        cp = cp + strspn(cp, " \t");
                   2031:                        errno = 0;
                   2032:                        serial = strtoull(cp, &ep, 0);
                   2033:                        if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
                   2034:                                fatal("%s:%lu: invalid serial \"%s\"",
                   2035:                                    path, lnum, cp);
                   2036:                        if (errno == ERANGE && serial == ULLONG_MAX)
                   2037:                                fatal("%s:%lu: serial out of range",
                   2038:                                    path, lnum);
                   2039:                        serial2 = serial;
                   2040:                        if (*ep == '-') {
                   2041:                                cp = ep + 1;
                   2042:                                errno = 0;
                   2043:                                serial2 = strtoull(cp, &ep, 0);
                   2044:                                if (*cp == '\0' || *ep != '\0')
                   2045:                                        fatal("%s:%lu: invalid serial \"%s\"",
                   2046:                                            path, lnum, cp);
                   2047:                                if (errno == ERANGE && serial2 == ULLONG_MAX)
                   2048:                                        fatal("%s:%lu: serial out of range",
                   2049:                                            path, lnum);
                   2050:                                if (serial2 <= serial)
                   2051:                                        fatal("%s:%lu: invalid serial range "
                   2052:                                            "%llu:%llu", path, lnum,
                   2053:                                            (unsigned long long)serial,
                   2054:                                            (unsigned long long)serial2);
                   2055:                        }
                   2056:                        if (ssh_krl_revoke_cert_by_serial_range(krl,
                   2057:                            ca, serial, serial2) != 0) {
                   2058:                                fatal("%s: revoke serial failed",
                   2059:                                    __func__);
                   2060:                        }
                   2061:                } else if (strncasecmp(cp, "id:", 3) == 0) {
1.261     djm      2062:                        if (ca == NULL && !wild_ca) {
1.232     djm      2063:                                fatal("revoking certificates by key ID "
1.223     djm      2064:                                    "requires specification of a CA key");
                   2065:                        }
                   2066:                        cp += 3;
                   2067:                        cp = cp + strspn(cp, " \t");
                   2068:                        if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
                   2069:                                fatal("%s: revoke key ID failed", __func__);
                   2070:                } else {
                   2071:                        if (strncasecmp(cp, "key:", 4) == 0) {
                   2072:                                cp += 4;
                   2073:                                cp = cp + strspn(cp, " \t");
                   2074:                                was_explicit_key = 1;
                   2075:                        } else if (strncasecmp(cp, "sha1:", 5) == 0) {
                   2076:                                cp += 5;
                   2077:                                cp = cp + strspn(cp, " \t");
                   2078:                                was_sha1 = 1;
                   2079:                        } else {
                   2080:                                /*
                   2081:                                 * Just try to process the line as a key.
                   2082:                                 * Parsing will fail if it isn't.
                   2083:                                 */
                   2084:                        }
1.252     djm      2085:                        if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
1.223     djm      2086:                                fatal("key_new");
1.252     djm      2087:                        if ((r = sshkey_read(key, &cp)) != 0)
                   2088:                                fatal("%s:%lu: invalid key: %s",
                   2089:                                    path, lnum, ssh_err(r));
1.223     djm      2090:                        if (was_explicit_key)
                   2091:                                r = ssh_krl_revoke_key_explicit(krl, key);
                   2092:                        else if (was_sha1)
                   2093:                                r = ssh_krl_revoke_key_sha1(krl, key);
                   2094:                        else
                   2095:                                r = ssh_krl_revoke_key(krl, key);
                   2096:                        if (r != 0)
1.252     djm      2097:                                fatal("%s: revoke key failed: %s",
                   2098:                                    __func__, ssh_err(r));
                   2099:                        sshkey_free(key);
1.223     djm      2100:                }
                   2101:        }
                   2102:        if (strcmp(path, "-") != 0)
                   2103:                fclose(krl_spec);
1.226     djm      2104:        free(path);
1.223     djm      2105: }
                   2106:
                   2107: static void
                   2108: do_gen_krl(struct passwd *pw, int updating, int argc, char **argv)
                   2109: {
                   2110:        struct ssh_krl *krl;
                   2111:        struct stat sb;
1.252     djm      2112:        struct sshkey *ca = NULL;
1.261     djm      2113:        int fd, i, r, wild_ca = 0;
1.223     djm      2114:        char *tmp;
1.252     djm      2115:        struct sshbuf *kbuf;
1.223     djm      2116:
                   2117:        if (*identity_file == '\0')
                   2118:                fatal("KRL generation requires an output file");
                   2119:        if (stat(identity_file, &sb) == -1) {
                   2120:                if (errno != ENOENT)
                   2121:                        fatal("Cannot access KRL \"%s\": %s",
                   2122:                            identity_file, strerror(errno));
                   2123:                if (updating)
                   2124:                        fatal("KRL \"%s\" does not exist", identity_file);
                   2125:        }
                   2126:        if (ca_key_path != NULL) {
1.261     djm      2127:                if (strcasecmp(ca_key_path, "none") == 0)
                   2128:                        wild_ca = 1;
                   2129:                else {
                   2130:                        tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
                   2131:                        if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
                   2132:                                fatal("Cannot load CA public key %s: %s",
                   2133:                                    tmp, ssh_err(r));
                   2134:                        free(tmp);
                   2135:                }
1.223     djm      2136:        }
                   2137:
                   2138:        if (updating)
                   2139:                load_krl(identity_file, &krl);
                   2140:        else if ((krl = ssh_krl_init()) == NULL)
                   2141:                fatal("couldn't create KRL");
                   2142:
                   2143:        if (cert_serial != 0)
                   2144:                ssh_krl_set_version(krl, cert_serial);
                   2145:        if (identity_comment != NULL)
                   2146:                ssh_krl_set_comment(krl, identity_comment);
                   2147:
                   2148:        for (i = 0; i < argc; i++)
1.261     djm      2149:                update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
1.223     djm      2150:
1.252     djm      2151:        if ((kbuf = sshbuf_new()) == NULL)
                   2152:                fatal("sshbuf_new failed");
                   2153:        if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
1.223     djm      2154:                fatal("Couldn't generate KRL");
                   2155:        if ((fd = open(identity_file, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
                   2156:                fatal("open %s: %s", identity_file, strerror(errno));
1.252     djm      2157:        if (atomicio(vwrite, fd, (void *)sshbuf_ptr(kbuf), sshbuf_len(kbuf)) !=
                   2158:            sshbuf_len(kbuf))
1.223     djm      2159:                fatal("write %s: %s", identity_file, strerror(errno));
                   2160:        close(fd);
1.252     djm      2161:        sshbuf_free(kbuf);
1.223     djm      2162:        ssh_krl_free(krl);
1.286     mmcc     2163:        sshkey_free(ca);
1.223     djm      2164: }
                   2165:
                   2166: static void
                   2167: do_check_krl(struct passwd *pw, int argc, char **argv)
                   2168: {
                   2169:        int i, r, ret = 0;
                   2170:        char *comment;
                   2171:        struct ssh_krl *krl;
1.252     djm      2172:        struct sshkey *k;
1.223     djm      2173:
                   2174:        if (*identity_file == '\0')
                   2175:                fatal("KRL checking requires an input file");
                   2176:        load_krl(identity_file, &krl);
                   2177:        for (i = 0; i < argc; i++) {
1.252     djm      2178:                if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
                   2179:                        fatal("Cannot load public key %s: %s",
                   2180:                            argv[i], ssh_err(r));
1.223     djm      2181:                r = ssh_krl_check_key(krl, k);
                   2182:                printf("%s%s%s%s: %s\n", argv[i],
                   2183:                    *comment ? " (" : "", comment, *comment ? ")" : "",
                   2184:                    r == 0 ? "ok" : "REVOKED");
                   2185:                if (r != 0)
                   2186:                        ret = 1;
1.252     djm      2187:                sshkey_free(k);
1.223     djm      2188:                free(comment);
                   2189:        }
                   2190:        ssh_krl_free(krl);
                   2191:        exit(ret);
                   2192: }
1.246     markus   2193: #endif
1.223     djm      2194:
                   2195: static void
1.10      markus   2196: usage(void)
                   2197: {
1.243     deraadt  2198:        fprintf(stderr,
                   2199:            "usage: ssh-keygen [-q] [-b bits] [-t dsa | ecdsa | ed25519 | rsa | rsa1]\n"
                   2200:            "                  [-N new_passphrase] [-C comment] [-f output_keyfile]\n"
                   2201:            "       ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]\n"
                   2202:            "       ssh-keygen -i [-m key_format] [-f input_keyfile]\n"
                   2203:            "       ssh-keygen -e [-m key_format] [-f input_keyfile]\n"
                   2204:            "       ssh-keygen -y [-f input_keyfile]\n"
                   2205:            "       ssh-keygen -c [-P passphrase] [-C comment] [-f keyfile]\n"
1.265     naddy    2206:            "       ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
1.243     deraadt  2207:            "       ssh-keygen -B [-f input_keyfile]\n");
1.177     markus   2208: #ifdef ENABLE_PKCS11
1.243     deraadt  2209:        fprintf(stderr,
                   2210:            "       ssh-keygen -D pkcs11\n");
1.177     markus   2211: #endif
1.243     deraadt  2212:        fprintf(stderr,
                   2213:            "       ssh-keygen -F hostname [-f known_hosts_file] [-l]\n"
                   2214:            "       ssh-keygen -H [-f known_hosts_file]\n"
                   2215:            "       ssh-keygen -R hostname [-f known_hosts_file]\n"
                   2216:            "       ssh-keygen -r hostname [-f input_keyfile] [-g]\n"
1.274     djm      2217: #ifdef WITH_OPENSSL
1.243     deraadt  2218:            "       ssh-keygen -G output_file [-v] [-b bits] [-M memory] [-S start_point]\n"
                   2219:            "       ssh-keygen -T output_file -f input_file [-v] [-a rounds] [-J num_lines]\n"
                   2220:            "                  [-j start_line] [-K checkpt] [-W generator]\n"
1.274     djm      2221: #endif
1.243     deraadt  2222:            "       ssh-keygen -s ca_key -I certificate_identity [-h] [-n principals]\n"
                   2223:            "                  [-O option] [-V validity_interval] [-z serial_number] file ...\n"
                   2224:            "       ssh-keygen -L [-f input_keyfile]\n"
                   2225:            "       ssh-keygen -A\n"
                   2226:            "       ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
                   2227:            "                  file ...\n"
                   2228:            "       ssh-keygen -Q -f krl_file file ...\n");
1.12      markus   2229:        exit(1);
1.10      markus   2230: }
                   2231:
1.13      deraadt  2232: /*
                   2233:  * Main program for key management.
                   2234:  */
1.2       provos   2235: int
1.156     deraadt  2236: main(int argc, char **argv)
1.1       deraadt  2237: {
1.253     deraadt  2238:        char dotsshdir[PATH_MAX], comment[1024], *passphrase1, *passphrase2;
1.274     djm      2239:        char *rr_hostname = NULL, *ep, *fp, *ra;
1.252     djm      2240:        struct sshkey *private, *public;
1.12      markus   2241:        struct passwd *pw;
                   2242:        struct stat st;
1.252     djm      2243:        int r, opt, type, fd;
1.274     djm      2244:        int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
                   2245:        FILE *f;
                   2246:        const char *errstr;
                   2247: #ifdef WITH_OPENSSL
                   2248:        /* Moduli generation/screening */
                   2249:        char out_file[PATH_MAX], *checkpoint = NULL;
1.237     markus   2250:        u_int32_t memory = 0, generator_wanted = 0;
1.107     djm      2251:        int do_gen_candidates = 0, do_screen_candidates = 0;
1.215     dtucker  2252:        unsigned long start_lineno = 0, lines_to_process = 0;
1.107     djm      2253:        BIGNUM *start = NULL;
1.274     djm      2254: #endif
1.33      markus   2255:
1.12      markus   2256:        extern int optind;
                   2257:        extern char *optarg;
1.129     djm      2258:
1.288     dtucker  2259:        ssh_malloc_init();      /* must be called before any mallocs */
1.129     djm      2260:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                   2261:        sanitise_stdfd();
1.12      markus   2262:
1.201     djm      2263:        OpenSSL_add_all_algorithms();
1.156     deraadt  2264:        log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
1.19      markus   2265:
1.14      markus   2266:        /* we need this for the home * directory.  */
1.12      markus   2267:        pw = getpwuid(getuid());
1.269     djm      2268:        if (!pw)
                   2269:                fatal("No user exists for uid %lu", (u_long)getuid());
                   2270:        if (gethostname(hostname, sizeof(hostname)) < 0)
                   2271:                fatal("gethostname: %s", strerror(errno));
1.14      markus   2272:
1.251     djm      2273:        /* Remaining characters: UYdw */
1.237     markus   2274:        while ((opt = getopt(argc, argv, "ABHLQXceghiklopquvxy"
1.251     djm      2275:            "C:D:E:F:G:I:J:K:M:N:O:P:R:S:T:V:W:Z:"
                   2276:            "a:b:f:g:j:m:n:r:s:t:z:")) != -1) {
1.12      markus   2277:                switch (opt) {
1.206     stevesk  2278:                case 'A':
                   2279:                        gen_all_hostkeys = 1;
                   2280:                        break;
1.12      markus   2281:                case 'b':
1.202     markus   2282:                        bits = (u_int32_t)strtonum(optarg, 256, 32768, &errstr);
1.125     avsm     2283:                        if (errstr)
                   2284:                                fatal("Bits has bad value %s (%s)",
                   2285:                                        optarg, errstr);
1.12      markus   2286:                        break;
1.251     djm      2287:                case 'E':
                   2288:                        fingerprint_hash = ssh_digest_alg_by_name(optarg);
                   2289:                        if (fingerprint_hash == -1)
                   2290:                                fatal("Invalid hash algorithm \"%s\"", optarg);
                   2291:                        break;
1.119     djm      2292:                case 'F':
                   2293:                        find_host = 1;
                   2294:                        rr_hostname = optarg;
                   2295:                        break;
                   2296:                case 'H':
                   2297:                        hash_hosts = 1;
                   2298:                        break;
1.179     djm      2299:                case 'I':
                   2300:                        cert_key_id = optarg;
                   2301:                        break;
1.119     djm      2302:                case 'R':
                   2303:                        delete_host = 1;
                   2304:                        rr_hostname = optarg;
                   2305:                        break;
1.182     djm      2306:                case 'L':
                   2307:                        show_cert = 1;
                   2308:                        break;
1.12      markus   2309:                case 'l':
                   2310:                        print_fingerprint = 1;
                   2311:                        break;
1.49      markus   2312:                case 'B':
                   2313:                        print_bubblebabble = 1;
                   2314:                        break;
1.193     djm      2315:                case 'm':
                   2316:                        if (strcasecmp(optarg, "RFC4716") == 0 ||
                   2317:                            strcasecmp(optarg, "ssh2") == 0) {
                   2318:                                convert_format = FMT_RFC4716;
                   2319:                                break;
                   2320:                        }
                   2321:                        if (strcasecmp(optarg, "PKCS8") == 0) {
                   2322:                                convert_format = FMT_PKCS8;
                   2323:                                break;
                   2324:                        }
                   2325:                        if (strcasecmp(optarg, "PEM") == 0) {
                   2326:                                convert_format = FMT_PEM;
                   2327:                                break;
                   2328:                        }
                   2329:                        fatal("Unsupported conversion format \"%s\"", optarg);
1.179     djm      2330:                case 'n':
                   2331:                        cert_principals = optarg;
                   2332:                        break;
1.237     markus   2333:                case 'o':
                   2334:                        use_new_format = 1;
                   2335:                        break;
1.12      markus   2336:                case 'p':
                   2337:                        change_passphrase = 1;
                   2338:                        break;
                   2339:                case 'c':
                   2340:                        change_comment = 1;
                   2341:                        break;
                   2342:                case 'f':
1.274     djm      2343:                        if (strlcpy(identity_file, optarg,
                   2344:                            sizeof(identity_file)) >= sizeof(identity_file))
1.124     avsm     2345:                                fatal("Identity filename too long");
1.12      markus   2346:                        have_identity = 1;
                   2347:                        break;
1.105     jakob    2348:                case 'g':
                   2349:                        print_generic = 1;
                   2350:                        break;
1.12      markus   2351:                case 'P':
                   2352:                        identity_passphrase = optarg;
                   2353:                        break;
                   2354:                case 'N':
                   2355:                        identity_new_passphrase = optarg;
                   2356:                        break;
1.223     djm      2357:                case 'Q':
                   2358:                        check_krl = 1;
                   2359:                        break;
1.179     djm      2360:                case 'O':
1.186     djm      2361:                        add_cert_option(optarg);
1.179     djm      2362:                        break;
1.237     markus   2363:                case 'Z':
                   2364:                        new_format_cipher = optarg;
                   2365:                        break;
1.12      markus   2366:                case 'C':
                   2367:                        identity_comment = optarg;
                   2368:                        break;
                   2369:                case 'q':
                   2370:                        quiet = 1;
1.20      deraadt  2371:                        break;
1.57      markus   2372:                case 'e':
1.19      markus   2373:                case 'x':
1.57      markus   2374:                        /* export key */
1.193     djm      2375:                        convert_to = 1;
1.19      markus   2376:                        break;
1.179     djm      2377:                case 'h':
                   2378:                        cert_key_type = SSH2_CERT_TYPE_HOST;
1.190     djm      2379:                        certflags_flags = 0;
1.179     djm      2380:                        break;
1.223     djm      2381:                case 'k':
                   2382:                        gen_krl = 1;
                   2383:                        break;
1.57      markus   2384:                case 'i':
1.19      markus   2385:                case 'X':
1.57      markus   2386:                        /* import key */
1.193     djm      2387:                        convert_from = 1;
1.19      markus   2388:                        break;
                   2389:                case 'y':
                   2390:                        print_public = 1;
                   2391:                        break;
1.179     djm      2392:                case 's':
                   2393:                        ca_key_path = optarg;
                   2394:                        break;
1.33      markus   2395:                case 't':
                   2396:                        key_type_name = optarg;
                   2397:                        break;
1.75      markus   2398:                case 'D':
1.177     markus   2399:                        pkcs11provider = optarg;
1.66      markus   2400:                        break;
1.223     djm      2401:                case 'u':
                   2402:                        update_krl = 1;
                   2403:                        break;
1.113     djm      2404:                case 'v':
                   2405:                        if (log_level == SYSLOG_LEVEL_INFO)
                   2406:                                log_level = SYSLOG_LEVEL_DEBUG1;
                   2407:                        else {
1.117     deraadt  2408:                                if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
1.113     djm      2409:                                    log_level < SYSLOG_LEVEL_DEBUG3)
                   2410:                                        log_level++;
                   2411:                        }
                   2412:                        break;
1.105     jakob    2413:                case 'r':
1.119     djm      2414:                        rr_hostname = optarg;
1.105     jakob    2415:                        break;
1.107     djm      2416:                case 'a':
1.237     markus   2417:                        rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
1.124     avsm     2418:                        if (errstr)
1.237     markus   2419:                                fatal("Invalid number: %s (%s)",
1.124     avsm     2420:                                        optarg, errstr);
1.107     djm      2421:                        break;
1.274     djm      2422:                case 'V':
                   2423:                        parse_cert_times(optarg);
                   2424:                        break;
                   2425:                case 'z':
                   2426:                        errno = 0;
                   2427:                        cert_serial = strtoull(optarg, &ep, 10);
                   2428:                        if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
                   2429:                            (errno == ERANGE && cert_serial == ULLONG_MAX))
                   2430:                                fatal("Invalid serial number \"%s\"", optarg);
1.107     djm      2431:                        break;
1.274     djm      2432: #ifdef WITH_OPENSSL
                   2433:                /* Moduli generation/screening */
1.107     djm      2434:                case 'G':
                   2435:                        do_gen_candidates = 1;
1.124     avsm     2436:                        if (strlcpy(out_file, optarg, sizeof(out_file)) >=
                   2437:                            sizeof(out_file))
                   2438:                                fatal("Output filename too long");
1.107     djm      2439:                        break;
1.274     djm      2440:                case 'J':
                   2441:                        lines_to_process = strtoul(optarg, NULL, 10);
1.292     dtucker  2442:                        break;
1.274     djm      2443:                case 'j':
                   2444:                        start_lineno = strtoul(optarg, NULL, 10);
1.292     dtucker  2445:                        break;
1.211     dtucker  2446:                case 'K':
1.253     deraadt  2447:                        if (strlen(optarg) >= PATH_MAX)
1.211     dtucker  2448:                                fatal("Checkpoint filename too long");
                   2449:                        checkpoint = xstrdup(optarg);
                   2450:                        break;
1.274     djm      2451:                case 'M':
                   2452:                        memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX,
                   2453:                            &errstr);
                   2454:                        if (errstr)
                   2455:                                fatal("Memory limit is %s: %s", errstr, optarg);
                   2456:                        break;
1.107     djm      2457:                case 'S':
                   2458:                        /* XXX - also compare length against bits */
                   2459:                        if (BN_hex2bn(&start, optarg) == 0)
                   2460:                                fatal("Invalid start point.");
                   2461:                        break;
1.274     djm      2462:                case 'T':
                   2463:                        do_screen_candidates = 1;
                   2464:                        if (strlcpy(out_file, optarg, sizeof(out_file)) >=
                   2465:                            sizeof(out_file))
                   2466:                                fatal("Output filename too long");
1.186     djm      2467:                        break;
1.274     djm      2468:                case 'W':
                   2469:                        generator_wanted = (u_int32_t)strtonum(optarg, 1,
                   2470:                            UINT_MAX, &errstr);
                   2471:                        if (errstr != NULL)
                   2472:                                fatal("Desired generator invalid: %s (%s)",
                   2473:                                    optarg, errstr);
1.179     djm      2474:                        break;
1.274     djm      2475: #endif /* WITH_OPENSSL */
1.12      markus   2476:                case '?':
                   2477:                default:
                   2478:                        usage();
                   2479:                }
                   2480:        }
1.113     djm      2481:
                   2482:        /* reinit */
1.156     deraadt  2483:        log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
1.113     djm      2484:
1.179     djm      2485:        argv += optind;
                   2486:        argc -= optind;
                   2487:
                   2488:        if (ca_key_path != NULL) {
1.223     djm      2489:                if (argc < 1 && !gen_krl) {
1.269     djm      2490:                        error("Too few arguments.");
1.179     djm      2491:                        usage();
                   2492:                }
1.223     djm      2493:        } else if (argc > 0 && !gen_krl && !check_krl) {
1.269     djm      2494:                error("Too many arguments.");
1.87      djm      2495:                usage();
                   2496:        }
1.12      markus   2497:        if (change_passphrase && change_comment) {
1.269     djm      2498:                error("Can only have one of -p and -c.");
1.166     djm      2499:                usage();
                   2500:        }
                   2501:        if (print_fingerprint && (delete_host || hash_hosts)) {
1.269     djm      2502:                error("Cannot use -l with -H or -R.");
1.12      markus   2503:                usage();
1.223     djm      2504:        }
1.246     markus   2505: #ifdef WITH_OPENSSL
1.223     djm      2506:        if (gen_krl) {
                   2507:                do_gen_krl(pw, update_krl, argc, argv);
                   2508:                return (0);
                   2509:        }
                   2510:        if (check_krl) {
                   2511:                do_check_krl(pw, argc, argv);
                   2512:                return (0);
1.179     djm      2513:        }
1.246     markus   2514: #endif
1.179     djm      2515:        if (ca_key_path != NULL) {
                   2516:                if (cert_key_id == NULL)
                   2517:                        fatal("Must specify key id (-I) when certifying");
                   2518:                do_ca_sign(pw, argc, argv);
1.12      markus   2519:        }
1.182     djm      2520:        if (show_cert)
                   2521:                do_show_cert(pw);
1.119     djm      2522:        if (delete_host || hash_hosts || find_host)
                   2523:                do_known_hosts(pw, rr_hostname);
1.221     djm      2524:        if (pkcs11provider != NULL)
                   2525:                do_download(pw);
1.49      markus   2526:        if (print_fingerprint || print_bubblebabble)
1.12      markus   2527:                do_fingerprint(pw);
                   2528:        if (change_passphrase)
                   2529:                do_change_passphrase(pw);
                   2530:        if (change_comment)
                   2531:                do_change_comment(pw);
1.246     markus   2532: #ifdef WITH_OPENSSL
1.193     djm      2533:        if (convert_to)
                   2534:                do_convert_to(pw);
                   2535:        if (convert_from)
                   2536:                do_convert_from(pw);
1.246     markus   2537: #endif
1.19      markus   2538:        if (print_public)
                   2539:                do_print_public(pw);
1.119     djm      2540:        if (rr_hostname != NULL) {
1.138     jakob    2541:                unsigned int n = 0;
                   2542:
                   2543:                if (have_identity) {
                   2544:                        n = do_print_resource_record(pw,
                   2545:                            identity_file, rr_hostname);
1.269     djm      2546:                        if (n == 0)
                   2547:                                fatal("%s: %s", identity_file, strerror(errno));
1.138     jakob    2548:                        exit(0);
                   2549:                } else {
                   2550:
                   2551:                        n += do_print_resource_record(pw,
                   2552:                            _PATH_HOST_RSA_KEY_FILE, rr_hostname);
                   2553:                        n += do_print_resource_record(pw,
                   2554:                            _PATH_HOST_DSA_KEY_FILE, rr_hostname);
1.214     djm      2555:                        n += do_print_resource_record(pw,
                   2556:                            _PATH_HOST_ECDSA_KEY_FILE, rr_hostname);
1.244     logan    2557:                        n += do_print_resource_record(pw,
                   2558:                            _PATH_HOST_ED25519_KEY_FILE, rr_hostname);
1.138     jakob    2559:                        if (n == 0)
                   2560:                                fatal("no keys found.");
                   2561:                        exit(0);
                   2562:                }
1.105     jakob    2563:        }
1.107     djm      2564:
1.274     djm      2565: #ifdef WITH_OPENSSL
1.107     djm      2566:        if (do_gen_candidates) {
                   2567:                FILE *out = fopen(out_file, "w");
1.111     djm      2568:
1.107     djm      2569:                if (out == NULL) {
                   2570:                        error("Couldn't open modulus candidate file \"%s\": %s",
                   2571:                            out_file, strerror(errno));
                   2572:                        return (1);
                   2573:                }
1.130     markus   2574:                if (bits == 0)
                   2575:                        bits = DEFAULT_BITS;
1.107     djm      2576:                if (gen_candidates(out, memory, bits, start) != 0)
1.131     stevesk  2577:                        fatal("modulus candidate generation failed");
1.107     djm      2578:
                   2579:                return (0);
                   2580:        }
                   2581:
                   2582:        if (do_screen_candidates) {
                   2583:                FILE *in;
1.225     djm      2584:                FILE *out = fopen(out_file, "a");
1.107     djm      2585:
                   2586:                if (have_identity && strcmp(identity_file, "-") != 0) {
                   2587:                        if ((in = fopen(identity_file, "r")) == NULL) {
                   2588:                                fatal("Couldn't open modulus candidate "
1.111     djm      2589:                                    "file \"%s\": %s", identity_file,
1.107     djm      2590:                                    strerror(errno));
                   2591:                        }
                   2592:                } else
                   2593:                        in = stdin;
                   2594:
                   2595:                if (out == NULL) {
                   2596:                        fatal("Couldn't open moduli file \"%s\": %s",
                   2597:                            out_file, strerror(errno));
                   2598:                }
1.237     markus   2599:                if (prime_test(in, out, rounds == 0 ? 100 : rounds,
                   2600:                    generator_wanted, checkpoint,
1.215     dtucker  2601:                    start_lineno, lines_to_process) != 0)
1.131     stevesk  2602:                        fatal("modulus screening failed");
1.108     markus   2603:                return (0);
1.75      markus   2604:        }
1.274     djm      2605: #endif
1.12      markus   2606:
1.206     stevesk  2607:        if (gen_all_hostkeys) {
                   2608:                do_gen_all_hostkeys(pw);
                   2609:                return (0);
                   2610:        }
                   2611:
1.133     djm      2612:        if (key_type_name == NULL)
1.273     djm      2613:                key_type_name = DEFAULT_KEY_TYPE_NAME;
1.133     djm      2614:
1.252     djm      2615:        type = sshkey_type_from_name(key_type_name);
1.255     djm      2616:        type_bits_valid(type, key_type_name, &bits);
1.206     stevesk  2617:
1.33      markus   2618:        if (!quiet)
1.252     djm      2619:                printf("Generating public/private %s key pair.\n",
                   2620:                    key_type_name);
1.269     djm      2621:        if ((r = sshkey_generate(type, bits, &private)) != 0)
                   2622:                fatal("key_generate failed");
                   2623:        if ((r = sshkey_from_private(private, &public)) != 0)
                   2624:                fatal("key_from_private failed: %s\n", ssh_err(r));
1.12      markus   2625:
                   2626:        if (!have_identity)
                   2627:                ask_filename(pw, "Enter file in which to save the key");
                   2628:
1.132     djm      2629:        /* Create ~/.ssh directory if it doesn't already exist. */
1.188     djm      2630:        snprintf(dotsshdir, sizeof dotsshdir, "%s/%s",
                   2631:            pw->pw_dir, _PATH_SSH_USER_DIR);
                   2632:        if (strstr(identity_file, dotsshdir) != NULL) {
                   2633:                if (stat(dotsshdir, &st) < 0) {
                   2634:                        if (errno != ENOENT) {
                   2635:                                error("Could not stat %s: %s", dotsshdir,
                   2636:                                    strerror(errno));
                   2637:                        } else if (mkdir(dotsshdir, 0700) < 0) {
                   2638:                                error("Could not create directory '%s': %s",
                   2639:                                    dotsshdir, strerror(errno));
                   2640:                        } else if (!quiet)
                   2641:                                printf("Created directory '%s'.\n", dotsshdir);
                   2642:                }
1.12      markus   2643:        }
                   2644:        /* If the file already exists, ask the user to confirm. */
                   2645:        if (stat(identity_file, &st) >= 0) {
                   2646:                char yesno[3];
                   2647:                printf("%s already exists.\n", identity_file);
                   2648:                printf("Overwrite (y/n)? ");
                   2649:                fflush(stdout);
                   2650:                if (fgets(yesno, sizeof(yesno), stdin) == NULL)
                   2651:                        exit(1);
                   2652:                if (yesno[0] != 'y' && yesno[0] != 'Y')
                   2653:                        exit(1);
                   2654:        }
                   2655:        /* Ask for a passphrase (twice). */
                   2656:        if (identity_passphrase)
                   2657:                passphrase1 = xstrdup(identity_passphrase);
                   2658:        else if (identity_new_passphrase)
                   2659:                passphrase1 = xstrdup(identity_new_passphrase);
                   2660:        else {
                   2661: passphrase_again:
                   2662:                passphrase1 =
1.65      markus   2663:                        read_passphrase("Enter passphrase (empty for no "
                   2664:                            "passphrase): ", RP_ALLOW_STDIN);
                   2665:                passphrase2 = read_passphrase("Enter same passphrase again: ",
                   2666:                    RP_ALLOW_STDIN);
1.12      markus   2667:                if (strcmp(passphrase1, passphrase2) != 0) {
1.65      markus   2668:                        /*
                   2669:                         * The passphrases do not match.  Clear them and
                   2670:                         * retry.
                   2671:                         */
1.240     djm      2672:                        explicit_bzero(passphrase1, strlen(passphrase1));
                   2673:                        explicit_bzero(passphrase2, strlen(passphrase2));
1.227     djm      2674:                        free(passphrase1);
                   2675:                        free(passphrase2);
1.12      markus   2676:                        printf("Passphrases do not match.  Try again.\n");
                   2677:                        goto passphrase_again;
                   2678:                }
                   2679:                /* Clear the other copy of the passphrase. */
1.240     djm      2680:                explicit_bzero(passphrase2, strlen(passphrase2));
1.227     djm      2681:                free(passphrase2);
1.12      markus   2682:        }
                   2683:
                   2684:        if (identity_comment) {
                   2685:                strlcpy(comment, identity_comment, sizeof(comment));
                   2686:        } else {
1.172     stevesk  2687:                /* Create default comment field for the passphrase. */
1.12      markus   2688:                snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
                   2689:        }
                   2690:
                   2691:        /* Save the key with the given passphrase and comment. */
1.252     djm      2692:        if ((r = sshkey_save_private(private, identity_file, passphrase1,
                   2693:            comment, use_new_format, new_format_cipher, rounds)) != 0) {
1.269     djm      2694:                error("Saving key \"%s\" failed: %s",
1.252     djm      2695:                    identity_file, ssh_err(r));
1.240     djm      2696:                explicit_bzero(passphrase1, strlen(passphrase1));
1.227     djm      2697:                free(passphrase1);
1.12      markus   2698:                exit(1);
                   2699:        }
                   2700:        /* Clear the passphrase. */
1.240     djm      2701:        explicit_bzero(passphrase1, strlen(passphrase1));
1.227     djm      2702:        free(passphrase1);
1.12      markus   2703:
                   2704:        /* Clear the private key and the random number generator. */
1.252     djm      2705:        sshkey_free(private);
1.12      markus   2706:
                   2707:        if (!quiet)
                   2708:                printf("Your identification has been saved in %s.\n", identity_file);
                   2709:
                   2710:        strlcat(identity_file, ".pub", sizeof(identity_file));
1.269     djm      2711:        if ((fd = open(identity_file, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
                   2712:                fatal("Unable to save public key to %s: %s",
                   2713:                    identity_file, strerror(errno));
                   2714:        if ((f = fdopen(fd, "w")) == NULL)
                   2715:                fatal("fdopen %s failed: %s", identity_file, strerror(errno));
1.252     djm      2716:        if ((r = sshkey_write(public, f)) != 0)
1.269     djm      2717:                error("write key failed: %s", ssh_err(r));
1.19      markus   2718:        fprintf(f, " %s\n", comment);
1.12      markus   2719:        fclose(f);
                   2720:
                   2721:        if (!quiet) {
1.259     djm      2722:                fp = sshkey_fingerprint(public, fingerprint_hash,
1.251     djm      2723:                    SSH_FP_DEFAULT);
1.259     djm      2724:                ra = sshkey_fingerprint(public, fingerprint_hash,
1.167     grunk    2725:                    SSH_FP_RANDOMART);
1.259     djm      2726:                if (fp == NULL || ra == NULL)
                   2727:                        fatal("sshkey_fingerprint failed");
1.19      markus   2728:                printf("Your public key has been saved in %s.\n",
                   2729:                    identity_file);
1.12      markus   2730:                printf("The key fingerprint is:\n");
1.50      markus   2731:                printf("%s %s\n", fp, comment);
1.167     grunk    2732:                printf("The key's randomart image is:\n");
                   2733:                printf("%s\n", ra);
1.227     djm      2734:                free(ra);
                   2735:                free(fp);
1.12      markus   2736:        }
1.19      markus   2737:
1.252     djm      2738:        sshkey_free(public);
1.12      markus   2739:        exit(0);
1.1       deraadt  2740: }