1 /*
2  * ProFTPD - mod_sftp key exchange (kex)
3  * Copyright (c) 2008-2020 TJ Saunders
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
18  *
19  * As a special exemption, TJ Saunders and other respective copyright holders
20  * give permission to link this program with OpenSSL, and distribute the
21  * resulting executable, without including the source code for OpenSSL in the
22  * source distribution.
23  */
24 
25 #include "mod_sftp.h"
26 #include "ssh2.h"
27 #include "msg.h"
28 #include "packet.h"
29 #include "session.h"
30 #include "cipher.h"
31 #include "mac.h"
32 #include "compress.h"
33 #include "kex.h"
34 #include "keys.h"
35 #include "crypto.h"
36 #include "disconnect.h"
37 #include "interop.h"
38 #include "tap.h"
39 #include "misc.h"
40 
41 #ifdef PR_USE_SODIUM
42 # include <sodium.h>
43 # define CURVE25519_SIZE	32
44 #endif /* PR_USE_SODIUM */
45 
46 /* Define the minimum DH group length we allow (unless the AllowWeakDH
47  * SFTPOption is used).
48  */
49 #define SFTP_DH_MIN_LEN			2048
50 
51 extern pr_response_t *resp_list, *resp_err_list;
52 extern module sftp_module;
53 
54 /* For managing the kexinit process */
55 static pool *kex_pool = NULL;
56 
57 static int kex_rekey_interval = 0;
58 static int kex_rekey_timeout = 0;
59 static int kex_rekey_timerno = -1;
60 static int kex_rekey_timeout_timerno = -1;
61 
62 struct sftp_kex_names {
63   const char *kex_algo;
64   const char *server_hostkey_algo;
65   const char *c2s_encrypt_algo;
66   const char *s2c_encrypt_algo;
67   const char *c2s_mac_algo;
68   const char *s2c_mac_algo;
69   const char *c2s_comp_algo;
70   const char *s2c_comp_algo;
71   const char *c2s_lang;
72   const char *s2c_lang;
73 };
74 
75 struct sftp_kex {
76   pool *pool;
77 
78   /* Versions */
79   const char *client_version;
80   const char *server_version;
81 
82   /* KEXINIT lists from client */
83   struct sftp_kex_names *client_names;
84 
85   /* KEXINIT lists from server. */
86   struct sftp_kex_names *server_names;
87 
88   /* Session algorithms */
89   struct sftp_kex_names *session_names;
90 
91   /* For constructing the session ID/hash */
92   unsigned char *client_kexinit_payload;
93   size_t client_kexinit_payload_len;
94 
95   unsigned char *server_kexinit_payload;
96   size_t server_kexinit_payload_len;
97 
98   int first_kex_follows;
99 
100   /* Client-preferred hostkey type, based on algorithm:
101    *
102    *  "ssh-dss"      --> SFTP_KEY_DSA
103    *  "ssh-rsa"      --> SFTP_KEY_RSA
104    *  "ecdsa-sha2-*" --> SFTP_KEY_ECDSA_*
105    *  "ssh-ed25519"  --> SFTP_KEY_ED25519
106    *  "rsa-sha2-256" --> SFTP_KEY_RSA_SHA256
107    *  "rsa-sha2-512" --> SFTP_KEY_RSA_SHA512
108    */
109   enum sftp_key_type_e use_hostkey_type;
110 
111   /* Using DH group-exchange? */
112   int use_gex;
113 
114   /* Using RSA key exchange? */
115   int use_kexrsa;
116 
117   /* Using ECDH? */
118   int use_ecdh;
119 
120   /* Using Curve25519? */
121   int use_curve25519;
122 
123   /* Using extension negotiations? */
124   int use_ext_info;
125 
126   /* For generating the session ID */
127   DH *dh;
128   BIGNUM *e;
129   const EVP_MD *hash;
130 
131   BIGNUM *k;
132   const char *h;
133   uint32_t hlen;
134 
135   RSA *rsa;
136   unsigned char *rsa_encrypted;
137   uint32_t rsa_encrypted_len;
138 
139 #ifdef PR_USE_OPENSSL_ECC
140   EC_KEY *ec;
141   EC_POINT *client_point;
142 #endif /* PR_USE_OPENSSL_ECC */
143 #if defined(PR_USE_SODIUM) && defined(HAVE_SHA256_OPENSSL)
144   unsigned char *client_curve25519;
145 #endif /* PR_USE_SODIUM and HAVE_SHA256_OPENSSL */
146 };
147 
148 static struct sftp_kex *kex_first_kex = NULL;
149 static struct sftp_kex *kex_rekey_kex = NULL;
150 static int kex_sent_kexinit = FALSE;
151 
152 /* Diffie-Hellman group moduli */
153 
154 static const char *dh_group1_str =
155   "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74"
156   "020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437"
157   "4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
158   "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF";
159 
160 static const char *dh_group14_str =
161   "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74"
162   "020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437"
163   "4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
164   "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05"
165   "98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB"
166   "9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
167   "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
168   "3995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF";
169 
170 static const char *dh_group16_str =
171   "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
172   "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
173   "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
174   "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
175   "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
176   "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
177   "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
178   "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
179   "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
180   "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
181   "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
182   "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
183   "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
184   "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
185   "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
186   "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7"
187   "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA"
188   "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6"
189   "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED"
190   "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9"
191   "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199"
192   "FFFFFFFFFFFFFFFF";
193 
194 static const char *dh_group18_str =
195   "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
196   "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
197   "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
198   "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
199   "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
200   "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
201   "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
202   "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
203   "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"
204   "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
205   "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"
206   "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
207   "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"
208   "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
209   "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"
210   "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7"
211   "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA"
212   "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6"
213   "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED"
214   "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9"
215   "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492"
216   "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD"
217   "F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831"
218   "179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
219   "DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF"
220   "5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6"
221   "D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3"
222   "23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA"
223   "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328"
224   "06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C"
225   "DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE"
226   "12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4"
227   "38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300"
228   "741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568"
229   "3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9"
230   "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B"
231   "4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A"
232   "062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36"
233   "4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1"
234   "B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92"
235   "4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47"
236   "9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71"
237   "60C980DD98EDD3DFFFFFFFFFFFFFFFFF";
238 
239 
240 #define SFTP_DH_GROUP1_SHA1		1
241 #define SFTP_DH_GROUP14_SHA1		2
242 #define SFTP_DH_GEX_SHA1		3
243 #define SFTP_DH_GEX_SHA256		4
244 #define SFTP_KEXRSA_SHA1		5
245 #define SFTP_KEXRSA_SHA256		6
246 #define SFTP_ECDH_SHA256		7
247 #define SFTP_ECDH_SHA384		8
248 #define SFTP_ECDH_SHA512		9
249 #define SFTP_DH_GROUP14_SHA256		10
250 #define SFTP_DH_GROUP16_SHA512		11
251 #define SFTP_DH_GROUP18_SHA512		12
252 
253 #define SFTP_KEXRSA_SHA1_SIZE		2048
254 #define SFTP_KEXRSA_SHA256_SIZE		3072
255 
256 static const char *kex_client_version = NULL;
257 static const char *kex_server_version = NULL;
258 static unsigned char kex_digest_buf[EVP_MAX_MD_SIZE];
259 
260 /* Used for access to a SFTPDHParamsFile during rekeys, even if the process
261  * has chrooted itself.
262  */
263 static FILE *kex_dhparams_fp = NULL;
264 
265 /* Necessary prototypes. */
266 static struct ssh2_packet *read_kex_packet(pool *, struct sftp_kex *, int,
267   char *, unsigned int, ...);
268 
269 static const char *trace_channel = "ssh2";
270 
kex_rekey_timeout_cb(CALLBACK_FRAME)271 static int kex_rekey_timeout_cb(CALLBACK_FRAME) {
272   pr_trace_msg(trace_channel, 5,
273     "Failed to rekey before %d %s timeout, disconnecting client",
274     kex_rekey_timeout, kex_rekey_timeout != 1 ? "seconds" : "second");
275   (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
276     "Failed to rekey before %d %s timeout, disconnecting client",
277     kex_rekey_timeout, kex_rekey_timeout != 1 ? "seconds" : "second");
278   SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
279   return 0;
280 }
281 
kex_rekey_timer_cb(CALLBACK_FRAME)282 static int kex_rekey_timer_cb(CALLBACK_FRAME) {
283   pr_trace_msg(trace_channel, 17,
284     "SFTPRekey timer (%d %s) expired, requesting rekey", kex_rekey_interval,
285     kex_rekey_interval != 1 ? "secs" : "sec");
286   sftp_kex_rekey();
287   return 0;
288 }
289 
calculate_h(struct sftp_kex * kex,const unsigned char * hostkey_data,uint32_t hostkey_datalen,const BIGNUM * k,uint32_t * hlen)290 static const unsigned char *calculate_h(struct sftp_kex *kex,
291     const unsigned char *hostkey_data, uint32_t hostkey_datalen,
292     const BIGNUM *k, uint32_t *hlen) {
293 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
294     defined(HAVE_LIBRESSL)
295   EVP_MD_CTX ctx;
296 #endif /* prior to OpenSSL-1.1.0 */
297   EVP_MD_CTX *pctx;
298   const BIGNUM *dh_pub_key = NULL;
299   unsigned char *buf, *ptr;
300   uint32_t buflen, bufsz;
301 
302   bufsz = buflen = 8192;
303 
304   /* XXX Is this buffer large enough? Too large? */
305   ptr = buf = sftp_msg_getbuf(kex_pool, bufsz);
306 
307   /* Write all of the data into the buffer in the SSH2 format, and hash it. */
308 
309   /* First, the version strings */
310   sftp_msg_write_string(&buf, &buflen, kex->client_version);
311   sftp_msg_write_string(&buf, &buflen, kex->server_version);
312 
313   /* Client's KEXINIT */
314   sftp_msg_write_int(&buf, &buflen, kex->client_kexinit_payload_len + 1);
315   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEXINIT);
316   sftp_msg_write_data(&buf, &buflen, kex->client_kexinit_payload,
317     kex->client_kexinit_payload_len, FALSE);
318 
319   /* Server's KEXINIT */
320   sftp_msg_write_int(&buf, &buflen, kex->server_kexinit_payload_len + 1);
321   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEXINIT);
322   sftp_msg_write_data(&buf, &buflen, kex->server_kexinit_payload,
323     kex->server_kexinit_payload_len, FALSE);
324 
325   /* Hostkey data */
326   sftp_msg_write_data(&buf, &buflen, hostkey_data, hostkey_datalen, TRUE);
327 
328   /* Client's key */
329   sftp_msg_write_mpint(&buf, &buflen, kex->e);
330 
331   /* Server's key */
332 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
333     !defined(HAVE_LIBRESSL)
334   DH_get0_key(kex->dh, &dh_pub_key, NULL);
335 #else
336   dh_pub_key = kex->dh->pub_key;
337 #endif /* prior to OpenSSL-1.1.0 */
338   sftp_msg_write_mpint(&buf, &buflen, dh_pub_key);
339 
340   /* Shared secret */
341   sftp_msg_write_mpint(&buf, &buflen, k);
342 
343 #if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
344     !defined(HAVE_LIBRESSL)
345   pctx = EVP_MD_CTX_new();
346 #else
347   pctx = &ctx;
348 #endif /* OpenSSL-1.1.0 and later */
349 
350   /* In OpenSSL 0.9.6, many of the EVP_Digest* functions returned void, not
351    * int.  Without these ugly OpenSSL version preprocessor checks, the
352    * compiler will error out with "void value not ignored as it ought to be".
353    */
354 
355 #if OPENSSL_VERSION_NUMBER >= 0x000907000L
356   if (EVP_DigestInit(pctx, kex->hash) != 1) {
357     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
358       "error initializing message digest: %s", sftp_crypto_get_errors());
359     BN_clear_free(kex->e);
360     kex->e = NULL;
361     pr_memscrub(ptr, bufsz);
362 # if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
363      !defined(HAVE_LIBRESSL)
364     EVP_MD_CTX_free(pctx);
365 # endif /* OpenSSL-1.1.0 and later */
366     return NULL;
367   }
368 #else
369   EVP_DigestInit(pctx, kex->hash);
370 #endif
371 
372 #if OPENSSL_VERSION_NUMBER >= 0x000907000L
373   if (EVP_DigestUpdate(pctx, ptr, (bufsz - buflen)) != 1) {
374     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
375       "error updating message digest: %s", sftp_crypto_get_errors());
376     BN_clear_free(kex->e);
377     kex->e = NULL;
378     pr_memscrub(ptr, bufsz);
379 # if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
380      !defined(HAVE_LIBRESSL)
381     EVP_MD_CTX_free(pctx);
382 # endif /* OpenSSL-1.1.0 and later */
383     return NULL;
384   }
385 #else
386   EVP_DigestUpdate(pctx, ptr, (bufsz - buflen));
387 #endif
388 
389 #if OPENSSL_VERSION_NUMBER >= 0x000907000L
390   if (EVP_DigestFinal(pctx, kex_digest_buf, hlen) != 1) {
391     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
392       "error finalizing message digest: %s", sftp_crypto_get_errors());
393     BN_clear_free(kex->e);
394     kex->e = NULL;
395     pr_memscrub(ptr, bufsz);
396 # if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
397      !defined(HAVE_LIBRESSL)
398     EVP_MD_CTX_free(pctx);
399 # endif /* OpenSSL-1.1.0 and later */
400     return NULL;
401   }
402 #else
403   EVP_DigestFinal(pctx, kex_digest_buf, hlen);
404 #endif
405 
406 #if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
407     !defined(HAVE_LIBRESSL)
408   EVP_MD_CTX_free(pctx);
409 #endif /* OpenSSL-1.1.0 and later */
410 
411   BN_clear_free(kex->e);
412   kex->e = NULL;
413 
414   pr_memscrub(ptr, bufsz);
415   return kex_digest_buf;
416 }
417 
calculate_gex_h(struct sftp_kex * kex,const unsigned char * hostkey_data,uint32_t hostkey_datalen,const BIGNUM * k,uint32_t min,uint32_t pref,uint32_t max,uint32_t * hlen)418 static const unsigned char *calculate_gex_h(struct sftp_kex *kex,
419     const unsigned char *hostkey_data, uint32_t hostkey_datalen,
420     const BIGNUM *k, uint32_t min, uint32_t pref, uint32_t max,
421     uint32_t *hlen) {
422 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
423     defined(HAVE_LIBRESSL)
424   EVP_MD_CTX ctx;
425 #endif /* prior to OpenSSL-1.1.0 */
426   EVP_MD_CTX *pctx;
427   const BIGNUM *dh_p = NULL, *dh_g = NULL, *dh_pub_key = NULL;
428   unsigned char *buf, *ptr;
429   uint32_t buflen, bufsz;
430 
431   bufsz = buflen = 8192;
432 
433   /* XXX Is this buffer large enough? Too large? */
434   ptr = buf = sftp_msg_getbuf(kex_pool, bufsz);
435 
436   /* Write all of the data into the buffer in the SSH2 format, and hash it.
437    * The ordering of these fields is described in RFC4419.
438    */
439 
440   /* First, the version strings */
441   sftp_msg_write_string(&buf, &buflen, kex->client_version);
442   sftp_msg_write_string(&buf, &buflen, kex->server_version);
443 
444   /* Client's KEXINIT */
445   sftp_msg_write_int(&buf, &buflen, kex->client_kexinit_payload_len + 1);
446   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEXINIT);
447   sftp_msg_write_data(&buf, &buflen, kex->client_kexinit_payload,
448     kex->client_kexinit_payload_len, FALSE);
449 
450   /* Server's KEXINIT */
451   sftp_msg_write_int(&buf, &buflen, kex->server_kexinit_payload_len + 1);
452   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEXINIT);
453   sftp_msg_write_data(&buf, &buflen, kex->server_kexinit_payload,
454     kex->server_kexinit_payload_len, FALSE);
455 
456   /* Hostkey data */
457   sftp_msg_write_data(&buf, &buflen, hostkey_data, hostkey_datalen, TRUE);
458 
459   if (min == 0 ||
460       max == 0) {
461     sftp_msg_write_int(&buf, &buflen, pref);
462 
463   } else {
464     sftp_msg_write_int(&buf, &buflen, min);
465     sftp_msg_write_int(&buf, &buflen, pref);
466     sftp_msg_write_int(&buf, &buflen, max);
467   }
468 
469 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
470     !defined(HAVE_LIBRESSL)
471   DH_get0_pqg(kex->dh, &dh_p, NULL, &dh_g);
472 #else
473   dh_p = kex->dh->p;
474   dh_g = kex->dh->g;
475 #endif /* prior to OpenSSL-1.1.0 */
476   sftp_msg_write_mpint(&buf, &buflen, dh_p);
477   sftp_msg_write_mpint(&buf, &buflen, dh_g);
478 
479   /* Client's key */
480   sftp_msg_write_mpint(&buf, &buflen, kex->e);
481 
482   /* Server's key */
483 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
484     !defined(HAVE_LIBRESSL)
485   DH_get0_key(kex->dh, &dh_pub_key, NULL);
486 #else
487   dh_pub_key = kex->dh->pub_key;
488 #endif /* prior to OpenSSL-1.1.0 */
489   sftp_msg_write_mpint(&buf, &buflen, dh_pub_key);
490 
491   /* Shared secret */
492   sftp_msg_write_mpint(&buf, &buflen, k);
493 
494 #if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
495     !defined(HAVE_LIBRESSL)
496   pctx = EVP_MD_CTX_new();
497 #else
498   pctx = &ctx;
499 #endif /* OpenSSL-1.1.0 and later */
500 
501   /* In OpenSSL 0.9.6, many of the EVP_Digest* functions returned void, not
502    * int.  Without these ugly OpenSSL version preprocessor checks, the
503    * compiler will error out with "void value not ignored as it ought to be".
504    */
505 
506 #if OPENSSL_VERSION_NUMBER >= 0x000907000L
507   if (EVP_DigestInit(pctx, kex->hash) != 1) {
508     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
509       "error initializing message digest: %s", sftp_crypto_get_errors());
510     BN_clear_free(kex->e);
511     kex->e = NULL;
512     pr_memscrub(ptr, bufsz);
513 # if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
514      !defined(HAVE_LIBRESSL)
515     EVP_MD_CTX_free(pctx);
516 # endif /* OpenSSL-1.1.0 and later */
517     return NULL;
518   }
519 #else
520   EVP_DigestInit(pctx, kex->hash);
521 #endif
522 
523 #if OPENSSL_VERSION_NUMBER >= 0x000907000L
524   if (EVP_DigestUpdate(pctx, ptr, (bufsz - buflen)) != 1) {
525     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
526       "error updating message digest: %s", sftp_crypto_get_errors());
527     BN_clear_free(kex->e);
528     kex->e = NULL;
529     pr_memscrub(ptr, bufsz);
530 # if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
531      !defined(HAVE_LIBRESSL)
532     EVP_MD_CTX_free(pctx);
533 # endif /* OpenSSL-1.1.0 and later */
534     return NULL;
535   }
536 #else
537   EVP_DigestUpdate(pctx, ptr, (bufsz - buflen));
538 #endif
539 
540 #if OPENSSL_VERSION_NUMBER >= 0x000907000L
541   if (EVP_DigestFinal(pctx, kex_digest_buf, hlen) != 1) {
542     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
543       "error finalizing message digest: %s", sftp_crypto_get_errors());
544     BN_clear_free(kex->e);
545     kex->e = NULL;
546     pr_memscrub(ptr, bufsz);
547 # if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
548      !defined(HAVE_LIBRESSL)
549     EVP_MD_CTX_free(pctx);
550 # endif /* OpenSSL-1.1.0 and later */
551     return NULL;
552   }
553 #else
554   EVP_DigestFinal(pctx, kex_digest_buf, hlen);
555 #endif
556 
557 #if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
558     !defined(HAVE_LIBRESSL)
559   EVP_MD_CTX_free(pctx);
560 #endif /* OpenSSL-1.1.0 and later */
561   BN_clear_free(kex->e);
562   kex->e = NULL;
563   pr_memscrub(ptr, bufsz);
564 
565   return kex_digest_buf;
566 }
567 
calculate_kexrsa_h(struct sftp_kex * kex,const unsigned char * hostkey_data,uint32_t hostkey_datalen,const BIGNUM * k,unsigned char * rsa_key,uint32_t rsa_keylen,uint32_t * hlen)568 static const unsigned char *calculate_kexrsa_h(struct sftp_kex *kex,
569     const unsigned char *hostkey_data, uint32_t hostkey_datalen,
570     const BIGNUM *k, unsigned char *rsa_key, uint32_t rsa_keylen,
571     uint32_t *hlen) {
572 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
573     defined(HAVE_LIBRESSL)
574   EVP_MD_CTX ctx;
575 #endif /* prior to OpenSSL-1.1.0 */
576   EVP_MD_CTX *pctx;
577   unsigned char *buf, *ptr;
578   uint32_t buflen, bufsz;
579 
580   bufsz = buflen = 4096;
581 
582   /* XXX Is this buffer large enough? Too large? */
583   ptr = buf = sftp_msg_getbuf(kex_pool, bufsz);
584 
585   /* Write all of the data into the buffer in the SSH2 format, and hash it. */
586 
587   /* First, the version strings */
588   sftp_msg_write_string(&buf, &buflen, kex->client_version);
589   sftp_msg_write_string(&buf, &buflen, kex->server_version);
590 
591   /* Client's KEXINIT */
592   sftp_msg_write_int(&buf, &buflen, kex->client_kexinit_payload_len + 1);
593   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEXINIT);
594   sftp_msg_write_data(&buf, &buflen, kex->client_kexinit_payload,
595     kex->client_kexinit_payload_len, FALSE);
596 
597   /* Server's KEXINIT */
598   sftp_msg_write_int(&buf, &buflen, kex->server_kexinit_payload_len + 1);
599   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEXINIT);
600   sftp_msg_write_data(&buf, &buflen, kex->server_kexinit_payload,
601     kex->server_kexinit_payload_len, FALSE);
602 
603   /* Hostkey data */
604   sftp_msg_write_data(&buf, &buflen, hostkey_data, hostkey_datalen, TRUE);
605 
606   /* Transient RSA public key */
607   sftp_msg_write_data(&buf, &buflen, rsa_key, rsa_keylen, TRUE);
608 
609   /* RSA-encrypted secret */
610   sftp_msg_write_data(&buf, &buflen, kex->rsa_encrypted, kex->rsa_encrypted_len,
611     TRUE);
612 
613   /* Shared secret. */
614   sftp_msg_write_mpint(&buf, &buflen, k);
615 
616 #if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
617     !defined(HAVE_LIBRESSL)
618   pctx = EVP_MD_CTX_new();
619 #else
620   pctx = &ctx;
621 #endif /* OpenSSL-1.1.0 and later */
622 
623   /* In OpenSSL 0.9.6, many of the EVP_Digest* functions returned void, not
624    * int.  Without these ugly OpenSSL version preprocessor checks, the
625    * compiler will error out with "void value not ignored as it ought to be".
626    */
627 
628 #if OPENSSL_VERSION_NUMBER >= 0x000907000L
629   if (EVP_DigestInit(pctx, kex->hash) != 1) {
630     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
631       "error initializing message digest: %s", sftp_crypto_get_errors());
632     pr_memscrub(ptr, bufsz);
633 # if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
634      !defined(HAVE_LIBRESSL)
635     EVP_MD_CTX_free(pctx);
636 # endif /* OpenSSL-1.1.0 and later */
637     return NULL;
638   }
639 #else
640   EVP_DigestInit(pctx, kex->hash);
641 #endif
642 
643 #if OPENSSL_VERSION_NUMBER >= 0x000907000L
644   if (EVP_DigestUpdate(pctx, ptr, (bufsz - buflen)) != 1) {
645     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
646       "error updating message digest: %s", sftp_crypto_get_errors());
647     pr_memscrub(ptr, bufsz);
648 # if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
649      !defined(HAVE_LIBRESSL)
650     EVP_MD_CTX_free(pctx);
651 # endif /* OpenSSL-1.1.0 and later */
652     return NULL;
653   }
654 #else
655   EVP_DigestUpdate(pctx, ptr, (bufsz - buflen));
656 #endif
657 
658 #if OPENSSL_VERSION_NUMBER >= 0x000907000L
659   if (EVP_DigestFinal(pctx, kex_digest_buf, hlen) != 1) {
660     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
661       "error finalizing message digest: %s", sftp_crypto_get_errors());
662     pr_memscrub(ptr, bufsz);
663 # if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
664      !defined(HAVE_LIBRESSL)
665     EVP_MD_CTX_free(pctx);
666 # endif /* OpenSSL-1.1.0 and later */
667     return NULL;
668   }
669 #else
670   EVP_DigestFinal(pctx, kex_digest_buf, hlen);
671 #endif
672 
673 #if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
674     !defined(HAVE_LIBRESSL)
675   EVP_MD_CTX_free(pctx);
676 #endif /* OpenSSL-1.1.0 and later */
677   pr_memscrub(ptr, bufsz);
678 
679   return kex_digest_buf;
680 }
681 
682 #ifdef PR_USE_OPENSSL_ECC
calculate_ecdh_h(struct sftp_kex * kex,const unsigned char * hostkey_data,uint32_t hostkey_datalen,const BIGNUM * k,uint32_t * hlen)683 static const unsigned char *calculate_ecdh_h(struct sftp_kex *kex,
684     const unsigned char *hostkey_data, uint32_t hostkey_datalen,
685     const BIGNUM *k, uint32_t *hlen) {
686 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
687     defined(HAVE_LIBRESSL)
688   EVP_MD_CTX ctx;
689 #endif /* prior to OpenSSL-1.1.0 */
690   EVP_MD_CTX *pctx;
691   unsigned char *buf, *ptr;
692   uint32_t buflen, bufsz;
693 
694   bufsz = buflen = 4096;
695 
696   /* XXX Is this buffer large enough? Too large? */
697   ptr = buf = sftp_msg_getbuf(kex_pool, bufsz);
698 
699   /* Write all of the data into the buffer in the SSH2 format, and hash it.
700    * The ordering of these fields is described in RFC5656.
701    */
702 
703   /* First, the version strings */
704   sftp_msg_write_string(&buf, &buflen, kex->client_version);
705   sftp_msg_write_string(&buf, &buflen, kex->server_version);
706 
707   /* Client's KEXINIT */
708   sftp_msg_write_int(&buf, &buflen, kex->client_kexinit_payload_len + 1);
709   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEXINIT);
710   sftp_msg_write_data(&buf, &buflen, kex->client_kexinit_payload,
711     kex->client_kexinit_payload_len, FALSE);
712 
713   /* Server's KEXINIT */
714   sftp_msg_write_int(&buf, &buflen, kex->server_kexinit_payload_len + 1);
715   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEXINIT);
716   sftp_msg_write_data(&buf, &buflen, kex->server_kexinit_payload,
717     kex->server_kexinit_payload_len, FALSE);
718 
719   /* Hostkey data */
720   sftp_msg_write_data(&buf, &buflen, hostkey_data, hostkey_datalen, TRUE);
721 
722   /* Client's key */
723   sftp_msg_write_ecpoint(&buf, &buflen, EC_KEY_get0_group(kex->ec),
724     kex->client_point);
725 
726   /* Server's key */
727   sftp_msg_write_ecpoint(&buf, &buflen, EC_KEY_get0_group(kex->ec),
728     EC_KEY_get0_public_key(kex->ec));
729 
730   /* Shared secret */
731   sftp_msg_write_mpint(&buf, &buflen, k);
732 
733 #if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
734     !defined(HAVE_LIBRESSL)
735   pctx = EVP_MD_CTX_new();
736 #else
737   pctx = &ctx;
738 #endif /* OpenSSL-1.1.0 and later */
739 
740   /* In OpenSSL 0.9.6, many of the EVP_Digest* functions returned void, not
741    * int.  Without these ugly OpenSSL version preprocessor checks, the
742    * compiler will error out with "void value not ignored as it ought to be".
743    */
744 
745 #if OPENSSL_VERSION_NUMBER >= 0x000907000L
746   if (EVP_DigestInit(pctx, kex->hash) != 1) {
747     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
748       "error initializing message digest: %s", sftp_crypto_get_errors());
749     BN_clear_free(kex->e);
750     kex->e = NULL;
751     pr_memscrub(ptr, bufsz);
752 # if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
753      !defined(HAVE_LIBRESSL)
754     EVP_MD_CTX_free(pctx);
755 # endif /* OpenSSL-1.1.0 and later */
756     return NULL;
757   }
758 #else
759   EVP_DigestInit(pctx, kex->hash);
760 #endif
761 
762 #if OPENSSL_VERSION_NUMBER >= 0x000907000L
763   if (EVP_DigestUpdate(pctx, ptr, (bufsz - buflen)) != 1) {
764     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
765       "error updating message digest: %s", sftp_crypto_get_errors());
766     BN_clear_free(kex->e);
767     kex->e = NULL;
768     pr_memscrub(ptr, bufsz);
769 # if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
770      !defined(HAVE_LIBRESSL)
771     EVP_MD_CTX_free(pctx);
772 # endif /* OpenSSL-1.1.0 and later */
773     return NULL;
774   }
775 #else
776   EVP_DigestUpdate(pctx, ptr, (bufsz - buflen));
777 #endif
778 
779 #if OPENSSL_VERSION_NUMBER >= 0x000907000L
780   if (EVP_DigestFinal(pctx, kex_digest_buf, hlen) != 1) {
781     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
782       "error finalizing message digest: %s", sftp_crypto_get_errors());
783     BN_clear_free(kex->e);
784     kex->e = NULL;
785     pr_memscrub(ptr, bufsz);
786 # if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
787      !defined(HAVE_LIBRESSL)
788     EVP_MD_CTX_free(pctx);
789 # endif /* OpenSSL-1.1.0 and later */
790     return NULL;
791   }
792 #else
793   EVP_DigestFinal(pctx, kex_digest_buf, hlen);
794 #endif
795 
796 #if OPENSSL_VERSION_NUMBER >= 0x10100000LL && \
797     !defined(HAVE_LIBRESSL)
798   EVP_MD_CTX_free(pctx);
799 #endif /* OpenSSL-1.1.0 and later */
800   BN_clear_free(kex->e);
801   kex->e = NULL;
802   pr_memscrub(ptr, bufsz);
803 
804   return kex_digest_buf;
805 }
806 #endif /* PR_USE_OPENSSL_ECC */
807 
808 /* Make sure that the DH key we're generating is good enough. */
have_good_dh(DH * dh,BIGNUM * pub_key)809 static int have_good_dh(DH *dh, BIGNUM *pub_key) {
810   register int i;
811   unsigned int nbits = 0;
812   const BIGNUM *dh_p = NULL;
813   BIGNUM *tmp;
814 
815 #if OPENSSL_VERSION_NUMBER >= 0x0090801fL
816   if (BN_is_negative(pub_key)) {
817     pr_trace_msg(trace_channel, 10,
818       "DH public keys cannot have negative numbers");
819     errno = EINVAL;
820     return -1;
821   }
822 #endif /* OpenSSL-0.9.8a or later */
823 
824   if (BN_cmp(pub_key, BN_value_one()) != 1) {
825     pr_trace_msg(trace_channel, 10, "bad DH public key exponent (<= 1)");
826     errno = EINVAL;
827     return -1;
828   }
829 
830 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
831     !defined(HAVE_LIBRESSL)
832   DH_get0_pqg(dh, &dh_p, NULL, NULL);
833 #else
834   dh_p = dh->p;
835 #endif /* prior to OpenSSL-1.1.0 */
836 
837   tmp = BN_new();
838   if (!BN_sub(tmp, dh_p, BN_value_one()) ||
839       BN_cmp(pub_key, tmp) != -1) {
840     BN_clear_free(tmp);
841     pr_trace_msg(trace_channel, 10, "bad DH public key (>= p-1)");
842     errno = EINVAL;
843     return -1;
844   }
845 
846   BN_clear_free(tmp);
847 
848   for (i = 0; i <= BN_num_bits(pub_key); i++) {
849     if (BN_is_bit_set(pub_key, i)) {
850       nbits++;
851     }
852   }
853 
854   /* The number of bits set in the public key must be greater than one.
855    * Otherwise, the public key will not hold up under scrutiny, not for
856    * our needs.  (The OpenSSH client is picky about the DH public keys it
857    * will accept as well, so this is necessary to pass OpenSSH's requirements).
858    */
859   if (nbits <= 1) {
860     errno = EINVAL;
861     return -1;
862   }
863 
864   pr_trace_msg(trace_channel, 10, "good DH public key: %u bits set", nbits);
865   return 0;
866 }
867 
get_dh_nbits(struct sftp_kex * kex)868 static int get_dh_nbits(struct sftp_kex *kex) {
869   int dh_nbits = 0, dh_size = 0;
870   const char *algo;
871   const EVP_CIPHER *cipher;
872   const EVP_MD *digest;
873 
874   algo = kex->session_names->c2s_encrypt_algo;
875   cipher = sftp_crypto_get_cipher(algo, NULL, NULL);
876   if (cipher != NULL) {
877     int block_size, key_len;
878 
879     key_len = EVP_CIPHER_key_length(cipher);
880     if (dh_size < key_len) {
881       dh_size = key_len;
882       pr_trace_msg(trace_channel, 19,
883         "set DH size to %d bytes, matching client-to-server '%s' cipher "
884         "key length", dh_size, algo);
885     }
886 
887     block_size = EVP_CIPHER_block_size(cipher);
888     if (dh_size < block_size) {
889       dh_size = block_size;
890       pr_trace_msg(trace_channel, 19,
891         "set DH size to %d bytes, matching client-to-server '%s' cipher "
892         "block size", dh_size, algo);
893     }
894   }
895 
896   algo = kex->session_names->s2c_encrypt_algo;
897   cipher = sftp_crypto_get_cipher(algo, NULL, NULL);
898   if (cipher != NULL) {
899     int block_size, key_len;
900 
901     key_len = EVP_CIPHER_key_length(cipher);
902     if (dh_size < key_len) {
903       dh_size = key_len;
904       pr_trace_msg(trace_channel, 19,
905         "set DH size to %d bytes, matching server-to-client '%s' cipher "
906         "key length", dh_size, algo);
907     }
908 
909     block_size = EVP_CIPHER_block_size(cipher);
910     if (dh_size < block_size) {
911       dh_size = block_size;
912       pr_trace_msg(trace_channel, 19,
913         "set DH size to %d bytes, matching server-to-client '%s' cipher "
914         "block size", dh_size, algo);
915     }
916   }
917 
918   algo = kex->session_names->c2s_mac_algo;
919   digest = sftp_crypto_get_digest(algo, NULL);
920   if (digest != NULL) {
921     int mac_len;
922 
923     mac_len = EVP_MD_size(digest);
924     if (dh_size < mac_len) {
925       dh_size = mac_len;
926       pr_trace_msg(trace_channel, 19,
927         "set DH size to %d bytes, matching client-to-server '%s' digest size",
928         dh_size, algo);
929     }
930   }
931 
932   algo = kex->session_names->s2c_mac_algo;
933   digest = sftp_crypto_get_digest(algo, NULL);
934   if (digest != NULL) {
935     int mac_len;
936 
937     mac_len = EVP_MD_size(digest);
938     if (dh_size < mac_len) {
939       dh_size = mac_len;
940       pr_trace_msg(trace_channel, 19,
941         "set DH size to %d bytes, matching server-to-client '%s' digest size",
942         dh_size, algo);
943     }
944   }
945 
946   /* We want to return bits, not bytes. */
947   dh_nbits = dh_size * 8;
948 
949   pr_trace_msg(trace_channel, 8, "requesting DH size of %d bits", dh_nbits);
950   return dh_nbits;
951 }
952 
create_dh(struct sftp_kex * kex,int type)953 static int create_dh(struct sftp_kex *kex, int type) {
954   unsigned int attempts = 0;
955   int dh_nbits;
956   DH *dh;
957 
958   if (type != SFTP_DH_GROUP1_SHA1 &&
959       type != SFTP_DH_GROUP14_SHA1 &&
960       type != SFTP_DH_GROUP14_SHA256 &&
961       type != SFTP_DH_GROUP16_SHA512 &&
962       type != SFTP_DH_GROUP18_SHA512) {
963     errno = EINVAL;
964     return -1;
965   }
966 
967   if (kex->dh) {
968 #if OPENSSL_VERSION_NUMBER < 0x10100000L
969     if (kex->dh->p) {
970       BN_clear_free(kex->dh->p);
971       kex->dh->p = NULL;
972     }
973 
974     if (kex->dh->g) {
975       BN_clear_free(kex->dh->g);
976       kex->dh->g = NULL;
977     }
978 
979     if (kex->dh->priv_key) {
980       BN_clear_free(kex->dh->priv_key);
981       kex->dh->priv_key = NULL;
982     }
983 
984     if (kex->dh->pub_key) {
985       BN_clear_free(kex->dh->pub_key);
986       kex->dh->pub_key = NULL;
987     }
988 #endif /* prior to OpenSSL-1.1.0 */
989 
990     DH_free(kex->dh);
991     kex->dh = NULL;
992   }
993 
994   dh_nbits = get_dh_nbits(kex);
995 
996   /* We have 10 attempts to make a DH key which passes muster. */
997   while (attempts <= 10) {
998     BIGNUM *dh_p, *dh_g, *dh_pub_key = NULL, *dh_priv_key = NULL;
999 
1000     pr_signals_handle();
1001 
1002     attempts++;
1003     pr_trace_msg(trace_channel, 9, "attempt #%u to create a good DH key",
1004       attempts);
1005 
1006     dh = DH_new();
1007     if (dh == NULL) {
1008       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1009         "error creating DH: %s", sftp_crypto_get_errors());
1010       return -1;
1011     }
1012 
1013     dh_p = BN_new();
1014 
1015     switch (type) {
1016       case SFTP_DH_GROUP18_SHA512:
1017         if (BN_hex2bn(&dh_p, dh_group18_str) == 0) {
1018           (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1019             "error setting DH (group18) P: %s", sftp_crypto_get_errors());
1020           BN_clear_free(dh_p);
1021           DH_free(dh);
1022           return -1;
1023         }
1024         break;
1025 
1026       case SFTP_DH_GROUP16_SHA512:
1027         if (BN_hex2bn(&dh_p, dh_group16_str) == 0) {
1028           (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1029             "error setting DH (group16) P: %s", sftp_crypto_get_errors());
1030           BN_clear_free(dh_p);
1031           DH_free(dh);
1032           return -1;
1033         }
1034         break;
1035 
1036       case SFTP_DH_GROUP14_SHA1:
1037       case SFTP_DH_GROUP14_SHA256:
1038         if (BN_hex2bn(&dh_p, dh_group14_str) == 0) {
1039           (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1040             "error setting DH (group14) P: %s", sftp_crypto_get_errors());
1041           BN_clear_free(dh_p);
1042           DH_free(dh);
1043           return -1;
1044         }
1045         break;
1046 
1047       default:
1048         if (BN_hex2bn(&dh_p, dh_group1_str) == 0) {
1049           (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1050             "error setting DH (group1) P: %s", sftp_crypto_get_errors());
1051           BN_clear_free(dh_p);
1052           DH_free(dh);
1053           return -1;
1054         }
1055         break;
1056     }
1057 
1058     dh_g = BN_new();
1059 
1060     if (BN_hex2bn(&dh_g, "2") == 0) {
1061       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1062         "error setting DH G: %s", sftp_crypto_get_errors());
1063       BN_clear_free(dh_p);
1064       BN_clear_free(dh_g);
1065       DH_free(dh);
1066       return -1;
1067     }
1068 
1069 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
1070     !defined(HAVE_LIBRESSL)
1071     DH_set0_pqg(dh, dh_p, NULL, dh_g);
1072 #else
1073     dh->p = dh_p;
1074     dh->g = dh_g;
1075 #endif /* prior to OpenSSL-1.1.0 */
1076 
1077     dh_priv_key = BN_new();
1078 
1079     /* Generate a random private exponent of the desired size, in bits. */
1080     if (!BN_rand(dh_priv_key, dh_nbits, 0, 0)) {
1081       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1082         "error generating DH random key (%d bits): %s", dh_nbits,
1083         sftp_crypto_get_errors());
1084       BN_clear_free(dh_priv_key);
1085       DH_free(dh);
1086       return -1;
1087     }
1088 
1089     dh_pub_key = BN_new();
1090 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
1091     !defined(HAVE_LIBRESSL)
1092     DH_set0_key(dh, dh_pub_key, dh_priv_key);
1093 #else
1094     dh->pub_key = dh_pub_key;
1095     dh->priv_key = dh_priv_key;
1096 #endif /* prior to OpenSSL-1.1.0 */
1097 
1098     pr_trace_msg(trace_channel, 12, "generating DH key");
1099     if (DH_generate_key(dh) != 1) {
1100       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1101         "error generating DH key: %s", sftp_crypto_get_errors());
1102       DH_free(dh);
1103       return -1;
1104     }
1105 
1106 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
1107     !defined(HAVE_LIBRESSL)
1108     DH_get0_key(dh, &dh_pub_key, NULL);
1109 #else
1110     dh_pub_key = dh->pub_key;
1111 #endif /* prior to OpenSSL-1.1.0 */
1112 
1113     if (have_good_dh(dh, dh_pub_key) < 0) {
1114       DH_free(dh);
1115       continue;
1116     }
1117 
1118     kex->dh = dh;
1119 
1120     switch (type) {
1121 #if defined(HAVE_SHA512_OPENSSL)
1122       case SFTP_DH_GROUP16_SHA512:
1123       case SFTP_DH_GROUP18_SHA512:
1124         kex->hash = EVP_sha512();
1125         break;
1126 #endif /* HAVE_SHA512_OPENSSL */
1127 
1128 #if defined(HAVE_SHA256_OPENSSL)
1129       case SFTP_DH_GROUP14_SHA256:
1130         kex->hash = EVP_sha256();
1131         break;
1132 #endif /* HAVE_SHA256_OPENSSL */
1133 
1134       default:
1135         kex->hash = EVP_sha1();
1136     }
1137 
1138     return 0;
1139   }
1140 
1141   errno = EPERM;
1142   return -1;
1143 }
1144 
prepare_dh(struct sftp_kex * kex,int type)1145 static int prepare_dh(struct sftp_kex *kex, int type) {
1146   DH *dh;
1147 
1148   if (type != SFTP_DH_GEX_SHA1 &&
1149       type != SFTP_DH_GEX_SHA256) {
1150     errno = EINVAL;
1151     return -1;
1152   }
1153 
1154   if (kex->dh) {
1155 #if OPENSSL_VERSION_NUMBER < 0x10100000L
1156     if (kex->dh->p) {
1157       BN_clear_free(kex->dh->p);
1158       kex->dh->p = NULL;
1159     }
1160 
1161     if (kex->dh->g) {
1162       BN_clear_free(kex->dh->g);
1163       kex->dh->g = NULL;
1164     }
1165 
1166     if (kex->dh->priv_key) {
1167       BN_clear_free(kex->dh->priv_key);
1168       kex->dh->priv_key = NULL;
1169     }
1170 
1171     if (kex->dh->pub_key) {
1172       BN_clear_free(kex->dh->pub_key);
1173       kex->dh->pub_key = NULL;
1174     }
1175 #endif /* prior to OpenSSL-1.1.0 */
1176 
1177     DH_free(kex->dh);
1178     kex->dh = NULL;
1179   }
1180 
1181   dh = DH_new();
1182   if (!dh) {
1183     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1184       "error creating DH: %s", sftp_crypto_get_errors());
1185     return -1;
1186   }
1187 
1188   kex->dh = dh;
1189 
1190   if (type == SFTP_DH_GEX_SHA1) {
1191     kex->hash = EVP_sha1();
1192 
1193 #if ((OPENSSL_VERSION_NUMBER > 0x000907000L && defined(OPENSSL_FIPS)) || \
1194      (OPENSSL_VERSION_NUMBER > 0x000908000L)) && \
1195      defined(HAVE_SHA256_OPENSSL)
1196   } else if (type == SFTP_DH_GEX_SHA256) {
1197     kex->hash = EVP_sha256();
1198 #endif
1199   }
1200 
1201   return 0;
1202 }
1203 
finish_dh(struct sftp_kex * kex)1204 static int finish_dh(struct sftp_kex *kex) {
1205   unsigned int attempts = 0;
1206   int dh_nbits;
1207   BIGNUM *dh_pub_key, *dh_priv_key;
1208 
1209   dh_nbits = get_dh_nbits(kex);
1210 
1211   /* We have 10 attempts to make a DH key which passes muster. */
1212   while (attempts <= 10) {
1213     pr_signals_handle();
1214 
1215     attempts++;
1216     pr_trace_msg(trace_channel, 9, "attempt #%u to create a good DH key",
1217       attempts);
1218 
1219     dh_priv_key = BN_new();
1220 
1221     /* Generate a random private exponent of the desired size, in bits. */
1222     if (!BN_rand(dh_priv_key, dh_nbits, 0, 0)) {
1223       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1224         "error generating DH random key (%d bits): %s", dh_nbits,
1225         sftp_crypto_get_errors());
1226       BN_clear_free(dh_priv_key);
1227       return -1;
1228     }
1229 
1230     dh_pub_key = BN_new();
1231 
1232 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
1233     !defined(HAVE_LIBRESSL)
1234     DH_set0_key(kex->dh, dh_pub_key, dh_priv_key);
1235 #else
1236     kex->dh->pub_key = dh_pub_key;
1237     kex->dh->priv_key = dh_priv_key;
1238 #endif /* prior to OpenSSL-1.1.0 */
1239 
1240     pr_trace_msg(trace_channel, 12, "generating DH key");
1241     if (DH_generate_key(kex->dh) != 1) {
1242       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1243         "error generating DH key: %s", sftp_crypto_get_errors());
1244       return -1;
1245     }
1246 
1247     if (have_good_dh(kex->dh, kex->e) < 0) {
1248       dh_pub_key = NULL;
1249       dh_priv_key = NULL;
1250 
1251 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
1252     !defined(HAVE_LIBRESSL)
1253       DH_get0_key(kex->dh, &dh_pub_key, &dh_priv_key);
1254 #else
1255       dh_pub_key = kex->dh->pub_key;
1256       dh_priv_key = kex->dh->priv_key;
1257 #endif /* prior to OpenSSL-1.1.0 */
1258 
1259       if (dh_priv_key != NULL) {
1260         BN_clear_free(dh_priv_key);
1261       }
1262 
1263       if (dh_pub_key != NULL) {
1264         BN_clear_free(dh_pub_key);
1265       }
1266 
1267 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
1268       /* Per the docs, this is a no-no -- but its the only way to actually
1269        * set the public DH key to null.
1270        */
1271       dh_pub_key = dh_priv_key = NULL;
1272 #else
1273       kex->dh->pub_key = kex->dh->priv_key = NULL;
1274 #endif /* prior to OpenSSL-1.1.0 */
1275 
1276       continue;
1277     }
1278 
1279     return 0;
1280   }
1281 
1282   errno = EPERM;
1283   return -1;
1284 }
1285 
create_kexrsa(struct sftp_kex * kex,int type)1286 static int create_kexrsa(struct sftp_kex *kex, int type) {
1287   RSA *rsa = NULL;
1288 
1289   if (type != SFTP_KEXRSA_SHA1 &&
1290       type != SFTP_KEXRSA_SHA256) {
1291     errno = EINVAL;
1292     return -1;
1293   }
1294 
1295   if (kex->rsa) {
1296     RSA_free(kex->rsa);
1297     kex->rsa = NULL;
1298   }
1299 
1300   if (kex->rsa_encrypted) {
1301     pr_memscrub(kex->rsa_encrypted, kex->rsa_encrypted_len);
1302     kex->rsa_encrypted = NULL;
1303     kex->rsa_encrypted_len = 0;
1304   }
1305 
1306   if (type == SFTP_KEXRSA_SHA1) {
1307     BIGNUM *e = NULL;
1308 
1309 #if OPENSSL_VERSION_NUMBER > 0x000908000L
1310     e = BN_new();
1311     if (e == NULL) {
1312       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1313         "error allocated BIGNUM: %s", sftp_crypto_get_errors());
1314       return -1;
1315     }
1316 
1317     if (BN_set_word(e, 17) != 1) {
1318       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1319         "error setting BIGNUM word: %s", sftp_crypto_get_errors());
1320       BN_free(e);
1321       return -1;
1322     }
1323 
1324     if (RSA_generate_key_ex(rsa, SFTP_KEXRSA_SHA1_SIZE, e, NULL) != 1) {
1325 #else
1326     rsa = RSA_generate_key(SFTP_KEXRSA_SHA1_SIZE, 17, NULL, NULL);
1327     if (rsa == NULL) {
1328 #endif /* OpenSSL version 0.9.8 and later */
1329       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1330         "error generating %u-bit RSA key: %s", SFTP_KEXRSA_SHA1_SIZE,
1331         sftp_crypto_get_errors());
1332 
1333       if (e != NULL) {
1334         BN_free(e);
1335       }
1336 
1337       return -1;
1338     }
1339 
1340     kex->hash = EVP_sha1();
1341 
1342 #if ((OPENSSL_VERSION_NUMBER > 0x000907000L && defined(OPENSSL_FIPS)) || \
1343      (OPENSSL_VERSION_NUMBER > 0x000908000L)) && \
1344      defined(HAVE_SHA256_OPENSSL)
1345   } else if (type == SFTP_KEXRSA_SHA256) {
1346     BIGNUM *e = NULL;
1347 
1348 # if OPENSSL_VERSION_NUMBER > 0x000908000L
1349     e = BN_new();
1350     if (e == NULL) {
1351       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1352         "error allocated BIGNUM: %s", sftp_crypto_get_errors());
1353       return -1;
1354     }
1355 
1356     if (BN_set_word(e, 65537) != 1) {
1357       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1358         "error setting BIGNUM word: %s", sftp_crypto_get_errors());
1359       BN_free(e);
1360       return -1;
1361     }
1362 
1363     if (RSA_generate_key_ex(rsa, SFTP_KEXRSA_SHA256_SIZE, e, NULL) != 1) {
1364 # else
1365     rsa = RSA_generate_key(SFTP_KEXRSA_SHA256_SIZE, 65537, NULL, NULL);
1366     if (rsa == NULL) {
1367 # endif /* OpenSSL version 0.9.8 and later */
1368       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1369         "error generating %u-bit RSA key: %s", SFTP_KEXRSA_SHA256_SIZE,
1370         sftp_crypto_get_errors());
1371 
1372       if (e != NULL) {
1373         BN_free(e);
1374       }
1375 
1376       return -1;
1377     }
1378 
1379     kex->hash = EVP_sha256();
1380 #endif
1381   }
1382 
1383 #if OPENSSL_VERSION_NUMBER < 0x0090702fL
1384   /* In OpenSSL-0.9.7a and later, RSA blinding is turned on by default.  Thus
1385    * if our OpenSSL is older than that, manually enable RSA blinding.
1386    */
1387   if (RSA_blinding_on(rsa, NULL) != 1) {
1388     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1389       "error enabling RSA blinding for generated key: %s",
1390       sftp_crypto_get_errors());
1391 
1392   } else {
1393     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1394       "RSA blinding enabled for generated key");
1395   }
1396 #endif
1397 
1398   kex->rsa = rsa;
1399   return 0;
1400 }
1401 
1402 #ifdef PR_USE_OPENSSL_ECC
1403 static int create_ecdh(struct sftp_kex *kex, int type) {
1404   EC_KEY *ec;
1405   int curve_nid = -1;
1406   char *curve_name = NULL;
1407 
1408   switch (type) {
1409     case SFTP_ECDH_SHA256:
1410       curve_name = "NID_X9_62_prime256v1";
1411 # if defined(HAVE_SHA256_OPENSSL)
1412       curve_nid = NID_X9_62_prime256v1;
1413       kex->hash = EVP_sha256();
1414 # else
1415       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1416         "unable to generate EC key using '%s': OpenSSL lacks SHA256 support",
1417         curve_name);
1418       errno = ENOSYS;
1419       return -1;
1420 # endif /* HAVE_SHA256_OPENSSL */
1421       break;
1422 
1423     case SFTP_ECDH_SHA384:
1424       curve_name = "NID_secp384r1";
1425 # if defined(HAVE_SHA256_OPENSSL)
1426       curve_nid = NID_secp384r1;
1427       kex->hash = EVP_sha384();
1428 # else
1429       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1430         "unable to generate EC key using '%s': OpenSSL lacks SHA256 support",
1431         curve_name);
1432       errno = ENOSYS;
1433       return -1;
1434 # endif /* HAVE_SHA256_OPENSSL */
1435       break;
1436 
1437     case SFTP_ECDH_SHA512:
1438       curve_name = "NID_secp521r1";
1439 # if defined(HAVE_SHA512_OPENSSL)
1440       curve_nid = NID_secp521r1;
1441       kex->hash = EVP_sha512();
1442 # else
1443       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1444         "unable to generate EC key using '%s': OpenSSL lacks SHA512 support",
1445         curve_name);
1446       errno = ENOSYS;
1447       return -1;
1448 # endif /* HAVE_SHA512_OPENSSL */
1449       break;
1450 
1451     default:
1452       errno = EINVAL;
1453       return -1;
1454   }
1455 
1456   ec = EC_KEY_new_by_curve_name(curve_nid);
1457   if (ec == NULL) {
1458     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1459       "error generating new EC key using '%s': %s", curve_name,
1460       sftp_crypto_get_errors());
1461     return -1;
1462   }
1463 
1464   if (EC_KEY_generate_key(ec) != 1) {
1465     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1466       "error generating new EC key: %s", sftp_crypto_get_errors());
1467     EC_KEY_free(ec);
1468     return -1;
1469   }
1470 
1471   kex->ec = ec;
1472   return 0;
1473 }
1474 
1475 static int finish_ecdh(struct sftp_kex *kex) {
1476   if (kex->ec) {
1477     EC_KEY_free(kex->ec);
1478     kex->ec = NULL;
1479   }
1480 
1481   if (kex->client_point) {
1482     EC_POINT_clear_free(kex->client_point);
1483     kex->client_point = NULL;
1484   }
1485 
1486   return 0;
1487 }
1488 #endif /* PR_USE_OPENSSL_ECC */
1489 
1490 /* Given a name-list, return the first (i.e. preferred) name in the list. */
1491 static const char *get_preferred_name(pool *p, const char *names) {
1492   register unsigned int i;
1493 
1494   /* Advance to the first comma, or NUL. */
1495   for (i = 0; names[i] && names[i] != ','; i++);
1496 
1497   if (names[i] == ',' ||
1498       names[i] == '\0') {
1499     char *pref;
1500 
1501     pref = pcalloc(p, i + 1);
1502     memcpy(pref, names, i);
1503 
1504     return pref;
1505   }
1506 
1507   /* This should never happen. */
1508   (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1509     "unable to find preferred name in '%s'", names);
1510   return NULL;
1511 }
1512 
1513 /* Note that in this default list of key exchange algorithms, one of the
1514  * REQUIRED algorithms is conspicuously absent:
1515  *
1516  *   diffie-hellman-group1-sha1
1517  *
1518  * This exchange has a weak hardcoded DH group, and will thus only be used
1519  * if explicitly requested via SFTPKeyExchanges, or if the AllowWeakDH
1520  * SFTPOption is used.
1521  */
1522 static const char *kex_exchanges[] = {
1523 #if defined(PR_USE_SODIUM) && defined(HAVE_SHA256_OPENSSL)
1524   "curve25519-sha256",
1525   "curve25519-sha256@libssh.org",
1526 #endif /* PR_USE_SODIUM and HAVE_SHA256_OPENSSL */
1527 #ifdef PR_USE_OPENSSL_ECC
1528   "ecdh-sha2-nistp521",
1529   "ecdh-sha2-nistp384",
1530   "ecdh-sha2-nistp256",
1531 #endif /* PR_USE_OPENSSL_ECC */
1532 
1533 #if (OPENSSL_VERSION_NUMBER > 0x000907000L && defined(OPENSSL_FIPS)) || \
1534     (OPENSSL_VERSION_NUMBER > 0x000908000L)
1535 # if defined(HAVE_SHA512_OPENSSL)
1536   "diffie-hellman-group18-sha512",
1537   "diffie-hellman-group16-sha512",
1538 # endif /* HAVE_SHA512_OPENSSL */
1539 # if defined(HAVE_SHA256_OPENSSL)
1540   "diffie-hellman-group14-sha256",
1541   "diffie-hellman-group-exchange-sha256",
1542 # endif /* HAVE_SHA256_OPENSSL */
1543 #endif
1544   "diffie-hellman-group-exchange-sha1",
1545   "diffie-hellman-group14-sha1",
1546 
1547 #if 0
1548 /* We cannot currently support rsa2048-sha256, since it requires support
1549  * for PKCS#1 v2.1 (RFC3447).  OpenSSL only supports PKCS#1 v2.0 (RFC2437)
1550  * at present, which only allows EME-OAEP using SHA1.  v2.1 allows for
1551  * using other message digests, e.g. SHA256, for EME-OAEP.
1552  */
1553 #if ((OPENSSL_VERSION_NUMBER > 0x000907000L && defined(OPENSSL_FIPS)) || \
1554      (OPENSSL_VERSION_NUMBER > 0x000908000L)) && \
1555      defined(HAVE_SHA256_OPENSSL)
1556   "rsa2048-sha256",
1557 #endif
1558 #endif
1559 
1560   "rsa1024-sha1",
1561   NULL,
1562 };
1563 
1564 static const char *get_kexinit_exchange_list(pool *p) {
1565   char *res = "";
1566   config_rec *c;
1567 
1568   c = find_config(main_server->conf, CONF_PARAM, "SFTPKeyExchanges", FALSE);
1569   if (c != NULL) {
1570     res = pstrdup(p, c->argv[0]);
1571 
1572   } else {
1573     register unsigned int i;
1574 
1575     for (i = 0; kex_exchanges[i]; i++) {
1576       res = pstrcat(p, res, *res ? "," : "", pstrdup(p, kex_exchanges[i]),
1577         NULL);
1578     }
1579 
1580     if (sftp_opts & SFTP_OPT_ALLOW_WEAK_DH) {
1581       /* The hardcoded group for this exchange is rather weak in the face of
1582        * the "Logjam" vulnerability (see https://weakdh.org).  Thus it is
1583        * only appended to the end of the default exchanges if the AllowWeakDH
1584        * SFTPOption is in effect.
1585        */
1586       res = pstrcat(p, res, ",", pstrdup(p, "diffie-hellman-group1-sha1"),
1587         NULL);
1588     }
1589   }
1590 
1591   if (!(sftp_opts & SFTP_OPT_NO_EXT_INFO)) {
1592     /* Indicate support for RFC 8308's extension negotiation mechanism. */
1593     res = pstrcat(p, res, *res ? "," : "", pstrdup(p, "ext-info-s"), NULL);
1594   }
1595 
1596   return res;
1597 }
1598 
1599 static const char *get_kexinit_hostkey_algo_list(pool *p) {
1600 #ifdef PR_USE_OPENSSL_ECC
1601   int *nids = NULL, res;
1602 #endif /* PR_USE_OPENSSL_ECC */
1603   char *list = "";
1604 
1605   /* Our list of supported hostkey algorithms depends on the hostkeys
1606    * that have been configured.  Show a preference for RSA over DSA,
1607    * and ECDSA over both RSA and DSA, and ED25519 over all.
1608    *
1609    * XXX Should this be configurable later?
1610    */
1611 
1612   if (sftp_keys_have_ed25519_hostkey() == 0) {
1613     list = pstrcat(p, list, *list ? "," : "", "ssh-ed25519", NULL);
1614   }
1615 
1616 #ifdef PR_USE_OPENSSL_ECC
1617   res = sftp_keys_have_ecdsa_hostkey(p, &nids);
1618   if (res > 0) {
1619     register int i;
1620 
1621     for (i = 0; i < res; i++) {
1622       char *algo_name = NULL;
1623 
1624       switch (nids[i]) {
1625         case NID_X9_62_prime256v1:
1626           algo_name = "ecdsa-sha2-nistp256";
1627           break;
1628 
1629         case NID_secp384r1:
1630           algo_name = "ecdsa-sha2-nistp384";
1631           break;
1632 
1633         case NID_secp521r1:
1634           algo_name = "ecdsa-sha2-nistp521";
1635           break;
1636 
1637         default:
1638           (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1639             "unknown/unsupported ECDSA NID %d, skipping", nids[i]);
1640           break;
1641       }
1642 
1643       if (algo_name != NULL) {
1644         list = pstrcat(p, list, *list ? "," : "", algo_name, NULL);
1645       }
1646     }
1647   }
1648 #endif /* PR_USE_OPENSSL_ECC */
1649 
1650   if (sftp_keys_have_rsa_hostkey() == 0) {
1651 #if defined(HAVE_SHA512_OPENSSL)
1652     list = pstrcat(p, list, *list ? "," : "", "rsa-sha2-512", NULL);
1653 #endif /* HAVE_SHA512_OPENSSL */
1654 
1655 #if defined(HAVE_SHA256_OPENSSL)
1656     list = pstrcat(p, list, *list ? "," : "", "rsa-sha2-256", NULL);
1657 #endif /* HAVE_SHA256_OPENSSL */
1658 
1659     list = pstrcat(p, list, *list ? "," : "", "ssh-rsa", NULL);
1660   }
1661 
1662   if (sftp_keys_have_dsa_hostkey() == 0) {
1663     list = pstrcat(p, list, *list ? "," : "", "ssh-dss", NULL);
1664   }
1665 
1666   return list;
1667 }
1668 
1669 static struct sftp_kex *create_kex(pool *p) {
1670   struct sftp_kex *kex;
1671   const char *list;
1672   config_rec *c;
1673   pool *tmp_pool;
1674 
1675   tmp_pool = make_sub_pool(p);
1676   pr_pool_tag(tmp_pool, "Kex KEXINIT Pool");
1677 
1678   kex = pcalloc(tmp_pool, sizeof(struct sftp_kex));
1679   kex->pool = tmp_pool;
1680   kex->client_version = kex_client_version;
1681   kex->server_version = kex_server_version;
1682   kex->client_names = pcalloc(kex->pool, sizeof(struct sftp_kex_names));
1683   kex->server_names = pcalloc(kex->pool, sizeof(struct sftp_kex_names));
1684   kex->session_names = pcalloc(kex->pool, sizeof(struct sftp_kex_names));
1685   kex->use_hostkey_type = SFTP_KEY_UNKNOWN;
1686   kex->dh = NULL;
1687   kex->e = NULL;
1688   kex->hash = NULL;
1689   kex->k = NULL;
1690   kex->h = NULL;
1691   kex->hlen = 0;
1692   kex->rsa = NULL;
1693   kex->rsa_encrypted = NULL;
1694   kex->rsa_encrypted_len = 0;
1695 
1696   list = get_kexinit_exchange_list(kex->pool);
1697   kex->server_names->kex_algo = list;
1698 
1699   list = get_kexinit_hostkey_algo_list(kex->pool);
1700   kex->server_names->server_hostkey_algo = list;
1701 
1702   list = sftp_crypto_get_kexinit_cipher_list(kex->pool);
1703   kex->server_names->c2s_encrypt_algo = list;
1704   kex->server_names->s2c_encrypt_algo = list;
1705 
1706   list = sftp_crypto_get_kexinit_digest_list(kex->pool);
1707   kex->server_names->c2s_mac_algo = list;
1708   kex->server_names->s2c_mac_algo = list;
1709 
1710   c = find_config(main_server->conf, CONF_PARAM, "SFTPCompression", FALSE);
1711   if (c) {
1712     int comp_mode;
1713 
1714     comp_mode = *((int *) c->argv[0]);
1715 
1716     switch (comp_mode) {
1717       case 2:
1718         /* Advertise that we support OpenSSH's "delayed" compression mode. */
1719         kex->server_names->c2s_comp_algo = "zlib@openssh.com,zlib,none";
1720         kex->server_names->s2c_comp_algo = "zlib@openssh.com,zlib,none";
1721         break;
1722 
1723       case 1:
1724         kex->server_names->c2s_comp_algo = "zlib,none";
1725         kex->server_names->s2c_comp_algo = "zlib,none";
1726         break;
1727 
1728       default:
1729         kex->server_names->c2s_comp_algo = "none";
1730         kex->server_names->s2c_comp_algo = "none";
1731         break;
1732     }
1733 
1734   } else {
1735     kex->server_names->c2s_comp_algo = "none";
1736     kex->server_names->s2c_comp_algo = "none";
1737   }
1738 
1739 #ifdef PR_USE_NLS
1740   c = find_config(main_server->conf, CONF_PARAM, "SFTPLanguages", FALSE);
1741   if (c) {
1742     /* XXX Need to implement functionality here. */
1743 
1744   } else {
1745     kex->server_names->c2s_lang = "en_US";
1746     kex->server_names->s2c_lang = "en_US";
1747   }
1748 #else
1749   kex->server_names->c2s_lang = "";
1750   kex->server_names->s2c_lang = "";
1751 #endif /* !PR_USE_NLS */
1752 
1753   return kex;
1754 }
1755 
1756 static void destroy_kex(struct sftp_kex *kex) {
1757   if (kex) {
1758     if (kex->dh) {
1759 #if OPENSSL_VERSION_NUMBER < 0x10100000L
1760       if (kex->dh->p) {
1761         BN_clear_free(kex->dh->p);
1762         kex->dh->p = NULL;
1763       }
1764 
1765       if (kex->dh->g) {
1766         BN_clear_free(kex->dh->g);
1767         kex->dh->g = NULL;
1768       }
1769 #endif /* prior to OpenSSL-1.1.0 */
1770 
1771       DH_free(kex->dh);
1772       kex->dh = NULL;
1773     }
1774 
1775     if (kex->rsa) {
1776       RSA_free(kex->rsa);
1777       kex->rsa = NULL;
1778     }
1779 
1780     if (kex->rsa_encrypted) {
1781       pr_memscrub(kex->rsa_encrypted, kex->rsa_encrypted_len);
1782       kex->rsa_encrypted = NULL;
1783       kex->rsa_encrypted_len = 0;
1784     }
1785 
1786     if (kex->e) {
1787       BN_clear_free(kex->e);
1788       kex->e = NULL;
1789     }
1790 
1791     if (kex->k) {
1792       BN_clear_free(kex->k);
1793       kex->k = NULL;
1794     }
1795 
1796     if (kex->hlen > 0) {
1797       pr_memscrub((char *) kex->h, kex->hlen);
1798       kex->hlen = 0;
1799     }
1800 
1801     if (kex->pool) {
1802       destroy_pool(kex->pool);
1803       kex->pool = NULL;
1804     }
1805   }
1806 
1807   kex_first_kex = kex_rekey_kex = NULL;
1808 }
1809 
1810 static int setup_kex_algo(struct sftp_kex *kex, const char *algo) {
1811 
1812   if (strncmp(algo, "diffie-hellman-group1-sha1", 27) == 0) {
1813     if (create_dh(kex, SFTP_DH_GROUP1_SHA1) < 0) {
1814       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1815         "error using '%s' as the key exchange algorithm: %s", algo,
1816         strerror(errno));
1817       return -1;
1818     }
1819 
1820     kex->session_names->kex_algo = algo;
1821     return 0;
1822   }
1823 
1824   if (strncmp(algo, "diffie-hellman-group14-sha1", 28) == 0) {
1825     if (create_dh(kex, SFTP_DH_GROUP14_SHA1) < 0) {
1826       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1827         "error using '%s' as the key exchange algorithm: %s", algo,
1828         strerror(errno));
1829       return -1;
1830     }
1831 
1832     kex->session_names->kex_algo = algo;
1833     return 0;
1834   }
1835 
1836   if (strncmp(algo, "diffie-hellman-group14-sha256", 30) == 0) {
1837     if (create_dh(kex, SFTP_DH_GROUP14_SHA256) < 0) {
1838       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1839         "error using '%s' as the key exchange algorithm: %s", algo,
1840         strerror(errno));
1841       return -1;
1842     }
1843 
1844     kex->session_names->kex_algo = algo;
1845     return 0;
1846   }
1847 
1848   if (strncmp(algo, "diffie-hellman-group16-sha512", 30) == 0) {
1849     if (create_dh(kex, SFTP_DH_GROUP16_SHA512) < 0) {
1850       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1851         "error using '%s' as the key exchange algorithm: %s", algo,
1852         strerror(errno));
1853       return -1;
1854     }
1855 
1856     kex->session_names->kex_algo = algo;
1857     return 0;
1858   }
1859 
1860   if (strncmp(algo, "diffie-hellman-group18-sha512", 30) == 0) {
1861     if (create_dh(kex, SFTP_DH_GROUP18_SHA512) < 0) {
1862       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1863         "error using '%s' as the key exchange algorithm: %s", algo,
1864         strerror(errno));
1865       return -1;
1866     }
1867 
1868     kex->session_names->kex_algo = algo;
1869     return 0;
1870   }
1871 
1872   if (strncmp(algo, "diffie-hellman-group-exchange-sha1", 35) == 0) {
1873     if (prepare_dh(kex, SFTP_DH_GEX_SHA1) < 0) {
1874       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1875         "error using '%s' as the key exchange algorithm: %s", algo,
1876         strerror(errno));
1877       return -1;
1878     }
1879 
1880     kex->session_names->kex_algo = algo;
1881     kex->use_gex = TRUE;
1882     return 0;
1883   }
1884 
1885   if (strncmp(algo, "rsa1024-sha1", 13) == 0) {
1886     if (create_kexrsa(kex, SFTP_KEXRSA_SHA1) < 0) {
1887       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1888         "error using '%s' as the key exchange algorithm: %s", algo,
1889         strerror(errno));
1890       return -1;
1891     }
1892 
1893     kex->session_names->kex_algo = algo;
1894     kex->use_kexrsa = TRUE;
1895     return 0;
1896   }
1897 
1898 #if ((OPENSSL_VERSION_NUMBER > 0x000907000L && defined(OPENSSL_FIPS)) || \
1899      (OPENSSL_VERSION_NUMBER > 0x000908000L)) && \
1900      defined(HAVE_SHA256_OPENSSL)
1901   if (strncmp(algo, "diffie-hellman-group-exchange-sha256", 37) == 0) {
1902     if (prepare_dh(kex, SFTP_DH_GEX_SHA256) < 0) {
1903       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1904         "error using '%s' as the key exchange algorithm: %s", algo,
1905         strerror(errno));
1906       return -1;
1907     }
1908 
1909     kex->session_names->kex_algo = algo;
1910     kex->use_gex = TRUE;
1911     return 0;
1912   }
1913 
1914   if (strncmp(algo, "rsa2048-sha256", 15) == 0) {
1915     if (create_kexrsa(kex, SFTP_KEXRSA_SHA256) < 0) {
1916       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1917         "error using '%s' as the key exchange algorithm: %s", algo,
1918         strerror(errno));
1919       return -1;
1920     }
1921 
1922     kex->session_names->kex_algo = algo;
1923     kex->use_kexrsa = TRUE;
1924     return 0;
1925   }
1926 #endif
1927 
1928 #ifdef PR_USE_OPENSSL_ECC
1929   if (strncmp(algo, "ecdh-sha2-nistp256", 19) == 0) {
1930     if (create_ecdh(kex, SFTP_ECDH_SHA256) < 0) {
1931       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1932         "error using '%s' as the key exchange algorithm: %s", algo,
1933         strerror(errno));
1934       return -1;
1935     }
1936 
1937     kex->session_names->kex_algo = algo;
1938     kex->use_ecdh = TRUE;
1939     return 0;
1940   }
1941 
1942   if (strncmp(algo, "ecdh-sha2-nistp384", 19) == 0) {
1943     if (create_ecdh(kex, SFTP_ECDH_SHA384) < 0) {
1944       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1945         "error using '%s' as the key exchange algorithm: %s", algo,
1946         strerror(errno));
1947       return -1;
1948     }
1949 
1950     kex->session_names->kex_algo = algo;
1951     kex->use_ecdh = TRUE;
1952     return 0;
1953   }
1954 
1955   if (strncmp(algo, "ecdh-sha2-nistp521", 19) == 0) {
1956     if (create_ecdh(kex, SFTP_ECDH_SHA512) < 0) {
1957       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1958         "error using '%s' as the key exchange algorithm: %s", algo,
1959         strerror(errno));
1960       return -1;
1961     }
1962 
1963     kex->session_names->kex_algo = algo;
1964     kex->use_ecdh = TRUE;
1965     return 0;
1966   }
1967 #endif /* PR_USE_OPENSSL_ECC */
1968 
1969 #if defined(PR_USE_SODIUM) && defined(HAVE_SHA256_OPENSSL)
1970   if (strncmp(algo, "curve25519-sha256", 18) == 0 ||
1971       strncmp(algo, "curve25519-sha256@libssh.org", 29) == 0) {
1972     kex->hash = EVP_sha256();
1973     kex->session_names->kex_algo = algo;
1974     kex->use_curve25519 = TRUE;
1975     return 0;
1976   }
1977 #endif /* PR_USE_SODIUM and HAVE_SHA256_OPENSSL */
1978 
1979   if (strcmp(algo, "ext-info-c") == 0 ||
1980       strcmp(algo, "ext-info-s") == 0) {
1981     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1982       "unable to use extension negotiation algorithm '%s' for key exchange",
1983       algo);
1984     errno = EINVAL;
1985     return -1;
1986   }
1987 
1988   (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1989     "unsupported key exchange algorithm '%s'", algo);
1990   errno = EINVAL;
1991   return -1;
1992 }
1993 
1994 static int setup_hostkey_algo(struct sftp_kex *kex, const char *algo) {
1995   kex->session_names->server_hostkey_algo = (char *) algo;
1996 
1997   if (strncmp(algo, "ssh-dss", 8) == 0) {
1998     kex->use_hostkey_type = SFTP_KEY_DSA;
1999     return 0;
2000   }
2001 
2002   if (strncmp(algo, "ssh-rsa", 8) == 0) {
2003     kex->use_hostkey_type = SFTP_KEY_RSA;
2004     return 0;
2005   }
2006 
2007 #if defined(HAVE_SHA256_OPENSSL)
2008   if (strncmp(algo, "rsa-sha2-256", 12) == 0) {
2009     kex->use_hostkey_type = SFTP_KEY_RSA_SHA256;
2010     return 0;
2011   }
2012 #endif /* HAVE_SHA256_OPENSSL */
2013 
2014 #if defined(HAVE_SHA512_OPENSSL)
2015   if (strncmp(algo, "rsa-sha2-512", 12) == 0) {
2016     kex->use_hostkey_type = SFTP_KEY_RSA_SHA512;
2017     return 0;
2018   }
2019 #endif /* HAVE_SHA512_OPENSSL */
2020 
2021 #ifdef PR_USE_OPENSSL_ECC
2022   if (strncmp(algo, "ecdsa-sha2-nistp256", 20) == 0) {
2023     kex->use_hostkey_type = SFTP_KEY_ECDSA_256;
2024     return 0;
2025   }
2026 
2027   if (strncmp(algo, "ecdsa-sha2-nistp384", 20) == 0) {
2028     kex->use_hostkey_type = SFTP_KEY_ECDSA_384;
2029     return 0;
2030   }
2031 
2032   if (strncmp(algo, "ecdsa-sha2-nistp521", 20) == 0) {
2033     kex->use_hostkey_type = SFTP_KEY_ECDSA_521;
2034     return 0;
2035   }
2036 #endif /* PR_USE_OPENSSL_ECC */
2037 
2038 #ifdef PR_USE_SODIUM
2039   if (strncmp(algo, "ssh-ed25519", 12) == 0) {
2040     kex->use_hostkey_type = SFTP_KEY_ED25519;
2041     return 0;
2042   }
2043 #endif /* PR_USE_SODIUM */
2044 
2045   /* XXX Need to handle "x509v3-ssh-dss", "x509v3-ssh-rsa", "x509v3-sign"
2046    * algorithms here.
2047    */
2048 
2049   errno = EINVAL;
2050   return -1;
2051 }
2052 
2053 static int setup_c2s_encrypt_algo(struct sftp_kex *kex, const char *algo) {
2054   if (sftp_cipher_set_read_algo(algo) < 0) {
2055     return -1;
2056   }
2057 
2058   kex->session_names->c2s_encrypt_algo = algo;
2059   return 0;
2060 }
2061 
2062 static int setup_s2c_encrypt_algo(struct sftp_kex *kex, const char *algo) {
2063   if (sftp_cipher_set_write_algo(algo) < 0) {
2064     return -1;
2065   }
2066 
2067   kex->session_names->s2c_encrypt_algo = algo;
2068   return 0;
2069 }
2070 
2071 static int setup_c2s_mac_algo(struct sftp_kex *kex, const char *algo) {
2072   if (sftp_mac_set_read_algo(algo) < 0) {
2073     return -1;
2074   }
2075 
2076   kex->session_names->c2s_mac_algo = algo;
2077   return 0;
2078 }
2079 
2080 static int setup_s2c_mac_algo(struct sftp_kex *kex, const char *algo) {
2081   if (sftp_mac_set_write_algo(algo) < 0) {
2082     return -1;
2083   }
2084 
2085   kex->session_names->s2c_mac_algo = algo;
2086   return 0;
2087 }
2088 
2089 static int setup_c2s_comp_algo(struct sftp_kex *kex, const char *algo) {
2090   if (sftp_compress_set_read_algo(algo) < 0) {
2091     return -1;
2092   }
2093 
2094   kex->session_names->c2s_comp_algo = algo;
2095   return 0;
2096 }
2097 
2098 static int setup_s2c_comp_algo(struct sftp_kex *kex, const char *algo) {
2099   if (sftp_compress_set_write_algo(algo) < 0) {
2100     return -1;
2101   }
2102 
2103   kex->session_names->s2c_comp_algo = algo;
2104   return 0;
2105 }
2106 
2107 static int setup_c2s_lang(struct sftp_kex *kex, const char *lang) {
2108   /* XXX Need to implement the functionality here. */
2109   kex->session_names->c2s_lang = lang;
2110   return 0;
2111 }
2112 
2113 static int setup_s2c_lang(struct sftp_kex *kex, const char *lang) {
2114   /* XXX Need to implement the functionality here. */
2115   kex->session_names->s2c_lang = lang;
2116   return 0;
2117 }
2118 
2119 static int get_session_names(struct sftp_kex *kex, int *correct_guess) {
2120   const char *kex_algo, *shared, *client_list, *server_list;
2121   const char *client_pref, *server_pref;
2122   pool *tmp_pool;
2123 
2124   tmp_pool = make_sub_pool(kex->pool);
2125   pr_pool_tag(tmp_pool, "SSH2 session shared name pool");
2126 
2127   client_list = kex->client_names->kex_algo;
2128   server_list = kex->server_names->kex_algo;
2129 
2130   pr_trace_msg(trace_channel, 8, "client-sent key exchange algorithms: %s",
2131     client_list);
2132   pr_trace_msg(trace_channel, 8, "server-sent key exchange algorithms: %s",
2133     server_list);
2134 
2135   client_pref = get_preferred_name(tmp_pool, client_list);
2136   server_pref = get_preferred_name(tmp_pool, server_list);
2137 
2138   /* Did the client correctly guess at the key exchange algorithm that
2139    * we would list first in our server list, if it says it sent
2140    * a guess KEX packet?
2141    */
2142 
2143   if (kex->first_kex_follows == TRUE &&
2144       *correct_guess == TRUE &&
2145       client_pref != NULL &&
2146       server_pref != NULL) {
2147 
2148     if (strcmp(client_pref, server_pref) != 0) {
2149       *correct_guess = FALSE;
2150 
2151       pr_trace_msg(trace_channel, 7,
2152         "client incorrectly guessed key exchange algorithm '%s'", client_pref);
2153 
2154     } else {
2155       pr_trace_msg(trace_channel, 7,
2156         "client correctly guessed key exchange algorithm '%s'", server_pref);
2157     }
2158   }
2159 
2160   kex_algo = sftp_misc_namelist_shared(kex->pool, client_list, server_list);
2161   if (kex_algo != NULL) {
2162     /* Unlike the following algorithms, we wait to setup the chosen kex algo
2163      * until the end.  Why?  The kex algo setup may require knowledge of the
2164      * ciphers chosen for encryption, MAC, etc (Bug#4097).
2165      */
2166     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2167       " + Session key exchange: %s", kex_algo);
2168     pr_trace_msg(trace_channel, 20, "session key exchange algorithm: %s",
2169       kex_algo);
2170 
2171     /* Did the client indicate EXT_INFO support (Issue #984)? */
2172     kex->use_ext_info = sftp_misc_namelist_contains(kex->pool, client_list,
2173       "ext-info-c");
2174     pr_trace_msg(trace_channel, 20, "client %s EXT_INFO support",
2175       kex->use_ext_info ? "signaled" : "did not signal" );
2176 
2177   } else {
2178     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2179       "no shared key exchange algorithm found (client sent '%s', server sent "
2180       "'%s')", client_list, server_list);
2181     destroy_pool(tmp_pool);
2182     return -1;
2183   }
2184 
2185   client_list = kex->client_names->server_hostkey_algo;
2186   server_list = kex->server_names->server_hostkey_algo;
2187 
2188   pr_trace_msg(trace_channel, 8,
2189     "client-sent host key algorithms: %s", client_list);
2190   pr_trace_msg(trace_channel, 8,
2191     "server-sent host key algorithms: %s", server_list);
2192 
2193   shared = sftp_misc_namelist_shared(kex->pool, client_list, server_list);
2194   if (shared) {
2195     if (setup_hostkey_algo(kex, shared) < 0) {
2196       destroy_pool(tmp_pool);
2197       return -1;
2198     }
2199 
2200     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2201       " + Session server hostkey: %s", shared);
2202     pr_trace_msg(trace_channel, 20, "session server hostkey algorithm: %s",
2203       shared);
2204 
2205   } else {
2206     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2207       "no shared server hostkey algorithm found (client sent '%s', server sent "
2208       "'%s'", client_list, server_list);
2209     destroy_pool(tmp_pool);
2210     return -1;
2211   }
2212 
2213   client_list = kex->client_names->c2s_encrypt_algo;
2214   server_list = kex->server_names->c2s_encrypt_algo;
2215 
2216   pr_trace_msg(trace_channel, 8, "client-sent client encryption algorithms: %s",
2217     client_list);
2218   pr_trace_msg(trace_channel, 8, "server-sent client encryption algorithms: %s",
2219     server_list);
2220 
2221   shared = sftp_misc_namelist_shared(kex->pool, client_list, server_list);
2222   if (shared) {
2223     if (setup_c2s_encrypt_algo(kex, shared) < 0) {
2224       destroy_pool(tmp_pool);
2225       return -1;
2226     }
2227 
2228     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2229       " + Session client-to-server encryption: %s", shared);
2230     pr_trace_msg(trace_channel, 20,
2231       "session client-to-server encryption algorithm: %s", shared);
2232 
2233   } else {
2234     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2235       "no shared client-to-server encryption algorithm found (client sent '%s',"
2236       " server sent '%s')", client_list, server_list);
2237     destroy_pool(tmp_pool);
2238     return -1;
2239   }
2240 
2241   client_list = kex->client_names->s2c_encrypt_algo;
2242   server_list = kex->server_names->s2c_encrypt_algo;
2243 
2244   pr_trace_msg(trace_channel, 8, "client-sent server encryption algorithms: %s",
2245     client_list);
2246   pr_trace_msg(trace_channel, 8, "server-sent server encryption algorithms: %s",
2247     server_list);
2248 
2249   shared = sftp_misc_namelist_shared(kex->pool, client_list, server_list);
2250   if (shared) {
2251     if (setup_s2c_encrypt_algo(kex, shared) < 0) {
2252       destroy_pool(tmp_pool);
2253       return -1;
2254     }
2255 
2256     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2257       " + Session server-to-client encryption: %s", shared);
2258     pr_trace_msg(trace_channel, 20,
2259       "session server-to-client encryption algorithm: %s", shared);
2260 
2261   } else {
2262     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2263       "no shared server-to-client encryption algorithm found (client sent '%s',"
2264       " server sent '%s')", client_list, server_list);
2265     destroy_pool(tmp_pool);
2266     return -1;
2267   }
2268 
2269   client_list = kex->client_names->c2s_mac_algo;
2270   server_list = kex->server_names->c2s_mac_algo;
2271 
2272   pr_trace_msg(trace_channel, 8, "client-sent client MAC algorithms: %s",
2273     client_list);
2274   pr_trace_msg(trace_channel, 8, "server-sent client MAC algorithms: %s",
2275     server_list);
2276 
2277   shared = sftp_misc_namelist_shared(kex->pool, client_list, server_list);
2278   if (shared) {
2279     if (setup_c2s_mac_algo(kex, shared) < 0) {
2280       destroy_pool(tmp_pool);
2281       return -1;
2282     }
2283 
2284     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2285       " + Session client-to-server MAC: %s", shared);
2286     pr_trace_msg(trace_channel, 20,
2287       "session client-to-server MAC algorithm: %s", shared);
2288 
2289   } else {
2290     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2291       "no shared client-to-server MAC algorithm found (client sent '%s', "
2292       "server sent '%s')", client_list, server_list);
2293     destroy_pool(tmp_pool);
2294     return -1;
2295   }
2296 
2297   client_list = kex->client_names->s2c_mac_algo;
2298   server_list = kex->server_names->s2c_mac_algo;
2299 
2300   pr_trace_msg(trace_channel, 8, "client-sent server MAC algorithms: %s",
2301     client_list);
2302   pr_trace_msg(trace_channel, 8, "server-sent server MAC algorithms: %s",
2303     server_list);
2304 
2305   shared = sftp_misc_namelist_shared(kex->pool, client_list, server_list);
2306   if (shared) {
2307     if (setup_s2c_mac_algo(kex, shared) < 0) {
2308       destroy_pool(tmp_pool);
2309       return -1;
2310     }
2311 
2312     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2313       " + Session server-to-client MAC: %s", shared);
2314     pr_trace_msg(trace_channel, 20,
2315       "session server-to-client MAC algorithm: %s", shared);
2316 
2317   } else {
2318     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2319       "no shared server-to-client MAC algorithm found (client sent '%s', "
2320       "server sent '%s')", client_list, server_list);
2321     destroy_pool(tmp_pool);
2322     return -1;
2323   }
2324 
2325   client_list = kex->client_names->c2s_comp_algo;
2326   server_list = kex->server_names->c2s_comp_algo;
2327 
2328   pr_trace_msg(trace_channel, 8,
2329     "client-sent client compression algorithms: %s", client_list);
2330   pr_trace_msg(trace_channel, 8,
2331     "server-sent client compression algorithms: %s", server_list);
2332 
2333   shared = sftp_misc_namelist_shared(kex->pool, client_list, server_list);
2334   if (shared) {
2335     if (setup_c2s_comp_algo(kex, shared) < 0) {
2336       destroy_pool(tmp_pool);
2337       return -1;
2338     }
2339 
2340     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2341       " + Session client-to-server compression: %s", shared);
2342     pr_trace_msg(trace_channel, 20,
2343       "session client-to-server compression algorithm: %s", shared);
2344 
2345   } else {
2346     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2347       "no shared client-to-server compression algorithm found (client sent "
2348       "'%s', server sent '%s'", client_list, server_list);
2349     destroy_pool(tmp_pool);
2350     return -1;
2351   }
2352 
2353   client_list = kex->client_names->s2c_comp_algo;
2354   server_list = kex->server_names->s2c_comp_algo;
2355 
2356   pr_trace_msg(trace_channel, 8,
2357     "client-sent server compression algorithms: %s", client_list);
2358   pr_trace_msg(trace_channel, 8,
2359     "server-sent server compression algorithms: %s", server_list);
2360 
2361   shared = sftp_misc_namelist_shared(kex->pool, client_list, server_list);
2362   if (shared) {
2363     if (setup_s2c_comp_algo(kex, shared) < 0) {
2364       destroy_pool(tmp_pool);
2365       return -1;
2366     }
2367 
2368     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2369       " + Session server-to-client compression: %s", shared);
2370     pr_trace_msg(trace_channel, 20,
2371       "session server-to-client compression algorithm: %s", shared);
2372 
2373   } else {
2374     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2375       "no shared server-to-client compression algorithm found (client sent "
2376       "'%s', server sent '%s'", client_list, server_list);
2377     destroy_pool(tmp_pool);
2378     return -1;
2379   }
2380 
2381   client_list = kex->client_names->c2s_lang;
2382   server_list = kex->server_names->c2s_lang;
2383 
2384   pr_trace_msg(trace_channel, 8,
2385     "client-sent client languages: %s", client_list);
2386   pr_trace_msg(trace_channel, 8,
2387     "server-sent client languages: %s", client_list);
2388 
2389   shared = sftp_misc_namelist_shared(kex->pool, client_list, server_list);
2390   if (shared) {
2391     if (setup_c2s_lang(kex, shared) < 0) {
2392       destroy_pool(tmp_pool);
2393       return -1;
2394     }
2395 
2396     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2397       " + Session client-to-server language: %s", shared);
2398     pr_trace_msg(trace_channel, 20,
2399       "session client-to-server language: %s", shared);
2400 
2401 /* XXX Do not error out if there are no shared languages yet. */
2402 #if 0
2403   } else {
2404     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2405       "no shared client-to-server language found (client sent '%s', server "
2406       "sent '%s'", client_list, server_list);
2407     destroy_pool(tmp_pool);
2408     return -1;
2409 #endif
2410   }
2411 
2412   client_list = kex->client_names->s2c_lang;
2413   server_list = kex->server_names->s2c_lang;
2414 
2415   pr_trace_msg(trace_channel, 8,
2416     "client-sent server languages: %s", client_list);
2417   pr_trace_msg(trace_channel, 8,
2418     "server-sent server languages: %s", client_list);
2419 
2420   shared = sftp_misc_namelist_shared(kex->pool, client_list, server_list);
2421   if (shared) {
2422     if (setup_s2c_lang(kex, shared) < 0) {
2423       destroy_pool(tmp_pool);
2424       return -1;
2425     }
2426 
2427     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2428       " + Session server-to-client language: %s", shared);
2429     pr_trace_msg(trace_channel, 20,
2430       "session server-to-client language: %s", shared);
2431 
2432 /* XXX Do not error out if there are no shared languages yet. */
2433 #if 0
2434   } else {
2435     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2436       "no shared server-to-client language found (client sent '%s', server "
2437       "sent '%s'", client_list, server_list);
2438     destroy_pool(tmp_pool);
2439     return -1;
2440 #endif
2441   }
2442 
2443   /* Now that we've finished setting up the other bits, we can set up the
2444    * kex algo.
2445    */
2446   if (setup_kex_algo(kex, kex_algo) < 0) {
2447     destroy_pool(tmp_pool);
2448     return -1;
2449   }
2450 
2451   destroy_pool(tmp_pool);
2452   return 0;
2453 }
2454 
2455 static int read_kexinit(struct ssh2_packet *pkt, struct sftp_kex *kex) {
2456   unsigned char *buf;
2457   char *list;
2458   uint32_t buflen;
2459 
2460   buf = pkt->payload;
2461   buflen = pkt->payload_len;
2462 
2463   /* Make a copy of the payload for later. */
2464   kex->client_kexinit_payload = palloc(kex->pool, pkt->payload_len);
2465   kex->client_kexinit_payload_len = pkt->payload_len;
2466   memcpy(kex->client_kexinit_payload, pkt->payload, pkt->payload_len);
2467 
2468   /* Read the cookie, which is a mandated length of 16 bytes. */
2469   (void) sftp_msg_read_data(pkt->pool, &buf, &buflen, 16);
2470 
2471   list = sftp_msg_read_string(kex->pool, &buf, &buflen);
2472   kex->client_names->kex_algo = list;
2473 
2474   list = sftp_msg_read_string(kex->pool, &buf, &buflen);
2475   kex->client_names->server_hostkey_algo = list;
2476 
2477   list = sftp_msg_read_string(kex->pool, &buf, &buflen);
2478   kex->client_names->c2s_encrypt_algo = list;
2479 
2480   list = sftp_msg_read_string(kex->pool, &buf, &buflen);
2481   kex->client_names->s2c_encrypt_algo = list;
2482 
2483   list = sftp_msg_read_string(kex->pool, &buf, &buflen);
2484   kex->client_names->c2s_mac_algo = list;
2485 
2486   list = sftp_msg_read_string(kex->pool, &buf, &buflen);
2487   kex->client_names->s2c_mac_algo = list;
2488 
2489   list = sftp_msg_read_string(kex->pool, &buf, &buflen);
2490   kex->client_names->c2s_comp_algo = list;
2491 
2492   list = sftp_msg_read_string(kex->pool, &buf, &buflen);
2493   kex->client_names->s2c_comp_algo = list;
2494 
2495   /* Client-to-server languages */
2496   list = sftp_msg_read_string(kex->pool, &buf, &buflen);
2497   kex->client_names->c2s_lang = list;
2498 
2499   /* Server-to-client languages */
2500   list = sftp_msg_read_string(kex->pool, &buf, &buflen);
2501   kex->client_names->s2c_lang = list;
2502 
2503   /* Read the "first kex packet follows" byte */
2504   kex->first_kex_follows = sftp_msg_read_bool(pkt->pool, &buf, &buflen);
2505 
2506   pr_trace_msg(trace_channel, 3, "first kex packet follows = %s",
2507     kex->first_kex_follows ? "true" : "false");
2508 
2509   /* Reserved flags */
2510   (void) sftp_msg_read_int(pkt->pool, &buf, &buflen);
2511 
2512   return 0;
2513 }
2514 
2515 static int write_kexinit(struct ssh2_packet *pkt, struct sftp_kex *kex) {
2516   unsigned char cookie[16];
2517   unsigned char *buf, *ptr;
2518   const char *list;
2519   uint32_t bufsz, buflen;
2520 
2521   /* XXX Always have empty language lists; we really don't care. */
2522   const char *langs = "";
2523 
2524   bufsz = buflen = sizeof(char) +
2525     sizeof(cookie) +
2526     sizeof(uint32_t) + strlen(kex->server_names->kex_algo) +
2527     sizeof(uint32_t) + strlen(kex->server_names->server_hostkey_algo) +
2528     sizeof(uint32_t) + strlen(kex->server_names->c2s_encrypt_algo) +
2529     sizeof(uint32_t) + strlen(kex->server_names->s2c_encrypt_algo) +
2530     sizeof(uint32_t) + strlen(kex->server_names->c2s_mac_algo) +
2531     sizeof(uint32_t) + strlen(kex->server_names->s2c_mac_algo) +
2532     sizeof(uint32_t) + strlen(kex->server_names->c2s_comp_algo) +
2533     sizeof(uint32_t) + strlen(kex->server_names->s2c_comp_algo) +
2534     sizeof(uint32_t) + strlen(langs) +
2535     sizeof(uint32_t) + strlen(langs) +
2536     sizeof(char) +
2537     sizeof(uint32_t);
2538 
2539   ptr = buf = pcalloc(pkt->pool, bufsz);
2540 
2541   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEXINIT);
2542 
2543   /* Try first to use cryptographically secure bytes for the cookie.
2544    * If that fails (e.g. if the PRNG hasn't been seeded well), use
2545    * pseudo-cryptographically secure bytes.
2546    */
2547   memset(cookie, 0, sizeof(cookie));
2548 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
2549   RAND_bytes(cookie, sizeof(cookie));
2550 #else
2551   if (RAND_bytes(cookie, sizeof(cookie)) != 1) {
2552     RAND_pseudo_bytes(cookie, sizeof(cookie));
2553   }
2554 #endif /* prior to OpenSSL-1.1.0 */
2555 
2556   sftp_msg_write_data(&buf, &buflen, cookie, sizeof(cookie), FALSE);
2557 
2558   list = kex->server_names->kex_algo;
2559   sftp_msg_write_string(&buf, &buflen, list);
2560 
2561   list = kex->server_names->server_hostkey_algo;
2562   sftp_msg_write_string(&buf, &buflen, list);
2563 
2564   list = kex->server_names->c2s_encrypt_algo;
2565   sftp_msg_write_string(&buf, &buflen, list);
2566 
2567   list = kex->server_names->s2c_encrypt_algo;
2568   sftp_msg_write_string(&buf, &buflen, list);
2569 
2570   list = kex->server_names->c2s_mac_algo;
2571   sftp_msg_write_string(&buf, &buflen, list);
2572 
2573   list = kex->server_names->s2c_mac_algo;
2574   sftp_msg_write_string(&buf, &buflen, list);
2575 
2576   list = kex->server_names->c2s_comp_algo;
2577   sftp_msg_write_string(&buf, &buflen, list);
2578 
2579   list = kex->server_names->s2c_comp_algo;
2580   sftp_msg_write_string(&buf, &buflen, list);
2581 
2582   /* XXX Need to support langs here. */
2583   sftp_msg_write_string(&buf, &buflen, langs);
2584   sftp_msg_write_string(&buf, &buflen, langs);
2585 
2586   /* We don't try to optimistically guess what algorithms the client would
2587    * use and send a preemptive kex packet.
2588    */
2589   sftp_msg_write_bool(&buf, &buflen, FALSE);
2590   sftp_msg_write_int(&buf, &buflen, 0);
2591 
2592   pkt->payload = ptr;
2593   pkt->payload_len = (bufsz - buflen);
2594 
2595   /* Make a copy of the payload for later. Skip past the first byte, which
2596    * is the KEXINIT identifier.
2597    */
2598   kex->server_kexinit_payload_len = pkt->payload_len - 1;
2599   kex->server_kexinit_payload = palloc(kex->pool, pkt->payload_len - 1);
2600   memcpy(kex->server_kexinit_payload, pkt->payload + 1, pkt->payload_len - 1);
2601 
2602   return 0;
2603 }
2604 
2605 static int read_dh_init(struct ssh2_packet *pkt, struct sftp_kex *kex) {
2606   unsigned char *buf;
2607   uint32_t buflen;
2608 
2609   buf = pkt->payload;
2610   buflen = pkt->payload_len;
2611 
2612   /* Read in 'e' */
2613   kex->e = sftp_msg_read_mpint(pkt->pool, &buf, &buflen);
2614   if (kex->e == NULL) {
2615     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2616       "error reading DH_INIT: %s", strerror(errno));
2617     return -1;
2618   }
2619 
2620   return 0;
2621 }
2622 
2623 /* Only set the given environment variable/value IFF it is not already
2624  * present.
2625  */
2626 static void set_env_var(pool *p, const char *k, const char *v) {
2627   const char *val;
2628   int have_val = FALSE;
2629 
2630   val = pr_env_get(p, k);
2631   if (val != NULL) {
2632     if (strcmp(val, v) == 0) {
2633       have_val = TRUE;
2634     }
2635   }
2636 
2637   if (have_val == FALSE) {
2638     k = pstrdup(p, k);
2639     v = pstrdup(p, v);
2640     pr_env_unset(p, k);
2641     pr_env_set(p, k, v);
2642   }
2643 }
2644 
2645 static int set_session_keys(struct sftp_kex *kex) {
2646   const char *k;
2647   int comp_read_flags, comp_write_flags;
2648 
2649   if (sftp_cipher_set_read_key(kex_pool, kex->hash, kex->k, kex->h,
2650       kex->hlen, SFTP_ROLE_SERVER) < 0) {
2651     return -1;
2652   }
2653 
2654   if (sftp_cipher_set_write_key(kex_pool, kex->hash, kex->k, kex->h,
2655       kex->hlen, SFTP_ROLE_SERVER) < 0) {
2656     return -1;
2657   }
2658 
2659   if (sftp_mac_set_read_key(kex_pool, kex->hash, kex->k, kex->h,
2660       kex->hlen, SFTP_ROLE_SERVER) < 0) {
2661     return -1;
2662   }
2663 
2664   if (sftp_mac_set_write_key(kex_pool, kex->hash, kex->k, kex->h,
2665       kex->hlen, SFTP_ROLE_SERVER) < 0) {
2666     return -1;
2667   }
2668 
2669   comp_read_flags = comp_write_flags = SFTP_COMPRESS_FL_NEW_KEY;
2670 
2671   /* If we are rekeying, AND the existing compression is "delayed", then
2672    * we need to use slightly different compression flags.
2673    */
2674   if (kex_rekey_kex) {
2675     const char *algo;
2676 
2677     algo = sftp_compress_get_read_algo();
2678     if (strncmp(algo, "zlib@openssh.com", 17) == 0) {
2679       comp_read_flags = SFTP_COMPRESS_FL_AUTHENTICATED;
2680     }
2681 
2682     algo = sftp_compress_get_write_algo();
2683     if (strncmp(algo, "zlib@openssh.com", 17) == 0) {
2684       comp_write_flags = SFTP_COMPRESS_FL_AUTHENTICATED;
2685     }
2686   }
2687 
2688   if (sftp_compress_init_read(comp_read_flags) < 0) {
2689     return -1;
2690   }
2691 
2692   if (sftp_compress_init_write(comp_write_flags) < 0) {
2693     return -1;
2694   }
2695 
2696   set_env_var(session.pool, "SFTP_CLIENT_CIPHER_ALGO",
2697     sftp_cipher_get_read_algo());
2698   set_env_var(session.pool, "SFTP_SERVER_CIPHER_ALGO",
2699     sftp_cipher_get_write_algo());
2700   set_env_var(session.pool, "SFTP_CLIENT_MAC_ALGO",
2701     sftp_mac_get_read_algo());
2702   set_env_var(session.pool, "SFTP_SERVER_MAC_ALGO",
2703     sftp_mac_get_write_algo());
2704   set_env_var(session.pool, "SFTP_CLIENT_COMPRESSION_ALGO",
2705     sftp_compress_get_read_algo());
2706   set_env_var(session.pool, "SFTP_SERVER_COMPRESSION_ALGO",
2707     sftp_compress_get_write_algo());
2708   set_env_var(session.pool, "SFTP_KEX_ALGO",
2709     kex->session_names->kex_algo);
2710 
2711   if (kex_rekey_interval > 0 &&
2712       kex_rekey_timerno == -1) {
2713     /* Register the rekey timer. */
2714     kex_rekey_timerno = pr_timer_add(kex_rekey_interval, -1,
2715       &sftp_module, kex_rekey_timer_cb, "SFTP KEX Rekey timer");
2716   }
2717 
2718   if (kex_rekey_timeout > 0 &&
2719       kex_rekey_timeout_timerno > 0) {
2720     pr_timer_remove(kex_rekey_timeout_timerno, &sftp_module);
2721     kex_rekey_timeout_timerno = -1;
2722   }
2723 
2724   if (kex_rekey_kex != NULL) {
2725     pr_trace_msg("ssh2", 3, "rekey KEX completed");
2726   }
2727 
2728   sftp_ssh2_packet_rekey_reset();
2729   kex_rekey_kex = NULL;
2730 
2731   /* If any CBC mode ciphers have been negotiated for the server-to-client
2732    * stream, then we need to use the 'rogaway' TAP policy.
2733    */
2734   k = sftp_cipher_get_write_algo();
2735   if (strncmp(k + strlen(k) - 4, "-cbc", 4) == 0) {
2736     const char *policy = "rogaway";
2737 
2738     pr_trace_msg("ssh2", 4, "CBC mode cipher chosen for server-to-client "
2739       "messages, automatically enabling '%s' TAP policy", policy);
2740 
2741     if (sftp_tap_set_policy(policy) < 0) {
2742       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2743         "error setting TrafficPolicy '%s': %s", policy, strerror(errno));
2744     }
2745   }
2746 
2747   return 0;
2748 }
2749 
2750 static int write_dh_reply(struct ssh2_packet *pkt, struct sftp_kex *kex) {
2751   const unsigned char *h;
2752   const unsigned char *hostkey_data, *hsig;
2753   unsigned char *buf, *ptr;
2754   uint32_t bufsz, buflen, hlen = 0, hostkey_datalen = 0;
2755   size_t dhlen, hsiglen;
2756   BIGNUM *k = NULL, *dh_pub_key = NULL;
2757   int res;
2758 
2759   /* Compute the shared secret */
2760   dhlen = DH_size(kex->dh);
2761   buf = palloc(pkt->pool, dhlen);
2762 
2763   pr_trace_msg(trace_channel, 12, "computing DH key");
2764   res = DH_compute_key((unsigned char *) buf, kex->e, kex->dh);
2765   if (res < 0) {
2766     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2767       "error computing DH shared secret: %s", sftp_crypto_get_errors());
2768     return -1;
2769   }
2770 
2771   k = BN_new();
2772   if (BN_bin2bn((unsigned char *) buf, res, k) == NULL) {
2773     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2774       "error converting DH shared secret to BN: %s", sftp_crypto_get_errors());
2775 
2776     pr_memscrub(buf, res);
2777     return -1;
2778   }
2779 
2780   pr_memscrub(buf, res);
2781   kex->k = k;
2782 
2783   /* Get the hostkey data; it will be part of the data we hash in order
2784    * to create the session key.
2785    */
2786   hostkey_data = sftp_keys_get_hostkey_data(pkt->pool, kex->use_hostkey_type,
2787     &hostkey_datalen);
2788   if (hostkey_data == NULL) {
2789     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2790       "error converting hostkey for signing: %s", strerror(errno));
2791 
2792     BN_clear_free(kex->k);
2793     kex->k = NULL;
2794     return -1;
2795   }
2796 
2797   /* Calculate H */
2798   h = calculate_h(kex, hostkey_data, hostkey_datalen, k, &hlen);
2799   if (h == NULL) {
2800     pr_memscrub((char *) hostkey_data, hostkey_datalen);
2801     BN_clear_free(kex->k);
2802     kex->k = NULL;
2803     return -1;
2804   }
2805 
2806   kex->h = palloc(pkt->pool, hlen);
2807   kex->hlen = hlen;
2808   memcpy((char *) kex->h, h, kex->hlen);
2809 
2810   /* Save H as the session ID */
2811   sftp_session_set_id(h, hlen);
2812 
2813   /* Sign H with our hostkey */
2814   hsig = sftp_keys_sign_data(pkt->pool, kex->use_hostkey_type, h, hlen,
2815     &hsiglen);
2816   if (hsig == NULL) {
2817     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error signing H");
2818     pr_memscrub((char *) hostkey_data, hostkey_datalen);
2819     BN_clear_free(kex->k);
2820     kex->k = NULL;
2821     return -1;
2822   }
2823 
2824   /* XXX Is this large enough?  Too large? */
2825   buflen = bufsz = 8192;
2826   ptr = buf = palloc(pkt->pool, bufsz);
2827 
2828   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEX_DH_REPLY);
2829   sftp_msg_write_data(&buf, &buflen, hostkey_data, hostkey_datalen, TRUE);
2830 
2831 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
2832     !defined(HAVE_LIBRESSL)
2833   DH_get0_key(kex->dh, &dh_pub_key, NULL);
2834 #else
2835   dh_pub_key = kex->dh->pub_key;
2836 #endif /* prior to OpenSSL-1.1.0 */
2837   sftp_msg_write_mpint(&buf, &buflen, dh_pub_key);
2838 
2839   sftp_msg_write_data(&buf, &buflen, hsig, hsiglen, TRUE);
2840 
2841   /* Scrub any sensitive data when done */
2842   pr_memscrub((char *) hostkey_data, hostkey_datalen);
2843   pr_memscrub((char *) hsig, hsiglen);
2844 
2845   pkt->payload = ptr;
2846   pkt->payload_len = (bufsz - buflen);
2847 
2848   return 0;
2849 }
2850 
2851 static int write_newkeys_reply(struct ssh2_packet *pkt) {
2852   unsigned char *buf, *ptr;
2853   uint32_t bufsz, buflen;
2854 
2855   /* Write out the NEWKEYS message. */
2856   bufsz = buflen = 1;
2857   ptr = buf = palloc(pkt->pool, bufsz);
2858 
2859   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_NEWKEYS);
2860 
2861   pkt->payload = ptr;
2862   pkt->payload_len = (bufsz - buflen);
2863 
2864   return 0;
2865 }
2866 
2867 static int write_ext_info_server_sig_algs(struct ssh2_packet *pkt,
2868     unsigned char **buf, uint32_t *buflen) {
2869   char *sig_algs = "";
2870 
2871 #if defined(PR_USE_SODIUM)
2872   sig_algs = pstrcat(pkt->pool, sig_algs, *sig_algs ? "," : "", "ssh-ed25519",
2873     NULL);
2874 #endif /* PR_USE_SODIUM */
2875 
2876 #if defined(HAVE_SHA256_OPENSSL)
2877   sig_algs = pstrcat(pkt->pool, sig_algs, *sig_algs ? "," : "", "rsa-sha2-256",
2878     NULL);
2879 #endif /* HAVE_SHA256_OPENSSL */
2880 
2881 #if defined(HAVE_SHA512_OPENSSL)
2882   sig_algs = pstrcat(pkt->pool, sig_algs, *sig_algs ? "," : "", "rsa-sha2-512",
2883     NULL);
2884 #endif /* HAVE_SHA512_OPENSSL */
2885 
2886 #if defined(PR_USE_OPENSSL_ECC)
2887   sig_algs = pstrcat(pkt->pool, sig_algs, *sig_algs ? "," : "",
2888     "ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521", NULL);
2889 #endif /* PR_USE_OPENSSL_ECC */
2890 
2891   sig_algs = pstrcat(pkt->pool, sig_algs, *sig_algs ? "," : "", "ssh-rsa",
2892     NULL);
2893 #if !defined(OPENSSL_NO_DSA)
2894   sig_algs = pstrcat(pkt->pool, sig_algs, ",", "ssh-dss", NULL);
2895 #endif /* OPENSSL_NO_DSA */
2896 
2897   pr_trace_msg(trace_channel, 11,
2898     "writing 'server-sig-algs' EXT_INFO extension: %s", sig_algs);
2899 
2900   sftp_msg_write_string(buf, buflen, "server-sig-algs");
2901   sftp_msg_write_string(buf, buflen, sig_algs);
2902 
2903   return 0;
2904 }
2905 
2906 static int write_ext_info(struct ssh2_packet *pkt) {
2907   unsigned char *buf, *ptr;
2908   uint32_t bufsz, buflen, ext_count = 1;
2909 
2910   /* XXX Is this large enough?  Too large? */
2911   buflen = bufsz = 8192;
2912   ptr = buf = palloc(pkt->pool, bufsz);
2913 
2914   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_EXT_INFO);
2915 
2916   /* TODO: Consider supporting the "no-flow-control" extension. */
2917 
2918   ext_count = 1;
2919   sftp_msg_write_int(&buf, &buflen, ext_count);
2920   write_ext_info_server_sig_algs(pkt, &buf, &buflen);
2921 
2922   pkt->payload = ptr;
2923   pkt->payload_len = (bufsz - buflen);
2924 
2925   return 0;
2926 }
2927 
2928 static int handle_kex_dh(struct ssh2_packet *pkt, struct sftp_kex *kex) {
2929   int res;
2930   cmd_rec *cmd;
2931 
2932   cmd = pr_cmd_alloc(pkt->pool, 1, pstrdup(pkt->pool, "DH_INIT"));
2933   cmd->arg = "(data)";
2934   cmd->cmd_class = CL_AUTH|CL_SSH;
2935 
2936   pr_trace_msg(trace_channel, 9, "reading DH_INIT message from client");
2937 
2938   res = read_dh_init(pkt, kex);
2939   if (res < 0) {
2940     pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
2941 
2942     destroy_pool(pkt->pool);
2943     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
2944   }
2945 
2946   pr_cmd_dispatch_phase(cmd, LOG_CMD, 0);
2947   destroy_pool(pkt->pool);
2948 
2949   pr_trace_msg(trace_channel, 9, "writing DH_INIT message to client");
2950 
2951   /* Send our key exchange reply. */
2952   pkt = sftp_ssh2_packet_create(kex_pool);
2953   res = write_dh_reply(pkt, kex);
2954   if (res < 0) {
2955     destroy_pool(pkt->pool);
2956     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
2957   }
2958 
2959   res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt);
2960   if (res < 0) {
2961     destroy_pool(pkt->pool);
2962     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
2963   }
2964 
2965   destroy_pool(pkt->pool);
2966   return 0;
2967 }
2968 
2969 static int read_dh_gex(struct ssh2_packet *pkt, uint32_t *min, uint32_t *pref,
2970     uint32_t *max, int old_request) {
2971   unsigned char *buf;
2972   uint32_t buflen;
2973 
2974   buf = pkt->payload;
2975   buflen = pkt->payload_len;
2976 
2977   if (!old_request) {
2978     *min = sftp_msg_read_int(pkt->pool, &buf, &buflen);
2979     if (*min < SFTP_KEX_DH_GROUP_MIN) {
2980       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2981         "DH_GEX_REQUEST min value (%lu) too small (< %lu)",
2982         (unsigned long) *min, (unsigned long) SFTP_KEX_DH_GROUP_MIN);
2983       return -1;
2984     }
2985 
2986     *pref = sftp_msg_read_int(pkt->pool, &buf, &buflen);
2987 
2988     *max = sftp_msg_read_int(pkt->pool, &buf, &buflen);
2989     if (*max > SFTP_KEX_DH_GROUP_MAX) {
2990       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
2991         "DH_GEX_REQUEST max value (%lu) too large (> %lu)",
2992         (unsigned long) *max, (unsigned long) SFTP_KEX_DH_GROUP_MAX);
2993       return -1;
2994     }
2995 
2996   } else {
2997     *min = SFTP_KEX_DH_GROUP_MIN;
2998     *pref = sftp_msg_read_int(pkt->pool, &buf, &buflen);
2999     *max = SFTP_KEX_DH_GROUP_MAX;
3000   }
3001 
3002   if (*max < *min ||
3003       *pref < *min ||
3004       *pref > *max) {
3005     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3006       "bad DH_GEX_REQUEST parameters: min = %lu, pref = %lu, max = %lu",
3007       (unsigned long) *min, (unsigned long) *pref, (unsigned long) *max);
3008     return -1;
3009   }
3010 
3011   return 0;
3012 }
3013 
3014 static int get_dh_gex_group(struct sftp_kex *kex, uint32_t min,
3015     uint32_t pref, uint32_t max) {
3016   const char *dhparam_path;
3017   config_rec *c;
3018   int use_fixed_modulus = FALSE;
3019 
3020   dhparam_path = PR_CONFIG_DIR "/dhparams.pem";
3021   c = find_config(main_server->conf, CONF_PARAM, "SFTPDHParamFile", FALSE);
3022   if (c != NULL) {
3023     dhparam_path = c->argv[0];
3024   }
3025 
3026   /* If the preferred DH is less than SFTP_DH_MIN_LEN, AND the AllowWeakDH
3027    * SFTPOption is not used, then use a pref of SFTP_DH_MIN_LEN (Bug#4184).
3028    */
3029   if (pref < SFTP_DH_MIN_LEN) {
3030     if (!(sftp_opts & SFTP_OPT_ALLOW_WEAK_DH)) {
3031       pref = SFTP_DH_MIN_LEN;
3032 
3033     } else {
3034       pr_trace_msg(trace_channel, 14,
3035        "client prefers relatively weak DH group size (%lu) but AllowWeakDH "
3036        "SFTPOption in effect", (unsigned long) pref);
3037     }
3038   }
3039 
3040   if (dhparam_path) {
3041     if (kex_dhparams_fp != NULL) {
3042       /* Rewind to the start of the file. */
3043       fseek(kex_dhparams_fp, 0, SEEK_SET);
3044 
3045     } else {
3046       kex_dhparams_fp = fopen(dhparam_path, "r");
3047     }
3048 
3049     if (kex_dhparams_fp) {
3050       register unsigned int i;
3051       pool *tmp_pool;
3052       array_header *smaller_dhs, *pref_dhs, *larger_dhs;
3053       DH *chosen_dh, **dhs;
3054       uint32_t smaller_dh_nbits = 0, larger_dh_nbits = 0;
3055 
3056       pr_trace_msg(trace_channel, 15,
3057         "using DH parameters from SFTPDHParamFile '%s' for group exchange",
3058         dhparam_path);
3059 
3060       tmp_pool = make_sub_pool(kex->pool);
3061       pr_pool_tag(tmp_pool, "Kex DHparams selection pool");
3062 
3063       smaller_dhs = make_array(tmp_pool, 1, sizeof(DH *));
3064       pref_dhs = make_array(tmp_pool, 1, sizeof(DH *));
3065       larger_dhs = make_array(tmp_pool, 1, sizeof(DH *));
3066 
3067       /* From Section 3 of RFC4419:
3068        *
3069        *  "The server should return the smallest group it knows that is larger
3070        *   than the size the client requested.  If the server does not know a
3071        *   group that is larger than the client request, then it SHOULD return
3072        *   the largest group it knows.  In all cases, the size of the returned
3073        *   group SHOULD be at least 1024 bits."
3074        *
3075        * Make lists of DHs in the param file whose size falls within the
3076        * bit lengths requested by the client.  Note that DH_size() returns
3077        * the sizes _in bytes_, not bits.  We have three lists: one for DHs
3078        * which match the client-requested preferred size, one for DHs which
3079        * are smaller than the preferred size, and one for DHs which are larger
3080        * than the preferred size.  DHs in these last two lists will be of the
3081        * same size.  Once the lists are populated, we will randomly choose one
3082        * from the preferred DH list (if available), else one from the larger
3083        * DH list (if available), else one from the smaller DH list.
3084        */
3085 
3086       while (TRUE) {
3087         uint32_t nbits;
3088 
3089         pr_signals_handle();
3090 
3091         chosen_dh = PEM_read_DHparams(kex_dhparams_fp, NULL, NULL, NULL);
3092         if (chosen_dh == NULL) {
3093           if (!feof(kex_dhparams_fp)) {
3094             pr_trace_msg(trace_channel, 5, "error reading DH params from "
3095               "SFTPDHParamFile '%s': %s", dhparam_path,
3096               sftp_crypto_get_errors());
3097           }
3098 
3099           break;
3100         }
3101 
3102         nbits = DH_size(chosen_dh) * 8;
3103 
3104         if (nbits < min ||
3105             nbits > max) {
3106           pr_trace_msg(trace_channel, 17,
3107             "skipping %lu-bit DH from %s (exceeds min %lu, max %lu bits)",
3108             (unsigned long) nbits, dhparam_path, (unsigned long) min,
3109             (unsigned long) max);
3110           DH_free(chosen_dh);
3111           continue;
3112         }
3113 
3114         if (nbits == pref) {
3115           *((DH **) push_array(pref_dhs)) = chosen_dh;
3116 
3117         } else if (nbits < pref) {
3118           if (nbits > smaller_dh_nbits) {
3119             if (smaller_dhs->nelts > 0) {
3120               dhs = smaller_dhs->elts;
3121               for (i = 0; i < smaller_dhs->nelts; i++) {
3122                 DH_free(dhs[i]);
3123               }
3124 
3125               clear_array(smaller_dhs);
3126             }
3127 
3128             smaller_dh_nbits = nbits;
3129             *((DH **) push_array(smaller_dhs)) = chosen_dh;
3130 
3131           } else if (nbits == smaller_dh_nbits) {
3132             *((DH **) push_array(smaller_dhs)) = chosen_dh;
3133 
3134           } else {
3135             DH_free(chosen_dh);
3136           }
3137 
3138         } else {
3139           /* By process of elimination, nbits here MUST be > pref. */
3140 
3141           if (nbits < larger_dh_nbits) {
3142             if (larger_dhs->nelts > 0) {
3143               dhs = larger_dhs->elts;
3144               for (i = 0; i < larger_dhs->nelts; i++) {
3145                 DH_free(dhs[i]);
3146               }
3147 
3148               clear_array(larger_dhs);
3149             }
3150 
3151             larger_dh_nbits = nbits;
3152             *((DH **) push_array(larger_dhs)) = chosen_dh;
3153 
3154           } else if (nbits == larger_dh_nbits) {
3155             *((DH **) push_array(larger_dhs)) = chosen_dh;
3156 
3157           } else {
3158             DH_free(chosen_dh);
3159           }
3160         }
3161       }
3162 
3163       chosen_dh = NULL;
3164 
3165       /* The use of rand(3) below is NOT intended to be perfect, or even
3166        * uniformly distributed.  It simply needs to be good enough to pick
3167        * a single item from a small list, where all items are equally
3168        * usable and valid.
3169        *
3170        * Ideally we want to find a preferred DH first.  Failing that, a larger
3171        * DH is better; if none found there, then we settle for a smaller DH.
3172        */
3173 
3174       if (pref_dhs->nelts > 0) {
3175         int r = (int) (rand() / (RAND_MAX / pref_dhs->nelts + 1));
3176 
3177         pr_trace_msg(trace_channel, 17,
3178           "%s DH selection: preferred DHs (count %u, idx %d)", dhparam_path,
3179           pref_dhs->nelts, r);
3180         dhs = pref_dhs->elts;
3181         chosen_dh = dhs[r];
3182 
3183       } else if (larger_dhs->nelts > 0) {
3184         int r = (int) (rand() / (RAND_MAX / larger_dhs->nelts + 1));
3185 
3186         pr_trace_msg(trace_channel, 17,
3187           "%s DH selection: larger DHs (count %u, idx %d)", dhparam_path,
3188           larger_dhs->nelts, r);
3189         dhs = larger_dhs->elts;
3190         chosen_dh = dhs[r];
3191 
3192       } else if (smaller_dhs->nelts > 0) {
3193         int r = (int) (rand() / (RAND_MAX / smaller_dhs->nelts + 1));
3194 
3195         pr_trace_msg(trace_channel, 17,
3196           "%s DH selection: smaller DHs (count %u, idx %d)", dhparam_path,
3197           smaller_dhs->nelts, r);
3198         dhs = smaller_dhs->elts;
3199         chosen_dh = dhs[r];
3200 
3201       } else {
3202         (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3203           "unable to find suitable DH in SFTPDHParamFile '%s' for %lu-%lu "
3204           "bit sizes", dhparam_path, (unsigned long) min, (unsigned long) max);
3205         (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3206           "WARNING: using fixed modulus for DH group exchange");
3207         use_fixed_modulus = TRUE;
3208       }
3209 
3210       if (chosen_dh != NULL) {
3211         BIGNUM *dh_p = NULL, *dh_g = NULL, *dup_p, *dup_g;
3212 
3213         pr_trace_msg(trace_channel, 20, "client requested min %lu, pref %lu, "
3214           "max %lu sizes for DH group exchange, selected DH of %lu bits",
3215           (unsigned long) min, (unsigned long) pref, (unsigned long) max,
3216           (unsigned long) DH_size(chosen_dh) * 8);
3217 
3218         /* Get the P, G parameters of the chosen DH group, and make copies
3219          * of them for our KEX DH.
3220          */
3221 
3222 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
3223     !defined(HAVE_LIBRESSL)
3224         DH_get0_pqg(chosen_dh, &dh_p, NULL, &dh_g);
3225 #else
3226         dh_p = chosen_dh->p;
3227         dh_g = chosen_dh->g;
3228 #endif /* prior to OpenSSL-1.1.0 */
3229 
3230         dup_p = BN_dup(dh_p);
3231         if (dup_p == NULL) {
3232           (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3233             "error copying selected DH P: %s", sftp_crypto_get_errors());
3234           (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3235             "WARNING: using fixed modulus for DH group exchange");
3236           use_fixed_modulus = TRUE;
3237 
3238         } else {
3239           dup_g = BN_dup(dh_g);
3240           if (dup_g == NULL) {
3241             (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3242               "error copying selected DH G: %s", sftp_crypto_get_errors());
3243             (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3244               "WARNING: using fixed modulus for DH group exchange");
3245             BN_clear_free(dup_p);
3246             use_fixed_modulus = TRUE;
3247 
3248           } else {
3249             /* Now set those P, G copies into our KEX DH. */
3250 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
3251     !defined(HAVE_LIBRESSL)
3252             DH_set0_pqg(kex->dh, dup_p, NULL, dup_g);
3253 #else
3254             kex->dh->p = dup_p;
3255             kex->dh->g = dup_g;
3256 #endif /* prior to OpenSSL-1.1.0 */
3257           }
3258         }
3259       }
3260 
3261       /* Don't forget to clean up all of the allocated DHs. */
3262       dhs = (DH **) smaller_dhs->elts;
3263       for (i = 0; i < smaller_dhs->nelts; i++) {
3264         pr_signals_handle();
3265         DH_free(dhs[i]);
3266       }
3267 
3268       dhs = (DH **) pref_dhs->elts;
3269       for (i = 0; i < pref_dhs->nelts; i++) {
3270         pr_signals_handle();
3271         DH_free(dhs[i]);
3272       }
3273 
3274       dhs = (DH **) larger_dhs->elts;
3275       for (i = 0; i < larger_dhs->nelts; i++) {
3276         pr_signals_handle();
3277         DH_free(dhs[i]);
3278       }
3279 
3280       destroy_pool(tmp_pool);
3281 
3282     } else {
3283       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3284         "WARNING: unable to read SFTPDHParamFile '%s': %s", dhparam_path,
3285         strerror(errno));
3286       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3287         "WARNING: using fixed modulus for DH group exchange");
3288       use_fixed_modulus = TRUE;
3289     }
3290   }
3291 
3292   if (use_fixed_modulus) {
3293     BIGNUM *dh_p, *dh_g;
3294 
3295     dh_p = BN_new();
3296 
3297     /* Note: Consider using a stronger fixed DH group here! */
3298     if (BN_hex2bn(&dh_p, dh_group14_str) == 0) {
3299       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3300         "error setting DH P: %s", sftp_crypto_get_errors());
3301       BN_clear_free(dh_p);
3302       errno = EACCES;
3303       return -1;
3304     }
3305 
3306     dh_g = BN_new();
3307     if (BN_hex2bn(&dh_g, "2") == 0) {
3308       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3309         "error setting DH G: %s", sftp_crypto_get_errors());
3310       BN_clear_free(dh_p);
3311       BN_clear_free(dh_g);
3312       errno = EACCES;
3313       return -1;
3314     }
3315 
3316 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
3317     !defined(HAVE_LIBRESSL)
3318     DH_set0_pqg(kex->dh, dh_p, NULL, dh_g);
3319 #else
3320     kex->dh->p = dh_p;
3321     kex->dh->g = dh_g;
3322 #endif /* prior to OpenSSL-1.1.0 */
3323   }
3324 
3325   return 0;
3326 }
3327 
3328 static int write_dh_gex_group(struct ssh2_packet *pkt, struct sftp_kex *kex,
3329     uint32_t min, uint32_t pref, uint32_t max) {
3330   BIGNUM *dh_p = NULL, *dh_g = NULL;
3331   unsigned char *buf, *ptr;
3332   uint32_t buflen, bufsz;
3333 
3334   if (get_dh_gex_group(kex, min, pref, max) < 0) {
3335     return -1;
3336   }
3337 
3338   /* XXX Is this large enough?  Too large? */
3339   buflen = bufsz = 4096;
3340   ptr = buf = palloc(pkt->pool, bufsz);
3341 
3342   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEX_DH_GEX_GROUP);
3343 
3344 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
3345     !defined(HAVE_LIBRESSL)
3346   DH_get0_pqg(kex->dh, &dh_p, NULL, &dh_g);
3347 #else
3348   dh_p = kex->dh->p;
3349   dh_g = kex->dh->g;
3350 #endif /* prior to OpenSSL-1.1.0 */
3351   sftp_msg_write_mpint(&buf, &buflen, dh_p);
3352   sftp_msg_write_mpint(&buf, &buflen, dh_g);
3353 
3354   pkt->payload = ptr;
3355   pkt->payload_len = (bufsz - buflen);
3356 
3357   return 0;
3358 }
3359 
3360 static int read_dh_gex_init(struct ssh2_packet *pkt, struct sftp_kex *kex) {
3361   unsigned char *buf;
3362   uint32_t buflen;
3363 
3364   buf = pkt->payload;
3365   buflen = pkt->payload_len;
3366 
3367   /* Read in 'e' */
3368   kex->e = sftp_msg_read_mpint(pkt->pool, &buf, &buflen);
3369   if (kex->e == NULL) {
3370     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3371       "error reading DH_GEX_INIT: %s", strerror(errno));
3372     return -1;
3373   }
3374 
3375   return 0;
3376 }
3377 
3378 static int write_dh_gex_reply(struct ssh2_packet *pkt, struct sftp_kex *kex,
3379     uint32_t min, uint32_t pref, uint32_t max, int old_request) {
3380   const unsigned char *h, *hostkey_data, *hsig;
3381   unsigned char *buf, *ptr;
3382   uint32_t bufsz, buflen, hlen = 0, hostkey_datalen = 0;
3383   size_t dhlen, hsiglen = 0;
3384   BIGNUM *k = NULL, *dh_pub_key = NULL;
3385   int res;
3386 
3387   /* Compute the shared secret. */
3388   dhlen = DH_size(kex->dh);
3389   buf = palloc(kex_pool, dhlen);
3390 
3391   pr_trace_msg(trace_channel, 12, "computing DH key");
3392   res = DH_compute_key(buf, kex->e, kex->dh);
3393   if (res < 0) {
3394     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3395       "error computing DH shared secret: %s", sftp_crypto_get_errors());
3396     return -1;
3397   }
3398 
3399   k = BN_new();
3400   if (BN_bin2bn(buf, res, k) == NULL) {
3401     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3402       "error converting DH shared secret to BN: %s", sftp_crypto_get_errors());
3403 
3404     pr_memscrub(buf, res);
3405     BN_clear_free(k);
3406     return -1;
3407   }
3408 
3409   pr_memscrub(buf, res);
3410   kex->k = k;
3411 
3412   /* Get the hostkey data; it will be part of the data we hash in order
3413    * to create the session key.
3414    */
3415   hostkey_data = sftp_keys_get_hostkey_data(pkt->pool, kex->use_hostkey_type,
3416     &hostkey_datalen);
3417   if (hostkey_data == NULL) {
3418     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3419       "error converting hostkey for signing: %s", strerror(errno));
3420 
3421     BN_clear_free(kex->k);
3422     kex->k = NULL;
3423     return -1;
3424   }
3425 
3426   if (old_request) {
3427     max = min = 0;
3428   }
3429 
3430   /* Calculate H */
3431   h = calculate_gex_h(kex, hostkey_data, hostkey_datalen, k, min, pref, max,
3432     &hlen);
3433   if (h == NULL) {
3434     pr_memscrub((char *) hostkey_data, hostkey_datalen);
3435     BN_clear_free(kex->k);
3436     kex->k = NULL;
3437     return -1;
3438   }
3439 
3440   kex->h = palloc(pkt->pool, hlen);
3441   kex->hlen = hlen;
3442   memcpy((char *) kex->h, h, kex->hlen);
3443 
3444   /* Save H as the session ID */
3445   sftp_session_set_id(h, hlen);
3446 
3447   /* Sign H with our hostkey */
3448   hsig = sftp_keys_sign_data(pkt->pool, kex->use_hostkey_type, h, hlen,
3449     &hsiglen);
3450   if (hsig == NULL) {
3451     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error signing H");
3452     pr_memscrub((char *) hostkey_data, hostkey_datalen);
3453     BN_clear_free(kex->k);
3454     kex->k = NULL;
3455     return -1;
3456   }
3457 
3458   /* XXX Is this large enough?  Too large? */
3459   buflen = bufsz = 8192;
3460   ptr = buf = palloc(pkt->pool, bufsz);
3461 
3462   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEX_DH_GEX_REPLY);
3463   sftp_msg_write_data(&buf, &buflen, hostkey_data, hostkey_datalen, TRUE);
3464 
3465 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
3466     !defined(HAVE_LIBRESSL)
3467   DH_get0_key(kex->dh, &dh_pub_key, NULL);
3468 #else
3469   dh_pub_key = kex->dh->pub_key;
3470 #endif /* prior to OpenSSL-1.1.0 */
3471   sftp_msg_write_mpint(&buf, &buflen, dh_pub_key);
3472 
3473   sftp_msg_write_data(&buf, &buflen, hsig, hsiglen, TRUE);
3474 
3475   /* Scrub any sensitive data when done */
3476   pr_memscrub((char *) hostkey_data, hostkey_datalen);
3477   pr_memscrub((char *) hsig, hsiglen);
3478 
3479   pkt->payload = ptr;
3480   pkt->payload_len = (bufsz - buflen);
3481 
3482   return 0;
3483 }
3484 
3485 static int handle_kex_dh_gex(struct ssh2_packet *pkt, struct sftp_kex *kex,
3486     int old_request) {
3487   int res;
3488   uint32_t min = 0, pref = 0, max = 0;
3489   cmd_rec *cmd;
3490 
3491   if (!old_request) {
3492     pr_trace_msg(trace_channel, 9,
3493       "reading DH_GEX_REQUEST message from client");
3494 
3495     cmd = pr_cmd_alloc(pkt->pool, 1, pstrdup(pkt->pool, "DH_GEX_REQUEST"));
3496     cmd->arg = "(data)";
3497     cmd->cmd_class = CL_AUTH|CL_SSH;
3498 
3499   } else {
3500     pr_trace_msg(trace_channel, 9,
3501       "reading DH_GEX_REQUEST_OLD message from client");
3502 
3503     cmd = pr_cmd_alloc(pkt->pool, 1, pstrdup(pkt->pool, "DH_GEX_REQUEST_OLD"));
3504     cmd->arg = "(data)";
3505     cmd->cmd_class = CL_AUTH|CL_SSH;
3506   }
3507 
3508   res = read_dh_gex(pkt, &min, &pref, &max, old_request);
3509   if (res < 0) {
3510     pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
3511 
3512     destroy_pool(pkt->pool);
3513     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
3514   }
3515 
3516   pr_cmd_dispatch_phase(cmd, LOG_CMD, 0);
3517   destroy_pool(pkt->pool);
3518 
3519   pkt = sftp_ssh2_packet_create(kex_pool);
3520   res = write_dh_gex_group(pkt, kex, min, pref, max);
3521   if (res < 0) {
3522     destroy_pool(pkt->pool);
3523     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
3524   }
3525 
3526   pr_trace_msg(trace_channel, 9, "writing DH_GEX_GROUP message to client");
3527 
3528   res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt);
3529   if (res < 0) {
3530     destroy_pool(pkt->pool);
3531     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
3532   }
3533 
3534   destroy_pool(pkt->pool);
3535 
3536   pkt = read_kex_packet(kex_pool, kex, SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED,
3537     NULL, 1, SFTP_SSH2_MSG_KEX_DH_GEX_INIT);
3538 
3539   cmd = pr_cmd_alloc(pkt->pool, 1, pstrdup(pkt->pool, "DH_GEX_INIT"));
3540   cmd->arg = "(data)";
3541   cmd->cmd_class = CL_AUTH|CL_SSH;
3542 
3543   pr_trace_msg(trace_channel, 9, "reading DH_GEX_INIT message from client");
3544 
3545   res = read_dh_gex_init(pkt, kex);
3546   if (res < 0) {
3547     pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
3548 
3549     destroy_pool(pkt->pool);
3550     return -1;
3551   }
3552 
3553   pr_cmd_dispatch_phase(cmd, LOG_CMD, 0);
3554   destroy_pool(pkt->pool);
3555 
3556   if (finish_dh(kex) < 0) {
3557     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3558       "error finishing DH key for group exchange: %s", strerror(errno));
3559     return -1;
3560   }
3561 
3562   pkt = sftp_ssh2_packet_create(kex_pool);
3563   res = write_dh_gex_reply(pkt, kex, min, pref, max, old_request);
3564   if (res < 0) {
3565     destroy_pool(pkt->pool);
3566     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
3567   }
3568 
3569   pr_trace_msg(trace_channel, 9, "writing DH_GEX_REPLY message to client");
3570 
3571   res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt);
3572   if (res < 0) {
3573     destroy_pool(pkt->pool);
3574     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
3575   }
3576 
3577   destroy_pool(pkt->pool);
3578   return 0;
3579 }
3580 
3581 static int read_kexrsa_secret(struct ssh2_packet *pkt, struct sftp_kex *kex) {
3582   unsigned char *buf, *encrypted, *decrypted;
3583   uint32_t buflen, encrypted_len;
3584   BIGNUM *k = NULL;
3585   int res;
3586 
3587   buf = pkt->payload;
3588   buflen = pkt->payload_len;
3589 
3590   encrypted_len = sftp_msg_read_int(pkt->pool, &buf, &buflen);
3591   encrypted = (unsigned char *) sftp_msg_read_data(pkt->pool, &buf, &buflen,
3592     encrypted_len);
3593 
3594   /* Save the encrypted secret for calculating H. */
3595   kex->rsa_encrypted_len = encrypted_len;
3596   kex->rsa_encrypted = palloc(kex_pool, encrypted_len);
3597   memcpy(kex->rsa_encrypted, encrypted, encrypted_len);
3598 
3599   pr_trace_msg(trace_channel, 12, "decrypting RSA shared secret");
3600 
3601   decrypted = palloc(pkt->pool, RSA_size(kex->rsa));
3602 
3603   res = RSA_private_decrypt((int) encrypted_len, encrypted, decrypted,
3604     kex->rsa, RSA_PKCS1_OAEP_PADDING);
3605   if (res == -1) {
3606     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3607       "error decrypting RSA shared secret: %s", sftp_crypto_get_errors());
3608     RSA_free(kex->rsa);
3609     kex->rsa = NULL;
3610     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
3611   }
3612 
3613   /* When converting the decrypted secret into an mpint, watch out for any
3614    * leading padding (as required per SSH RFCs).
3615    */
3616 
3617   k = BN_new();
3618   if (BN_mpi2bn(decrypted, res, k) == NULL) {
3619     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3620       "error converting RSA shared secret to BN: %s", sftp_crypto_get_errors());
3621 
3622     pr_memscrub(decrypted, res);
3623     RSA_free(kex->rsa);
3624     kex->rsa = NULL;
3625     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
3626   }
3627 
3628   pr_memscrub(decrypted, res);
3629 
3630   kex->k = k;
3631   return 0;
3632 }
3633 
3634 static int write_kexrsa_pubkey(struct ssh2_packet *pkt, struct sftp_kex *kex) {
3635   BIGNUM *rsa_n = NULL, *rsa_e = NULL;
3636   unsigned char *buf, *ptr, *buf2, *ptr2;
3637   const unsigned char *hostkey_data;
3638   uint32_t buflen, bufsz, buflen2, bufsz2, hostkey_datalen;
3639 
3640   hostkey_data = sftp_keys_get_hostkey_data(pkt->pool, kex->use_hostkey_type,
3641     &hostkey_datalen);
3642   if (hostkey_data == NULL) {
3643     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3644       "error obtaining hostkey for KEXRSA key exchange: %s", strerror(errno));
3645     RSA_free(kex->rsa);
3646     kex->rsa = NULL;
3647     return -1;
3648   }
3649 
3650   /* XXX Is this buffer large enough?  Too large? */
3651   bufsz = buflen = 2048;
3652   ptr = buf = palloc(kex_pool, bufsz);
3653 
3654   /* Write the transient RSA public key into its own buffer, to then be
3655    * written in its entirety as an SSH2 string.
3656    */
3657   sftp_msg_write_string(&buf, &buflen, "ssh-rsa");
3658 
3659 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
3660     !defined(HAVE_LIBRESSL)
3661   RSA_get0_key(kex->rsa, &rsa_n, &rsa_e, NULL);
3662 #else
3663   rsa_e = kex->rsa->e;
3664   rsa_n = kex->rsa->n;
3665 #endif /* prior to OpenSSL-1.1.0 */
3666   sftp_msg_write_mpint(&buf, &buflen, rsa_e);
3667   sftp_msg_write_mpint(&buf, &buflen, rsa_n);
3668 
3669   /* XXX Is this buffer large enough?  Too large? */
3670   bufsz2 = buflen2 = 4096;
3671   ptr2 = buf2 = palloc(pkt->pool, bufsz2);
3672 
3673   sftp_msg_write_byte(&buf2, &buflen2, SFTP_SSH2_MSG_KEXRSA_PUBKEY);
3674   sftp_msg_write_data(&buf2, &buflen2, hostkey_data, hostkey_datalen, TRUE);
3675   sftp_msg_write_data(&buf2, &buflen2, ptr, (bufsz - buflen), TRUE);
3676 
3677   pr_memscrub((char *) hostkey_data, hostkey_datalen);
3678 
3679   pkt->payload = ptr2;
3680   pkt->payload_len = (bufsz2 - buflen2);
3681 
3682   return 0;
3683 }
3684 
3685 static int write_kexrsa_done(struct ssh2_packet *pkt, struct sftp_kex *kex) {
3686   BIGNUM *rsa_e = NULL, *rsa_n = NULL;
3687   unsigned char *buf, *ptr, *buf2, *ptr2;
3688   const unsigned char *h, *hostkey_data, *hsig;
3689   uint32_t buflen, bufsz, buflen2, bufsz2, hlen, hostkey_datalen = 0;
3690   size_t hsiglen;
3691 
3692   hostkey_data = sftp_keys_get_hostkey_data(pkt->pool, kex->use_hostkey_type,
3693     &hostkey_datalen);
3694   if (hostkey_data == NULL) {
3695     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3696       "error obtaining hostkey for KEXRSA key exchange: %s", strerror(errno));
3697 
3698     RSA_free(kex->rsa);
3699     kex->rsa = NULL;
3700     BN_clear_free(kex->k);
3701     kex->k = NULL;
3702     pr_memscrub(kex->rsa_encrypted, kex->rsa_encrypted_len);
3703     kex->rsa_encrypted = NULL;
3704     kex->rsa_encrypted_len = 0;
3705 
3706     return -1;
3707   }
3708 
3709   /* XXX Is this buffer large enough?  Too large? */
3710   bufsz2 = buflen2 = 4096;
3711   ptr2 = buf2 = palloc(kex_pool, bufsz2);
3712 
3713   /* Write the transient RSA public key into its own buffer, to then be
3714    * written in its entirety as an SSH2 string.
3715    */
3716   sftp_msg_write_string(&buf2, &buflen2, "ssh-rsa");
3717 
3718 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
3719     !defined(HAVE_LIBRESSL)
3720   RSA_get0_key(kex->rsa, &rsa_n, &rsa_e, NULL);
3721 #else
3722   rsa_e = kex->rsa->e;
3723   rsa_n = kex->rsa->n;
3724 #endif /* prior to OpenSSL-1.1.0 */
3725   sftp_msg_write_mpint(&buf2, &buflen2, rsa_e);
3726   sftp_msg_write_mpint(&buf2, &buflen2, rsa_n);
3727 
3728   /* Calculate H */
3729   h = calculate_kexrsa_h(kex, hostkey_data, hostkey_datalen, kex->k,
3730     ptr2, (bufsz2 - buflen2), &hlen);
3731   if (h == NULL) {
3732     pr_memscrub((char *) hostkey_data, hostkey_datalen);
3733     RSA_free(kex->rsa);
3734     kex->rsa = NULL;
3735     BN_clear_free(kex->k);
3736     kex->k = NULL;
3737     pr_memscrub(kex->rsa_encrypted, kex->rsa_encrypted_len);
3738     kex->rsa_encrypted = NULL;
3739     kex->rsa_encrypted_len = 0;
3740 
3741     return -1;
3742   }
3743 
3744   kex->h = palloc(pkt->pool, hlen);
3745   kex->hlen = hlen;
3746   memcpy((char *) kex->h, h, kex->hlen);
3747 
3748   /* Save H as the session ID */
3749   sftp_session_set_id(h, hlen);
3750 
3751   /* Sign H with our host key */
3752   hsig = sftp_keys_sign_data(pkt->pool, kex->use_hostkey_type, h, hlen,
3753     &hsiglen);
3754   if (hsig == NULL) {
3755     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error signing H");
3756 
3757     pr_memscrub((char *) hostkey_data, hostkey_datalen);
3758     RSA_free(kex->rsa);
3759     kex->rsa = NULL;
3760     BN_clear_free(kex->k);
3761     kex->k = NULL;
3762     pr_memscrub(kex->rsa_encrypted, kex->rsa_encrypted_len);
3763     kex->rsa_encrypted = NULL;
3764     kex->rsa_encrypted_len = 0;
3765 
3766     return -1;
3767   }
3768 
3769   /* XXX Is this buffer large enough?  Too large? */
3770   bufsz = buflen = 4096;
3771   ptr = buf = palloc(pkt->pool, bufsz);
3772 
3773   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEXRSA_DONE);
3774   sftp_msg_write_data(&buf, &buflen, hsig, hsiglen, TRUE);
3775 
3776   pr_memscrub((char *) hostkey_data, hostkey_datalen);
3777   pr_memscrub((char *) h, hlen);
3778   pr_memscrub((char *) hsig, hsiglen);
3779 
3780   pr_memscrub(kex->rsa_encrypted, kex->rsa_encrypted_len);
3781   kex->rsa_encrypted = NULL;
3782   kex->rsa_encrypted_len = 0;
3783 
3784   pkt->payload = ptr;
3785   pkt->payload_len = (bufsz - buflen);
3786 
3787   return 0;
3788 }
3789 
3790 static int handle_kex_rsa(struct sftp_kex *kex) {
3791   struct ssh2_packet *pkt;
3792   int res;
3793   cmd_rec *cmd;
3794 
3795   pkt = sftp_ssh2_packet_create(kex_pool);
3796   res = write_kexrsa_pubkey(pkt, kex);
3797   if (res < 0) {
3798     destroy_pool(pkt->pool);
3799     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
3800   }
3801 
3802   pr_trace_msg(trace_channel, 9, "writing KEXRSA_PUBKEY message to client");
3803 
3804   res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt);
3805   if (res < 0) {
3806     destroy_pool(pkt->pool);
3807     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
3808   }
3809 
3810   destroy_pool(pkt->pool);
3811 
3812   pkt = read_kex_packet(kex_pool, kex, SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED,
3813     NULL, 1, SFTP_SSH2_MSG_KEXRSA_SECRET);
3814 
3815   cmd = pr_cmd_alloc(pkt->pool, 1, pstrdup(pkt->pool, "KEXRSA_SECRET"));
3816   cmd->arg = "(data)";
3817   cmd->cmd_class = CL_AUTH|CL_SSH;
3818 
3819   pr_trace_msg(trace_channel, 9, "reading KEXRSA_SECRET message from client");
3820 
3821   res = read_kexrsa_secret(pkt, kex);
3822   if (res < 0) {
3823     pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
3824 
3825     destroy_pool(pkt->pool);
3826     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
3827   }
3828 
3829   pr_cmd_dispatch_phase(cmd, LOG_CMD, 0);
3830   destroy_pool(pkt->pool);
3831 
3832   pkt = sftp_ssh2_packet_create(kex_pool);
3833   res = write_kexrsa_done(pkt, kex);
3834   if (res < 0) {
3835     destroy_pool(pkt->pool);
3836     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
3837   }
3838 
3839   pr_trace_msg(trace_channel, 9, "writing KEXRSA_DONE message to client");
3840 
3841   res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt);
3842   if (res < 0) {
3843     destroy_pool(pkt->pool);
3844     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
3845   }
3846 
3847   destroy_pool(pkt->pool);
3848   return 0;
3849 }
3850 
3851 #if defined(PR_USE_SODIUM) && defined(HAVE_SHA256_OPENSSL)
3852 static int generate_curve25519_keys(unsigned char *priv_key,
3853     unsigned char *pub_key) {
3854   static const unsigned char basepoint[CURVE25519_SIZE] = {9};
3855   unsigned char zero_curve25519[CURVE25519_SIZE];
3856   int res;
3857 
3858   randombytes_buf(priv_key, CURVE25519_SIZE);
3859   res = crypto_scalarmult_curve25519(pub_key, priv_key, basepoint);
3860   if (res < 0) {
3861     pr_trace_msg(trace_channel, 3,
3862       "error performing Curve25519 scalar multiplication");
3863     errno = EINVAL;
3864     return -1;
3865   }
3866 
3867   /* Check for all-zero public keys. */
3868   sodium_memzero(zero_curve25519, CURVE25519_SIZE);
3869   if (sodium_memcmp(pub_key, zero_curve25519, CURVE25519_SIZE) == 0) {
3870     pr_trace_msg(trace_channel, 12,
3871       "generated all-zero Curve25519 public key, trying again");
3872     return generate_curve25519_keys(priv_key, pub_key);
3873   }
3874 
3875   return 0;
3876 }
3877 
3878 static int read_curve25519_init(struct ssh2_packet *pkt, struct sftp_kex *kex) {
3879   unsigned char zero_curve25519[CURVE25519_SIZE];
3880   unsigned char *client_curve25519;
3881   unsigned char *buf;
3882   uint32_t buflen, data_len;
3883   char *data;
3884 
3885   buf = pkt->payload;
3886   buflen = data_len = pkt->payload_len;
3887 
3888   data = sftp_msg_read_string(pkt->pool, &buf, &buflen);
3889 
3890   /* The "string" we read MIGHT contain NULs, thus using strlen(3) to determine
3891    * the length of data is a Bad Idea (Issue #556).  Thus instead, we track
3892    * the packet payload length remaining after the read; the data length is
3893    * the difference, including the length value prefix of 4 bytes.
3894    */
3895   data_len -= (buflen + sizeof(uint32_t));
3896 
3897   if (data_len != CURVE25519_SIZE) {
3898     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3899       "rejecting invalid length (%lu %s, wanted %d) client Curve25519 key",
3900       (unsigned long) data_len, data_len != 1 ? "bytes" : "byte",
3901       CURVE25519_SIZE);
3902     errno = EINVAL;
3903     return -1;
3904   }
3905 
3906   client_curve25519 = (unsigned char *) data;
3907 
3908   /* Watch for all-zero public keys, and reject them. */
3909   sodium_memzero(zero_curve25519, CURVE25519_SIZE);
3910   if (sodium_memcmp(client_curve25519, zero_curve25519, CURVE25519_SIZE) == 0) {
3911     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3912       "rejecting invalid (all-zero) client Curve25519 key");
3913     errno = EINVAL;
3914     return -1;
3915   }
3916 
3917   kex->client_curve25519 = client_curve25519;
3918   return 0;
3919 }
3920 
3921 static int get_curve25519_shared_key(unsigned char *shared_key,
3922     unsigned char *client_curve25519, unsigned char *server_key) {
3923   int res;
3924 
3925   res = crypto_scalarmult_curve25519(shared_key, server_key, client_curve25519);
3926   if (res < 0) {
3927     pr_trace_msg(trace_channel, 3,
3928       "error performing Curve25519 scalar multiplication");
3929     errno = EINVAL;
3930     return -1;
3931   }
3932 
3933   return CURVE25519_SIZE;
3934 }
3935 
3936 static const unsigned char *calculate_curve25519_h(struct sftp_kex *kex,
3937     const unsigned char *hostkey_data, uint32_t hostkey_datalen,
3938     const BIGNUM *k, unsigned char *client_curve25519,
3939     unsigned char *server_curve25519, uint32_t *hlen) {
3940 #if OPENSSL_VERSION_NUMBER < 0x10100000L
3941   EVP_MD_CTX ctx;
3942 #endif /* prior to OpenSSL-1.1.0 */
3943   EVP_MD_CTX *pctx;
3944   unsigned char *buf, *ptr;
3945   uint32_t buflen, bufsz;
3946 
3947   bufsz = buflen = 4096;
3948 
3949   /* XXX Is this buffer large enough? Too large? */
3950   ptr = buf = sftp_msg_getbuf(kex_pool, bufsz);
3951 
3952   /* Write all of the data into the buffer in the SSH2 format, and hash it.
3953    * The ordering of these fields is described in RFC5656.
3954    */
3955 
3956   /* First, the version strings */
3957   sftp_msg_write_string(&buf, &buflen, kex->client_version);
3958   sftp_msg_write_string(&buf, &buflen, kex->server_version);
3959 
3960   /* Client's KEXINIT */
3961   sftp_msg_write_int(&buf, &buflen, kex->client_kexinit_payload_len + 1);
3962   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEXINIT);
3963   sftp_msg_write_data(&buf, &buflen, kex->client_kexinit_payload,
3964     kex->client_kexinit_payload_len, FALSE);
3965 
3966   /* Server's KEXINIT */
3967   sftp_msg_write_int(&buf, &buflen, kex->server_kexinit_payload_len + 1);
3968   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEXINIT);
3969   sftp_msg_write_data(&buf, &buflen, kex->server_kexinit_payload,
3970     kex->server_kexinit_payload_len, FALSE);
3971 
3972   /* Hostkey data */
3973   sftp_msg_write_data(&buf, &buflen, hostkey_data, hostkey_datalen, TRUE);
3974 
3975   /* Client's key */
3976   sftp_msg_write_data(&buf, &buflen, client_curve25519, CURVE25519_SIZE, TRUE);
3977 
3978   /* Server's key */
3979   sftp_msg_write_data(&buf, &buflen, server_curve25519, CURVE25519_SIZE, TRUE);
3980 
3981   /* Shared secret */
3982   sftp_msg_write_mpint(&buf, &buflen, k);
3983 
3984 #if OPENSSL_VERSION_NUMBER >= 0x10100000LL
3985     pctx = EVP_MD_CTX_new();
3986 #else
3987     pctx = &ctx;
3988 #endif /* OpenSSL-1.1.0 and later */
3989 
3990   /* In OpenSSL 0.9.6, many of the EVP_Digest* functions returned void, not
3991    * int.  Without these ugly OpenSSL version preprocessor checks, the
3992    * compiler will error out with "void value not ignored as it ought to be".
3993    */
3994 
3995 #if OPENSSL_VERSION_NUMBER >= 0x000907000L
3996   if (EVP_DigestInit(pctx, kex->hash) != 1) {
3997     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
3998       "error initializing message digest: %s", sftp_crypto_get_errors());
3999     BN_clear_free(kex->e);
4000     kex->e = NULL;
4001     pr_memscrub(ptr, bufsz);
4002 # if OPENSSL_VERSION_NUMBER >= 0x10100000LL
4003     EVP_MD_CTX_free(pctx);
4004 # endif /* OpenSSL-1.1.0 and later */
4005     return NULL;
4006   }
4007 #else
4008   EVP_DigestInit(pctx, kex->hash);
4009 #endif
4010 
4011 #if OPENSSL_VERSION_NUMBER >= 0x000907000L
4012   if (EVP_DigestUpdate(pctx, ptr, (bufsz - buflen)) != 1) {
4013     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4014       "error updating message digest: %s", sftp_crypto_get_errors());
4015     BN_clear_free(kex->e);
4016     kex->e = NULL;
4017     pr_memscrub(ptr, bufsz);
4018 # if OPENSSL_VERSION_NUMBER >= 0x10100000LL
4019     EVP_MD_CTX_free(pctx);
4020 # endif /* OpenSSL-1.1.0 and later */
4021     return NULL;
4022   }
4023 #else
4024   EVP_DigestUpdate(pctx, ptr, (bufsz - buflen));
4025 #endif
4026 
4027 #if OPENSSL_VERSION_NUMBER >= 0x000907000L
4028   if (EVP_DigestFinal(pctx, kex_digest_buf, hlen) != 1) {
4029     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4030       "error finalizing message digest: %s", sftp_crypto_get_errors());
4031     BN_clear_free(kex->e);
4032     kex->e = NULL;
4033     pr_memscrub(ptr, bufsz);
4034 # if OPENSSL_VERSION_NUMBER >= 0x10100000LL
4035     EVP_MD_CTX_free(pctx);
4036 # endif /* OpenSSL-1.1.0 and later */
4037     return NULL;
4038   }
4039 #else
4040   EVP_DigestFinal(pctx, kex_digest_buf, hlen);
4041 #endif
4042 
4043 #if OPENSSL_VERSION_NUMBER >= 0x10100000LL
4044   EVP_MD_CTX_free(pctx);
4045 #endif /* OpenSSL-1.1.0 and later */
4046   BN_clear_free(kex->e);
4047   kex->e = NULL;
4048   pr_memscrub(ptr, bufsz);
4049 
4050   return kex_digest_buf;
4051 }
4052 
4053 static int write_curve25519_reply(struct ssh2_packet *pkt,
4054     struct sftp_kex *kex) {
4055   const unsigned char *h, *hostkey_data, *hsig;
4056   unsigned char *buf, *ptr;
4057   unsigned char server_curve25519[CURVE25519_SIZE];
4058   unsigned char server_key[CURVE25519_SIZE];
4059   uint32_t bufsz, buflen, hlen = 0, hostkey_datalen = 0;
4060   size_t hsiglen;
4061   BIGNUM *k = NULL;
4062   int res;
4063 
4064   if (generate_curve25519_keys(server_key, server_curve25519) < 0) {
4065     return -1;
4066   }
4067 
4068   /* Compute the shared secret. */
4069   buf = palloc(kex_pool, CURVE25519_SIZE);
4070 
4071   pr_trace_msg(trace_channel, 12, "computing Curve25519 key");
4072   res = get_curve25519_shared_key((unsigned char *) buf, kex->client_curve25519,
4073     server_key);
4074   if (res < 0) {
4075     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4076       "error computing Curve25519 shared secret: %s", strerror(errno));
4077     return -1;
4078   }
4079 
4080   k = BN_new();
4081   if (k == NULL) {
4082     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4083       "error allocating new BIGNUM: %s", sftp_crypto_get_errors());
4084     pr_memscrub(buf, res);
4085     return -1;
4086   }
4087 
4088   if (BN_bin2bn((unsigned char *) buf, res, k) == NULL) {
4089     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4090       "error converting Curve25519 shared secret to BN: %s",
4091       sftp_crypto_get_errors());
4092     pr_memscrub(buf, res);
4093     return -1;
4094   }
4095 
4096   pr_memscrub(buf, res);
4097   kex->k = k;
4098 
4099   /* Get the hostkey data; it will be part of the data we hash in order
4100    * to create the session key.
4101    */
4102   hostkey_data = sftp_keys_get_hostkey_data(pkt->pool, kex->use_hostkey_type,
4103     &hostkey_datalen);
4104   if (hostkey_data == NULL) {
4105     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4106       "error converting hostkey for signing: %s", strerror(errno));
4107 
4108     BN_clear_free(kex->k);
4109     kex->k = NULL;
4110     return -1;
4111   }
4112 
4113   /* Calculate H */
4114   h = calculate_curve25519_h(kex, hostkey_data, hostkey_datalen, k,
4115     kex->client_curve25519, server_curve25519, &hlen);
4116   if (h == NULL) {
4117     pr_memscrub((char *) hostkey_data, hostkey_datalen);
4118     BN_clear_free(kex->k);
4119     kex->k = NULL;
4120     return -1;
4121   }
4122 
4123   kex->h = palloc(pkt->pool, hlen);
4124   kex->hlen = hlen;
4125   memcpy((char *) kex->h, h, kex->hlen);
4126 
4127   /* Save H as the session ID */
4128   sftp_session_set_id(h, hlen);
4129 
4130   /* Sign H with our hostkey */
4131   hsig = sftp_keys_sign_data(pkt->pool, kex->use_hostkey_type, h, hlen,
4132     &hsiglen);
4133   if (hsig == NULL) {
4134     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error signing H");
4135     pr_memscrub((char *) hostkey_data, hostkey_datalen);
4136     BN_clear_free(kex->k);
4137     kex->k = NULL;
4138     return -1;
4139   }
4140 
4141   /* XXX Is this large enough?  Too large? */
4142   buflen = bufsz = 4096;
4143   ptr = buf = palloc(pkt->pool, bufsz);
4144 
4145   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEX_ECDH_REPLY);
4146   sftp_msg_write_data(&buf, &buflen, hostkey_data, hostkey_datalen, TRUE);
4147   sftp_msg_write_data(&buf, &buflen, server_curve25519, CURVE25519_SIZE, TRUE);
4148   sftp_msg_write_data(&buf, &buflen, hsig, hsiglen, TRUE);
4149 
4150   /* Scrub any sensitive data when done */
4151   pr_memscrub((char *) server_key, CURVE25519_SIZE);
4152   pr_memscrub((char *) hostkey_data, hostkey_datalen);
4153   pr_memscrub((char *) hsig, hsiglen);
4154 
4155   pkt->payload = ptr;
4156   pkt->payload_len = (bufsz - buflen);
4157 
4158   return 0;
4159 }
4160 
4161 static int handle_kex_curve25519(struct ssh2_packet *pkt,
4162     struct sftp_kex *kex) {
4163   int res;
4164   cmd_rec *cmd;
4165   const char *req;
4166 
4167   req = "ECDH_INIT";
4168   cmd = pr_cmd_alloc(pkt->pool, 1, pstrdup(pkt->pool, req));
4169   cmd->arg = "(data)";
4170   cmd->cmd_class = CL_AUTH|CL_SSH;
4171 
4172   pr_trace_msg(trace_channel, 9, "reading %s message from client", req);
4173 
4174   res = read_curve25519_init(pkt, kex);
4175   if (res < 0) {
4176     pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
4177 
4178     destroy_pool(pkt->pool);
4179     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
4180   }
4181 
4182   pr_cmd_dispatch_phase(cmd, LOG_CMD, 0);
4183   destroy_pool(pkt->pool);
4184 
4185   /* Send our key exchange reply. */
4186   pkt = sftp_ssh2_packet_create(kex_pool);
4187   res = write_curve25519_reply(pkt, kex);
4188   if (res < 0) {
4189     destroy_pool(pkt->pool);
4190     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
4191   }
4192 
4193   pr_trace_msg(trace_channel, 9, "writing %s message to client", req);
4194 
4195   res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt);
4196   if (res < 0) {
4197     destroy_pool(pkt->pool);
4198     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
4199   }
4200 
4201   destroy_pool(pkt->pool);
4202   return 0;
4203 }
4204 #endif /* PR_USE_SODIUM and HAVE_SHA256_OPENSSL */
4205 
4206 #ifdef PR_USE_OPENSSL_ECC
4207 static int read_ecdh_init(struct ssh2_packet *pkt, struct sftp_kex *kex) {
4208   unsigned char *buf;
4209   uint32_t buflen;
4210   const EC_GROUP *curve;
4211   EC_POINT *point;
4212 
4213   buf = pkt->payload;
4214   buflen = pkt->payload_len;
4215 
4216   curve = EC_KEY_get0_group(kex->ec);
4217 
4218   point = EC_POINT_new(curve);
4219   if (point == NULL) {
4220     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4221       "error allocating EC_POINT: %s", sftp_crypto_get_errors());
4222     return -1;
4223   }
4224 
4225   /* Read in the client's EC point (i.e. their ECC "public key"). */
4226   kex->client_point = sftp_msg_read_ecpoint(pkt->pool, &buf, &buflen, curve,
4227     point);
4228   if (kex->client_point == NULL) {
4229     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4230       "error reading ECDH_INIT: %s", strerror(errno));
4231     EC_POINT_clear_free(point);
4232     kex->client_point = NULL;
4233     return -1;
4234   }
4235 
4236   if (sftp_keys_validate_ecdsa_params(curve, kex->client_point) < 0) {
4237     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4238       "invalid client ECDH public key (EC point): %s", strerror(errno));
4239     EC_POINT_clear_free(kex->client_point);
4240     kex->client_point = NULL;
4241     return -1;
4242   }
4243 
4244   return 0;
4245 }
4246 
4247 static int write_ecdh_reply(struct ssh2_packet *pkt, struct sftp_kex *kex) {
4248   const unsigned char *h;
4249   const unsigned char *hostkey_data, *hsig;
4250   unsigned char *buf, *ptr;
4251   uint32_t bufsz, buflen, hlen = 0, hostkey_datalen = 0;
4252   size_t ecdhlen, hsiglen;
4253   BIGNUM *k = NULL;
4254   int res;
4255 
4256   /* Compute the shared secret */
4257   ecdhlen = ((EC_GROUP_get_degree(EC_KEY_get0_group(kex->ec)) + 7) / 8);
4258   buf = palloc(kex_pool, ecdhlen);
4259 
4260   pr_trace_msg(trace_channel, 12, "computing ECDH key");
4261   res = ECDH_compute_key((unsigned char *) buf, ecdhlen, kex->client_point,
4262     kex->ec, NULL);
4263   if (res <= 0) {
4264     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4265       "error computing ECDH shared secret: %s", sftp_crypto_get_errors());
4266     return -1;
4267   }
4268 
4269   if ((size_t) res != ecdhlen) {
4270     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4271       "computed ECDH shared secret length (%d) does not match needed length "
4272       "(%lu), rejecting", res, (unsigned long) ecdhlen);
4273     return -1;
4274   }
4275 
4276   k = BN_new();
4277   if (k == NULL) {
4278     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4279       "error allocating new BIGNUM: %s", sftp_crypto_get_errors());
4280     pr_memscrub(buf, res);
4281     return -1;
4282   }
4283 
4284   if (BN_bin2bn((unsigned char *) buf, res, k) == NULL) {
4285     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4286       "error converting ECDH shared secret to BN: %s",
4287       sftp_crypto_get_errors());
4288 
4289     pr_memscrub(buf, res);
4290     return -1;
4291   }
4292 
4293   pr_memscrub(buf, res);
4294   kex->k = k;
4295 
4296   /* Get the hostkey data; it will be part of the data we hash in order
4297    * to create the session key.
4298    */
4299   hostkey_data = sftp_keys_get_hostkey_data(pkt->pool, kex->use_hostkey_type,
4300     &hostkey_datalen);
4301   if (hostkey_data == NULL) {
4302     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4303       "error converting hostkey for signing: %s", strerror(errno));
4304 
4305     BN_clear_free(kex->k);
4306     kex->k = NULL;
4307     return -1;
4308   }
4309 
4310   /* Calculate H */
4311   h = calculate_ecdh_h(kex, hostkey_data, hostkey_datalen, k, &hlen);
4312   if (h == NULL) {
4313     pr_memscrub((char *) hostkey_data, hostkey_datalen);
4314     BN_clear_free(kex->k);
4315     kex->k = NULL;
4316     return -1;
4317   }
4318 
4319   kex->h = palloc(pkt->pool, hlen);
4320   kex->hlen = hlen;
4321   memcpy((char *) kex->h, h, kex->hlen);
4322 
4323   /* Save H as the session ID */
4324   sftp_session_set_id(h, hlen);
4325 
4326   /* Sign H with our hostkey */
4327   hsig = sftp_keys_sign_data(pkt->pool, kex->use_hostkey_type, h, hlen,
4328     &hsiglen);
4329   if (hsig == NULL) {
4330     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error signing H");
4331     pr_memscrub((char *) hostkey_data, hostkey_datalen);
4332     BN_clear_free(kex->k);
4333     kex->k = NULL;
4334     return -1;
4335   }
4336 
4337   /* XXX Is this large enough?  Too large? */
4338   buflen = bufsz = 4096;
4339   ptr = buf = palloc(pkt->pool, bufsz);
4340 
4341   sftp_msg_write_byte(&buf, &buflen, SFTP_SSH2_MSG_KEX_ECDH_REPLY);
4342   sftp_msg_write_data(&buf, &buflen, hostkey_data, hostkey_datalen, TRUE);
4343   sftp_msg_write_ecpoint(&buf, &buflen, EC_KEY_get0_group(kex->ec),
4344     EC_KEY_get0_public_key(kex->ec));
4345   sftp_msg_write_data(&buf, &buflen, hsig, hsiglen, TRUE);
4346 
4347   /* Scrub any sensitive data when done */
4348   pr_memscrub((char *) hostkey_data, hostkey_datalen);
4349   pr_memscrub((char *) hsig, hsiglen);
4350 
4351   pkt->payload = ptr;
4352   pkt->payload_len = (bufsz - buflen);
4353 
4354   return 0;
4355 }
4356 
4357 static int handle_kex_ecdh(struct ssh2_packet *pkt, struct sftp_kex *kex) {
4358   int res;
4359   cmd_rec *cmd;
4360   const char *req;
4361 
4362   req = "ECDH_INIT";
4363   cmd = pr_cmd_alloc(pkt->pool, 1, pstrdup(pkt->pool, req));
4364   cmd->arg = "(data)";
4365   cmd->cmd_class = CL_AUTH|CL_SSH;
4366 
4367   pr_trace_msg(trace_channel, 9, "reading %s message from client", req);
4368 
4369   res = read_ecdh_init(pkt, kex);
4370   if (res < 0) {
4371     pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
4372 
4373     destroy_pool(pkt->pool);
4374     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
4375   }
4376 
4377   pr_cmd_dispatch_phase(cmd, LOG_CMD, 0);
4378   destroy_pool(pkt->pool);
4379 
4380   /* Send our key exchange reply. */
4381   pkt = sftp_ssh2_packet_create(kex_pool);
4382   res = write_ecdh_reply(pkt, kex);
4383   if (res < 0) {
4384     destroy_pool(pkt->pool);
4385     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
4386   }
4387 
4388   /* Don't clean up the EC key in the kex struct until after we've
4389    * written out a reply.
4390    */
4391   if (finish_ecdh(kex) < 0) {
4392     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4393       "error finishing ECDH key: %s", strerror(errno));
4394     destroy_pool(pkt->pool);
4395     return -1;
4396   }
4397 
4398   pr_trace_msg(trace_channel, 9, "writing %s message to client", req);
4399 
4400   res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt);
4401   if (res < 0) {
4402     destroy_pool(pkt->pool);
4403     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
4404   }
4405 
4406   destroy_pool(pkt->pool);
4407   return 0;
4408 }
4409 
4410 #endif /* PR_USE_OPENSSL_ECC */
4411 
4412 static struct ssh2_packet *read_kex_packet(pool *p, struct sftp_kex *kex,
4413     int disconn_code, char *found_mesg_type, unsigned int ntypes, ...) {
4414   register unsigned int i;
4415   va_list ap;
4416   struct ssh2_packet *pkt = NULL;
4417   array_header *allowed_types;
4418 
4419   pr_trace_msg(trace_channel, 9, "waiting for a message of %d %s from client",
4420     ntypes, ntypes != 1 ? "types" : "type");
4421 
4422   allowed_types = make_array(p, 1, sizeof(char));
4423 
4424   va_start(ap, ntypes);
4425 
4426   while (ntypes-- > 0) {
4427     *((char *) push_array(allowed_types)) = va_arg(ap, int);
4428   }
4429 
4430   va_end(ap);
4431 
4432   /* Keep looping until we get the desired message, or we time out (hopefully
4433    * via TimeoutLogin or somesuch).
4434    */
4435   while (pkt == NULL) {
4436     int found = FALSE, res;
4437     char mesg_type;
4438 
4439     pr_signals_handle();
4440 
4441     pkt = sftp_ssh2_packet_create(p);
4442     res = sftp_ssh2_packet_read(sftp_conn->rfd, pkt);
4443     if (res < 0) {
4444       int xerrno = errno;
4445 
4446       destroy_kex(kex);
4447       destroy_pool(pkt->pool);
4448 
4449       errno = xerrno;
4450       return NULL;
4451     }
4452 
4453     pr_response_clear(&resp_list);
4454     pr_response_clear(&resp_err_list);
4455     pr_response_set_pool(pkt->pool);
4456 
4457     /* Per RFC 4253, Section 11, DEBUG, DISCONNECT, IGNORE, and UNIMPLEMENTED
4458      * messages can occur at any time, even during KEX.  We have to be prepared
4459      * for this, and Do The Right Thing(tm).
4460      */
4461 
4462     mesg_type = sftp_ssh2_packet_get_mesg_type(pkt);
4463 
4464     for (i = 0; i < allowed_types->nelts; i++) {
4465       if (mesg_type == ((unsigned char *) allowed_types->elts)[i]) {
4466         /* Exactly what we were looking for.  Excellent. */
4467         pr_trace_msg(trace_channel, 13,
4468           "received expected %s message",
4469           sftp_ssh2_packet_get_mesg_type_desc(mesg_type));
4470 
4471         if (found_mesg_type != NULL) {
4472           /* The caller wants to know the type of message we're returning;
4473            * packet_get_mesg_type() performs a destructive read.
4474            */
4475           *found_mesg_type = mesg_type;
4476         }
4477 
4478         found = TRUE;
4479         break;
4480       }
4481     }
4482 
4483     if (found == TRUE) {
4484       break;
4485     }
4486 
4487     switch (mesg_type) {
4488       case SFTP_SSH2_MSG_DEBUG:
4489         sftp_ssh2_packet_handle_debug(pkt);
4490         pr_response_set_pool(NULL);
4491         pkt = NULL;
4492         break;
4493 
4494       case SFTP_SSH2_MSG_DISCONNECT:
4495         sftp_ssh2_packet_handle_disconnect(pkt);
4496         pr_response_set_pool(NULL);
4497         pkt = NULL;
4498         break;
4499 
4500       case SFTP_SSH2_MSG_IGNORE:
4501         sftp_ssh2_packet_handle_ignore(pkt);
4502         pr_response_set_pool(NULL);
4503         pkt = NULL;
4504         break;
4505 
4506       case SFTP_SSH2_MSG_UNIMPLEMENTED:
4507         sftp_ssh2_packet_handle_unimplemented(pkt);
4508         pr_response_set_pool(NULL);
4509         pkt = NULL;
4510         break;
4511 
4512       default:
4513         /* For any other message type, it's considered a protocol error. */
4514         (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4515           "received %s (%d) unexpectedly, disconnecting",
4516           sftp_ssh2_packet_get_mesg_type_desc(mesg_type), mesg_type);
4517         pr_response_set_pool(NULL);
4518         destroy_kex(kex);
4519         destroy_pool(pkt->pool);
4520         SFTP_DISCONNECT_CONN(disconn_code, NULL);
4521     }
4522   }
4523 
4524   return pkt;
4525 }
4526 
4527 int sftp_kex_handle(struct ssh2_packet *pkt) {
4528   int correct_guess = TRUE, res, sent_newkeys = FALSE;
4529   char mesg_type;
4530   struct sftp_kex *kex;
4531   cmd_rec *cmd;
4532 
4533   /* We may already have a kex structure, either from the client
4534    * initial connect (kex_first_kex not null), or because we
4535    * are in a server-initiated rekeying (kex_rekey_kex not null).
4536    */
4537   if (kex_first_kex) {
4538     kex = kex_first_kex;
4539 
4540     /* We need to assign the client/server versions, which this struct
4541      * will not have.
4542      */
4543     kex->client_version = kex_client_version;
4544     kex->server_version = kex_server_version;
4545 
4546   } else if (kex_rekey_kex) {
4547     kex = kex_rekey_kex;
4548 
4549   } else {
4550     kex = create_kex(kex_pool);
4551   }
4552 
4553   /* The packet we are given is guaranteed to be a KEXINIT packet. */
4554 
4555   cmd = pr_cmd_alloc(pkt->pool, 1, pstrdup(pkt->pool, "KEXINIT"));
4556   cmd->arg = "(data)";
4557   cmd->cmd_class = CL_AUTH|CL_SSH;
4558 
4559   pr_trace_msg(trace_channel, 9, "reading KEXINIT message from client");
4560 
4561   res = read_kexinit(pkt, kex);
4562   if (res < 0) {
4563     pr_cmd_dispatch_phase(cmd, LOG_CMD_ERR, 0);
4564 
4565     destroy_kex(kex);
4566     destroy_pool(pkt->pool);
4567     return -1;
4568   }
4569 
4570   pr_cmd_dispatch_phase(cmd, LOG_CMD, 0);
4571   destroy_pool(pkt->pool);
4572   cmd = NULL;
4573 
4574   pr_trace_msg(trace_channel, 9,
4575     "determining shared algorithms for SSH session");
4576 
4577   if (get_session_names(kex, &correct_guess) < 0) {
4578     destroy_kex(kex);
4579     return -1;
4580   }
4581 
4582   /* Once we have received the client KEXINIT message, we can compare what we
4583    * want to send against what we already received from the client.
4584    *
4585    * If the client said that it was going to send a "guess" KEX packet,
4586    * and we determine that its key exchange guess matches what we would have
4587    * sent in our KEXINIT, then we proceed on with reading and handling that
4588    * guess packet.  If not, we ignore that packet, and proceed.
4589    */
4590 
4591   if (!kex->first_kex_follows) {
4592     /* No guess packet sent; send our KEXINIT as normal (as long as we are
4593      * not in a server-initiated rekeying).
4594      */
4595 
4596     if (!kex_sent_kexinit) {
4597       pkt = sftp_ssh2_packet_create(kex_pool);
4598       res = write_kexinit(pkt, kex);
4599       if (res < 0) {
4600         destroy_kex(kex);
4601         destroy_pool(pkt->pool);
4602         return -1;
4603       }
4604 
4605       pr_trace_msg(trace_channel, 9, "sending KEXINIT message to client");
4606 
4607       res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt);
4608       if (res < 0) {
4609         destroy_kex(kex);
4610         destroy_pool(pkt->pool);
4611         return res;
4612       }
4613 
4614       kex_sent_kexinit = TRUE;
4615       destroy_pool(pkt->pool);
4616     }
4617 
4618   } else {
4619 
4620     /* If the client sent a guess kex packet, but that guess was incorrect,
4621      * then we need to consume and silently ignore that packet, and proceed
4622      * as normal.
4623      */
4624     if (correct_guess == FALSE) {
4625       pr_trace_msg(trace_channel, 3, "client sent incorrect key exchange "
4626         "guess, ignoring guess packet");
4627 
4628       pkt = read_kex_packet(kex_pool, kex,
4629         SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, &mesg_type, 3,
4630         SFTP_SSH2_MSG_KEX_DH_INIT,
4631         SFTP_SSH2_MSG_KEX_DH_GEX_INIT,
4632         SFTP_SSH2_MSG_KEX_ECDH_INIT);
4633 
4634       pr_trace_msg(trace_channel, 3,
4635         "ignored %s (%d) guess message sent by client",
4636         sftp_ssh2_packet_get_mesg_type_desc(mesg_type), mesg_type);
4637 
4638       destroy_pool(pkt->pool);
4639 
4640       if (!kex_sent_kexinit) {
4641         pkt = sftp_ssh2_packet_create(kex_pool);
4642         res = write_kexinit(pkt, kex);
4643         if (res < 0) {
4644           destroy_kex(kex);
4645           destroy_pool(pkt->pool);
4646           return -1;
4647         }
4648 
4649         pr_trace_msg(trace_channel, 9, "sending KEXINIT message to client");
4650 
4651         res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt);
4652         if (res < 0) {
4653           destroy_kex(kex);
4654           destroy_pool(pkt->pool);
4655           return res;
4656         }
4657 
4658         kex_sent_kexinit = TRUE;
4659         destroy_pool(pkt->pool);
4660       }
4661     }
4662 
4663     if (!kex_sent_kexinit) {
4664       pkt = sftp_ssh2_packet_create(kex_pool);
4665       res = write_kexinit(pkt, kex);
4666       if (res < 0) {
4667         destroy_kex(kex);
4668         destroy_pool(pkt->pool);
4669         return -1;
4670       }
4671 
4672       pr_trace_msg(trace_channel, 9, "sending KEXINIT message to client");
4673 
4674       res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt);
4675       if (res < 0) {
4676         destroy_kex(kex);
4677         destroy_pool(pkt->pool);
4678         return res;
4679       }
4680 
4681       kex_sent_kexinit = TRUE;
4682       destroy_pool(pkt->pool);
4683     }
4684   }
4685 
4686   if (!kex->use_kexrsa) {
4687     /* Read the client key exchange mesg. */
4688     pkt = read_kex_packet(kex_pool, kex,
4689       SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, &mesg_type, 3,
4690       SFTP_SSH2_MSG_KEX_DH_INIT,
4691       SFTP_SSH2_MSG_KEX_DH_GEX_REQUEST,
4692       SFTP_SSH2_MSG_KEX_ECDH_INIT);
4693 
4694     switch (mesg_type) {
4695       case SFTP_SSH2_MSG_KEX_DH_INIT:
4696         /* This handles the case of SFTP_SSH2_MSG_KEX_DH_GEX_REQUEST_OLD as
4697          * well; that ID has the same value as the KEX_DH_INIT ID.
4698          */
4699 #if defined(PR_USE_SODIUM) && defined(HAVE_SHA256_OPENSSL)
4700         if (kex->use_curve25519) {
4701           res = handle_kex_curve25519(pkt, kex);
4702 
4703         } else
4704 #endif /* PR_USE_SODIUM and HAVE_SHA256_OPENSSL */
4705 #ifdef PR_USE_OPENSSL_ECC
4706         if (kex->use_ecdh) {
4707           res = handle_kex_ecdh(pkt, kex);
4708 
4709         } else
4710 #endif /* PR_USE_OPENSSL_ECC */
4711 
4712         if (kex->use_gex) {
4713           res = handle_kex_dh_gex(pkt, kex, TRUE);
4714 
4715         } else {
4716           res = handle_kex_dh(pkt, kex);
4717         }
4718 
4719         if (res < 0) {
4720           destroy_kex(kex);
4721           destroy_pool(pkt->pool);
4722           return -1;
4723         }
4724         break;
4725 
4726       case SFTP_SSH2_MSG_KEX_DH_GEX_REQUEST:
4727         res = handle_kex_dh_gex(pkt, kex, FALSE);
4728         if (res < 0) {
4729           destroy_kex(kex);
4730           destroy_pool(pkt->pool);
4731           return -1;
4732         }
4733         break;
4734 
4735       default:
4736         (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4737 #ifdef PR_USE_OPENSSL_ECC
4738           "expecting KEX_DH_INIT, KEX_ECDH_INIT or KEX_DH_GEX_GROUP message, "
4739 #else
4740           "expecting KEX_DH_INIT or KEX_DH_GEX_GROUP message, "
4741 #endif /* PR_USE_OPENSSL_ECC */
4742           "received %s (%d), disconnecting",
4743           sftp_ssh2_packet_get_mesg_type_desc(mesg_type), mesg_type);
4744         destroy_kex(kex);
4745         destroy_pool(pkt->pool);
4746         SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_PROTOCOL_ERROR, NULL);
4747     }
4748 
4749     /* Note: All of the above handle_kex_*() functions are REQUIRED to have
4750      * destroyed the pkt->pool themselves, thus we do NOT need to do it here.
4751      */
4752 
4753   } else {
4754     res = handle_kex_rsa(kex);
4755     if (res < 0) {
4756       destroy_kex(kex);
4757       return -1;
4758     }
4759   }
4760 
4761   if (!sftp_interop_supports_feature(SFTP_SSH2_FEAT_PESSIMISTIC_NEWKEYS)) {
4762     pr_trace_msg(trace_channel, 9, "sending NEWKEYS message to client");
4763 
4764     /* Send our NEWKEYS reply. */
4765     pkt = sftp_ssh2_packet_create(kex_pool);
4766     res = write_newkeys_reply(pkt);
4767     if (res < 0) {
4768       destroy_kex(kex);
4769       destroy_pool(pkt->pool);
4770       return -1;
4771     }
4772 
4773     res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt);
4774     if (res < 0) {
4775       destroy_kex(kex);
4776       destroy_pool(pkt->pool);
4777       return -1;
4778     }
4779 
4780     destroy_pool(pkt->pool);
4781     sent_newkeys = TRUE;
4782   }
4783 
4784   pkt = read_kex_packet(kex_pool, kex, SFTP_SSH2_DISCONNECT_PROTOCOL_ERROR,
4785     NULL, 1, SFTP_SSH2_MSG_NEWKEYS);
4786 
4787   /* If we didn't send our NEWKEYS message earlier, do it now. */
4788   if (!sent_newkeys) {
4789     struct ssh2_packet *pkt2;
4790 
4791     pr_trace_msg(trace_channel, 9, "sending NEWKEYS message to client");
4792 
4793     /* Send our NEWKEYS reply. */
4794     pkt2 = sftp_ssh2_packet_create(kex_pool);
4795     res = write_newkeys_reply(pkt2);
4796     if (res < 0) {
4797       destroy_kex(kex);
4798       destroy_pool(pkt2->pool);
4799       return -1;
4800     }
4801 
4802     res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt2);
4803     if (res < 0) {
4804       destroy_kex(kex);
4805       destroy_pool(pkt2->pool);
4806       return -1;
4807     }
4808 
4809     destroy_pool(pkt2->pool);
4810   }
4811 
4812   /* Last but certainly not least, set up the keys for encryption and
4813    * authentication, based on H and K.
4814    */
4815   pr_trace_msg(trace_channel, 9, "setting session keys");
4816   if (set_session_keys(kex) < 0) {
4817     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
4818       "error setting session keys, disconnecting");
4819     destroy_kex(kex);
4820     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_BY_APPLICATION, NULL);
4821   }
4822 
4823   cmd = pr_cmd_alloc(pkt->pool, 1, pstrdup(pkt->pool, "NEWKEYS"));
4824   cmd->arg = "";
4825   cmd->cmd_class = CL_AUTH|CL_SSH;
4826 
4827   pr_cmd_dispatch_phase(cmd, LOG_CMD, 0);
4828   destroy_pool(pkt->pool);
4829   cmd = NULL;
4830 
4831   /* If extension negotiation has not been disabled, AND if we have not
4832    * received a service request, AND if the client sent "ext-info-c", THEN
4833    * send our EXT_INFO.  We do not want send this during rekeys.
4834    */
4835   if (!(sftp_opts & SFTP_OPT_NO_EXT_INFO) &&
4836       kex->use_ext_info == TRUE &&
4837       !(sftp_sess_state & SFTP_SESS_STATE_HAVE_SERVICE)) {
4838     struct ssh2_packet *pkt2;
4839 
4840     pr_trace_msg(trace_channel, 9, "sending EXT_INFO message to client");
4841 
4842     pkt2 = sftp_ssh2_packet_create(kex_pool);
4843     res = write_ext_info(pkt2);
4844     if (res < 0) {
4845       destroy_kex(kex);
4846       destroy_pool(pkt2->pool);
4847       return -1;
4848     }
4849 
4850     res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt2);
4851     if (res < 0) {
4852       destroy_kex(kex);
4853       destroy_pool(pkt2->pool);
4854       return -1;
4855     }
4856 
4857     cmd = pr_cmd_alloc(pkt2->pool, 1, pstrdup(pkt->pool, "EXT_INFO"));
4858     cmd->arg = "";
4859     cmd->cmd_class = CL_AUTH|CL_SSH;
4860 
4861     pr_cmd_dispatch_phase(cmd, LOG_CMD, 0);
4862 
4863     destroy_pool(pkt2->pool);
4864     cmd = NULL;
4865   }
4866 
4867   /* Reset this flag for the next time through. */
4868   kex_sent_kexinit = FALSE;
4869 
4870   destroy_kex(kex);
4871   return 0;
4872 }
4873 
4874 int sftp_kex_free(void) {
4875   struct sftp_kex *first_kex, *rekey_kex;
4876 
4877   if (kex_dhparams_fp != NULL) {
4878     (void) fclose(kex_dhparams_fp);
4879     kex_dhparams_fp = NULL;
4880   }
4881 
4882   /* destroy_kex() will set the kex_first_kex AND kex_rekey_kex pointers to
4883    * null, so we need to keep our own copies of those pointers here.
4884    */
4885   first_kex = kex_first_kex;
4886   rekey_kex = kex_rekey_kex;
4887 
4888   if (first_kex != NULL) {
4889     destroy_kex(first_kex);
4890   }
4891 
4892   if (rekey_kex != NULL) {
4893     destroy_kex(rekey_kex);
4894   }
4895 
4896   if (kex_pool) {
4897     destroy_pool(kex_pool);
4898     kex_pool = NULL;
4899   }
4900 
4901   return 0;
4902 }
4903 
4904 int sftp_kex_init(const char *client_version, const char *server_version) {
4905   /* If we are called with client_version and server_version both NULL,
4906    * then we're setting up for a rekey.  We can destroy/create the Kex
4907    * pool in that case.  But not otherwise.
4908    */
4909   if (client_version == NULL &&
4910       server_version == NULL) {
4911     if (kex_pool) {
4912       destroy_pool(kex_pool);
4913       kex_pool = NULL;
4914     }
4915   }
4916 
4917   if (kex_pool == NULL) {
4918     kex_pool = make_sub_pool(sftp_pool);
4919     pr_pool_tag(kex_pool, "Kex Pool");
4920   }
4921 
4922   /* Save the client and server versions, the first time through.  They
4923    * will be used for any future rekey KEXINIT exchanges.
4924    */
4925 
4926   if (client_version != NULL &&
4927       kex_client_version == NULL) {
4928     kex_client_version = pstrdup(sftp_pool, client_version);
4929   }
4930 
4931   if (server_version != NULL &&
4932       kex_server_version == NULL) {
4933     kex_server_version = pstrdup(sftp_pool, server_version);
4934   }
4935 
4936   return 0;
4937 }
4938 
4939 int sftp_kex_rekey(void) {
4940   int res;
4941   struct ssh2_packet *pkt;
4942 
4943   /* We cannot perform a rekey if we have not even finished the first kex. */
4944   if (!(sftp_sess_state & SFTP_SESS_STATE_HAVE_KEX)) {
4945     pr_trace_msg(trace_channel, 3,
4946       "unable to request rekey: KEX not completed");
4947 
4948     /* If this was triggered by a rekey timer, register a new timer and
4949      * try the rekey request in another 5 seconds.
4950      */
4951     if (kex_rekey_interval > 0 &&
4952         kex_rekey_timerno == -1) {
4953       pr_trace_msg(trace_channel, 3,
4954         "trying rekey request in another 5 seconds");
4955       kex_rekey_timerno = pr_timer_add(5, -1, &sftp_module, kex_rekey_timer_cb,
4956         "SFTP KEX Rekey timer");
4957     }
4958 
4959     return 0;
4960   }
4961 
4962   if (!sftp_interop_supports_feature(SFTP_SSH2_FEAT_REKEYING)) {
4963     pr_trace_msg(trace_channel, 3,
4964       "unable to request rekeying: Not supported by client");
4965     sftp_ssh2_packet_rekey_reset();
4966     return 0;
4967   }
4968 
4969   /* If already rekeying, return now. */
4970   if (sftp_sess_state & SFTP_SESS_STATE_REKEYING) {
4971     pr_trace_msg(trace_channel, 17,
4972       "rekeying already in effect, ignoring rekey request");
4973     return 0;
4974   }
4975 
4976   /* If the client has NOT authenticated by this point in time, try again
4977    * later.  Some clients do not deal well with having their authentication
4978    * processes interrupted by a rekey (Bug#4254).
4979    */
4980   if (!(sftp_sess_state & SFTP_SESS_STATE_HAVE_AUTH)) {
4981     pr_trace_msg(trace_channel, 17,
4982       "authentication not completed, delaying rekey request");
4983 
4984     /* If the rekey interval is so short as to interfere the client before
4985      * it has authenticated, assume the rekey interval is short enough to
4986      * fire again soon, such that we do not need to change its schedule.
4987      */
4988     return 1;
4989   }
4990 
4991   /* Make sure that any rekey timer will try not to interfere while the
4992    * rekeying is happening.
4993    */
4994   if (kex_rekey_timerno != -1) {
4995     pr_timer_remove(kex_rekey_timerno, &sftp_module);
4996     kex_rekey_timerno = -1;
4997   }
4998 
4999   pr_trace_msg(trace_channel, 17, "sending rekey KEXINIT");
5000 
5001   /* Some SSH2 clients are very particular about rekeying, and do NOT want
5002    * other data while they are rekeying.  Other clients are more forgiving.
5003    * For the strict clients, we set the REKEYING flag here, such that the
5004    * Channel API will buffer up its responses until the rekeying completes.
5005    */
5006   if (sftp_interop_supports_feature(SFTP_SSH2_FEAT_NO_DATA_WHILE_REKEYING)) {
5007     sftp_sess_state |= SFTP_SESS_STATE_REKEYING;
5008   }
5009 
5010   sftp_kex_init(NULL, NULL);
5011 
5012   kex_rekey_kex = create_kex(kex_pool);
5013 
5014   pr_trace_msg(trace_channel, 9, "writing KEXINIT message to client");
5015 
5016   /* Sent our KEXINIT mesg. */
5017   pkt = sftp_ssh2_packet_create(kex_pool);
5018   res = write_kexinit(pkt, kex_rekey_kex);
5019   if (res < 0) {
5020     destroy_pool(pkt->pool);
5021     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
5022   }
5023 
5024   res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt);
5025   if (res < 0) {
5026     destroy_pool(pkt->pool);
5027     SFTP_DISCONNECT_CONN(SFTP_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, NULL);
5028   }
5029 
5030   destroy_pool(pkt->pool);
5031 
5032   kex_sent_kexinit = TRUE;
5033 
5034   if (kex_rekey_timeout > 0) {
5035     pr_trace_msg(trace_channel, 17, "client has %d %s to rekey",
5036       kex_rekey_timeout, kex_rekey_timeout != 1 ? "secs" : "sec");
5037     kex_rekey_timeout_timerno = pr_timer_add(kex_rekey_timeout, -1,
5038       &sftp_module, kex_rekey_timeout_cb, "SFTP KEX Rekey Timeout timer");
5039   }
5040 
5041   return 0;
5042 }
5043 
5044 int sftp_kex_rekey_set_interval(int rekey_interval) {
5045   if (rekey_interval < 0) {
5046     errno = EINVAL;
5047     return -1;
5048   }
5049 
5050   kex_rekey_interval = rekey_interval;
5051   return 0;
5052 }
5053 
5054 int sftp_kex_rekey_set_timeout(int timeout) {
5055   if (timeout < 0) {
5056     errno = EINVAL;
5057     return -1;
5058   }
5059 
5060   kex_rekey_timeout = timeout;
5061   return 0;
5062 }
5063 
5064 int sftp_kex_send_first_kexinit(void) {
5065   struct ssh2_packet *pkt;
5066   int res;
5067 
5068   if (!kex_pool) {
5069     kex_pool = make_sub_pool(sftp_pool);
5070     pr_pool_tag(kex_pool, "Kex Pool");
5071   }
5072 
5073   /* The client has just connected to us.  We want to send our version
5074    * ID string _and_ the KEXINIT in the same TCP packet, and save a
5075    * TCP round trip (one TCP ACK for both messages, rather than one ACK
5076    * per message).  The packet API will automatically send the version
5077    * ID string along with the first packet we send; we just have to
5078    * send a packet, and the KEXINIT is the first one in the protocol.
5079    */
5080   kex_first_kex = create_kex(kex_pool);
5081 
5082   pkt = sftp_ssh2_packet_create(kex_pool);
5083   res = write_kexinit(pkt, kex_first_kex);
5084   if (res < 0) {
5085     destroy_kex(kex_first_kex);
5086     destroy_pool(pkt->pool);
5087     return -1;
5088   }
5089 
5090   pr_trace_msg(trace_channel, 9, "sending KEXINIT message to client");
5091 
5092   res = sftp_ssh2_packet_write(sftp_conn->wfd, pkt);
5093   if (res < 0) {
5094     destroy_kex(kex_first_kex);
5095     destroy_pool(pkt->pool);
5096     return -1;
5097   }
5098   kex_sent_kexinit = TRUE;
5099 
5100   destroy_pool(pkt->pool);
5101   return 0;
5102 }
5103 
5104