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

Annotation of src/usr.bin/ssh/kex.c, Revision 1.153

1.153   ! djm         1: /* $OpenBSD: kex.c,v 1.152 2019/09/05 09:35:19 djm Exp $ */
1.1       markus      2: /*
1.36      markus      3:  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
1.1       markus      4:  *
                      5:  * Redistribution and use in source and binary forms, with or without
                      6:  * modification, are permitted provided that the following conditions
                      7:  * are met:
                      8:  * 1. Redistributions of source code must retain the above copyright
                      9:  *    notice, this list of conditions and the following disclaimer.
                     10:  * 2. Redistributions in binary form must reproduce the above copyright
                     11:  *    notice, this list of conditions and the following disclaimer in the
                     12:  *    documentation and/or other materials provided with the distribution.
                     13:  *
                     14:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     15:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     16:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     17:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     18:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     19:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     20:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     21:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     22:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     23:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                     24:  */
                     25:
1.18      markus     26:
1.143     djm        27: #include <sys/types.h>
                     28: #include <errno.h>
1.76      deraadt    29: #include <signal.h>
1.75      stevesk    30: #include <stdio.h>
1.74      stevesk    31: #include <stdlib.h>
1.72      stevesk    32: #include <string.h>
1.143     djm        33: #include <unistd.h>
                     34: #include <poll.h>
1.1       markus     35:
1.99      markus     36: #ifdef WITH_OPENSSL
1.76      deraadt    37: #include <openssl/crypto.h>
1.99      markus     38: #endif
1.76      deraadt    39:
1.143     djm        40: #include "ssh.h"
1.1       markus     41: #include "ssh2.h"
1.143     djm        42: #include "atomicio.h"
                     43: #include "version.h"
1.7       markus     44: #include "packet.h"
1.1       markus     45: #include "compat.h"
1.18      markus     46: #include "cipher.h"
1.102     markus     47: #include "sshkey.h"
1.1       markus     48: #include "kex.h"
1.18      markus     49: #include "log.h"
1.21      markus     50: #include "mac.h"
1.23      markus     51: #include "match.h"
1.102     markus     52: #include "misc.h"
1.26      markus     53: #include "dispatch.h"
1.48      provos     54: #include "monitor.h"
1.102     markus     55:
                     56: #include "ssherr.h"
                     57: #include "sshbuf.h"
1.94      djm        58: #include "digest.h"
1.48      provos     59:
1.35      itojun     60: /* prototype */
1.102     markus     61: static int kex_choose_conf(struct ssh *);
1.133     markus     62: static int kex_input_newkeys(int, u_int32_t, struct ssh *);
1.86      djm        63:
1.110     djm        64: static const char *proposal_names[PROPOSAL_MAX] = {
                     65:        "KEX algorithms",
                     66:        "host key algorithms",
                     67:        "ciphers ctos",
                     68:        "ciphers stoc",
                     69:        "MACs ctos",
                     70:        "MACs stoc",
                     71:        "compression ctos",
                     72:        "compression stoc",
                     73:        "languages ctos",
                     74:        "languages stoc",
                     75: };
                     76:
