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

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