File: cipher.c

package info (click to toggle)
proftpd-mod-proxy 0.9.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,476 kB
  • sloc: ansic: 43,512; perl: 43,487; sh: 3,479; makefile: 248
file content (1170 lines) | stat: -rw-r--r-- 34,487 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
/*
 * ProFTPD - mod_proxy SSH ciphers
 * Copyright (c) 2021-2022 TJ Saunders
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
 *
 * As a special exemption, TJ Saunders and other respective copyright holders
 * give permission to link this program with OpenSSL, and distribute the
 * resulting executable, without including the source code for OpenSSL in the
 * source distribution.
 */

#include "mod_proxy.h"

#include "proxy/ssh/packet.h"
#include "proxy/ssh/msg.h"
#include "proxy/ssh/crypto.h"
#include "proxy/ssh/cipher.h"
#include "proxy/ssh/session.h"
#include "proxy/ssh/interop.h"

#if defined(PR_USE_OPENSSL)
#include <openssl/evp.h>

struct proxy_ssh_cipher {
  pool *pool;
  const char *algo;
  const EVP_CIPHER *cipher;

  unsigned char *iv;
  uint32_t iv_len;

  unsigned char *key;
  uint32_t key_len;

  uint32_t auth_len;
  size_t discard_len;
};

/* We need to keep the old ciphers around, so that we can handle N
 * arbitrary packets to/from the client using the old keys, as during rekeying.
 * Thus we have two read cipher contexts, two write cipher contexts.
 * The cipher idx variable indicates which of the ciphers is currently in use.
 */

static struct proxy_ssh_cipher read_ciphers[2] = {
  { NULL, NULL, NULL, NULL, 0, NULL, 0, 0, 0 },
  { NULL, NULL, NULL, NULL, 0, NULL, 0, 0, 0 }
};
static EVP_CIPHER_CTX *read_ctxs[2];

static struct proxy_ssh_cipher write_ciphers[2] = {
  { NULL, NULL, NULL, NULL, 0, NULL, 0, 0, 0 },
  { NULL, NULL, NULL, NULL, 0, NULL, 0, 0, 0 }
};
static EVP_CIPHER_CTX *write_ctxs[2];

#define PROXY_SSH_CIPHER_DEFAULT_BLOCK_SZ		8

static size_t read_blockszs[2] = {
  PROXY_SSH_CIPHER_DEFAULT_BLOCK_SZ,
  PROXY_SSH_CIPHER_DEFAULT_BLOCK_SZ,
};

static size_t write_blockszs[2] = {
  PROXY_SSH_CIPHER_DEFAULT_BLOCK_SZ,
  PROXY_SSH_CIPHER_DEFAULT_BLOCK_SZ,
};

static unsigned int read_cipher_idx = 0;
static unsigned int write_cipher_idx = 0;

static const char *trace_channel = "proxy.ssh.cipher";

static void clear_cipher(struct proxy_ssh_cipher *);

static unsigned int get_next_read_index(void) {
  if (read_cipher_idx == 1) {
    return 0;
  }

  return 1;
}

static unsigned int get_next_write_index(void) {
  if (write_cipher_idx == 1) {
    return 0;
  }

  return 1;
}