1.89      djm        77: struct kexalg {
                     78:        char *name;
1.102     markus     79:        u_int type;
1.89      djm        80:        int ec_nid;
1.94      djm        81:        int hash_alg;
1.89      djm        82: };
                     83: static const struct kexalg kexalgs[] = {
1.99      markus     84: #ifdef WITH_OPENSSL
1.94      djm        85:        { KEX_DH1, KEX_DH_GRP1_SHA1, 0, SSH_DIGEST_SHA1 },
1.118     djm        86:        { KEX_DH14_SHA1, KEX_DH_GRP14_SHA1, 0, SSH_DIGEST_SHA1 },
                     87:        { KEX_DH14_SHA256, KEX_DH_GRP14_SHA256, 0, SSH_DIGEST_SHA256 },
                     88:        { KEX_DH16_SHA512, KEX_DH_GRP16_SHA512, 0, SSH_DIGEST_SHA512 },
                     89:        { KEX_DH18_SHA512, KEX_DH_GRP18_SHA512, 0, SSH_DIGEST_SHA512 },
1.94      djm        90:        { KEX_DHGEX_SHA1, KEX_DH_GEX_SHA1, 0, SSH_DIGEST_SHA1 },
                     91:        { KEX_DHGEX_SHA256, KEX_DH_GEX_SHA256, 0, SSH_DIGEST_SHA256 },
                     92:        { KEX_ECDH_SHA2_NISTP256, KEX_ECDH_SHA2,
                     93:            NID_X9_62_prime256v1, SSH_DIGEST_SHA256 },
                     94:        { KEX_ECDH_SHA2_NISTP384, KEX_ECDH_SHA2, NID_secp384r1,
                     95:            SSH_DIGEST_SHA384 },
                     96:        { KEX_ECDH_SHA2_NISTP521, KEX_ECDH_SHA2, NID_secp521r1,
                     97:            SSH_DIGEST_SHA512 },
1.99      markus     98: #endif
1.94      djm        99:        { KEX_CURVE25519_SHA256, KEX_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
1.124     djm       100:        { KEX_CURVE25519_SHA256_OLD, KEX_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
1.147     djm       101:        { KEX_SNTRUP4591761X25519_SHA512, KEX_KEM_SNTRUP4591761X25519_SHA512, 0,
                    102:            SSH_DIGEST_SHA512 },
1.94      djm       103:        { NULL, -1, -1, -1},
1.89      djm       104: };
                    105:
                    106: char *
1.93      dtucker   107: kex_alg_list(char sep)
1.89      djm       108: {
1.102     markus    109:        char *ret = NULL, *tmp;
1.89      djm       110:        size_t nlen, rlen = 0;
                    111:        const struct kexalg *k;
                    112:
                    113:        for (k = kexalgs; k->name != NULL; k++) {
                    114:                if (ret != NULL)
1.93      dtucker   115:                        ret[rlen++] = sep;
1.89      djm       116:                nlen = strlen(k->name);
1.102     markus    117:                if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
                    118:                        free(ret);
                    119:                        return NULL;
                    120:                }
                    121:                ret = tmp;
1.89      djm       122:                memcpy(ret + rlen, k->name, nlen + 1);
                    123:                rlen += nlen;
                    124:        }
                    125:        return ret;
                    126: }
                    127:
                    128: static const struct kexalg *
                    129: kex_alg_by_name(const char *name)
                    130: {
                    131:        const struct kexalg *k;
                    132:
                    133:        for (k = kexalgs; k->name != NULL; k++) {
                    134:                if (strcmp(k->name, name) == 0)
                    135:                        return k;
                    136:        }
                    137:        return NULL;
                    138: }
                    139:
1.86      djm       140: /* Validate KEX method name list */
                    141: int
                    142: kex_names_valid(const char *names)
                    143: {
                    144:        char *s, *cp, *p;
                    145:
                    146:        if (names == NULL || strcmp(names, "") == 0)
                    147:                return 0;
1.102     markus    148:        if ((s = cp = strdup(names)) == NULL)
                    149:                return 0;
1.86      djm       150:        for ((p = strsep(&cp, ",")); p && *p != '\0';
                    151:            (p = strsep(&cp, ","))) {
1.89      djm       152:                if (kex_alg_by_name(p) == NULL) {
1.86      djm       153:                        error("Unsupported KEX algorithm \"%.100s\"", p);
1.91      djm       154:                        free(s);
1.86      djm       155:                        return 0;
                    156:                }
                    157:        }
                    158:        debug3("kex names ok: [%s]", names);
1.91      djm       159:        free(s);
1.86      djm       160:        return 1;
1.109     djm       161: }
                    162:
                    163: /*
                    164:  * Concatenate algorithm names, avoiding duplicates in the process.
                    165:  * Caller must free returned string.
                    166:  */
                    167: char *
                    168: kex_names_cat(const char *a, const char *b)
                    169: {
1.129     dtucker   170:        char *ret = NULL, *tmp = NULL, *cp, *p, *m;
1.109     djm       171:        size_t len;
                    172:
                    173:        if (a == NULL || *a == '\0')
1.138     djm       174:                return strdup(b);
1.109     djm       175:        if (b == NULL || *b == '\0')
                    176:                return strdup(a);
                    177:        if (strlen(b) > 1024*1024)
                    178:                return NULL;
                    179:        len = strlen(a) + strlen(b) + 2;
                    180:        if ((tmp = cp = strdup(b)) == NULL ||
                    181:            (ret = calloc(1, len)) == NULL) {
                    182:                free(tmp);
                    183:                return NULL;
                    184:        }
                    185:        strlcpy(ret, a, len);
                    186:        for ((p = strsep(&cp, ",")); p && *p != '\0'; (p = strsep(&cp, ","))) {
1.129     dtucker   187:                if ((m = match_list(ret, p, NULL)) != NULL) {
                    188:                        free(m);
1.109     djm       189:                        continue; /* Algorithm already present */
1.129     dtucker   190:                }
1.109     djm       191:                if (strlcat(ret, ",", len) >= len ||
                    192:                    strlcat(ret, p, len) >= len) {
                    193:                        free(tmp);
                    194:                        free(ret);
                    195:                        return NULL; /* Shouldn't happen */
                    196:                }
                    197:        }
                    198:        free(tmp);
                    199:        return ret;
                    200: }
                    201:
                    202: /*
                    203:  * Assemble a list of algorithms from a default list and a string from a
                    204:  * configuration file. The user-provided string may begin with '+' to
1.128     djm       205:  * indicate that it should be appended to the default or '-' that the
                    206:  * specified names should be removed.
1.109     djm       207:  */
                    208: int
1.138     djm       209: kex_assemble_names(char **listp, const char *def, const char *all)
1.109     djm       210: {
1.138     djm       211:        char *cp, *tmp, *patterns;
                    212:        char *list = NULL, *ret = NULL, *matching = NULL, *opatterns = NULL;
                    213:        int r = SSH_ERR_INTERNAL_ERROR;
                    214:
1.153   ! djm       215:        if (listp == NULL || def == NULL || all == NULL)
        !           216:                return SSH_ERR_INVALID_ARGUMENT;
        !           217:
        !           218:        if (*listp == NULL || **listp == '\0') {
1.138     djm       219:                if ((*listp = strdup(def)) == NULL)
                    220:                        return SSH_ERR_ALLOC_FAIL;
                    221:                return 0;
                    222:        }
1.109     djm       223:
1.138     djm       224:        list = *listp;
                    225:        *listp = NULL;
                    226:        if (*list == '+') {
                    227:                /* Append names to default list */
                    228:                if ((tmp = kex_names_cat(def, list + 1)) == NULL) {
                    229:                        r = SSH_ERR_ALLOC_FAIL;
                    230:                        goto fail;
                    231:                }
                    232:                free(list);
                    233:                list = tmp;
                    234:        } else if (*list == '-') {
                    235:                /* Remove names from default list */
                    236:                if ((*listp = match_filter_blacklist(def, list + 1)) == NULL) {
                    237:                        r = SSH_ERR_ALLOC_FAIL;
                    238:                        goto fail;
                    239:                }
                    240:                free(list);
                    241:                /* filtering has already been done */
1.109     djm       242:                return 0;
1.138     djm       243:        } else {
                    244:                /* Explicit list, overrides default - just use "list" as is */
                    245:        }
                    246:
                    247:        /*
                    248:         * The supplied names may be a pattern-list. For the -list case,
                    249:         * the patterns are applied above. For the +list and explicit list
                    250:         * cases we need to do it now.
                    251:         */
                    252:        ret = NULL;
                    253:        if ((patterns = opatterns = strdup(list)) == NULL) {
                    254:                r = SSH_ERR_ALLOC_FAIL;
                    255:                goto fail;
                    256:        }
                    257:        /* Apply positive (i.e. non-negated) patterns from the list */
                    258:        while ((cp = strsep(&patterns, ",")) != NULL) {
                    259:                if (*cp == '!') {
                    260:                        /* negated matches are not supported here */
                    261:                        r = SSH_ERR_INVALID_ARGUMENT;
                    262:                        goto fail;
                    263:                }
                    264:                free(matching);
                    265:                if ((matching = match_filter_whitelist(all, cp)) == NULL) {
                    266:                        r = SSH_ERR_ALLOC_FAIL;
                    267:                        goto fail;
                    268:                }
                    269:                if ((tmp = kex_names_cat(ret, matching)) == NULL) {
                    270:                        r = SSH_ERR_ALLOC_FAIL;
                    271:                        goto fail;
                    272:                }
                    273:                free(ret);
                    274:                ret = tmp;
1.109     djm       275:        }
1.138     djm       276:        if (ret == NULL || *ret == '\0') {
                    277:                /* An empty name-list is an error */
                    278:                /* XXX better error code? */
                    279:                r = SSH_ERR_INVALID_ARGUMENT;
                    280:                goto fail;
1.109     djm       281:        }
                    282:
1.138     djm       283:        /* success */
                    284:        *listp = ret;
                    285:        ret = NULL;
                    286:        r = 0;
                    287:
                    288:  fail:
                    289:        free(matching);
                    290:        free(opatterns);
                    291:        free(list);
                    292:        free(ret);
                    293:        return r;
1.86      djm       294: }
1.26      markus    295:
                    296: /* put algorithm proposal into buffer */
1.102     markus    297: int
                    298: kex_prop2buf(struct sshbuf *b, char *proposal[PROPOSAL_MAX])
1.1       markus    299: {
1.61      djm       300:        u_int i;
1.102     markus    301:        int r;
                    302:
                    303:        sshbuf_reset(b);
1.26      markus    304:
1.49      markus    305:        /*
                    306:         * add a dummy cookie, the cookie will be overwritten by
                    307:         * kex_send_kexinit(), each time a kexinit is set
                    308:         */
1.102     markus    309:        for (i = 0; i < KEX_COOKIE_LEN; i++) {
                    310:                if ((r = sshbuf_put_u8(b, 0)) != 0)
                    311:                        return r;
                    312:        }
                    313:        for (i = 0; i < PROPOSAL_MAX; i++) {
                    314:                if ((r = sshbuf_put_cstring(b, proposal[i])) != 0)
                    315:                        return r;
                    316:        }
                    317:        if ((r = sshbuf_put_u8(b, 0)) != 0 ||   /* first_kex_packet_follows */
                    318:            (r = sshbuf_put_u32(b, 0)) != 0)    /* uint32 reserved */
                    319:                return r;
                    320:        return 0;
1.1       markus    321: }
                    322:
1.26      markus    323: /* parse buffer and return algorithm proposal */
1.102     markus    324: int
                    325: kex_buf2prop(struct sshbuf *raw, int *first_kex_follows, char ***propp)
1.7       markus    326: {
1.102     markus    327:        struct sshbuf *b = NULL;
                    328:        u_char v;
1.78      djm       329:        u_int i;
1.102     markus    330:        char **proposal = NULL;
                    331:        int r;
1.7       markus    332:
1.102     markus    333:        *propp = NULL;
                    334:        if ((proposal = calloc(PROPOSAL_MAX, sizeof(char *))) == NULL)
                    335:                return SSH_ERR_ALLOC_FAIL;
                    336:        if ((b = sshbuf_fromb(raw)) == NULL) {
                    337:                r = SSH_ERR_ALLOC_FAIL;
                    338:                goto out;
                    339:        }
1.152     djm       340:        if ((r = sshbuf_consume(b, KEX_COOKIE_LEN)) != 0) { /* skip cookie */
                    341:                error("%s: consume cookie: %s", __func__, ssh_err(r));
1.102     markus    342:                goto out;
1.152     djm       343:        }
1.7       markus    344:        /* extract kex init proposal strings */
                    345:        for (i = 0; i < PROPOSAL_MAX; i++) {
1.152     djm       346:                if ((r = sshbuf_get_cstring(b, &(proposal[i]), NULL)) != 0) {
                    347:                        error("%s: parse proposal %u: %s", __func__,
                    348:                            i, ssh_err(r));
1.102     markus    349:                        goto out;
1.152     djm       350:                }
1.110     djm       351:                debug2("%s: %s", proposal_names[i], proposal[i]);
1.7       markus    352:        }
1.26      markus    353:        /* first kex follows / reserved */
1.115     djm       354:        if ((r = sshbuf_get_u8(b, &v)) != 0 ||  /* first_kex_follows */
1.152     djm       355:            (r = sshbuf_get_u32(b, &i)) != 0) { /* reserved */
                    356:                error("%s: parse: %s", __func__, ssh_err(r));
1.102     markus    357:                goto out;
1.152     djm       358:        }
1.53      markus    359:        if (first_kex_follows != NULL)
1.115     djm       360:                *first_kex_follows = v;
1.110     djm       361:        debug2("first_kex_follows %d ", v);
                    362:        debug2("reserved %u ", i);
1.102     markus    363:        r = 0;
                    364:        *propp = proposal;
                    365:  out:
                    366:        if (r != 0 && proposal != NULL)
                    367:                kex_prop_free(proposal);
                    368:        sshbuf_free(b);
                    369:        return r;
1.1       markus    370: }
                    371:
1.102     markus    372: void
1.26      markus    373: kex_prop_free(char **proposal)
1.1       markus    374: {
1.61      djm       375:        u_int i;
1.26      markus    376:
1.106     djm       377:        if (proposal == NULL)
                    378:                return;
1.26      markus    379:        for (i = 0; i < PROPOSAL_MAX; i++)
1.91      djm       380:                free(proposal[i]);
                    381:        free(proposal);
1.1       markus    382: }
                    383:
1.78      djm       384: /* ARGSUSED */
1.101     markus    385: static int
1.133     markus    386: kex_protocol_error(int type, u_int32_t seq, struct ssh *ssh)
1.1       markus    387: {
1.112     djm       388:        int r;
                    389:
                    390:        error("kex protocol error: type %d seq %u", type, seq);
                    391:        if ((r = sshpkt_start(ssh, SSH2_MSG_UNIMPLEMENTED)) != 0 ||
                    392:            (r = sshpkt_put_u32(ssh, seq)) != 0 ||
                    393:            (r = sshpkt_send(ssh)) != 0)
                    394:                return r;
1.101     markus    395:        return 0;
1.26      markus    396: }
1.1       markus    397:
1.35      itojun    398: static void
1.102     markus    399: kex_reset_dispatch(struct ssh *ssh)
1.29      markus    400: {
1.102     markus    401:        ssh_dispatch_range(ssh, SSH2_MSG_TRANSPORT_MIN,
1.42      markus    402:            SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
1.29      markus    403: }
                    404:
1.113     markus    405: static int
                    406: kex_send_ext_info(struct ssh *ssh)
                    407: {
                    408:        int r;
1.121     djm       409:        char *algs;
1.113     markus    410:
1.151     djm       411:        debug("Sending SSH2_MSG_EXT_INFO");
1.130     djm       412:        if ((algs = sshkey_alg_list(0, 1, 1, ',')) == NULL)
1.121     djm       413:                return SSH_ERR_ALLOC_FAIL;
1.137     djm       414:        /* XXX filter algs list by allowed pubkey/hostbased types */
1.113     markus    415:        if ((r = sshpkt_start(ssh, SSH2_MSG_EXT_INFO)) != 0 ||
                    416:            (r = sshpkt_put_u32(ssh, 1)) != 0 ||
                    417:            (r = sshpkt_put_cstring(ssh, "server-sig-algs")) != 0 ||
1.121     djm       418:            (r = sshpkt_put_cstring(ssh, algs)) != 0 ||
1.152     djm       419:            (r = sshpkt_send(ssh)) != 0) {
                    420:                error("%s: compose: %s", __func__, ssh_err(r));
1.121     djm       421:                goto out;
1.152     djm       422:        }
1.121     djm       423:        /* success */
                    424:        r = 0;
                    425:  out:
                    426:        free(algs);
1.123     djm       427:        return r;
1.113     markus    428: }
                    429:
1.102     markus    430: int
                    431: kex_send_newkeys(struct ssh *ssh)
1.26      markus    432: {
1.102     markus    433:        int r;
1.28      markus    434:
1.102     markus    435:        kex_reset_dispatch(ssh);
                    436:        if ((r = sshpkt_start(ssh, SSH2_MSG_NEWKEYS)) != 0 ||
                    437:            (r = sshpkt_send(ssh)) != 0)
                    438:                return r;
1.26      markus    439:        debug("SSH2_MSG_NEWKEYS sent");
1.102     markus    440:        ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_input_newkeys);
1.151     djm       441:        if (ssh->kex->ext_info_c && (ssh->kex->flags & KEX_INITIAL) != 0)
1.113     markus    442:                if ((r = kex_send_ext_info(ssh)) != 0)
                    443:                        return r;
1.151     djm       444:        debug("expecting SSH2_MSG_NEWKEYS");
1.102     markus    445:        return 0;
                    446: }
                    447:
1.113     markus    448: int
1.133     markus    449: kex_input_ext_info(int type, u_int32_t seq, struct ssh *ssh)
1.113     markus    450: {
                    451:        struct kex *kex = ssh->kex;
                    452:        u_int32_t i, ninfo;
1.137     djm       453:        char *name;
1.134     djm       454:        u_char *val;
                    455:        size_t vlen;
1.113     markus    456:        int r;
                    457:
                    458:        debug("SSH2_MSG_EXT_INFO received");
                    459:        ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &kex_protocol_error);
                    460:        if ((r = sshpkt_get_u32(ssh, &ninfo)) != 0)
                    461:                return r;
                    462:        for (i = 0; i < ninfo; i++) {
                    463:                if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0)
                    464:                        return r;
1.134     djm       465:                if ((r = sshpkt_get_string(ssh, &val, &vlen)) != 0) {
1.113     markus    466:                        free(name);
                    467:                        return r;
                    468:                }
                    469:                if (strcmp(name, "server-sig-algs") == 0) {
1.134     djm       470:                        /* Ensure no \0 lurking in value */
                    471:                        if (memchr(val, '\0', vlen) != NULL) {
                    472:                                error("%s: nul byte in %s", __func__, name);
                    473:                                return SSH_ERR_INVALID_FORMAT;
                    474:                        }
                    475:                        debug("%s: %s=<%s>", __func__, name, val);
1.137     djm       476:                        kex->server_sig_algs = val;
                    477:                        val = NULL;
1.134     djm       478:                } else
                    479:                        debug("%s: %s (unrecognised)", __func__, name);
1.113     markus    480:                free(name);
                    481:                free(val);
                    482:        }
                    483:        return sshpkt_get_end(ssh);
                    484: }
                    485:
1.102     markus    486: static int
1.133     markus    487: kex_input_newkeys(int type, u_int32_t seq, struct ssh *ssh)
1.102     markus    488: {
                    489:        struct kex *kex = ssh->kex;
                    490:        int r;
1.19      stevesk   491:
1.26      markus    492:        debug("SSH2_MSG_NEWKEYS received");
1.102     markus    493:        ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error);
1.131     markus    494:        ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
1.102     markus    495:        if ((r = sshpkt_get_end(ssh)) != 0)
1.122     markus    496:                return r;
                    497:        if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0)
1.102     markus    498:                return r;
1.30      markus    499:        kex->done = 1;
1.142     djm       500:        kex->flags &= ~KEX_INITIAL;
1.102     markus    501:        sshbuf_reset(kex->peer);
                    502:        /* sshbuf_reset(kex->my); */
1.26      markus    503:        kex->flags &= ~KEX_INIT_SENT;
1.91      djm       504:        free(kex->name);
1.32      markus    505:        kex->name = NULL;
1.102     markus    506:        return 0;
1.26      markus    507: }
1.1       markus    508:
1.102     markus    509: int
                    510: kex_send_kexinit(struct ssh *ssh)
1.26      markus    511: {
1.49      markus    512:        u_char *cookie;
1.102     markus    513:        struct kex *kex = ssh->kex;
                    514:        int r;
1.49      markus    515:
1.152     djm       516:        if (kex == NULL) {
                    517:                error("%s: no hex", __func__);
1.102     markus    518:                return SSH_ERR_INTERNAL_ERROR;
1.152     djm       519:        }
1.102     markus    520:        if (kex->flags & KEX_INIT_SENT)
                    521:                return 0;
1.30      markus    522:        kex->done = 0;
1.49      markus    523:
                    524:        /* generate a random cookie */
1.152     djm       525:        if (sshbuf_len(kex->my) < KEX_COOKIE_LEN) {
                    526:                error("%s: bad kex length: %zu < %d", __func__,
                    527:                    sshbuf_len(kex->my), KEX_COOKIE_LEN);
1.102     markus    528:                return SSH_ERR_INVALID_FORMAT;
1.152     djm       529:        }
                    530:        if ((cookie = sshbuf_mutable_ptr(kex->my)) == NULL) {
                    531:                error("%s: buffer error", __func__);
1.102     markus    532:                return SSH_ERR_INTERNAL_ERROR;
1.152     djm       533:        }
1.102     markus    534:        arc4random_buf(cookie, KEX_COOKIE_LEN);
                    535:
                    536:        if ((r = sshpkt_start(ssh, SSH2_MSG_KEXINIT)) != 0 ||
                    537:            (r = sshpkt_putb(ssh, kex->my)) != 0 ||
1.152     djm       538:            (r = sshpkt_send(ssh)) != 0) {
                    539:                error("%s: compose reply: %s", __func__, ssh_err(r));
1.102     markus    540:                return r;
1.152     djm       541:        }
1.26      markus    542:        debug("SSH2_MSG_KEXINIT sent");
                    543:        kex->flags |= KEX_INIT_SENT;
1.102     markus    544:        return 0;
1.1       markus    545: }
                    546:
