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

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