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

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