1.78      djm       547: /* ARGSUSED */
1.101     markus    548: int
1.133     markus    549: kex_input_kexinit(int type, u_int32_t seq, struct ssh *ssh)
1.11      provos    550: {
1.102     markus    551:        struct kex *kex = ssh->kex;
                    552:        const u_char *ptr;
1.100     markus    553:        u_int i;
                    554:        size_t dlen;
1.102     markus    555:        int r;
1.11      provos    556:
1.26      markus    557:        debug("SSH2_MSG_KEXINIT received");
1.152     djm       558:        if (kex == NULL) {
                    559:                error("%s: no hex", __func__);
                    560:                return SSH_ERR_INTERNAL_ERROR;
                    561:        }
1.127     markus    562:        ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, NULL);
1.102     markus    563:        ptr = sshpkt_ptr(ssh, &dlen);
                    564:        if ((r = sshbuf_put(kex->peer, ptr, dlen)) != 0)
                    565:                return r;
1.31      markus    566:
                    567:        /* discard packet */
1.152     djm       568:        for (i = 0; i < KEX_COOKIE_LEN; i++) {
                    569:                if ((r = sshpkt_get_u8(ssh, NULL)) != 0) {
                    570:                        error("%s: discard cookie: %s", __func__, ssh_err(r));
1.102     markus    571:                        return r;
1.152     djm       572:                }
                    573:        }
                    574:        for (i = 0; i < PROPOSAL_MAX; i++) {
                    575:                if ((r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
                    576:                        error("%s: discard proposal: %s", __func__, ssh_err(r));
1.102     markus    577:                        return r;
1.152     djm       578:                }
                    579:        }
1.87      djm       580:        /*
                    581:         * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported
                    582:         * KEX method has the server move first, but a server might be using
                    583:         * a custom method or one that we otherwise don't support. We should
                    584:         * be prepared to remember first_kex_follows here so we can eat a
                    585:         * packet later.
                    586:         * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means
                    587:         * for cases where the server *doesn't* go first. I guess we should
                    588:         * ignore it when it is set for these cases, which is what we do now.
                    589:         */
1.102     markus    590:        if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||      /* first_kex_follows */
                    591:            (r = sshpkt_get_u32(ssh, NULL)) != 0 ||     /* reserved */
                    592:            (r = sshpkt_get_end(ssh)) != 0)
                    593:                        return r;
                    594:
                    595:        if (!(kex->flags & KEX_INIT_SENT))
                    596:                if ((r = kex_send_kexinit(ssh)) != 0)
                    597:                        return r;
                    598:        if ((r = kex_choose_conf(ssh)) != 0)
                    599:                return r;
1.19      stevesk   600:
1.102     markus    601:        if (kex->kex_type < KEX_MAX && kex->kex[kex->kex_type] != NULL)
                    602:                return (kex->kex[kex->kex_type])(ssh);
                    603:
1.152     djm       604:        error("%s: unknown kex type %u", __func__, kex->kex_type);
1.102     markus    605:        return SSH_ERR_INTERNAL_ERROR;
                    606: }
                    607:
1.143     djm       608: struct kex *
                    609: kex_new(void)
1.102     markus    610: {
                    611:        struct kex *kex;
                    612:
1.143     djm       613:        if ((kex = calloc(1, sizeof(*kex))) == NULL ||
                    614:            (kex->peer = sshbuf_new()) == NULL ||
                    615:            (kex->my = sshbuf_new()) == NULL ||
                    616:            (kex->client_version = sshbuf_new()) == NULL ||
                    617:            (kex->server_version = sshbuf_new()) == NULL) {
                    618:                kex_free(kex);
                    619:                return NULL;
1.102     markus    620:        }
1.143     djm       621:        return kex;
1.26      markus    622: }
1.11      provos    623:
1.100     markus    624: void
                    625: kex_free_newkeys(struct newkeys *newkeys)
                    626: {
                    627:        if (newkeys == NULL)
                    628:                return;
                    629:        if (newkeys->enc.key) {
                    630:                explicit_bzero(newkeys->enc.key, newkeys->enc.key_len);
                    631:                free(newkeys->enc.key);
                    632:                newkeys->enc.key = NULL;
                    633:        }
                    634:        if (newkeys->enc.iv) {
1.111     djm       635:                explicit_bzero(newkeys->enc.iv, newkeys->enc.iv_len);
1.100     markus    636:                free(newkeys->enc.iv);
                    637:                newkeys->enc.iv = NULL;
                    638:        }
                    639:        free(newkeys->enc.name);
                    640:        explicit_bzero(&newkeys->enc, sizeof(newkeys->enc));
                    641:        free(newkeys->comp.name);
                    642:        explicit_bzero(&newkeys->comp, sizeof(newkeys->comp));
                    643:        mac_clear(&newkeys->mac);
                    644:        if (newkeys->mac.key) {
                    645:                explicit_bzero(newkeys->mac.key, newkeys->mac.key_len);
                    646:                free(newkeys->mac.key);
                    647:                newkeys->mac.key = NULL;
                    648:        }
                    649:        free(newkeys->mac.name);
                    650:        explicit_bzero(&newkeys->mac, sizeof(newkeys->mac));
                    651:        explicit_bzero(newkeys, sizeof(*newkeys));
                    652:        free(newkeys);
                    653: }
                    654:
1.102     markus    655: void
                    656: kex_free(struct kex *kex)
1.26      markus    657: {
1.102     markus    658:        u_int mode;
1.11      provos    659:
1.143     djm       660:        if (kex == NULL)
                    661:                return;
                    662:
1.102     markus    663: #ifdef WITH_OPENSSL
1.136     jsing     664:        DH_free(kex->dh);
                    665:        EC_KEY_free(kex->ec_client_key);
1.102     markus    666: #endif
                    667:        for (mode = 0; mode < MODE_MAX; mode++) {
                    668:                kex_free_newkeys(kex->newkeys[mode]);
                    669:                kex->newkeys[mode] = NULL;
1.100     markus    670:        }
1.102     markus    671:        sshbuf_free(kex->peer);
                    672:        sshbuf_free(kex->my);
1.143     djm       673:        sshbuf_free(kex->client_version);
                    674:        sshbuf_free(kex->server_version);
1.149     djm       675:        sshbuf_free(kex->client_pub);
1.102     markus    676:        free(kex->session_id);
1.107     djm       677:        free(kex->failed_choice);
1.113     markus    678:        free(kex->hostkey_alg);
                    679:        free(kex->name);
1.102     markus    680:        free(kex);
1.11      provos    681: }
                    682:
1.102     markus    683: int
1.143     djm       684: kex_ready(struct ssh *ssh, char *proposal[PROPOSAL_MAX])
                    685: {
                    686:        int r;
                    687:
                    688:        if ((r = kex_prop2buf(ssh->kex->my, proposal)) != 0)
                    689:                return r;
                    690:        ssh->kex->flags = KEX_INITIAL;
                    691:        kex_reset_dispatch(ssh);
                    692:        ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
                    693:        return 0;
                    694: }
                    695:
                    696: int
