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

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