From feab568a7ac8a53816c03c33c978336b7523bc18 Mon Sep 17 00:00:00 2001 From: Dan Fandrich Date: Thu, 6 Mar 2014 13:05:47 +0100 Subject: [PATCH] knownhosts: Abort if the hosts buffer is too small This could otherwise cause a match on the wrong host --- src/knownhost.c | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/src/knownhost.c b/src/knownhost.c index fee6fb8..f1169f6 100644 --- a/src/knownhost.c +++ b/src/knownhost.c @@ -368,6 +368,24 @@ knownhost_check(LIBSSH2_KNOWNHOSTS *hosts, /* we can't work with a sha1 as given input */ return LIBSSH2_KNOWNHOST_CHECK_MISMATCH; + /* if a port number is given, check for a '[host]:port' first before the + plain 'host' */ + if(port >= 0) { + int len = snprintf(hostbuff, sizeof(hostbuff), "[%s]:%d", hostp, port); + if (len < 0 || len >= (int)sizeof(hostbuff)) { + _libssh2_error(hosts->session, + LIBSSH2_ERROR_BUFFER_TOO_SMALL, + "Known-host write buffer too small"); + return LIBSSH2_KNOWNHOST_CHECK_FAILURE; + } + host = hostbuff; + numcheck = 2; /* check both combos, start with this */ + } + else { + host = hostp; + numcheck = 1; /* only check this host version */ + } + if(!(typemask & LIBSSH2_KNOWNHOST_KEYENC_BASE64)) { /* we got a raw key input, convert it to base64 for the checks below */ size_t nlen = _libssh2_base64_encode(hosts->session, key, keylen, @@ -383,18 +401,6 @@ knownhost_check(LIBSSH2_KNOWNHOSTS *hosts, key = keyalloc; } - /* if a port number is given, check for a '[host]:port' first before the - plain 'host' */ - if(port >= 0) { - snprintf(hostbuff, sizeof(hostbuff), "[%s]:%d", hostp, port); - host = hostbuff; - numcheck = 2; /* check both combos, start with this */ - } - else { - host = hostp; - numcheck = 1; /* only check this host version */ - } - do { node = _libssh2_list_first(&hosts->head); while (node) {