1.102     markus    697: kex_setup(struct ssh *ssh, char *proposal[PROPOSAL_MAX])
1.1       markus    698: {
1.102     markus    699:        int r;
1.1       markus    700:
1.143     djm       701:        if ((r = kex_ready(ssh, proposal)) != 0)
1.102     markus    702:                return r;
                    703:        if ((r = kex_send_kexinit(ssh)) != 0) {         /* we start */
                    704:                kex_free(ssh->kex);
                    705:                ssh->kex = NULL;
                    706:                return r;
1.1       markus    707:        }
1.102     markus    708:        return 0;
1.117     djm       709: }
                    710:
                    711: /*
                    712:  * Request key re-exchange, returns 0 on success or a ssherr.h error
                    713:  * code otherwise. Must not be called if KEX is incomplete or in-progress.
                    714:  */
                    715: int
                    716: kex_start_rekex(struct ssh *ssh)
                    717: {
                    718:        if (ssh->kex == NULL) {
                    719:                error("%s: no kex", __func__);
                    720:                return SSH_ERR_INTERNAL_ERROR;
                    721:        }
                    722:        if (ssh->kex->done == 0) {
                    723:                error("%s: requested twice", __func__);
                    724:                return SSH_ERR_INTERNAL_ERROR;
                    725:        }
                    726:        ssh->kex->done = 0;
                    727:        return kex_send_kexinit(ssh);
1.1       markus    728: }
                    729:
1.102     markus    730: static int
                    731: choose_enc(struct sshenc *enc, char *client, char *server)
1.1       markus    732: {
1.23      markus    733:        char *name = match_list(client, server, NULL);
1.102     markus    734:
1.1       markus    735:        if (name == NULL)
1.102     markus    736:                return SSH_ERR_NO_CIPHER_ALG_MATCH;
1.129     dtucker   737:        if ((enc->cipher = cipher_by_name(name)) == NULL) {
1.152     djm       738:                error("%s: unsupported cipher %s", __func__, name);
1.129     dtucker   739:                free(name);
1.102     markus    740:                return SSH_ERR_INTERNAL_ERROR;
1.129     dtucker   741:        }
1.1       markus    742:        enc->name = name;
                    743:        enc->enabled = 0;
                    744:        enc->iv = NULL;
1.88      markus    745:        enc->iv_len = cipher_ivlen(enc->cipher);
1.1       markus    746:        enc->key = NULL;
1.45      markus    747:        enc->key_len = cipher_keylen(enc->cipher);
                    748:        enc->block_size = cipher_blocksize(enc->cipher);
1.102     markus    749:        return 0;
1.1       markus    750: }
1.69      deraadt   751:
1.102     markus    752: static int
                    753: choose_mac(struct ssh *ssh, struct sshmac *mac, char *client, char *server)
1.1       markus    754: {
1.23      markus    755:        char *name = match_list(client, server, NULL);
1.102     markus    756:
1.1       markus    757:        if (name == NULL)
1.102     markus    758:                return SSH_ERR_NO_MAC_ALG_MATCH;
1.129     dtucker   759:        if (mac_setup(mac, name) < 0) {
1.152     djm       760:                error("%s: unsupported MAC %s", __func__, name);
1.129     dtucker   761:                free(name);
1.102     markus    762:                return SSH_ERR_INTERNAL_ERROR;
1.129     dtucker   763:        }
1.1       markus    764:        mac->name = name;
                    765:        mac->key = NULL;
                    766:        mac->enabled = 0;
1.102     markus    767:        return 0;
1.1       markus    768: }
1.69      deraadt   769:
1.102     markus    770: static int
                    771: choose_comp(struct sshcomp *comp, char *client, char *server)
1.1       markus    772: {
1.23      markus    773:        char *name = match_list(client, server, NULL);
1.102     markus    774:
1.1       markus    775:        if (name == NULL)
1.102     markus    776:                return SSH_ERR_NO_COMPRESS_ALG_MATCH;
1.64      markus    777:        if (strcmp(name, "zlib@openssh.com") == 0) {
1.141     sf        778:                comp->type = COMP_DELAYED;
                    779:        } else if (strcmp(name, "zlib") == 0) {
1.140     sf        780:                comp->type = COMP_ZLIB;
1.1       markus    781:        } else if (strcmp(name, "none") == 0) {
1.64      markus    782:                comp->type = COMP_NONE;
1.1       markus    783:        } else {
1.152     djm       784:                error("%s: unsupported compression scheme %s", __func__, name);
1.129     dtucker   785:                free(name);
1.102     markus    786:                return SSH_ERR_INTERNAL_ERROR;
1.1       markus    787:        }
                    788:        comp->name = name;
1.102     markus    789:        return 0;
1.1       markus    790: }
1.69      deraadt   791:
1.102     markus    792: static int
                    793: choose_kex(struct kex *k, char *client, char *server)
1.1       markus    794: {
1.89      djm       795:        const struct kexalg *kexalg;
                    796:
1.23      markus    797:        k->name = match_list(client, server, NULL);
1.102     markus    798:
1.110     djm       799:        debug("kex: algorithm: %s", k->name ? k->name : "(no match)");
1.1       markus    800:        if (k->name == NULL)
1.102     markus    801:                return SSH_ERR_NO_KEX_ALG_MATCH;
1.152     djm       802:        if ((kexalg = kex_alg_by_name(k->name)) == NULL) {
                    803:                error("%s: unsupported KEX method %s", __func__, k->name);
1.102     markus    804:                return SSH_ERR_INTERNAL_ERROR;
1.152     djm       805:        }
1.89      djm       806:        k->kex_type = kexalg->type;
1.94      djm       807:        k->hash_alg = kexalg->hash_alg;
1.89      djm       808:        k->ec_nid = kexalg->ec_nid;
1.102     markus    809:        return 0;
1.1       markus    810: }
1.65      djm       811:
1.102     markus    812: static int
                    813: choose_hostkeyalg(struct kex *k, char *client, char *server)
1.1       markus    814: {
1.113     markus    815:        k->hostkey_alg = match_list(client, server, NULL);
1.102     markus    816:
1.110     djm       817:        debug("kex: host key algorithm: %s",
1.113     markus    818:            k->hostkey_alg ? k->hostkey_alg : "(no match)");
                    819:        if (k->hostkey_alg == NULL)
1.102     markus    820:                return SSH_ERR_NO_HOSTKEY_ALG_MATCH;
1.113     markus    821:        k->hostkey_type = sshkey_type_from_name(k->hostkey_alg);
1.152     djm       822:        if (k->hostkey_type == KEY_UNSPEC) {
                    823:                error("%s: unsupported hostkey algorithm %s", __func__,
                    824:                    k->hostkey_alg);
1.102     markus    825:                return SSH_ERR_INTERNAL_ERROR;
1.152     djm       826:        }
1.113     markus    827:        k->hostkey_nid = sshkey_ecdsa_nid_from_name(k->hostkey_alg);
1.102     markus    828:        return 0;
1.1       markus    829: }
                    830:
1.56      djm       831: static int
1.53      markus    832: proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX])
                    833: {
                    834:        static int check[] = {
                    835:                PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1
                    836:        };
                    837:        int *idx;
                    838:        char *p;
                    839:
                    840:        for (idx = &check[0]; *idx != -1; idx++) {
                    841:                if ((p = strchr(my[*idx], ',')) != NULL)
                    842:                        *p = '\0';
                    843:                if ((p = strchr(peer[*idx], ',')) != NULL)
                    844:                        *p = '\0';
                    845:                if (strcmp(my[*idx], peer[*idx]) != 0) {
                    846:                        debug2("proposal mismatch: my %s peer %s",
                    847:                            my[*idx], peer[*idx]);
                    848:                        return (0);
                    849:                }
                    850:        }
                    851:        debug2("proposals match");
                    852:        return (1);
                    853: }
                    854:
1.102     markus    855: static int
                    856: kex_choose_conf(struct ssh *ssh)
