1 /*
2  * ProFTPD - mod_sftp OpenSSL interface
3  * Copyright (c) 2008-2017 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 "crypto.h"
27 #include "umac.h"
28 
29 /* In OpenSSL 0.9.7, all des_ functions were renamed to DES_ to avoid
30  * clashes with older versions of libdes.
31  */
32 #if OPENSSL_VERSION_NUMBER < 0x000907000L
33 # define DES_key_schedule des_key_schedule
34 # define DES_cblock des_cblock
35 # define DES_encrypt3 des_encrypt3
36 # define DES_set_key_unchecked des_set_key_unchecked
37 #endif
38 
39 #if OPENSSL_VERSION_NUMBER > 0x000907000L
40 static const char *crypto_engine = NULL;
41 #endif
42 
43 struct sftp_cipher {
44   const char *name;
45   const char *openssl_name;
46 
47   /* Used mostly for the RC4/ArcFour algorithms, for mitigating attacks
48    * based on the first N bytes of the keystream.
49    */
50   size_t discard_len;
51 
52 #if OPENSSL_VERSION_NUMBER > 0x000907000L
53   const EVP_CIPHER *(*get_type)(void);
54 #else
55   EVP_CIPHER *(*get_type)(void);
56 #endif
57 
58   /* Is this cipher enabled by default?  If FALSE, then this cipher must
59    * be explicitly requested via SFTPCiphers.
60    */
61   int enabled;
62 
63   /* Is this cipher usable when FIPS is enabled?  If FALSE, then this
64    * cipher must NOT be advertised to clients in the KEXINIT.
65    */
66   int fips_allowed;
67 };
68 
69 /* Currently, OpenSSL does NOT support AES CTR modes (not sure why).
70  * Until then, we have to provide our own CTR code, for some of the ciphers
71  * recommended by RFC4344.
72  *
73  * And according to:
74  *
75  *   http://www.cpni.gov.uk/Docs/Vulnerability_Advisory_SSH.txt
76  *
77  * it is highly recommended to use CTR mode ciphers, rather than CBC mode,
78  * in order to avoid leaking plaintext.
79  */
80 
81 static struct sftp_cipher ciphers[] = {
82   /* The handling of NULL openssl_name and get_type fields is done in
83    * sftp_crypto_get_cipher(), as special cases.
84    */
85 #if OPENSSL_VERSION_NUMBER > 0x000907000L
86   { "aes256-ctr",	NULL,		0,	NULL,	TRUE, TRUE },
87   { "aes192-ctr",	NULL,		0,	NULL,	TRUE, TRUE },
88   { "aes128-ctr",	NULL,		0,	NULL,	TRUE, TRUE },
89 
90 # ifndef HAVE_AES_CRIPPLED_OPENSSL
91   { "aes256-cbc",	"aes-256-cbc",	0,	EVP_aes_256_cbc, TRUE, TRUE },
92   { "aes192-cbc",	"aes-192-cbc",	0,	EVP_aes_192_cbc, TRUE, TRUE },
93 # endif /* !HAVE_AES_CRIPPLED_OPENSSL */
94 
95   { "aes128-cbc",	"aes-128-cbc",	0,	EVP_aes_128_cbc, TRUE, TRUE },
96 #endif
97 
98 #if !defined(OPENSSL_NO_BF)
99   { "blowfish-ctr",	NULL,		0,	NULL,	FALSE, FALSE },
100   { "blowfish-cbc",	"bf-cbc",	0,	EVP_bf_cbc, FALSE, FALSE },
101 #endif /* !OPENSSL_NO_BF */
102 
103 #if !defined(OPENSSL_NO_CAST)
104   { "cast128-cbc",	"cast5-cbc",	0,	EVP_cast5_cbc, TRUE, FALSE },
105 #endif /* !OPENSSL_NO_CAST */
106 
107 #if !defined(OPENSSL_NO_RC4)
108   { "arcfour256",	"rc4",		1536,	EVP_rc4, FALSE, FALSE },
109   { "arcfour128",	"rc4",		1536,	EVP_rc4, FALSE, FALSE },
110 #endif /* !OPENSSL_NO_RC4 */
111 
112 #if 0
113   /* This cipher is explicitly NOT supported because it does not discard
114    * the first N bytes of the keystream, unlike the other RC4 ciphers.
115    *
116    * If there is a hue and cry, I might add this to the code BUT it would
117    * require explicit configuration via SFTPCiphers, and would generate
118    * warnings about its unsafe use.
119    */
120   { "arcfour",		"rc4",		0,	EVP_rc4, FALSE, FALSE },
121 #endif
122 
123 #if !defined(OPENSSL_NO_DES)
124   { "3des-ctr",		NULL,		0,	NULL, TRUE, TRUE },
125   { "3des-cbc",		"des-ede3-cbc",	0,	EVP_des_ede3_cbc, TRUE, TRUE },
126 #endif /* !OPENSSL_NO_DES */
127 
128   { "none",		"null",		0,	EVP_enc_null, FALSE, TRUE },
129   { NULL, NULL, 0, NULL, FALSE, FALSE }
130 };
131 
132 struct sftp_digest {
133   const char *name;
134   const char *openssl_name;
135 
136 #if OPENSSL_VERSION_NUMBER > 0x000907000L
137   const EVP_MD *(*get_type)(void);
138 #else
139   EVP_MD *(*get_type)(void);
140 #endif
141 
142   uint32_t mac_len;
143 
144   /* Is this MAC enabled by default?  If FALSE, then this MAC must be
145    * explicitly requested via SFTPDigests.
146    */
147   int enabled;
148 
149   /* Is this MAC usable when FIPS is enabled?  If FALSE, then this digest must
150    * NOT be advertised to clients in the KEXINIT.
151    */
152   int fips_allowed;
153 };
154 
155 static struct sftp_digest digests[] = {
156   /* The handling of NULL openssl_name and get_type fields is done in
157    * sftp_crypto_get_digest(), as special cases.
158    */
159 #ifdef HAVE_SHA256_OPENSSL
160   { "hmac-sha2-256",	"sha256",		EVP_sha256,	0, TRUE, TRUE },
161 #endif /* SHA256 support in OpenSSL */
162 #ifdef HAVE_SHA512_OPENSSL
163   { "hmac-sha2-512",	"sha512",		EVP_sha512,	0, TRUE, TRUE },
164 #endif /* SHA512 support in OpenSSL */
165   { "hmac-sha1",	"sha1",		EVP_sha1,	0, 	TRUE, TRUE },
166   { "hmac-sha1-96",	"sha1",		EVP_sha1,	12,	TRUE, TRUE },
167   { "hmac-md5",		"md5",		EVP_md5,	0,	FALSE, FALSE },
168   { "hmac-md5-96",	"md5",		EVP_md5,	12,	FALSE, FALSE },
169 #if !defined(OPENSSL_NO_RIPEMD)
170   { "hmac-ripemd160",	"rmd160",	EVP_ripemd160,	0,	FALSE, FALSE },
171 #endif /* !OPENSSL_NO_RIPEMD */
172 #if OPENSSL_VERSION_NUMBER > 0x000907000L
173   { "umac-64@openssh.com", NULL,	NULL,		8,	TRUE, FALSE },
174   { "umac-128@openssh.com", NULL,	NULL,		16,	TRUE, FALSE },
175 #endif /* OpenSSL-0.9.7 or later */
176   { "none",		"null",		EVP_md_null,	0,	FALSE, TRUE },
177   { NULL, NULL, NULL, 0, FALSE, FALSE }
178 };
179 
180 static const char *trace_channel = "ssh2";
181 
ctr_incr(unsigned char * ctr,size_t len)182 static void ctr_incr(unsigned char *ctr, size_t len) {
183   register int i;
184 
185   if (len == 0) {
186     return;
187   }
188 
189   for (i = len - 1; i >= 0; i--) {
190     /* If we haven't overflowed, we're done. */
191     if (++ctr[i]) {
192       return;
193     }
194   }
195 }
196 
197 #if !defined(OPENSSL_NO_BF)
198 /* Blowfish CTR mode implementation */
199 
200 struct bf_ctr_ex {
201   BF_KEY key;
202   unsigned char counter[BF_BLOCK];
203 };
204 
init_bf_ctr(EVP_CIPHER_CTX * ctx,const unsigned char * key,const unsigned char * iv,int enc)205 static int init_bf_ctr(EVP_CIPHER_CTX *ctx, const unsigned char *key,
206     const unsigned char *iv, int enc) {
207   struct bf_ctr_ex *bce;
208 
209   bce = EVP_CIPHER_CTX_get_app_data(ctx);
210   if (bce == NULL) {
211 
212     /* Allocate our data structure. */
213     bce = calloc(1, sizeof(struct bf_ctr_ex));
214     if (bce == NULL) {
215       pr_log_pri(PR_LOG_ALERT, MOD_SFTP_VERSION ": Out of memory!");
216       _exit(1);
217     }
218 
219     EVP_CIPHER_CTX_set_app_data(ctx, bce);
220   }
221 
222   if (key != NULL) {
223     int key_len;
224 
225 # if OPENSSL_VERSION_NUMBER == 0x0090805fL
226     /* OpenSSL 0.9.8e had a bug where EVP_CIPHER_CTX_key_length() returned
227      * the cipher key length rather than the context key length.
228      */
229     key_len = ctx->key_len;
230 # else
231     key_len = EVP_CIPHER_CTX_key_length(ctx);
232 # endif
233 
234     BF_set_key(&(bce->key), key_len, key);
235   }
236 
237   if (iv != NULL) {
238     memcpy(bce->counter, iv, BF_BLOCK);
239   }
240 
241   return 1;
242 }
243 
cleanup_bf_ctr(EVP_CIPHER_CTX * ctx)244 static int cleanup_bf_ctr(EVP_CIPHER_CTX *ctx) {
245   struct bf_ctr_ex *bce;
246 
247   bce = EVP_CIPHER_CTX_get_app_data(ctx);
248   if (bce != NULL) {
249     pr_memscrub(bce, sizeof(struct bf_ctr_ex));
250     free(bce);
251     EVP_CIPHER_CTX_set_app_data(ctx, NULL);
252   }
253 
254   return 1;
255 }
256 
do_bf_ctr(EVP_CIPHER_CTX * ctx,unsigned char * dst,const unsigned char * src,size_t len)257 static int do_bf_ctr(EVP_CIPHER_CTX *ctx, unsigned char *dst,
258     const unsigned char *src, size_t len) {
259   struct bf_ctr_ex *bce;
260   unsigned int n;
261   unsigned char buf[BF_BLOCK];
262 
263   if (len == 0)
264     return 1;
265 
266   bce = EVP_CIPHER_CTX_get_app_data(ctx);
267   if (bce == NULL)
268     return 0;
269 
270   n = 0;
271 
272   while ((len--) > 0) {
273     pr_signals_handle();
274 
275     if (n == 0) {
276       BF_LONG ctr[2];
277 
278       /* Ideally, we would not be using htonl/ntohl here, and the following
279        * code would be as simple as:
280        *
281        *  memcpy(buf, bce->counter, BF_BLOCK);
282        *  BF_encrypt((BF_LONG *) buf, &(bce->key));
283        *
284        * However, the above is susceptible to endianness issues.  The only
285        * client that I could find which implements the blowfish-ctr cipher,
286        * PuTTy, uses its own big-endian Blowfish implementation.  So the
287        * above code will work with PuTTy, but only on big-endian machines.
288        * For little-endian machines, we need to handle the endianness
289        * ourselves.  Whee.
290        */
291 
292       memcpy(&(ctr[0]), bce->counter, sizeof(BF_LONG));
293       memcpy(&(ctr[1]), bce->counter + sizeof(BF_LONG), sizeof(BF_LONG));
294 
295       /* Convert to big-endian values before encrypting the counter... */
296       ctr[0] = htonl(ctr[0]);
297       ctr[1] = htonl(ctr[1]);
298 
299       BF_encrypt(ctr, &(bce->key));
300 
301       /* ...and convert back to little-endian before XOR'ing the counter in. */
302       ctr[0] = ntohl(ctr[0]);
303       ctr[1] = ntohl(ctr[1]);
304 
305       memcpy(buf, ctr, BF_BLOCK);
306 
307       ctr_incr(bce->counter, BF_BLOCK);
308     }
309 
310     *(dst++) = *(src++) ^ buf[n];
311     n = (n + 1) % BF_BLOCK;
312   }
313 
314   return 1;
315 }
316 
get_bf_ctr_cipher(void)317 static const EVP_CIPHER *get_bf_ctr_cipher(void) {
318   EVP_CIPHER *cipher;
319 
320 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
321     !defined(HAVE_LIBRESSL)
322   /* XXX TODO: At some point, we also need to call EVP_CIPHER_meth_free() on
323    * this, to avoid a resource leak.
324    */
325   cipher = EVP_CIPHER_meth_new(NID_bf_cbc, BF_BLOCK, 32);
326   EVP_CIPHER_meth_set_iv_length(cipher, BF_BLOCK);
327   EVP_CIPHER_meth_set_init(cipher, init_bf_ctr);
328   EVP_CIPHER_meth_set_cleanup(cipher, cleanup_bf_ctr);
329   EVP_CIPHER_meth_set_do_cipher(cipher, do_bf_ctr);
330   EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_CBC_MODE|EVP_CIPH_VARIABLE_LENGTH|EVP_CIPH_ALWAYS_CALL_INIT|EVP_CIPH_CUSTOM_IV);
331 
332 #else
333   static EVP_CIPHER bf_ctr_cipher;
334 
335   memset(&bf_ctr_cipher, 0, sizeof(EVP_CIPHER));
336 
337   bf_ctr_cipher.nid = NID_bf_cbc;
338   bf_ctr_cipher.block_size = BF_BLOCK;
339   bf_ctr_cipher.iv_len = BF_BLOCK;
340   bf_ctr_cipher.key_len = 32;
341   bf_ctr_cipher.init = init_bf_ctr;
342   bf_ctr_cipher.cleanup = cleanup_bf_ctr;
343   bf_ctr_cipher.do_cipher = do_bf_ctr;
344 
345   bf_ctr_cipher.flags = EVP_CIPH_CBC_MODE|EVP_CIPH_VARIABLE_LENGTH|EVP_CIPH_ALWAYS_CALL_INIT|EVP_CIPH_CUSTOM_IV;
346 
347   cipher = &bf_ctr_cipher;
348 #endif /* prior to OpenSSL-1.1.0 */
349 
350   return cipher;
351 }
352 #endif /* !OPENSSL_NO_BF */
353 
354 #if OPENSSL_VERSION_NUMBER > 0x000907000L
355 
356 # if !defined(OPENSSL_NO_DES)
357 /* 3DES CTR mode implementation */
358 
359 struct des3_ctr_ex {
360   DES_key_schedule sched[3];
361   unsigned char counter[8];
362   int big_endian;
363 };
364 
byteswap32(uint32_t in)365 static uint32_t byteswap32(uint32_t in) {
366   uint32_t out;
367 
368   out = (((in & 0x000000ff) << 24) |
369          ((in & 0x0000ff00) << 8) |
370          ((in & 0x00ff0000) >> 8) |
371          ((in & 0xff000000) >> 24));
372 
373   return out;
374 }
375 
init_des3_ctr(EVP_CIPHER_CTX * ctx,const unsigned char * key,const unsigned char * iv,int enc)376 static int init_des3_ctr(EVP_CIPHER_CTX *ctx, const unsigned char *key,
377     const unsigned char *iv, int enc) {
378   struct des3_ctr_ex *dce;
379 
380   dce = EVP_CIPHER_CTX_get_app_data(ctx);
381   if (dce == NULL) {
382 
383     /* Allocate our data structure. */
384     dce = calloc(1, sizeof(struct des3_ctr_ex));
385     if (dce == NULL) {
386       pr_log_pri(PR_LOG_ALERT, MOD_SFTP_VERSION ": Out of memory!");
387       _exit(1);
388     }
389 
390     /* Simple test to see if we're on a big- or little-endian machine:
391      * on big-endian machines, the ntohl() et al will be no-ops.
392      */
393     dce->big_endian = (ntohl(1234) == 1234);
394 
395     EVP_CIPHER_CTX_set_app_data(ctx, dce);
396   }
397 
398   if (key != NULL) {
399     register unsigned int i;
400     unsigned char *ptr;
401 
402     ptr = (unsigned char *) key;
403 
404     for (i = 0; i < 3; i++) {
405       DES_cblock material[8];
406       memcpy(material, ptr, 8);
407       ptr += 8;
408 
409       DES_set_key_unchecked(material, &(dce->sched[i]));
410     }
411   }
412 
413   if (iv != NULL) {
414     memcpy(dce->counter, iv, 8);
415   }
416 
417   return 1;
418 }
419 
cleanup_des3_ctr(EVP_CIPHER_CTX * ctx)420 static int cleanup_des3_ctr(EVP_CIPHER_CTX *ctx) {
421   struct des3_ctr_ex *dce;
422 
423   dce = EVP_CIPHER_CTX_get_app_data(ctx);
424   if (dce != NULL) {
425     pr_memscrub(dce, sizeof(struct des3_ctr_ex));
426     free(dce);
427     EVP_CIPHER_CTX_set_app_data(ctx, NULL);
428   }
429 
430   return 1;
431 }
432 
do_des3_ctr(EVP_CIPHER_CTX * ctx,unsigned char * dst,const unsigned char * src,size_t len)433 static int do_des3_ctr(EVP_CIPHER_CTX *ctx, unsigned char *dst,
434     const unsigned char *src, size_t len) {
435   struct des3_ctr_ex *dce;
436   unsigned int n;
437   unsigned char buf[8];
438 
439   if (len == 0)
440     return 1;
441 
442   dce = EVP_CIPHER_CTX_get_app_data(ctx);
443   if (dce == NULL)
444     return 0;
445 
446   n = 0;
447 
448   while ((len--) > 0) {
449     pr_signals_handle();
450 
451     if (n == 0) {
452       DES_LONG ctr[2];
453 
454       memcpy(&(ctr[0]), dce->counter, sizeof(DES_LONG));
455       memcpy(&(ctr[1]), dce->counter + sizeof(DES_LONG), sizeof(DES_LONG));
456 
457       if (dce->big_endian) {
458         /* If we are on a big-endian machine, we need to initialize the counter
459          * using little-endian values, since that is what OpenSSL's
460          * DES_encryptX() functions expect.
461          */
462 
463         ctr[0] = byteswap32(ctr[0]);
464         ctr[1] = byteswap32(ctr[1]);
465       }
466 
467       DES_encrypt3(ctr, &(dce->sched[0]), &(dce->sched[1]), &(dce->sched[2]));
468 
469       if (dce->big_endian) {
470         ctr[0] = byteswap32(ctr[0]);
471         ctr[1] = byteswap32(ctr[1]);
472       }
473 
474       memcpy(buf, ctr, 8);
475 
476       ctr_incr(dce->counter, 8);
477     }
478 
479     *(dst++) = *(src++) ^ buf[n];
480     n = (n + 1) % 8;
481   }
482 
483   return 1;
484 }
485 
get_des3_ctr_cipher(void)486 static const EVP_CIPHER *get_des3_ctr_cipher(void) {
487   EVP_CIPHER *cipher;
488 
489 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
490     !defined(HAVE_LIBRESSL)
491   unsigned long flags;
492 
493   /* XXX TODO: At some point, we also need to call EVP_CIPHER_meth_free() on
494    * this, to avoid a resource leak.
495    */
496   cipher = EVP_CIPHER_meth_new(NID_des_ede3_ecb, 8, 24);
497   EVP_CIPHER_meth_set_iv_length(cipher, 8);
498   EVP_CIPHER_meth_set_init(cipher, init_des3_ctr);
499   EVP_CIPHER_meth_set_cleanup(cipher, cleanup_des3_ctr);
500   EVP_CIPHER_meth_set_do_cipher(cipher, do_des3_ctr);
501 
502   flags = EVP_CIPH_CBC_MODE|EVP_CIPH_VARIABLE_LENGTH|EVP_CIPH_ALWAYS_CALL_INIT|EVP_CIPH_CUSTOM_IV;
503 #ifdef OPENSSL_FIPS
504   flags |= EVP_CIPH_FLAG_FIPS;
505 #endif /* OPENSSL_FIPS */
506 
507   EVP_CIPHER_meth_set_flags(cipher, flags);
508 
509 #else
510   static EVP_CIPHER des3_ctr_cipher;
511 
512   memset(&des3_ctr_cipher, 0, sizeof(EVP_CIPHER));
513 
514   des3_ctr_cipher.nid = NID_des_ede3_ecb;
515   des3_ctr_cipher.block_size = 8;
516   des3_ctr_cipher.iv_len = 8;
517   des3_ctr_cipher.key_len = 24;
518   des3_ctr_cipher.init = init_des3_ctr;
519   des3_ctr_cipher.cleanup = cleanup_des3_ctr;
520   des3_ctr_cipher.do_cipher = do_des3_ctr;
521 
522   des3_ctr_cipher.flags = EVP_CIPH_CBC_MODE|EVP_CIPH_VARIABLE_LENGTH|EVP_CIPH_ALWAYS_CALL_INIT|EVP_CIPH_CUSTOM_IV;
523 #ifdef OPENSSL_FIPS
524   des3_ctr_cipher.flags |= EVP_CIPH_FLAG_FIPS;
525 #endif /* OPENSSL_FIPS */
526 
527   cipher = &des3_ctr_cipher;
528 #endif /* prior to OpenSSL-1.1.0 */
529 
530   return cipher;
531 }
532 # endif /* !OPENSSL_NO_DES */
533 
534 /* AES CTR mode implementation */
535 struct aes_ctr_ex {
536   AES_KEY key;
537   unsigned char counter[AES_BLOCK_SIZE];
538   unsigned char enc_counter[AES_BLOCK_SIZE];
539   unsigned int num;
540 };
541 
init_aes_ctr(EVP_CIPHER_CTX * ctx,const unsigned char * key,const unsigned char * iv,int enc)542 static int init_aes_ctr(EVP_CIPHER_CTX *ctx, const unsigned char *key,
543     const unsigned char *iv, int enc) {
544   struct aes_ctr_ex *ace;
545 
546   ace = EVP_CIPHER_CTX_get_app_data(ctx);
547   if (ace == NULL) {
548 
549     /* Allocate our data structure. */
550     ace = calloc(1, sizeof(struct aes_ctr_ex));
551     if (ace == NULL) {
552       pr_log_pri(PR_LOG_ALERT, MOD_SFTP_VERSION ": Out of memory!");
553       _exit(1);
554     }
555 
556     EVP_CIPHER_CTX_set_app_data(ctx, ace);
557   }
558 
559   if (key != NULL) {
560     int nbits;
561 
562 # if OPENSSL_VERSION_NUMBER == 0x0090805fL
563     /* OpenSSL 0.9.8e had a bug where EVP_CIPHER_CTX_key_length() returned
564      * the cipher key length rather than the context key length.
565      */
566     nbits = ctx->key_len * 8;
567 # else
568     nbits = EVP_CIPHER_CTX_key_length(ctx) * 8;
569 # endif
570 
571     AES_set_encrypt_key(key, nbits, &(ace->key));
572   }
573 
574   if (iv != NULL) {
575     memcpy(ace->counter, iv, AES_BLOCK_SIZE);
576   }
577 
578   return 1;
579 }
580 
cleanup_aes_ctr(EVP_CIPHER_CTX * ctx)581 static int cleanup_aes_ctr(EVP_CIPHER_CTX *ctx) {
582   struct aes_ctr_ex *ace;
583 
584   ace = EVP_CIPHER_CTX_get_app_data(ctx);
585   if (ace != NULL) {
586     pr_memscrub(ace, sizeof(struct aes_ctr_ex));
587     free(ace);
588     EVP_CIPHER_CTX_set_app_data(ctx, NULL);
589   }
590 
591   return 1;
592 }
593 
do_aes_ctr(EVP_CIPHER_CTX * ctx,unsigned char * dst,const unsigned char * src,size_t len)594 static int do_aes_ctr(EVP_CIPHER_CTX *ctx, unsigned char *dst,
595     const unsigned char *src, size_t len) {
596   struct aes_ctr_ex *ace;
597 # if OPENSSL_VERSION_NUMBER <= 0x0090704fL || \
598      OPENSSL_VERSION_NUMBER >= 0x10100000L
599   unsigned int n;
600   unsigned char buf[AES_BLOCK_SIZE];
601 # endif
602 
603   if (len == 0)
604     return 1;
605 
606   ace = EVP_CIPHER_CTX_get_app_data(ctx);
607   if (ace == NULL)
608     return 0;
609 
610 # if OPENSSL_VERSION_NUMBER <= 0x0090704fL || \
611      OPENSSL_VERSION_NUMBER >= 0x10100000L
612   /* In OpenSSL-0.9.7d and earlier, the AES CTR code did not properly handle
613    * the IV as big-endian; this would cause the dreaded "Incorrect MAC
614    * received on packet" error when using clients e.g. PuTTy.  To see
615    * the difference in OpenSSL, you have do manually do:
616    *
617    *  diff -u openssl-0.9.7d/crypto/aes/aes_ctr.c \
618    *    openssl-0.9.7e/crypto/aes/aes_ctr.c
619    *
620    * This change is not documented in OpenSSL's CHANGES file.  Sigh.
621    *
622    * And in OpenSSL-1.1.0 and later, the AES CTR code was removed entirely.
623    *
624    * Thus for these versions, we have to use our own AES CTR code.
625    */
626 
627   n = 0;
628 
629   while ((len--) > 0) {
630     pr_signals_handle();
631 
632     if (n == 0) {
633       AES_encrypt(ace->counter, buf, &(ace->key));
634       ctr_incr(ace->counter, AES_BLOCK_SIZE);
635     }
636 
637     *(dst++) = *(src++) ^ buf[n];
638     n = (n + 1) % AES_BLOCK_SIZE;
639   }
640 
641   return 1;
642 # else
643   /* Thin wrapper around AES_ctr128_encrypt(). */
644   AES_ctr128_encrypt(src, dst, len, &(ace->key), ace->counter, ace->enc_counter,
645     &(ace->num));
646 # endif
647 
648   return 1;
649 }
650 
get_aes_ctr_cipher_nid(int key_len)651 static int get_aes_ctr_cipher_nid(int key_len) {
652   int nid;
653 
654 #ifdef OPENSSL_FIPS
655   /* Set the NID depending on the key len. */
656   switch (key_len) {
657     case 16:
658       nid = NID_aes_128_cbc;
659       break;
660 
661     case 24:
662       nid = NID_aes_192_cbc;
663       break;
664 
665     case 32:
666       nid = NID_aes_256_cbc;
667       break;
668 
669     default:
670       nid = NID_undef;
671       break;
672   }
673 
674 #else
675   /* Setting this nid member to something other than NID_undef causes
676    * interesting problems on an OpenSolaris system, using the provided
677    * OpenSSL installation's pkcs11 engine via:
678    *
679    *  SFTPCryptoDevice pkcs11
680    *
681    * for the mod_sftp config.  I'm not sure why; I need to look into this
682    * issue more.
683    *
684    * For posterity, the issues seen when using the above config are
685    * described below.  After sending the NEWKEYS request, mod_sftp
686    * would log the following, upon receiving the next message from sftp(1):
687    *
688    *  <ssh2:20>: SSH2 packet len = 1500737511 bytes
689    *  <ssh2:20>: SSH2 packet padding len = 95 bytes
690    *  <ssh2:20>: SSH2 packet payload len = 1500737415 bytes
691    *  <ssh2:20>: payload len (1500737415 bytes) exceeds max payload len (262144), ignoring payload
692    *  client sent buggy/malicious packet payload length, ignoring
693    *
694    * and sftp(1), for its side, would report:
695    *
696    *  debug1: send SSH2_MSG_SERVICE_REQUEST
697    *  Disconnecting: Bad packet length.
698    *  debug1: Calling cleanup 0x807cc14(0x0)
699    *  Couldn't read packet: Error 0
700    */
701   nid = NID_undef;
702 #endif /* OPENSSL_FIPS */
703 
704   return nid;
705 }
706 
get_aes_ctr_cipher(int key_len)707 static const EVP_CIPHER *get_aes_ctr_cipher(int key_len) {
708   EVP_CIPHER *cipher;
709 
710 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
711     !defined(HAVE_LIBRESSL)
712   unsigned long flags;
713 
714   /* XXX TODO: At some point, we also need to call EVP_CIPHER_meth_free() on
715    * this, to avoid a resource leak.
716    */
717   cipher = EVP_CIPHER_meth_new(get_aes_ctr_cipher_nid(key_len), AES_BLOCK_SIZE,
718     key_len);
719   EVP_CIPHER_meth_set_iv_length(cipher, AES_BLOCK_SIZE);
720   EVP_CIPHER_meth_set_init(cipher, init_aes_ctr);
721   EVP_CIPHER_meth_set_cleanup(cipher, cleanup_aes_ctr);
722   EVP_CIPHER_meth_set_do_cipher(cipher, do_aes_ctr);
723 
724   flags = EVP_CIPH_CBC_MODE|EVP_CIPH_VARIABLE_LENGTH|EVP_CIPH_ALWAYS_CALL_INIT|EVP_CIPH_CUSTOM_IV;
725 #ifdef OPENSSL_FIPS
726   flags |= EVP_CIPH_FLAG_FIPS;
727 #endif /* OPENSSL_FIPS */
728 
729   EVP_CIPHER_meth_set_flags(cipher, flags);
730 
731 #else
732   static EVP_CIPHER aes_ctr_cipher;
733 
734   memset(&aes_ctr_cipher, 0, sizeof(EVP_CIPHER));
735 
736   aes_ctr_cipher.nid = get_aes_ctr_cipher_nid(key_len);
737   aes_ctr_cipher.block_size = AES_BLOCK_SIZE;
738   aes_ctr_cipher.iv_len = AES_BLOCK_SIZE;
739   aes_ctr_cipher.key_len = key_len;
740   aes_ctr_cipher.init = init_aes_ctr;
741   aes_ctr_cipher.cleanup = cleanup_aes_ctr;
742   aes_ctr_cipher.do_cipher = do_aes_ctr;
743 
744   aes_ctr_cipher.flags = EVP_CIPH_CBC_MODE|EVP_CIPH_VARIABLE_LENGTH|EVP_CIPH_ALWAYS_CALL_INIT|EVP_CIPH_CUSTOM_IV;
745 # ifdef OPENSSL_FIPS
746   aes_ctr_cipher.flags |= EVP_CIPH_FLAG_FIPS;
747 # endif /* OPENSSL_FIPS */
748 
749   cipher = &aes_ctr_cipher;
750 #endif /* prior to OpenSSL-1.1.0 */
751 
752   return cipher;
753 }
754 
update_umac64(EVP_MD_CTX * ctx,const void * data,size_t len)755 static int update_umac64(EVP_MD_CTX *ctx, const void *data, size_t len) {
756   int res;
757   void *md_data;
758 
759 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
760     !defined(HAVE_LIBRESSL)
761   md_data = EVP_MD_CTX_md_data(ctx);
762 #else
763   md_data = ctx->md_data;
764 #endif /* prior to OpenSSL-1.1.0 */
765   if (md_data == NULL) {
766     struct umac_ctx *umac;
767     void **ptr;
768 
769     umac = umac_new((unsigned char *) data);
770     if (umac == NULL) {
771       return 0;
772     }
773 
774     ptr = &md_data;
775     *ptr = umac;
776     return 1;
777   }
778 
779   res = umac_update(md_data, (unsigned char *) data, (long) len);
780   return res;
781 }
782 
update_umac128(EVP_MD_CTX * ctx,const void * data,size_t len)783 static int update_umac128(EVP_MD_CTX *ctx, const void *data, size_t len) {
784   int res;
785   void *md_data;
786 
787 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
788     !defined(HAVE_LIBRESSL)
789   md_data = EVP_MD_CTX_md_data(ctx);
790 #else
791   md_data = ctx->md_data;
792 #endif /* prior to OpenSSL-1.1.0 */
793 
794   if (md_data == NULL) {
795     struct umac_ctx *umac;
796     void **ptr;
797 
798     umac = umac128_new((unsigned char *) data);
799     if (umac == NULL) {
800       return 0;
801     }
802 
803     ptr = &md_data;
804     *ptr = umac;
805     return 1;
806   }
807 
808   res = umac128_update(md_data, (unsigned char *) data, (long) len);
809   return res;
810 }
811 
final_umac64(EVP_MD_CTX * ctx,unsigned char * md)812 static int final_umac64(EVP_MD_CTX *ctx, unsigned char *md) {
813   unsigned char nonce[8];
814   int res;
815   void *md_data;
816 
817 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
818     !defined(HAVE_LIBRESSL)
819   md_data = EVP_MD_CTX_md_data(ctx);
820 #else
821   md_data = ctx->md_data;
822 #endif /* prior to OpenSSL-1.1.0 */
823 
824   res = umac_final(md_data, md, nonce);
825   return res;
826 }
827 
final_umac128(EVP_MD_CTX * ctx,unsigned char * md)828 static int final_umac128(EVP_MD_CTX *ctx, unsigned char *md) {
829   unsigned char nonce[8];
830   int res;
831   void *md_data;
832 
833 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
834     !defined(HAVE_LIBRESSL)
835   md_data = EVP_MD_CTX_md_data(ctx);
836 #else
837   md_data = ctx->md_data;
838 #endif /* prior to OpenSSL-1.1.0 */
839 
840   res = umac128_final(md_data, md, nonce);
841   return res;
842 }
843 
delete_umac64(EVP_MD_CTX * ctx)844 static int delete_umac64(EVP_MD_CTX *ctx) {
845   struct umac_ctx *umac;
846   void *md_data, **ptr;
847 
848 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
849     !defined(HAVE_LIBRESSL)
850   md_data = EVP_MD_CTX_md_data(ctx);
851 #else
852   md_data = ctx->md_data;
853 #endif /* prior to OpenSSL-1.1.0 */
854 
855   umac = md_data;
856   umac_delete(umac);
857 
858   ptr = &md_data;
859   *ptr = NULL;
860 
861   return 1;
862 }
863 
delete_umac128(EVP_MD_CTX * ctx)864 static int delete_umac128(EVP_MD_CTX *ctx) {
865   struct umac_ctx *umac;
866   void *md_data, **ptr;
867 
868 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
869     !defined(HAVE_LIBRESSL)
870   md_data = EVP_MD_CTX_md_data(ctx);
871 #else
872   md_data = ctx->md_data;
873 #endif /* prior to OpenSSL-1.1.0 */
874 
875   umac = md_data;
876   umac128_delete(umac);
877 
878   ptr = &md_data;
879   *ptr = NULL;
880 
881   return 1;
882 }
883 
get_umac64_digest(void)884 static const EVP_MD *get_umac64_digest(void) {
885   EVP_MD *md;
886 
887 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
888     !defined(HAVE_LIBRESSL)
889   /* XXX TODO: At some point, we also need to call EVP_MD_meth_free() on
890    * this, to avoid a resource leak.
891    */
892   md = EVP_MD_meth_new(NID_undef, NID_undef);
893   EVP_MD_meth_set_input_blocksize(md, 32);
894   EVP_MD_meth_set_result_size(md, 8);
895   EVP_MD_meth_set_flags(md, 0UL);
896   EVP_MD_meth_set_update(md, update_umac64);
897   EVP_MD_meth_set_final(md, final_umac64);
898   EVP_MD_meth_set_cleanup(md, delete_umac64);
899 #else
900   static EVP_MD umac64_digest;
901 
902   memset(&umac64_digest, 0, sizeof(EVP_MD));
903 
904   umac64_digest.type = NID_undef;
905   umac64_digest.pkey_type = NID_undef;
906   umac64_digest.md_size = 8;
907   umac64_digest.flags = 0UL;
908   umac64_digest.update = update_umac64;
909   umac64_digest.final = final_umac64;
910   umac64_digest.cleanup = delete_umac64;
911   umac64_digest.block_size = 32;
912 
913   md = &umac64_digest;
914 #endif /* prior to OpenSSL-1.1.0 */
915 
916   return md;
917 }
918 
get_umac128_digest(void)919 static const EVP_MD *get_umac128_digest(void) {
920   EVP_MD *md;
921 
922 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
923     !defined(HAVE_LIBRESSL)
924   /* XXX TODO: At some point, we also need to call EVP_MD_meth_free() on
925    * this, to avoid a resource leak.
926    */
927   md = EVP_MD_meth_new(NID_undef, NID_undef);
928   EVP_MD_meth_set_input_blocksize(md, 64);
929   EVP_MD_meth_set_result_size(md, 16);
930   EVP_MD_meth_set_flags(md, 0UL);
931   EVP_MD_meth_set_update(md, update_umac128);
932   EVP_MD_meth_set_final(md, final_umac128);
933   EVP_MD_meth_set_cleanup(md, delete_umac128);
934 
935 #else
936   static EVP_MD umac128_digest;
937 
938   memset(&umac128_digest, 0, sizeof(EVP_MD));
939 
940   umac128_digest.type = NID_undef;
941   umac128_digest.pkey_type = NID_undef;
942   umac128_digest.md_size = 16;
943   umac128_digest.flags = 0UL;
944   umac128_digest.update = update_umac128;
945   umac128_digest.final = final_umac128;
946   umac128_digest.cleanup = delete_umac128;
947   umac128_digest.block_size = 64;
948 
949   md = &umac128_digest;
950 #endif /* prior to OpenSSL-1.1.0 */
951 
952   return md;
953 }
954 #endif /* OpenSSL older than 0.9.7 */
955 
sftp_crypto_get_cipher(const char * name,size_t * key_len,size_t * discard_len)956 const EVP_CIPHER *sftp_crypto_get_cipher(const char *name, size_t *key_len,
957     size_t *discard_len) {
958   register unsigned int i;
959 
960   for (i = 0; ciphers[i].name; i++) {
961     if (strcmp(ciphers[i].name, name) == 0) {
962       const EVP_CIPHER *cipher;
963 
964       if (strncmp(name, "blowfish-ctr", 13) == 0) {
965 #if !defined(OPENSSL_NO_BF)
966         cipher = get_bf_ctr_cipher();
967 #else
968         (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
969           "'%s' cipher unsupported", name);
970         errno = ENOENT;
971         return NULL;
972 #endif /* !OPENSSL_NO_BF */
973 
974 #if OPENSSL_VERSION_NUMBER > 0x000907000L
975       } else if (strncmp(name, "3des-ctr", 9) == 0) {
976 # if !defined(OPENSSL_NO_DES)
977         cipher = get_des3_ctr_cipher();
978 # else
979         (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
980           "'%s' cipher unsupported", name);
981         errno = ENOENT;
982         return NULL;
983 # endif /* !OPENSSL_NO_DES */
984 
985       } else if (strncmp(name, "aes256-ctr", 11) == 0) {
986         cipher = get_aes_ctr_cipher(32);
987 
988       } else if (strncmp(name, "aes192-ctr", 11) == 0) {
989         cipher = get_aes_ctr_cipher(24);
990 
991       } else if (strncmp(name, "aes128-ctr", 11) == 0) {
992         cipher = get_aes_ctr_cipher(16);
993 #endif /* OpenSSL older than 0.9.7 */
994 
995       } else {
996         cipher = ciphers[i].get_type();
997       }
998 
999       if (key_len) {
1000         if (strncmp(name, "arcfour256", 11) != 0) {
1001           *key_len = 0;
1002 
1003         } else {
1004           /* The arcfour256 cipher is special-cased here in order to use
1005            * a longer key (32 bytes), rather than the normal 16 bytes for the
1006            * RC4 cipher.
1007            */
1008           *key_len = 32;
1009         }
1010       }
1011 
1012       if (discard_len) {
1013         *discard_len = ciphers[i].discard_len;
1014       }
1015 
1016       return cipher;
1017     }
1018   }
1019 
1020   (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1021     "no cipher matching '%s' found", name);
1022   errno = ENOENT;
1023   return NULL;
1024 }
1025 
sftp_crypto_get_digest(const char * name,uint32_t * mac_len)1026 const EVP_MD *sftp_crypto_get_digest(const char *name, uint32_t *mac_len) {
1027   register unsigned int i;
1028 
1029   for (i = 0; digests[i].name; i++) {
1030     if (strcmp(digests[i].name, name) == 0) {
1031       const EVP_MD *digest = NULL;
1032 
1033 #if OPENSSL_VERSION_NUMBER > 0x000907000L
1034       if (strncmp(name, "umac-64@openssh.com", 12) == 0) {
1035         digest = get_umac64_digest();
1036 
1037       } else if (strncmp(name, "umac-128@openssh.com", 13) == 0) {
1038         digest = get_umac128_digest();
1039 #else
1040       if (FALSE) {
1041 #endif /* OpenSSL older than 0.9.7 */
1042 
1043       } else {
1044         digest = digests[i].get_type();
1045       }
1046 
1047       if (mac_len) {
1048         *mac_len = digests[i].mac_len;
1049       }
1050 
1051       return digest;
1052     }
1053   }
1054 
1055   (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1056     "no digest matching '%s' found", name);
1057   return NULL;
1058 }
1059 
1060 const char *sftp_crypto_get_kexinit_cipher_list(pool *p) {
1061   char *res = "";
1062   config_rec *c;
1063 
1064   /* Make sure that OpenSSL can use these ciphers.  For example, in FIPS mode,
1065    * some ciphers cannot be used.  So we should not advertise ciphers that we
1066    * know we cannot use.
1067    */
1068 
1069   c = find_config(main_server->conf, CONF_PARAM, "SFTPCiphers", FALSE);
1070   if (c) {
1071     register unsigned int i;
1072 
1073     for (i = 0; i < c->argc; i++) {
1074       register unsigned int j;
1075 
1076       for (j = 0; ciphers[j].name; j++) {
1077         if (strcmp(c->argv[i], ciphers[j].name) == 0) {
1078 #ifdef OPENSSL_FIPS
1079           if (FIPS_mode()) {
1080             /* If FIPS mode is enabled, check whether the cipher is allowed
1081              * for use.
1082              */
1083             if (ciphers[j].fips_allowed == FALSE) {
1084               pr_trace_msg(trace_channel, 5,
1085                 "cipher '%s' is disabled in FIPS mode, skipping",
1086                 ciphers[j].name);
1087               continue;
1088             }
1089           }
1090 #endif /* OPENSSL_FIPS */
1091           if (strncmp(c->argv[i], "none", 5) != 0) {
1092             if (EVP_get_cipherbyname(ciphers[j].openssl_name) != NULL) {
1093               res = pstrcat(p, res, *res ? "," : "",
1094                 pstrdup(p, ciphers[j].name), NULL);
1095 
1096             } else {
1097               /* The CTR modes are special cases. */
1098 
1099               if (strncmp(ciphers[j].name, "blowfish-ctr", 13) == 0 ||
1100                   strncmp(ciphers[j].name, "3des-ctr", 9) == 0
1101 #if OPENSSL_VERSION_NUMBER > 0x000907000L
1102                   || strncmp(ciphers[j].name, "aes256-ctr", 11) == 0 ||
1103                   strncmp(ciphers[j].name, "aes192-ctr", 11) == 0 ||
1104                   strncmp(ciphers[j].name, "aes128-ctr", 11) == 0
1105 #endif
1106                   ) {
1107                 res = pstrcat(p, res, *res ? "," : "",
1108                   pstrdup(p, ciphers[j].name), NULL);
1109 
1110               } else {
1111                 pr_trace_msg(trace_channel, 3,
1112                   "unable to use '%s' cipher: Unsupported by OpenSSL",
1113                   ciphers[j].name);
1114               }
1115             }
1116 
1117           } else {
1118             res = pstrcat(p, res, *res ? "," : "",
1119               pstrdup(p, ciphers[j].name), NULL);
1120           }
1121         }
1122       }
1123     }
1124 
1125   } else {
1126     register unsigned int i;
1127 
1128     for (i = 0; ciphers[i].name; i++) {
1129       if (ciphers[i].enabled) {
1130 #ifdef OPENSSL_FIPS
1131           if (FIPS_mode()) {
1132             /* If FIPS mode is enabled, check whether the cipher is allowed
1133              * for use.
1134              */
1135             if (ciphers[i].fips_allowed == FALSE) {
1136               pr_trace_msg(trace_channel, 5,
1137                 "cipher '%s' is disabled in FIPS mode, skipping",
1138                 ciphers[i].name);
1139               continue;
1140             }
1141           }
1142 #endif /* OPENSSL_FIPS */
1143 
1144         if (strncmp(ciphers[i].name, "none", 5) != 0) {
1145           if (EVP_get_cipherbyname(ciphers[i].openssl_name) != NULL) {
1146             res = pstrcat(p, res, *res ? "," : "",
1147               pstrdup(p, ciphers[i].name), NULL);
1148 
1149           } else {
1150             /* The CTR modes are special cases. */
1151 
1152             if (strncmp(ciphers[i].name, "blowfish-ctr", 13) == 0 ||
1153                 strncmp(ciphers[i].name, "3des-ctr", 9) == 0
1154 #if OPENSSL_VERSION_NUMBER > 0x000907000L
1155                 || strncmp(ciphers[i].name, "aes256-ctr", 11) == 0 ||
1156                 strncmp(ciphers[i].name, "aes192-ctr", 11) == 0 ||
1157                 strncmp(ciphers[i].name, "aes128-ctr", 11) == 0
1158 #endif
1159                 ) {
1160               res = pstrcat(p, res, *res ? "," : "",
1161                 pstrdup(p, ciphers[i].name), NULL);
1162 
1163             } else {
1164               pr_trace_msg(trace_channel, 3,
1165                 "unable to use '%s' cipher: Unsupported by OpenSSL",
1166                 ciphers[i].name);
1167             }
1168           }
1169 
1170         } else {
1171           res = pstrcat(p, res, *res ? "," : "",
1172             pstrdup(p, ciphers[i].name), NULL);
1173         }
1174 
1175       } else {
1176         pr_trace_msg(trace_channel, 3, "unable to use '%s' cipher: "
1177           "Must be explicitly requested via SFTPCiphers", ciphers[i].name);
1178       }
1179     }
1180   }
1181 
1182   return res;
1183 }
1184 
1185 const char *sftp_crypto_get_kexinit_digest_list(pool *p) {
1186   char *res = "";
1187   config_rec *c;
1188 
1189   /* Make sure that OpenSSL can use these digests.  For example, in FIPS
1190    * mode, some digests cannot be used.  So we should not advertise digests
1191    * that we know we cannot use.
1192    */
1193 
1194   c = find_config(main_server->conf, CONF_PARAM, "SFTPDigests", FALSE);
1195   if (c != NULL) {
1196     register unsigned int i;
1197 
1198     for (i = 0; i < c->argc; i++) {
1199       register unsigned int j;
1200 
1201       for (j = 0; digests[j].name; j++) {
1202         if (strcmp(c->argv[i], digests[j].name) == 0) {
1203 #ifdef OPENSSL_FIPS
1204           if (FIPS_mode()) {
1205             /* If FIPS mode is enabled, check whether the MAC is allowed
1206              * for use.
1207              */
1208             if (digests[j].fips_allowed == FALSE) {
1209               pr_trace_msg(trace_channel, 5,
1210                 "digest '%s' is disabled in FIPS mode, skipping",
1211                 digests[j].name);
1212               continue;
1213             }
1214           }
1215 #endif /* OPENSSL_FIPS */
1216 
1217           if (strncmp(c->argv[i], "none", 5) != 0) {
1218             if (digests[j].openssl_name != NULL &&
1219                 EVP_get_digestbyname(digests[j].openssl_name) != NULL) {
1220               res = pstrcat(p, res, *res ? "," : "",
1221                 pstrdup(p, digests[j].name), NULL);
1222 
1223             } else {
1224               /* The umac-64/umac-128 digests are special cases. */
1225               if (strncmp(digests[j].name, "umac-64@openssh.com", 12) == 0 ||
1226                   strncmp(digests[j].name, "umac-128@openssh.com", 13) == 0) {
1227                 res = pstrcat(p, res, *res ? "," : "",
1228                   pstrdup(p, digests[j].name), NULL);
1229 
1230               } else {
1231                 pr_trace_msg(trace_channel, 3,
1232                   "unable to use '%s' digest: Unsupported by OpenSSL",
1233                   digests[j].name);
1234               }
1235             }
1236 
1237           } else {
1238             res = pstrcat(p, res, *res ? "," : "",
1239               pstrdup(p, digests[j].name), NULL);
1240           }
1241         }
1242       }
1243     }
1244 
1245   } else {
1246     register unsigned int i;
1247 
1248     for (i = 0; digests[i].name; i++) {
1249       if (digests[i].enabled) {
1250 #ifdef OPENSSL_FIPS
1251           if (FIPS_mode()) {
1252             /* If FIPS mode is enabled, check whether the digest is allowed
1253              * for use.
1254              */
1255             if (digests[i].fips_allowed == FALSE) {
1256               pr_trace_msg(trace_channel, 5,
1257                 "digest '%s' is disabled in FIPS mode, skipping",
1258                 digests[i].name);
1259               continue;
1260             }
1261           }
1262 #endif /* OPENSSL_FIPS */
1263 
1264         if (strncmp(digests[i].name, "none", 5) != 0) {
1265           if (digests[i].openssl_name != NULL &&
1266               EVP_get_digestbyname(digests[i].openssl_name) != NULL) {
1267             res = pstrcat(p, res, *res ? "," : "",
1268               pstrdup(p, digests[i].name), NULL);
1269 
1270           } else {
1271             /* The umac-64/umac-128 digests are special cases. */
1272             if (strncmp(digests[i].name, "umac-64@openssh.com", 12) == 0 ||
1273                 strncmp(digests[i].name, "umac-128@openssh.com", 13) == 0) {
1274               res = pstrcat(p, res, *res ? "," : "",
1275                 pstrdup(p, digests[i].name), NULL);
1276 
1277             } else {
1278               pr_trace_msg(trace_channel, 3,
1279                 "unable to use '%s' digest: Unsupported by OpenSSL",
1280                 digests[i].name);
1281             }
1282           }
1283 
1284         } else {
1285           res = pstrcat(p, res, *res ? "," : "",
1286             pstrdup(p, digests[i].name), NULL);
1287         }
1288 
1289       } else {
1290         pr_trace_msg(trace_channel, 3, "unable to use '%s' digest: "
1291           "Must be explicitly requested via SFTPDigests", digests[i].name);
1292       }
1293     }
1294   }
1295 
1296   return res;
1297 }
1298 
1299 const char *sftp_crypto_get_errors(void) {
1300   unsigned int count = 0;
1301   unsigned long error_code;
1302   BIO *bio = NULL;
1303   char *data = NULL;
1304   long datalen;
1305   const char *error_data = NULL, *str = "(unknown)";
1306   int error_flags = 0;
1307 
1308   /* Use ERR_print_errors() and a memory BIO to build up a string with
1309    * all of the error messages from the error queue.
1310    */
1311 
1312   error_code = ERR_get_error_line_data(NULL, NULL, &error_data, &error_flags);
1313   if (error_code) {
1314     bio = BIO_new(BIO_s_mem());
1315   }
1316 
1317   while (error_code) {
1318     if (error_flags & ERR_TXT_STRING) {
1319       BIO_printf(bio, "\n  (%u) %s [%s]", ++count,
1320         ERR_error_string(error_code, NULL), error_data);
1321 
1322     } else {
1323       BIO_printf(bio, "\n  (%u) %s", ++count,
1324         ERR_error_string(error_code, NULL));
1325     }
1326 
1327     error_data = NULL;
1328     error_flags = 0;
1329     error_code = ERR_get_error_line_data(NULL, NULL, &error_data, &error_flags);
1330   }
1331 
1332   datalen = BIO_get_mem_data(bio, &data);
1333   if (data != NULL) {
1334     data[datalen] = '\0';
1335     str = pstrdup(sftp_pool, data);
1336   }
1337 
1338   if (bio) {
1339     BIO_free(bio);
1340   }
1341 
1342   return str;
1343 }
1344 
1345 /* Try to find the best multiple/block size which accommodates the two given
1346  * sizes by rounding up.
1347  */
1348 size_t sftp_crypto_get_size(size_t first, size_t second) {
1349 #ifdef roundup
1350   return roundup(first, second);
1351 #else
1352   return (((first + (second - 1)) / second) * second);
1353 #endif /* !roundup */
1354 }
1355 
1356 void sftp_crypto_free(int flags) {
1357 
1358   /* Only call EVP_cleanup() et al if other OpenSSL-using modules are not
1359    * present.  If we called EVP_cleanup() here during a restart,
1360    * and other modules want to use OpenSSL, we may be depriving those modules
1361    * of OpenSSL functionality.
1362    *
1363    * At the moment, the modules known to use OpenSSL are mod_ldap, mod_radius,
1364    * mod_sftp, mod_sql, and mod_sql_passwd, and mod_tls.
1365    */
1366   if (pr_module_get("mod_auth_otp.c") == NULL &&
1367       pr_module_get("mod_digest.c") == NULL &&
1368       pr_module_get("mod_ldap.c") == NULL &&
1369       pr_module_get("mod_radius.c") == NULL &&
1370       pr_module_get("mod_sql.c") == NULL &&
1371       pr_module_get("mod_sql_passwd.c") == NULL &&
1372       pr_module_get("mod_tls.c") == NULL) {
1373 
1374 #if OPENSSL_VERSION_NUMBER > 0x000907000L
1375     if (crypto_engine) {
1376       ENGINE_cleanup();
1377       crypto_engine = NULL;
1378     }
1379 #endif
1380 
1381     ERR_free_strings();
1382 
1383 #if OPENSSL_VERSION_NUMBER >= 0x10000001L
1384     /* The ERR_remove_state(0) usage is deprecated due to thread ID
1385      * differences among platforms; see the OpenSSL-1.0.0c CHANGES file
1386      * for details.  So for new enough OpenSSL installations, use the
1387      * proper way to clear the error queue state.
1388      */
1389     ERR_remove_thread_state(NULL);
1390 #else
1391     ERR_remove_state(0);
1392 #endif /* OpenSSL prior to 1.0.0-beta1 */
1393 
1394     EVP_cleanup();
1395     RAND_cleanup();
1396   }
1397 }
1398 
1399 int sftp_crypto_set_driver(const char *driver) {
1400 #if OPENSSL_VERSION_NUMBER > 0x000907000L
1401   if (driver == NULL) {
1402     errno = EINVAL;
1403     return -1;
1404   }
1405 
1406   crypto_engine = driver;
1407 
1408   if (strncasecmp(driver, "ALL", 4) == 0) {
1409     /* Load all ENGINE implementations bundled with OpenSSL. */
1410     ENGINE_load_builtin_engines();
1411     ENGINE_register_all_complete();
1412 
1413     (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1414       "enabled all builtin crypto devices");
1415 
1416   } else {
1417     ENGINE *e;
1418 
1419     /* Load all ENGINE implementations bundled with OpenSSL. */
1420     ENGINE_load_builtin_engines();
1421 
1422     e = ENGINE_by_id(driver);
1423     if (e) {
1424       if (ENGINE_init(e)) {
1425         if (ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
1426           ENGINE_finish(e);
1427           ENGINE_free(e);
1428 
1429           (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1430             "using SFTPCryptoDevice '%s'", driver);
1431 
1432         } else {
1433           /* The requested driver could not be used as the default for
1434            * some odd reason.
1435            */
1436           (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1437             "unable to register SFTPCryptoDevice '%s' as the default: %s",
1438             driver, sftp_crypto_get_errors());
1439 
1440           ENGINE_finish(e);
1441           ENGINE_free(e);
1442           e = NULL;
1443           crypto_engine = NULL;
1444 
1445           errno = EPERM;
1446           return -1;
1447         }
1448 
1449       } else {
1450         /* The requested driver could not be initialized. */
1451         (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1452           "unable to initialize SFTPCryptoDevice '%s': %s", driver,
1453           sftp_crypto_get_errors());
1454 
1455         ENGINE_free(e);
1456         e = NULL;
1457         crypto_engine = NULL;
1458 
1459         errno = EPERM;
1460         return -1;
1461       }
1462 
1463     } else {
1464       /* The requested driver is not available. */
1465       (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
1466         "SFTPCryptoDevice '%s' is not available", driver);
1467 
1468       crypto_engine = NULL;
1469 
1470       errno = EPERM;
1471       return -1;
1472     }
1473   }
1474 
1475   return 0;
1476 #else
1477   errno = ENOSYS;
1478   return -1;
1479 #endif
1480 }
1481 
1482