static void switch_read_cipher(void) {
  /* First, clear the context of the existing read cipher, if any. */
  if (read_ciphers[read_cipher_idx].key != NULL) {
    clear_cipher(&(read_ciphers[read_cipher_idx]));

#if OPENSSL_VERSION_NUMBER < 0x10100000L || \
    defined(HAVE_LIBRESSL)
    if (EVP_CIPHER_CTX_cleanup(read_ctxs[read_cipher_idx]) != 1) {
#else
    if (EVP_CIPHER_CTX_reset(read_ctxs[read_cipher_idx]) != 1) {
#endif /* OpenSSL-1.1.x and later */
      (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
        "error clearing cipher context: %s", proxy_ssh_crypto_get_errors());
    }

    read_blockszs[read_cipher_idx] = PROXY_SSH_CIPHER_DEFAULT_BLOCK_SZ;

    /* Now we can switch the index. */
    if (read_cipher_idx == 1) {
      read_cipher_idx = 0;
      return;
    }

    read_cipher_idx = 1;
  }
}

static void switch_write_cipher(void) {
  /* First, clear the context of the existing read cipher, if any. */
  if (write_ciphers[write_cipher_idx].key != NULL) {
    clear_cipher(&(write_ciphers[write_cipher_idx]));

#if OPENSSL_VERSION_NUMBER < 0x10100000L || \
    defined(HAVE_LIBRESSL)
    if (EVP_CIPHER_CTX_cleanup(write_ctxs[write_cipher_idx]) != 1) {
#else
    if (EVP_CIPHER_CTX_reset(write_ctxs[write_cipher_idx]) != 1) {
#endif /* OpenSSL-1.1.x and later */
      (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
        "error clearing cipher context: %s", proxy_ssh_crypto_get_errors());
    }

    write_blockszs[write_cipher_idx] = PROXY_SSH_CIPHER_DEFAULT_BLOCK_SZ;

    /* Now we can switch the index. */
    if (write_cipher_idx == 1) {
      write_cipher_idx = 0;
      return;
    }

    write_cipher_idx = 1;
  }
}

static void clear_cipher(struct proxy_ssh_cipher *cipher) {
  if (cipher->iv != NULL) {
    pr_memscrub(cipher->iv, cipher->iv_len);
    free(cipher->iv);
    cipher->iv = NULL;
    cipher->iv_len = 0;
  }

  if (cipher->key != NULL) {
    pr_memscrub(cipher->key, cipher->key_len);
    free(cipher->key);
    cipher->key = NULL;
    cipher->key_len = 0;
  }

  cipher->cipher = NULL;
  cipher->algo = NULL;
}

static int set_cipher_iv(struct proxy_ssh_cipher *cipher, const EVP_MD *md,
    const unsigned char *k, uint32_t klen, const char *h, uint32_t hlen,
    char letter, const unsigned char *id, uint32_t id_len) {
  EVP_MD_CTX *ctx;
  unsigned char *iv = NULL;
  size_t cipher_iv_len = 0, iv_sz = 0;
  uint32_t iv_len = 0;

  if (strcmp(cipher->algo, "none") == 0) {
    cipher->iv = iv;
    cipher->iv_len = iv_len;

    return 0;
  }

   /* Some ciphers do not use IVs; handle this case. */
  cipher_iv_len = EVP_CIPHER_iv_length(cipher->cipher);
  if (cipher_iv_len != 0) {
    iv_sz = proxy_ssh_crypto_get_size(cipher_iv_len, EVP_MD_size(md));

  } else {
    iv_sz = EVP_MD_size(md);
  }

  if (iv_sz == 0) {
    (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
      "unable to determine IV length for cipher '%s'", cipher->algo);
     errno = EINVAL;
    return -1;
  }

  iv = malloc(iv_sz);
  if (iv == NULL) {
    pr_log_pri(PR_LOG_ALERT, MOD_PROXY_VERSION ": Out of memory!");
    _exit(1);
  }

  ctx = EVP_MD_CTX_create();
  if (EVP_DigestInit(ctx, md) != 1) {
    (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
      "unable to initialize SSH MD context for '%s': %s", EVP_MD_name(md),
      proxy_ssh_crypto_get_errors());
    free(iv);
    errno = EINVAL;
    return -1;
  }

  if (proxy_ssh_interop_supports_feature(PROXY_SSH_FEAT_CIPHER_USE_K)) {
    EVP_DigestUpdate(ctx, k, klen);
  }

  if (EVP_DigestUpdate(ctx, h, hlen) != 1) {
    (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
      "unable to update SSH MD context for '%s': %s", EVP_MD_name(md),
      proxy_ssh_crypto_get_errors());
    free(iv);
    errno = EINVAL;
    return -1;
  }

  EVP_DigestUpdate(ctx, &letter, sizeof(letter));
  EVP_DigestUpdate(ctx, (char *) id, id_len);

  if (EVP_DigestFinal(ctx, iv, &iv_len) != 1) {
    (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
      "unable to finish SSH MD context for '%s': %s", EVP_MD_name(md),
      proxy_ssh_crypto_get_errors());
    free(iv);
    errno = EINVAL;
    return -1;
  }

  EVP_MD_CTX_destroy(ctx);

  /* If we need more, keep hashing, as per RFC, until we have enough
   * material.
   */
  while (iv_sz > iv_len) {
    uint32_t len = iv_len;

    pr_signals_handle();

    ctx = EVP_MD_CTX_create();
    EVP_DigestInit(ctx, md);
    if (proxy_ssh_interop_supports_feature(PROXY_SSH_FEAT_CIPHER_USE_K)) {
      EVP_DigestUpdate(ctx, k, klen);
    }
    EVP_DigestUpdate(ctx, h, hlen);
    EVP_DigestUpdate(ctx, iv, len);
    EVP_DigestFinal(ctx, iv + len, &len);
    EVP_MD_CTX_destroy(ctx);

    iv_len += len;
  }

  cipher->iv = iv;
  cipher->iv_len = iv_len;

  return 0;
}

static int set_cipher_key(struct proxy_ssh_cipher *cipher, const EVP_MD *md,
    const unsigned char *k, uint32_t klen, const char *h, uint32_t hlen,
    char letter, const unsigned char *id, uint32_t id_len) {
  EVP_MD_CTX *ctx;
  unsigned char *key = NULL;
  size_t key_sz = 0;
  uint32_t key_len = 0;

  if (strcmp(cipher->algo, "none") == 0) {
    cipher->key = key;
    cipher->key_len = key_len;

    return 0;
  }

  key_sz = proxy_ssh_crypto_get_size(cipher->key_len > 0 ?
      cipher->key_len : (size_t) EVP_CIPHER_key_length(cipher->cipher),
    EVP_MD_size(md));
  if (key_sz == 0) {
    (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
      "unable to determine key length for cipher '%s'", cipher->algo);
    errno = EINVAL;
    return -1;
  }

  pr_trace_msg(trace_channel, 19, "setting key (%lu bytes) for cipher %s",
    (unsigned long) key_sz, cipher->algo);

  key = malloc(key_sz);
  if (key == NULL) {
    pr_log_pri(PR_LOG_ALERT, MOD_PROXY_VERSION ": Out of memory!");
    _exit(1);
  }

  ctx = EVP_MD_CTX_create();
  if (EVP_DigestInit(ctx, md) != 1) {
    (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
      "unable to initialize SSH MD context for '%s': %s", EVP_MD_name(md),
      proxy_ssh_crypto_get_errors());
    free(key);
    errno = EINVAL;
    return -1;
  }

  if (EVP_DigestUpdate(ctx, k, klen) != 1) {
    (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
      "unable to update SSH MD context for '%s': %s", EVP_MD_name(md),
      proxy_ssh_crypto_get_errors());
    free(key);
    errno = EINVAL;
    return -1;
  }

  EVP_DigestUpdate(ctx, h, hlen);
  EVP_DigestUpdate(ctx, &letter, sizeof(letter));
  EVP_DigestUpdate(ctx, (char *) id, id_len);

  if (EVP_DigestFinal(ctx, key, &key_len) != 1) {
    (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
      "unable to finish SSH MD context for '%s': %s", EVP_MD_name(md),
      proxy_ssh_crypto_get_errors());
    free(key);
    errno = EINVAL;
    return -1;
  }

  EVP_MD_CTX_destroy(ctx);

  pr_trace_msg(trace_channel, 19, "hashed data to produce key (%lu bytes)",
    (unsigned long) key_len);

  /* If we need more, keep hashing, as per RFC, until we have enough
   * material.
   */
  while (key_sz > key_len) {
    uint32_t len = key_len;

    pr_signals_handle();

    ctx = EVP_MD_CTX_create();
    EVP_DigestInit(ctx, md);
    EVP_DigestUpdate(ctx, k, klen);
    EVP_DigestUpdate(ctx, h, hlen);
    EVP_DigestUpdate(ctx, key, len);
    EVP_DigestFinal(ctx, key + len, &len);
    EVP_MD_CTX_destroy(ctx);

    key_len += len;
  }

  cipher->key = key;
  return 0;
}

/* If the chosen cipher requires that we discard some of the initial bytes of
 * the cipher stream, then do so.  (This is mostly for any RC4 ciphers.)
 */
static int set_cipher_discarded(struct proxy_ssh_cipher *cipher,
    EVP_CIPHER_CTX *pctx) {
  unsigned char *garbage_in, *garbage_out;

  if (cipher->discard_len == 0) {
    return 0;
  }

  garbage_in = malloc(cipher->discard_len);
  if (garbage_in == NULL) {
    pr_log_pri(PR_LOG_ALERT, MOD_PROXY_VERSION ": Out of memory!");
    _exit(1);
  }

  garbage_out = malloc(cipher->discard_len);
  if (garbage_out == NULL) {
    free(garbage_in);
    pr_log_pri(PR_LOG_ALERT, MOD_PROXY_VERSION ": Out of memory!");
    _exit(1);
  }

  if (EVP_Cipher(pctx, garbage_out, garbage_in,
      cipher->discard_len) != 1) {
    free(garbage_in);
    pr_memscrub(garbage_out, cipher->discard_len);
    free(garbage_out);
    (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
      "error ciphering discard data: %s", proxy_ssh_crypto_get_errors());

    return -1;
  }

  pr_trace_msg(trace_channel, 19, "discarded %lu bytes of cipher data",
    (unsigned long) cipher->discard_len);
  free(garbage_in);
  pr_memscrub(garbage_out, cipher->discard_len);
  free(garbage_out);

  return 0;
}

/* These accessors to get the authenticated data length for the read, write
 * ciphers are used during packet IO, and thus do not return the AAD lengths
 * until those ciphers are keyed.
 *
 * However, during KEX, there are times when we want to know the ADD lengths
 * after the algorithms are selected, but before they are keyed.  Thus for
 * those cases, we have the accessor variants.
 */

size_t proxy_ssh_cipher_get_read_auth_size2(void) {
  return read_ciphers[read_cipher_idx].auth_len;
}

size_t proxy_ssh_cipher_get_read_auth_size(void) {
  /* Do not indicate the read cipher authentication tag size until the
   * cipher has been keyed.
   */
  if (read_ciphers[read_cipher_idx].key != NULL) {
    return proxy_ssh_cipher_get_read_auth_size2();
  }

  return 0;
}

size_t proxy_ssh_cipher_get_write_auth_size2(void) {
  return write_ciphers[write_cipher_idx].auth_len;
}

size_t proxy_ssh_cipher_get_write_auth_size(void) {
  /* Do not indicate the write cipher authentication tag size until the
   * cipher has been keyed.
   */
  if (write_ciphers[write_cipher_idx].key != NULL) {
    return proxy_ssh_cipher_get_write_auth_size2();
  }

  return 0;
}

size_t proxy_ssh_cipher_get_read_block_size(void) {
  return read_blockszs[read_cipher_idx];
}

size_t proxy_ssh_cipher_get_write_block_size(void) {
  return write_blockszs[write_cipher_idx];
}

void proxy_ssh_cipher_set_read_block_size(size_t blocksz) {
  if (blocksz > read_blockszs[read_cipher_idx]) {
    read_blockszs[read_cipher_idx] = blocksz;
  }
}

void proxy_ssh_cipher_set_write_block_size(size_t blocksz) {
  if (blocksz > write_blockszs[write_cipher_idx]) {
    write_blockszs[write_cipher_idx] = blocksz;
  }
}

const char *proxy_ssh_cipher_get_read_algo(void) {
  if (read_ciphers[read_cipher_idx].key != NULL ||
      strcmp(read_ciphers[read_cipher_idx].algo, "none") == 0) {
    return read_ciphers[read_cipher_idx].algo;
  }

  return NULL;
}

int proxy_ssh_cipher_set_read_algo(pool *p, const char *algo) {
  unsigned int idx = read_cipher_idx;
  size_t key_len = 0, auth_len = 0, discard_len = 0;

  if (read_ciphers[idx].key != NULL) {
    /* If we have an existing key, it means that we are currently rekeying. */
    idx = get_next_read_index();
  }

  read_ciphers[idx].cipher = proxy_ssh_crypto_get_cipher(algo, &key_len,
    &auth_len, &discard_len);
  if (read_ciphers[idx].cipher == NULL) {
    return -1;
  }

  if (key_len > 0) {
    pr_trace_msg(trace_channel, 19,
      "setting read key for cipher %s: key len = %lu", algo,
      (unsigned long) key_len);
  }

  if (auth_len > 0) {
    pr_trace_msg(trace_channel, 19,
      "setting read key for cipher %s: auth len = %lu", algo,
      (unsigned long) auth_len);
  }

  if (discard_len > 0) {
    pr_trace_msg(trace_channel, 19,
      "setting read key for cipher %s: discard len = %lu", algo,
      (unsigned long) discard_len);
  }

  /* Note that we use a new pool, each time the algorithm is set (which
   * happens during key exchange) to prevent undue memory growth for
   * long-lived sessions with many rekeys.
   */
  if (read_ciphers[idx].pool != NULL) {
    destroy_pool(read_ciphers[idx].pool);
  }

  read_ciphers[idx].pool = make_sub_pool(p);
  pr_pool_tag(read_ciphers[idx].pool, "Proxy SFTP cipher read pool");
  read_ciphers[idx].algo = pstrdup(read_ciphers[idx].pool, algo);

  read_ciphers[idx].key_len = (uint32_t) key_len;
  read_ciphers[idx].auth_len = (uint32_t) auth_len;
  read_ciphers[idx].discard_len = discard_len;
  return 0;
}

int proxy_ssh_cipher_set_read_key(pool *p, const EVP_MD *md,
    const unsigned char *k, uint32_t klen, const char *h, uint32_t hlen,
    int role) {
  const unsigned char *id = NULL;
  char letter;
  uint32_t id_len;
  int key_len, auth_len;
  struct proxy_ssh_cipher *cipher;
  EVP_CIPHER_CTX *pctx;

  /* Currently unused. */
  (void) p;

  switch_read_cipher();

  cipher = &(read_ciphers[read_cipher_idx]);
  pctx = read_ctxs[read_cipher_idx];

  id_len = proxy_ssh_session_get_id(&id);

  /* The letters used depend on the role; see:
   *  https://tools.ietf.org/html/rfc4253#section-7.2
   *
   * If we are the CLIENT, then we use the letters for the "server to client"
   * flows, since we are READING from the server.
   */

  /* client-to-server IV: HASH(K || H || "A" || session_id)
   * server-to-client IV: HASH(K || H || "B" || session_id)
   */
  letter = (role == PROXY_SSH_ROLE_CLIENT ? 'B' : 'A');
  if (set_cipher_iv(cipher, md, k, klen, h, hlen, letter, id, id_len) < 0) {
    return -1;
  }

  /* client-to-server key: HASH(K || H || "C" || session_id)
   * server-to-client key: HASH(K || H || "D" || session_id)
   */
  letter = (role == PROXY_SSH_ROLE_CLIENT ? 'D' : 'C');
  if (set_cipher_key(cipher, md, k, klen, h, hlen, letter, id, id_len) < 0) {
    return -1;
  }

#if OPENSSL_VERSION_NUMBER < 0x10100000L || \
    defined(HAVE_LIBRESSL)
  EVP_CIPHER_CTX_init(pctx);
#else
  EVP_CIPHER_CTX_reset(pctx);
#endif /* prior to OpenSSL-1.1.0 */

#if defined(PR_USE_OPENSSL_EVP_CIPHERINIT_EX)
  if (EVP_CipherInit_ex(pctx, cipher->cipher, NULL, NULL,
    cipher->iv, 0) != 1) {
#else
  if (EVP_CipherInit(pctx, cipher->cipher, NULL, cipher->iv, 0) != 1) {
#endif /* PR_USE_OPENSSL_EVP_CIPHERINIT_EX */
    (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
      "error initializing %s cipher for decryption: %s", cipher->algo,
      proxy_ssh_crypto_get_errors());
    return -1;
  }

  auth_len = (int) cipher->auth_len;
  if (auth_len > 0) {
#if defined(EVP_CTRL_GCM_SET_IV_FIXED)
    if (EVP_CIPHER_CTX_ctrl(pctx, EVP_CTRL_GCM_SET_IV_FIXED, -1,
        cipher->iv) != 1) {
      (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
        "error configuring %s cipher for decryption: %s", cipher->algo,
        proxy_ssh_crypto_get_errors());
      return -1;
    }
#endif /* EVP_CTRL_GCM_SET_IV_FIXED */

    pr_trace_msg(trace_channel, 19,
      "set auth length (%d) for %s cipher for decryption", auth_len,
      cipher->algo);
  }

  /* Next, set the key length. */
  key_len = (int) cipher->key_len;
  if (key_len > 0) {
    if (EVP_CIPHER_CTX_set_key_length(pctx, key_len) != 1) {
      (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
        "error setting key length (%d bytes) for %s cipher for decryption: %s",
        key_len, cipher->algo, proxy_ssh_crypto_get_errors());
      return -1;
    }

    pr_trace_msg(trace_channel, 19,
      "set key length (%d) for %s cipher for decryption", key_len,
      cipher->algo);
  }

#if defined(PR_USE_OPENSSL_EVP_CIPHERINIT_EX)
  if (EVP_CipherInit_ex(pctx, NULL, NULL, cipher->key, NULL, -1) != 1) {
#else
  if (EVP_CipherInit(pctx, NULL, cipher->key, NULL, -1) != 1) {
#endif /* PR_USE_OPENSSL_EVP_CIPHERINIT_EX */
    (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
      "error re-initializing %s cipher for decryption: %s", cipher->algo,
      proxy_ssh_crypto_get_errors());
    return -1;
  }

  if (set_cipher_discarded(cipher, pctx) < 0) {
    return -1;
  }

  if (strcmp(cipher->algo, "aes128-ctr") == 0 ||
      strcmp(cipher->algo, "aes128-gcm@openssh.com") == 0 ||
      strcmp(cipher->algo, "aes192-ctr") == 0 ||
      strcmp(cipher->algo, "aes256-ctr") == 0 ||
      strcmp(cipher->algo, "aes256-gcm@openssh.com") == 0) {
    /* For some reason, OpenSSL returns 8 for the AES CTR/GCM block size (even
     * though the AES block size is 16, per RFC 5647), but OpenSSH wants 16.
     */
    proxy_ssh_cipher_set_read_block_size(16);

  } else {
    proxy_ssh_cipher_set_read_block_size(EVP_CIPHER_block_size(cipher->cipher));
  }

  return 0;
}

int proxy_ssh_cipher_read_data(struct proxy_ssh_packet *pkt,
    unsigned char *data, uint32_t data_len, unsigned char **buf,
    uint32_t *buflen) {
  struct proxy_ssh_cipher *cipher;
  EVP_CIPHER_CTX *pctx;
  size_t auth_len, read_blocksz;
  uint32_t output_buflen;

  cipher = &(read_ciphers[read_cipher_idx]);
  pctx = read_ctxs[read_cipher_idx];
  read_blocksz = read_blockszs[read_cipher_idx];
  auth_len = proxy_ssh_cipher_get_read_auth_size();
  output_buflen = *buflen;

  if (cipher->key != NULL) {
    int res;
    unsigned char *ptr = NULL, *buf2 = NULL;

    if (*buf == NULL) {
      size_t bufsz;

      /* Allocate a buffer that's large enough. */
      bufsz = (data_len + read_blocksz - 1);
      ptr = buf2 = pcalloc(pkt->pool, bufsz);

    } else {
      ptr = buf2 = *buf;
    }

    if (pkt->packet_len == 0) {
      if (auth_len > 0) {
#if defined(EVP_CTRL_GCM_IV_GEN)
        unsigned char prev_iv[1];

        /* Increment the IV. */
        if (EVP_CIPHER_CTX_ctrl(pctx, EVP_CTRL_GCM_IV_GEN, 1, prev_iv) != 1) {
          (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
            "error incrementing %s IV data for server: %s", cipher->algo,
            proxy_ssh_crypto_get_errors());
          errno = EIO;
          return -1;
        }
#endif
      }

      if (pkt->aad_len > 0 &&
          pkt->aad == NULL) {
        pkt->aad = pcalloc(pkt->pool, pkt->aad_len);
        memcpy(pkt->aad, data, pkt->aad_len);
        memcpy(ptr, data, pkt->aad_len);

        /* Save room at the start of the output buffer `ptr` for the AAD
         * bytes.
         */
        buf2 += pkt->aad_len;
        data += pkt->aad_len;
        data_len -= pkt->aad_len;
        output_buflen -= pkt->aad_len;

        if (auth_len > 0) {
          if (EVP_Cipher(pctx, NULL, pkt->aad, pkt->aad_len) < 0) {
            (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
              "error setting %s AAD data for server: %s", cipher->algo,
              proxy_ssh_crypto_get_errors());
            errno = EIO;
            return -1;
          }
        }
      }
    }

    if (output_buflen % read_blocksz != 0) {
      (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
        "bad input length for decryption (%u bytes, %lu AAD bytes, "
        "%u block size)", output_buflen, (unsigned long) pkt->aad_len,
        (unsigned int) read_blocksz);
      return -1;
    }

    if (pkt->packet_len > 0 &&
        auth_len > 0) {
      unsigned char *tag_data = NULL;
      uint32_t tag_datalen = auth_len;

      /* The authentication tag appears after the unencrypted AAD bytes, and
       * the encrypted payload bytes.
       */
      tag_data = data + (data_len - auth_len);

#if defined(EVP_CTRL_GCM_GET_TAG)
      if (EVP_CIPHER_CTX_ctrl(pctx, EVP_CTRL_GCM_SET_TAG, tag_datalen,
          tag_data) != 1) {
        (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
          "error setting %s authentication tag for server: %s", cipher->algo,
          proxy_ssh_crypto_get_errors());
        errno = EIO;
        return -1;
      }
#endif

      data_len -= auth_len;
    }

    res = EVP_Cipher(pctx, buf2, data, data_len);
    if (res < 0) {
      (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
        "error decrypting %s data from server: %s", cipher->algo,
        proxy_ssh_crypto_get_errors());
      return -1;
    }

    if (pkt->packet_len > 0) {
      *buflen = data_len;

    } else {
      /* If we don't know the packet length yet, it means we need to allow for
       * the processing of the AAD bytes.
       */
      *buflen = pkt->aad_len + data_len;
    }

    *buf = ptr;

    if (pkt->packet_len > 0 &&
        auth_len > 0) {
      /* Verify the authentication tag, but only if we have the full packet. */
      if (EVP_Cipher(pctx, NULL, NULL, 0) < 0) {
        (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
          "error verifying %s authentication tag for server: %s", cipher->algo,
          proxy_ssh_crypto_get_errors());
        errno = EIO;
        return -1;
      }
    }

    return 0;
  }

  *buf = data;
  *buflen = data_len;
  return 0;
}

const char *proxy_ssh_cipher_get_write_algo(void) {
  if (write_ciphers[write_cipher_idx].key != NULL ||
      strcmp(write_ciphers[write_cipher_idx].algo, "none") == 0) {
    return write_ciphers[write_cipher_idx].algo;
  }

  return NULL;
}

int proxy_ssh_cipher_set_write_algo(pool *p, const char *algo) {
  unsigned int idx = write_cipher_idx;
  size_t key_len = 0, auth_len = 0, discard_len = 0;

  if (write_ciphers[idx].key != NULL) {
    /* If we have an existing key, it means that we are currently rekeying. */
    idx = get_next_write_index();
  }

  write_ciphers[idx].cipher = proxy_ssh_crypto_get_cipher(algo, &key_len,
    &auth_len, &discard_len);
  if (write_ciphers[idx].cipher == NULL) {
    return -1;
  }

  if (key_len > 0) {
    pr_trace_msg(trace_channel, 19,
      "setting write key for cipher %s: key len = %lu", algo,
      (unsigned long) key_len);
  }

  if (auth_len > 0) {
    pr_trace_msg(trace_channel, 19,
      "setting write key for cipher %s: auth len = %lu", algo,
      (unsigned long) auth_len);
  }

  if (discard_len > 0) {
    pr_trace_msg(trace_channel, 19,
      "setting write key for cipher %s: discard len = %lu", algo,
      (unsigned long) discard_len);
  }

  /* Note that we use a new pool, each time the algorithm is set (which
   * happens during key exchange) to prevent undue memory growth for
   * long-lived sessions with many rekeys.
   */
  if (write_ciphers[idx].pool != NULL) {
    destroy_pool(write_ciphers[idx].pool);
  }

  write_ciphers[idx].pool = make_sub_pool(p);
  pr_pool_tag(write_ciphers[idx].pool, "Proxy SFTP cipher write pool");
  write_ciphers[idx].algo = pstrdup(write_ciphers[idx].pool, algo);

  write_ciphers[idx].key_len = (uint32_t) key_len;
  write_ciphers[idx].auth_len = (uint32_t) auth_len;
  write_ciphers[idx].discard_len = discard_len;
  return 0;
}

int proxy_ssh_cipher_set_write_key(pool *p, const EVP_MD *md,
    const unsigned char *k, uint32_t klen, const char *h, uint32_t hlen,
    int role) {
  const unsigned char *id = NULL;
  char letter;
  uint32_t id_len;
  int key_len, auth_len;
  struct proxy_ssh_cipher *cipher;
  EVP_CIPHER_CTX *pctx;

  /* Currently unused. */
  (void) p;

  switch_write_cipher();

  cipher = &(write_ciphers[write_cipher_idx]);
  pctx = write_ctxs[write_cipher_idx];

  id_len = proxy_ssh_session_get_id(&id);

  /* The letters used depend on the role; see:
   *  https://tools.ietf.org/html/rfc4253#section-7.2
   *
   * If we are the CLIENT, then we use the letters for the "client to server"
   * flows, since we are WRITING to the server.
   */

  /* client-to-server IV: HASH(K || H || "A" || session_id)
   * server-to-client IV: HASH(K || H || "B" || session_id)
   */
  letter = (role == PROXY_SSH_ROLE_CLIENT ? 'A' : 'B');
  if (set_cipher_iv(cipher, md, k, klen, h, hlen, letter, id, id_len) < 0) {
    return -1;
  }

  /* client-to-server key: HASH(K || H || "C" || session_id)
   * server-to-client key: HASH(K || H || "D" || session_id)
   */
  letter = (role == PROXY_SSH_ROLE_CLIENT ? 'C' : 'D');
  if (set_cipher_key(cipher, md, k, klen, h, hlen, letter, id, id_len) < 0) {
    return -1;
  }

#if OPENSSL_VERSION_NUMBER < 0x10100000L || \
    defined(HAVE_LIBRESSL)
  EVP_CIPHER_CTX_init(pctx);
#else
  EVP_CIPHER_CTX_reset(pctx);
#endif

#if defined(PR_USE_OPENSSL_EVP_CIPHERINIT_EX)
  if (EVP_CipherInit_ex(pctx, cipher->cipher, NULL, NULL,
    cipher->iv, 1) != 1) {
#else
  if (EVP_CipherInit(pctx, cipher->cipher, NULL, cipher->iv, 1) != 1) {
#endif /* PR_USE_OPENSSL_EVP_CIPHERINIT_EX */
    (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
      "error initializing %s cipher for encryption: %s", cipher->algo,
      proxy_ssh_crypto_get_errors());
    return -1;
  }

  auth_len = (int) cipher->auth_len;
  if (auth_len > 0) {
#if defined(EVP_CTRL_GCM_SET_IV_FIXED)
    if (EVP_CIPHER_CTX_ctrl(pctx, EVP_CTRL_GCM_SET_IV_FIXED, -1,
        cipher->iv) != 1) {
      (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
        "error configuring %s cipher for encryption: %s", cipher->algo,
        proxy_ssh_crypto_get_errors());
      return -1;
    }
#endif /* EVP_CTRL_GCM_SET_IV_FIXED */

    pr_trace_msg(trace_channel, 19,
      "set auth length (%d) for %s cipher for encryption", auth_len,
      cipher->algo);
  }

  /* Next, set the key length. */
  key_len = (int) cipher->key_len;
  if (key_len > 0) {
    if (EVP_CIPHER_CTX_set_key_length(pctx, key_len) != 1) {
      (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
        "error setting key length (%d bytes) for %s cipher for decryption: %s",
        key_len, cipher->algo, proxy_ssh_crypto_get_errors());
      return -1;
    }

    pr_trace_msg(trace_channel, 19,
      "set key length (%d) for %s cipher for encryption", key_len,
      cipher->algo);
  }

#if defined(PR_USE_OPENSSL_EVP_CIPHERINIT_EX)
  if (EVP_CipherInit_ex(pctx, NULL, NULL, cipher->key, NULL, -1) != 1) {
#else
  if (EVP_CipherInit(pctx, NULL, cipher->key, NULL, -1) != 1) {
#endif /* PR_USE_OPENSSL_EVP_CIPHERINIT_EX */
    (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
      "error re-initializing %s cipher for encryption: %s", cipher->algo,
      proxy_ssh_crypto_get_errors());
    return -1;
  }

  if (set_cipher_discarded(cipher, pctx) < 0) {
    return -1;
  }

  if (strcmp(cipher->algo, "aes128-ctr") == 0 ||
      strcmp(cipher->algo, "aes128-gcm@openssh.com") == 0 ||
      strcmp(cipher->algo, "aes192-ctr") == 0 ||
      strcmp(cipher->algo, "aes256-ctr") == 0 ||
      strcmp(cipher->algo, "aes256-gcm@openssh.com") == 0) {
    /* For some reason, OpenSSL returns 8 for the AES CTR/GCM block size (even
     * though the AES block size is 16, per RFC 5647), but OpenSSH wants 16.
     */
    proxy_ssh_cipher_set_write_block_size(16);

  } else {
    proxy_ssh_cipher_set_write_block_size(EVP_CIPHER_block_size(cipher->cipher));
  }

  pr_trace_msg(trace_channel, 19,
    "set block size (%d) for %s cipher for encryption",
    (int) proxy_ssh_cipher_get_write_block_size(), cipher->algo);

  return 0;
}

int proxy_ssh_cipher_write_data(struct proxy_ssh_packet *pkt,
    unsigned char *buf, size_t *buflen) {
  struct proxy_ssh_cipher *cipher;
  EVP_CIPHER_CTX *pctx;
  size_t auth_len = 0;

  cipher = &(write_ciphers[write_cipher_idx]);
  pctx = write_ctxs[write_cipher_idx];
  auth_len = proxy_ssh_cipher_get_write_auth_size();

  if (cipher->key != NULL) {
    int res;
    unsigned char *data, *ptr;
    uint32_t datalen, datasz, len = 0;

    /* Always leave a little extra room in the buffer. */
    datasz = sizeof(uint32_t) + pkt->packet_len + 64;

    if (pkt->aad_len > 0) {
      /* Packet length is not encrypted for authentication encryption, or
       * Encrypt-Then-MAC modes.
       */
      datasz -= pkt->aad_len;

      /* And, for ETM modes, we may need a little more space. */
      datasz += proxy_ssh_cipher_get_write_block_size();
    }

    datalen = datasz;
    ptr = data = palloc(pkt->pool, datasz);

    if (auth_len > 0) {
#if defined(EVP_CTRL_GCM_IV_GEN)
      unsigned char prev_iv[1];

      /* Increment the IV. */
      if (EVP_CIPHER_CTX_ctrl(pctx, EVP_CTRL_GCM_IV_GEN, 1, prev_iv) != 1) {
        (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
          "error incrementing %s IV data for server: %s", cipher->algo,
          proxy_ssh_crypto_get_errors());
        errno = EIO;
        return -1;
      }
#endif
    }

    if (pkt->aad_len > 0 &&
        pkt->aad == NULL) {
      uint32_t packet_len;

      packet_len = htonl(pkt->packet_len);
      pkt->aad = pcalloc(pkt->pool, pkt->aad_len);
      memcpy(pkt->aad, &packet_len, pkt->aad_len);

      if (auth_len > 0) {
        if (EVP_Cipher(pctx, NULL, pkt->aad, pkt->aad_len) < 0) {
          (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
            "error setting %s AAD (%lu bytes) for server: %s", cipher->algo,
            (unsigned long) pkt->aad_len, proxy_ssh_crypto_get_errors());
          errno = EIO;
          return -1;
        }
      }

    } else {
      len += proxy_ssh_msg_write_int(&data, &datalen, pkt->packet_len);
    }

    len += proxy_ssh_msg_write_byte(&data, &datalen, pkt->padding_len);
    len += proxy_ssh_msg_write_data(&data, &datalen, pkt->payload,
      pkt->payload_len, FALSE);
    len += proxy_ssh_msg_write_data(&data, &datalen, pkt->padding,
      pkt->padding_len, FALSE);

    res = EVP_Cipher(pctx, buf, ptr, len);
    if (res < 0) {
      (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
        "error encrypting %s data for server: %s", cipher->algo,
        proxy_ssh_crypto_get_errors());
      errno = EIO;
      return -1;
    }

    *buflen = len;

#ifdef SFTP_DEBUG_PACKET
{
  unsigned int i;

  (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
    "encrypted packet data (len %lu):", (unsigned long) *buflen);
  for (i = 0; i < *buflen;) {
    (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
      "  %02x%02x %02x%02x %02x%02x %02x%02x",
      ((unsigned char *) buf)[i], ((unsigned char *) buf)[i+1],
      ((unsigned char *) buf)[i+2], ((unsigned char *) buf)[i+3],
      ((unsigned char *) buf)[i+4], ((unsigned char *) buf)[i+5],
      ((unsigned char *) buf)[i+6], ((unsigned char *) buf)[i+7]);
    i += 8;
  }
}
#endif

    if (auth_len > 0) {
      unsigned char *tag_data = NULL;
      uint32_t tag_datalen = 0;

      if (EVP_Cipher(pctx, NULL, NULL, 0) < 0) {
        (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
          "error generating %s authentication tag for server: %s", cipher->algo,
          proxy_ssh_crypto_get_errors());
        errno = EIO;
        return -1;
      }

      tag_datalen = auth_len;
      tag_data = pcalloc(pkt->pool, tag_datalen);

#if defined(EVP_CTRL_GCM_GET_TAG)
      if (EVP_CIPHER_CTX_ctrl(pctx, EVP_CTRL_GCM_GET_TAG, tag_datalen,
          tag_data) != 1) {
        (void) pr_log_writefile(proxy_logfd, MOD_PROXY_VERSION,
          "error getting %s authentication tag for server: %s", cipher->algo,
          proxy_ssh_crypto_get_errors());
        errno = EIO;
        return -1;
      }
#endif

      pkt->mac_len = tag_datalen;
      pkt->mac = tag_data;
    }

    return 0;
  }

  *buflen = 0;
  return 0;
}

#if OPENSSL_VERSION_NUMBER < 0x1000000fL
/* In older versions of OpenSSL, there was not a way to dynamically allocate
 * an EVP_CIPHER_CTX object.  Thus we have these static objects for those
 * older versions.
 */
static EVP_CIPHER_CTX read_ctx1, read_ctx2;
static EVP_CIPHER_CTX write_ctx1, write_ctx2;
#endif /* prior to OpenSSL-1.0.0 */

int proxy_ssh_cipher_init(void) {
#if OPENSSL_VERSION_NUMBER < 0x1000000fL
  read_ctxs[0] = &read_ctx1;
  read_ctxs[1] = &read_ctx2;
  write_ctxs[0] = &write_ctx1;
  write_ctxs[1] = &write_ctx2;
#else
  read_ctxs[0] = EVP_CIPHER_CTX_new();
  read_ctxs[1] = EVP_CIPHER_CTX_new();
  write_ctxs[0] = EVP_CIPHER_CTX_new();
  write_ctxs[1] = EVP_CIPHER_CTX_new();
#endif /* OpenSSL-1.0.0 and later */

  return 0;
}

int proxy_ssh_cipher_free(void) {
#if OPENSSL_VERSION_NUMBER >= 0x1000000fL
  EVP_CIPHER_CTX_free(read_ctxs[0]);
  EVP_CIPHER_CTX_free(read_ctxs[1]);
  EVP_CIPHER_CTX_free(write_ctxs[0]);
  EVP_CIPHER_CTX_free(write_ctxs[1]);
#endif /* OpenSSL-1.0.0 and later */

  return 0;
}
#endif /* PR_USE_OPENSSL */