1.1       markus    857: {
1.102     markus    858:        struct kex *kex = ssh->kex;
                    859:        struct newkeys *newkeys;
                    860:        char **my = NULL, **peer = NULL;
1.26      markus    861:        char **cprop, **sprop;
1.27      markus    862:        int nenc, nmac, ncomp;
1.96      dtucker   863:        u_int mode, ctos, need, dh_need, authlen;
1.102     markus    864:        int r, first_kex_follows;
1.1       markus    865:
1.110     djm       866:        debug2("local %s KEXINIT proposal", kex->server ? "server" : "client");
                    867:        if ((r = kex_buf2prop(kex->my, NULL, &my)) != 0)
                    868:                goto out;
                    869:        debug2("peer %s KEXINIT proposal", kex->server ? "client" : "server");
                    870:        if ((r = kex_buf2prop(kex->peer, &first_kex_follows, &peer)) != 0)
1.102     markus    871:                goto out;
1.26      markus    872:
1.27      markus    873:        if (kex->server) {
1.26      markus    874:                cprop=peer;
                    875:                sprop=my;
                    876:        } else {
                    877:                cprop=my;
                    878:                sprop=peer;
1.113     markus    879:        }
                    880:
                    881:        /* Check whether client supports ext_info_c */
1.142     djm       882:        if (kex->server && (kex->flags & KEX_INITIAL)) {
1.113     markus    883:                char *ext;
                    884:
                    885:                ext = match_list("ext-info-c", peer[PROPOSAL_KEX_ALGS], NULL);
1.119     markus    886:                kex->ext_info_c = (ext != NULL);
                    887:                free(ext);
1.26      markus    888:        }
1.1       markus    889:
1.30      markus    890:        /* Algorithm Negotiation */
1.110     djm       891:        if ((r = choose_kex(kex, cprop[PROPOSAL_KEX_ALGS],
                    892:            sprop[PROPOSAL_KEX_ALGS])) != 0) {
                    893:                kex->failed_choice = peer[PROPOSAL_KEX_ALGS];
                    894:                peer[PROPOSAL_KEX_ALGS] = NULL;
                    895:                goto out;
                    896:        }
                    897:        if ((r = choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
                    898:            sprop[PROPOSAL_SERVER_HOST_KEY_ALGS])) != 0) {
                    899:                kex->failed_choice = peer[PROPOSAL_SERVER_HOST_KEY_ALGS];
                    900:                peer[PROPOSAL_SERVER_HOST_KEY_ALGS] = NULL;
                    901:                goto out;
                    902:        }
1.1       markus    903:        for (mode = 0; mode < MODE_MAX; mode++) {
1.102     markus    904:                if ((newkeys = calloc(1, sizeof(*newkeys))) == NULL) {
                    905:                        r = SSH_ERR_ALLOC_FAIL;
                    906:                        goto out;
                    907:                }
1.30      markus    908:                kex->newkeys[mode] = newkeys;
1.78      djm       909:                ctos = (!kex->server && mode == MODE_OUT) ||
                    910:                    (kex->server && mode == MODE_IN);
1.1       markus    911:                nenc  = ctos ? PROPOSAL_ENC_ALGS_CTOS  : PROPOSAL_ENC_ALGS_STOC;
                    912:                nmac  = ctos ? PROPOSAL_MAC_ALGS_CTOS  : PROPOSAL_MAC_ALGS_STOC;
                    913:                ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
1.102     markus    914:                if ((r = choose_enc(&newkeys->enc, cprop[nenc],
1.107     djm       915:                    sprop[nenc])) != 0) {
                    916:                        kex->failed_choice = peer[nenc];
                    917:                        peer[nenc] = NULL;
1.102     markus    918:                        goto out;
1.107     djm       919:                }
1.102     markus    920:                authlen = cipher_authlen(newkeys->enc.cipher);
1.88      markus    921:                /* ignore mac for authenticated encryption */
1.102     markus    922:                if (authlen == 0 &&
                    923:                    (r = choose_mac(ssh, &newkeys->mac, cprop[nmac],
1.107     djm       924:                    sprop[nmac])) != 0) {
                    925:                        kex->failed_choice = peer[nmac];
                    926:                        peer[nmac] = NULL;
1.102     markus    927:                        goto out;
1.107     djm       928:                }
1.102     markus    929:                if ((r = choose_comp(&newkeys->comp, cprop[ncomp],
1.107     djm       930:                    sprop[ncomp])) != 0) {
                    931:                        kex->failed_choice = peer[ncomp];
                    932:                        peer[ncomp] = NULL;
1.102     markus    933:                        goto out;
1.107     djm       934:                }
1.110     djm       935:                debug("kex: %s cipher: %s MAC: %s compression: %s",
1.1       markus    936:                    ctos ? "client->server" : "server->client",
1.27      markus    937:                    newkeys->enc.name,
1.88      markus    938:                    authlen == 0 ? newkeys->mac.name : "<implicit>",
1.27      markus    939:                    newkeys->comp.name);
1.107     djm       940:        }
1.96      dtucker   941:        need = dh_need = 0;
1.1       markus    942:        for (mode = 0; mode < MODE_MAX; mode++) {
1.30      markus    943:                newkeys = kex->newkeys[mode];
1.120     deraadt   944:                need = MAXIMUM(need, newkeys->enc.key_len);
                    945:                need = MAXIMUM(need, newkeys->enc.block_size);
                    946:                need = MAXIMUM(need, newkeys->enc.iv_len);
                    947:                need = MAXIMUM(need, newkeys->mac.key_len);
                    948:                dh_need = MAXIMUM(dh_need, cipher_seclen(newkeys->enc.cipher));
                    949:                dh_need = MAXIMUM(dh_need, newkeys->enc.block_size);
                    950:                dh_need = MAXIMUM(dh_need, newkeys->enc.iv_len);
                    951:                dh_need = MAXIMUM(dh_need, newkeys->mac.key_len);
1.1       markus    952:        }
1.7       markus    953:        /* XXX need runden? */
1.27      markus    954:        kex->we_need = need;
1.96      dtucker   955:        kex->dh_need = dh_need;
1.53      markus    956:
                    957:        /* ignore the next message if the proposals do not match */
1.135     djm       958:        if (first_kex_follows && !proposals_match(my, peer))
1.102     markus    959:                ssh->dispatch_skip_packets = 1;
                    960:        r = 0;
                    961:  out:
1.26      markus    962:        kex_prop_free(my);
                    963:        kex_prop_free(peer);
1.102     markus    964:        return r;
1.26      markus    965: }
                    966:
1.102     markus    967: static int
                    968: derive_key(struct ssh *ssh, int id, u_int need, u_char *hash, u_int hashlen,
                    969:     const struct sshbuf *shared_secret, u_char **keyp)
1.26      markus    970: {
1.102     markus    971:        struct kex *kex = ssh->kex;
                    972:        struct ssh_digest_ctx *hashctx = NULL;
1.26      markus    973:        char c = id;
1.61      djm       974:        u_int have;
1.94      djm       975:        size_t mdsz;
1.61      djm       976:        u_char *digest;
1.102     markus    977:        int r;
1.62      djm       978:
1.94      djm       979:        if ((mdsz = ssh_digest_bytes(kex->hash_alg)) == 0)
1.102     markus    980:                return SSH_ERR_INVALID_ARGUMENT;
1.120     deraadt   981:        if ((digest = calloc(1, ROUNDUP(need, mdsz))) == NULL) {
1.102     markus    982:                r = SSH_ERR_ALLOC_FAIL;
                    983:                goto out;
                    984:        }
1.26      markus    985:
1.30      markus    986:        /* K1 = HASH(K || H || "A" || session_id) */
1.102     markus    987:        if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
                    988:            ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
1.94      djm       989:            ssh_digest_update(hashctx, hash, hashlen) != 0 ||
                    990:            ssh_digest_update(hashctx, &c, 1) != 0 ||
                    991:            ssh_digest_update(hashctx, kex->session_id,
1.102     markus    992:            kex->session_id_len) != 0 ||
                    993:            ssh_digest_final(hashctx, digest, mdsz) != 0) {
                    994:                r = SSH_ERR_LIBCRYPTO_ERROR;
1.152     djm       995:                error("%s: KEX hash failed", __func__);
1.102     markus    996:                goto out;
                    997:        }
1.94      djm       998:        ssh_digest_free(hashctx);
1.102     markus    999:        hashctx = NULL;
1.26      markus   1000:
1.30      markus   1001:        /*
                   1002:         * expand key:
                   1003:         * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
                   1004:         * Key = K1 || K2 || ... || Kn
                   1005:         */
1.26      markus   1006:        for (have = mdsz; need > have; have += mdsz) {
1.102     markus   1007:                if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
                   1008:                    ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
1.94      djm      1009:                    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
1.102     markus   1010:                    ssh_digest_update(hashctx, digest, have) != 0 ||
                   1011:                    ssh_digest_final(hashctx, digest + have, mdsz) != 0) {
1.152     djm      1012:                        error("%s: KDF failed", __func__);
1.102     markus   1013:                        r = SSH_ERR_LIBCRYPTO_ERROR;
                   1014:                        goto out;
                   1015:                }
