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

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