1.94      djm      1016:                ssh_digest_free(hashctx);
1.102     markus   1017:                hashctx = NULL;
1.26      markus   1018:        }
                   1019: #ifdef DEBUG_KEX
                   1020:        fprintf(stderr, "key '%c'== ", c);
                   1021:        dump_digest("key", digest, need);
                   1022: #endif
1.102     markus   1023:        *keyp = digest;
                   1024:        digest = NULL;
                   1025:        r = 0;
                   1026:  out:
1.114     mmcc     1027:        free(digest);
1.102     markus   1028:        ssh_digest_free(hashctx);
                   1029:        return r;
1.1       markus   1030: }
                   1031:
1.23      markus   1032: #define NKEYS  6
1.102     markus   1033: int
                   1034: kex_derive_keys(struct ssh *ssh, u_char *hash, u_int hashlen,
                   1035:     const struct sshbuf *shared_secret)
1.1       markus   1036: {
1.102     markus   1037:        struct kex *kex = ssh->kex;
1.15      markus   1038:        u_char *keys[NKEYS];
1.102     markus   1039:        u_int i, j, mode, ctos;
                   1040:        int r;
1.1       markus   1041:
1.144     djm      1042:        /* save initial hash as session id */
                   1043:        if (kex->session_id == NULL) {
                   1044:                kex->session_id_len = hashlen;
                   1045:                kex->session_id = malloc(kex->session_id_len);
                   1046:                if (kex->session_id == NULL)
                   1047:                        return SSH_ERR_ALLOC_FAIL;
                   1048:                memcpy(kex->session_id, hash, kex->session_id_len);
                   1049:        }
1.65      djm      1050:        for (i = 0; i < NKEYS; i++) {
1.102     markus   1051:                if ((r = derive_key(ssh, 'A'+i, kex->we_need, hash, hashlen,
                   1052:                    shared_secret, &keys[i])) != 0) {
                   1053:                        for (j = 0; j < i; j++)
                   1054:                                free(keys[j]);
                   1055:                        return r;
                   1056:                }
1.65      djm      1057:        }
1.1       markus   1058:        for (mode = 0; mode < MODE_MAX; mode++) {
1.69      deraadt  1059:                ctos = (!kex->server && mode == MODE_OUT) ||
                   1060:                    (kex->server && mode == MODE_IN);
1.100     markus   1061:                kex->newkeys[mode]->enc.iv  = keys[ctos ? 0 : 1];
                   1062:                kex->newkeys[mode]->enc.key = keys[ctos ? 2 : 3];
                   1063:                kex->newkeys[mode]->mac.key = keys[ctos ? 4 : 5];
1.1       markus   1064:        }
1.102     markus   1065:        return 0;
1.95      djm      1066: }
1.57      djm      1067:
1.145     djm      1068: int
1.150     djm      1069: kex_load_hostkey(struct ssh *ssh, struct sshkey **prvp, struct sshkey **pubp)
1.145     djm      1070: {
                   1071:        struct kex *kex = ssh->kex;
                   1072:
                   1073:        *pubp = NULL;
                   1074:        *prvp = NULL;
                   1075:        if (kex->load_host_public_key == NULL ||
1.152     djm      1076:            kex->load_host_private_key == NULL) {
                   1077:                error("%s: missing hostkey loader", __func__);
1.145     djm      1078:                return SSH_ERR_INVALID_ARGUMENT;
1.152     djm      1079:        }
1.145     djm      1080:        *pubp = kex->load_host_public_key(kex->hostkey_type,
                   1081:            kex->hostkey_nid, ssh);
                   1082:        *prvp = kex->load_host_private_key(kex->hostkey_type,
                   1083:            kex->hostkey_nid, ssh);
                   1084:        if (*pubp == NULL)
                   1085:                return SSH_ERR_NO_HOSTKEY_LOADED;
1.146     djm      1086:        return 0;
                   1087: }
                   1088:
                   1089: int
                   1090: kex_verify_host_key(struct ssh *ssh, struct sshkey *server_host_key)
                   1091: {
                   1092:        struct kex *kex = ssh->kex;
                   1093:
1.152     djm      1094:        if (kex->verify_host_key == NULL) {
                   1095:                error("%s: missing hostkey verifier", __func__);
1.146     djm      1096:                return SSH_ERR_INVALID_ARGUMENT;
1.152     djm      1097:        }
1.146     djm      1098:        if (server_host_key->type != kex->hostkey_type ||
                   1099:            (kex->hostkey_type == KEY_ECDSA &&
                   1100:            server_host_key->ecdsa_nid != kex->hostkey_nid))
                   1101:                return SSH_ERR_KEY_TYPE_MISMATCH;
                   1102:        if (kex->verify_host_key(server_host_key, ssh) == -1)
                   1103:                return  SSH_ERR_SIGNATURE_INVALID;
1.145     djm      1104:        return 0;
                   1105: }
1.26      markus   1106:
1.84      djm      1107: #if defined(DEBUG_KEX) || defined(DEBUG_KEXDH) || defined(DEBUG_KEXECDH)
1.26      markus   1108: void
1.147     djm      1109: dump_digest(const char *msg, const u_char *digest, int len)
1.26      markus   1110: {
                   1111:        fprintf(stderr, "%s\n", msg);
1.102     markus   1112:        sshbuf_dump_data(digest, len, stderr);
1.26      markus   1113: }
                   1114: #endif
1.143     djm      1115:
                   1116: /*
                   1117:  * Send a plaintext error message to the peer, suffixed by \r\n.
                   1118:  * Only used during banner exchange, and there only for the server.
                   1119:  */
                   1120: static void
                   1121: send_error(struct ssh *ssh, char *msg)
                   1122: {
                   1123:        char *crnl = "\r\n";
                   1124:
                   1125:        if (!ssh->kex->server)
                   1126:                return;
                   1127:
                   1128:        if (atomicio(vwrite, ssh_packet_get_connection_out(ssh),
                   1129:            msg, strlen(msg)) != strlen(msg) ||
                   1130:            atomicio(vwrite, ssh_packet_get_connection_out(ssh),
                   1131:            crnl, strlen(crnl)) != strlen(crnl))
                   1132:                error("%s: write: %.100s", __func__, strerror(errno));
                   1133: }
                   1134:
                   1135: /*
                   1136:  * Sends our identification string and waits for the peer's. Will block for
                   1137:  * up to timeout_ms (or indefinitely if timeout_ms <= 0).
                   1138:  * Returns on 0 success or a ssherr.h code on failure.
                   1139:  */
                   1140: int
                   1141: kex_exchange_identification(struct ssh *ssh, int timeout_ms,
                   1142:     const char *version_addendum)
                   1143: {
                   1144:        int remote_major, remote_minor, mismatch;
                   1145:        size_t len, i, n;
                   1146:        int r, expect_nl;
                   1147:        u_char c;
                   1148:        struct sshbuf *our_version = ssh->kex->server ?
                   1149:            ssh->kex->server_version : ssh->kex->client_version;
                   1150:        struct sshbuf *peer_version = ssh->kex->server ?
                   1151:            ssh->kex->client_version : ssh->kex->server_version;
                   1152:        char *our_version_string = NULL, *peer_version_string = NULL;
                   1153:        char *cp, *remote_version = NULL;
                   1154:
                   1155:        /* Prepare and send our banner */
                   1156:        sshbuf_reset(our_version);
                   1157:        if (version_addendum != NULL && *version_addendum == '\0')
                   1158:                version_addendum = NULL;
                   1159:        if ((r = sshbuf_putf(our_version, "SSH-%d.%d-%.100s%s%s\r\n",
                   1160:           PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION,
                   1161:            version_addendum == NULL ? "" : " ",
                   1162:            version_addendum == NULL ? "" : version_addendum)) != 0) {
                   1163:                error("%s: sshbuf_putf: %s", __func__, ssh_err(r));
                   1164:                goto out;
                   1165:        }
                   1166:
                   1167:        if (atomicio(vwrite, ssh_packet_get_connection_out(ssh),
                   1168:            sshbuf_mutable_ptr(our_version),
                   1169:            sshbuf_len(our_version)) != sshbuf_len(our_version)) {
                   1170:                error("%s: write: %.100s", __func__, strerror(errno));
                   1171:                r = SSH_ERR_SYSTEM_ERROR;
                   1172:                goto out;
                   1173:        }
                   1174:        if ((r = sshbuf_consume_end(our_version, 2)) != 0) { /* trim \r\n */
                   1175:                error("%s: sshbuf_consume_end: %s", __func__, ssh_err(r));
                   1176:                goto out;
                   1177:        }
                   1178:        our_version_string = sshbuf_dup_string(our_version);
                   1179:        if (our_version_string == NULL) {
                   1180:                error("%s: sshbuf_dup_string failed", __func__);
                   1181:                r = SSH_ERR_ALLOC_FAIL;
                   1182:                goto out;
                   1183:        }
                   1184:        debug("Local version string %.100s", our_version_string);
                   1185:
                   1186:        /* Read other side's version identification. */
                   1187:        for (n = 0; ; n++) {
                   1188:                if (n >= SSH_MAX_PRE_BANNER_LINES) {
                   1189:                        send_error(ssh, "No SSH identification string "
                   1190:                            "received.");
                   1191:                        error("%s: No SSH version received in first %u lines "
                   1192:                            "from server", __func__, SSH_MAX_PRE_BANNER_LINES);
                   1193:                        r = SSH_ERR_INVALID_FORMAT;
                   1194:                        goto out;
                   1195:                }
                   1196:                sshbuf_reset(peer_version);
                   1197:                expect_nl = 0;
                   1198:                for (i = 0; ; i++) {
                   1199:                        if (timeout_ms > 0) {
                   1200:                                r = waitrfd(ssh_packet_get_connection_in(ssh),
                   1201:                                    &timeout_ms);
                   1202:                                if (r == -1 && errno == ETIMEDOUT) {
                   1203:                                        send_error(ssh, "Timed out waiting "
                   1204:                                            "for SSH identification string.");
                   1205:                                        error("Connection timed out during "
                   1206:                                            "banner exchange");
                   1207:                                        r = SSH_ERR_CONN_TIMEOUT;
                   1208:                                        goto out;
                   1209:                                } else if (r == -1) {
                   1210:                                        error("%s: %s",
                   1211:                                            __func__, strerror(errno));
                   1212:                                        r = SSH_ERR_SYSTEM_ERROR;
                   1213:                                        goto out;
                   1214:                                }
                   1215:                        }
                   1216:
                   1217:                        len = atomicio(read, ssh_packet_get_connection_in(ssh),
                   1218:                            &c, 1);
                   1219:                        if (len != 1 && errno == EPIPE) {
                   1220:                                error("%s: Connection closed by remote host",
                   1221:                                    __func__);
                   1222:                                r = SSH_ERR_CONN_CLOSED;
                   1223:                                goto out;
                   1224:                        } else if (len != 1) {
                   1225:                                error("%s: read: %.100s",
                   1226:                                    __func__, strerror(errno));
                   1227:                                r = SSH_ERR_SYSTEM_ERROR;
                   1228:                                goto out;
                   1229:                        }
                   1230:                        if (c == '\r') {
                   1231:                                expect_nl = 1;
                   1232:                                continue;
                   1233:                        }
                   1234:                        if (c == '\n')
                   1235:                                break;
                   1236:                        if (c == '\0' || expect_nl) {
                   1237:                                error("%s: banner line contains invalid "
                   1238:                                    "characters", __func__);
                   1239:                                goto invalid;
                   1240:                        }
                   1241:                        if ((r = sshbuf_put_u8(peer_version, c)) != 0) {
                   1242:                                error("%s: sshbuf_put: %s",
                   1243:                                    __func__, ssh_err(r));
                   1244:                                goto out;
                   1245:                        }
                   1246:                        if (sshbuf_len(peer_version) > SSH_MAX_BANNER_LEN) {
                   1247:                                error("%s: banner line too long", __func__);
                   1248:                                goto invalid;
                   1249:                        }
                   1250:                }
                   1251:                /* Is this an actual protocol banner? */
                   1252:                if (sshbuf_len(peer_version) > 4 &&
                   1253:                    memcmp(sshbuf_ptr(peer_version), "SSH-", 4) == 0)
                   1254:                        break;
                   1255:                /* If not, then just log the line and continue */
                   1256:                if ((cp = sshbuf_dup_string(peer_version)) == NULL) {
                   1257:                        error("%s: sshbuf_dup_string failed", __func__);
                   1258:                        r = SSH_ERR_ALLOC_FAIL;
                   1259:                        goto out;
                   1260:                }
                   1261:                /* Do not accept lines before the SSH ident from a client */
                   1262:                if (ssh->kex->server) {
                   1263:                        error("%s: client sent invalid protocol identifier "
                   1264:                            "\"%.256s\"", __func__, cp);
                   1265:                        free(cp);
                   1266:                        goto invalid;
                   1267:                }
                   1268:                debug("%s: banner line %zu: %s", __func__, n, cp);
                   1269:                free(cp);
                   1270:        }
                   1271:        peer_version_string = sshbuf_dup_string(peer_version);
                   1272:        if (peer_version_string == NULL)
                   1273:                error("%s: sshbuf_dup_string failed", __func__);
                   1274:        /* XXX must be same size for sscanf */
                   1275:        if ((remote_version = calloc(1, sshbuf_len(peer_version))) == NULL) {
                   1276:                error("%s: calloc failed", __func__);
                   1277:                r = SSH_ERR_ALLOC_FAIL;
                   1278:                goto out;
                   1279:        }
                   1280:
                   1281:        /*
                   1282:         * Check that the versions match.  In future this might accept
                   1283:         * several versions and set appropriate flags to handle them.
                   1284:         */
                   1285:        if (sscanf(peer_version_string, "SSH-%d.%d-%[^\n]\n",
                   1286:            &remote_major, &remote_minor, remote_version) != 3) {
                   1287:                error("Bad remote protocol version identification: '%.100s'",
                   1288:                    peer_version_string);
                   1289:  invalid:
                   1290:                send_error(ssh, "Invalid SSH identification string.");
                   1291:                r = SSH_ERR_INVALID_FORMAT;
                   1292:                goto out;
                   1293:        }
                   1294:        debug("Remote protocol version %d.%d, remote software version %.100s",
                   1295:            remote_major, remote_minor, remote_version);
                   1296:        ssh->compat = compat_datafellows(remote_version);
                   1297:
                   1298:        mismatch = 0;
                   1299:        switch (remote_major) {
                   1300:        case 2:
                   1301:                break;
                   1302:        case 1:
                   1303:                if (remote_minor != 99)
                   1304:                        mismatch = 1;
                   1305:                break;
                   1306:        default:
                   1307:                mismatch = 1;
                   1308:                break;
                   1309:        }
                   1310:        if (mismatch) {
                   1311:                error("Protocol major versions differ: %d vs. %d",
                   1312:                    PROTOCOL_MAJOR_2, remote_major);
                   1313:                send_error(ssh, "Protocol major versions differ.");
                   1314:                r = SSH_ERR_NO_PROTOCOL_VERSION;
                   1315:                goto out;
                   1316:        }
                   1317:
                   1318:        if (ssh->kex->server && (ssh->compat & SSH_BUG_PROBE) != 0) {
                   1319:                logit("probed from %s port %d with %s.  Don't panic.",
                   1320:                    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
                   1321:                    peer_version_string);
                   1322:                r = SSH_ERR_CONN_CLOSED; /* XXX */
                   1323:                goto out;
                   1324:        }
                   1325:        if (ssh->kex->server && (ssh->compat & SSH_BUG_SCANNER) != 0) {
                   1326:                logit("scanned from %s port %d with %s.  Don't panic.",
                   1327:                    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
                   1328:                    peer_version_string);
                   1329:                r = SSH_ERR_CONN_CLOSED; /* XXX */
                   1330:                goto out;
                   1331:        }
                   1332:        if ((ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
                   1333:                logit("Remote version \"%.100s\" uses unsafe RSA signature "
                   1334:                    "scheme; disabling use of RSA keys", remote_version);
                   1335:        }
                   1336:        /* success */
                   1337:        r = 0;
                   1338:  out:
                   1339:        free(our_version_string);
                   1340:        free(peer_version_string);
                   1341:        free(remote_version);
                   1342:        return r;
                   1343: }
                   1344: