-
-
Notifications
You must be signed in to change notification settings - Fork 175
/
ssl.c
2362 lines (1925 loc) · 74.3 KB
/
ssl.c
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
/*
* Copyright 2016 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdbool.h>
#include <openssl/bio.h>
#ifndef OPENSSL_NO_ENGINE
#include <openssl/ui.h>
#endif // OPENSSL_NO_ENGINE
#include "tcn.h"
#include "apr_file_io.h"
#include "apr_thread_mutex.h"
#include "apr_atomic.h"
#include "apr_strings.h"
#include "apr_portable.h"
#include "ssl_private.h"
#include "ssl.h"
static int ssl_initialized = 0;
extern apr_pool_t *tcn_global_pool;
void *SSL_temp_keys[SSL_TMP_KEY_MAX];
#ifndef OPENSSL_NO_ENGINE
static ENGINE *tcn_ssl_engine = NULL;
static UI_METHOD *ui_method = NULL;
#endif // OPENSSL_NO_ENGINE
/* Global reference to the pool used by the dynamic mutexes */
static apr_pool_t *dynlockpool = NULL;
/* Dynamic lock structure */
struct CRYPTO_dynlock_value {
apr_pool_t *pool;
const char* file;
int line;
apr_thread_mutex_t *mutex;
};
struct TCN_bio_bytebuffer {
// Pointer arithmetic is done on this variable. The type must correspond to a "byte" size.
char* buffer;
char* nonApplicationBuffer;
jint nonApplicationBufferSize;
jint nonApplicationBufferOffset;
jint nonApplicationBufferLength;
jint bufferLength;
bool bufferIsSSLWriteSink;
};
/*
* Handle the Temporary RSA Keys and DH Params
*/
#define SSL_TMP_KEY_FREE(type, idx) \
if (SSL_temp_keys[idx]) { \
type##_free((type *)SSL_temp_keys[idx]); \
SSL_temp_keys[idx] = NULL; \
} else (void)(0)
#define SSL_TMP_KEYS_FREE(type) \
SSL_TMP_KEY_FREE(type, SSL_TMP_KEY_##type##_512); \
SSL_TMP_KEY_FREE(type, SSL_TMP_KEY_##type##_1024); \
SSL_TMP_KEY_FREE(type, SSL_TMP_KEY_##type##_2048); \
SSL_TMP_KEY_FREE(type, SSL_TMP_KEY_##type##_4096)
#define SSL_TMP_KEY_INIT_DH(bits) \
ssl_tmp_key_init_dh(bits, SSL_TMP_KEY_DH_##bits)
#define SSL_TMP_KEYS_INIT(R) \
R |= SSL_TMP_KEY_INIT_DH(512); \
R |= SSL_TMP_KEY_INIT_DH(1024); \
R |= SSL_TMP_KEY_INIT_DH(2048); \
R |= SSL_TMP_KEY_INIT_DH(4096)
#if !defined(OPENSSL_IS_BORINGSSL)
// This is the maximum overhead when encrypting plaintext as defined by
// <a href="https://www.ietf.org/rfc/rfc5246.txt">rfc5264</a>,
// <a href="https://www.ietf.org/rfc/rfc5289.txt">rfc5289</a> and openssl implementation itself.
//
// Please note that we use a padding of 16 here as openssl uses PKC#5 which uses 16 bytes while the spec itself
// allow up to 255 bytes. 16 bytes is the max for PKC#5 (which handles it the same way as PKC#7) as we use a block
// size of 16. See <a href="https://tools.ietf.org/html/rfc5652#section-6.3">rfc5652#section-6.3</a>.
//
// 16 (IV) + 48 (MAC) + 1 (Padding_length field) + 15 (Padding) + 1 (ContentType) + 2 (ProtocolVersion) + 2 (Length)
//
// TODO(scott): We may need to review this calculation once TLS 1.3 becomes available.
// Which may add a KeyUpdate in front of the current record.
#define TCN_MAX_ENCRYPTED_PACKET_LENGTH (16 + 48 + 1 + 15 + 1 + 2 + 2)
// This also includes the header overhead for TLS 1.2 and below.
// See SSL#getMaxWrapOverhead for the overhead based upon the SSL*
// TODO(scott): this may be an over estimate because we don't account for short headers.
#define TCN_MAX_SEAL_OVERHEAD_LENGTH (TCN_MAX_ENCRYPTED_PACKET_LENGTH + SSL3_RT_HEADER_LENGTH)
#endif /*!defined(OPENSSL_IS_BORINGSSL)*/
static jint tcn_flush_sslbuffer_to_bytebuffer(struct TCN_bio_bytebuffer* bioUserData) {
jint writeAmount = TCN_MIN(bioUserData->bufferLength, bioUserData->nonApplicationBufferLength) * sizeof(char);
jint writeChunk = bioUserData->nonApplicationBufferSize - bioUserData->nonApplicationBufferOffset;
#ifdef NETTY_TCNATIVE_BIO_DEBUG
fprintf(stderr, "tcn_flush_sslbuffer_to_bytebuffer1 bioUserData->nonApplicationBufferLength %d bioUserData->nonApplicationBufferOffset %d writeChunk %d writeAmount %d\n", bioUserData->nonApplicationBufferLength, bioUserData->nonApplicationBufferOffset, writeChunk, writeAmount);
#endif
// check if we need to account for wrap around when draining the internal SSL buffer.
if (writeAmount > writeChunk) {
jint newnonApplicationBufferOffset = writeAmount - writeChunk;
memcpy(bioUserData->buffer, &bioUserData->nonApplicationBuffer[bioUserData->nonApplicationBufferOffset], (size_t) writeChunk);
memcpy(&bioUserData->buffer[writeChunk], bioUserData->nonApplicationBuffer, (size_t) newnonApplicationBufferOffset);
bioUserData->nonApplicationBufferOffset = newnonApplicationBufferOffset;
} else {
memcpy(bioUserData->buffer, &bioUserData->nonApplicationBuffer[bioUserData->nonApplicationBufferOffset], (size_t) writeAmount);
bioUserData->nonApplicationBufferOffset += writeAmount;
}
bioUserData->nonApplicationBufferLength -= writeAmount;
bioUserData->bufferLength -= writeAmount;
bioUserData->buffer += writeAmount; // Pointer arithmetic based on char* type
if (bioUserData->nonApplicationBufferLength == 0) {
bioUserData->nonApplicationBufferOffset = 0;
}
#ifdef NETTY_TCNATIVE_BIO_DEBUG
fprintf(stderr, "tcn_flush_sslbuffer_to_bytebuffer2 bioUserData->nonApplicationBufferLength %d bioUserData->nonApplicationBufferOffset %d\n", bioUserData->nonApplicationBufferLength, bioUserData->nonApplicationBufferOffset);
#endif
return writeAmount;
}
static jint tcn_write_to_bytebuffer(BIO* bio, const char* in, int inl) {
jint writeAmount = 0;
jint writeChunk;
struct TCN_bio_bytebuffer* bioUserData = (struct TCN_bio_bytebuffer*) BIO_get_data(bio);
TCN_ASSERT(bioUserData != NULL);
#ifdef NETTY_TCNATIVE_BIO_DEBUG
fprintf(stderr, "tcn_write_to_bytebuffer bioUserData->bufferIsSSLWriteSink %d inl %d [%.*s]\n", bioUserData->bufferIsSSLWriteSink, inl, inl, in);
#endif
if (in == NULL || inl <= 0) {
return 0;
}
// If the buffer is currently being used for reading then we have to use the internal SSL buffer to queue the data.
if (!bioUserData->bufferIsSSLWriteSink) {
jint nonApplicationBufferFreeSpace = bioUserData->nonApplicationBufferSize - bioUserData->nonApplicationBufferLength;
jint startIndex;
#ifdef NETTY_TCNATIVE_BIO_DEBUG
fprintf(stderr, "tcn_write_to_bytebuffer nonApplicationBufferFreeSpace %d\n", nonApplicationBufferFreeSpace);
#endif
if (nonApplicationBufferFreeSpace == 0) {
BIO_set_retry_write(bio); /* buffer is full */
return -1;
}
writeAmount = TCN_MIN(nonApplicationBufferFreeSpace, (jint) inl) * sizeof(char);
startIndex = bioUserData->nonApplicationBufferOffset + bioUserData->nonApplicationBufferLength;
writeChunk = bioUserData->nonApplicationBufferSize - startIndex;
#ifdef NETTY_TCNATIVE_BIO_DEBUG
fprintf(stderr, "tcn_write_to_bytebuffer bioUserData->nonApplicationBufferLength %d bioUserData->nonApplicationBufferOffset %d startIndex %d writeChunk %d writeAmount %d\n", bioUserData->nonApplicationBufferLength, bioUserData->nonApplicationBufferOffset, startIndex, writeChunk, writeAmount);
#endif
// check if the write will wrap around the buffer.
if (writeAmount > writeChunk) {
memcpy(&bioUserData->nonApplicationBuffer[startIndex], in, (size_t) writeChunk);
memcpy(bioUserData->nonApplicationBuffer, &in[writeChunk], (size_t) (writeAmount - writeChunk));
} else {
memcpy(&bioUserData->nonApplicationBuffer[startIndex], in, (size_t) writeAmount);
}
bioUserData->nonApplicationBufferLength += writeAmount;
// This write amount will not be used by Java, and doesn't correlate to the ByteBuffer source.
// The internal SSL buffer exists because a SSL_read operation may actually write data (e.g. handshake).
return writeAmount;
}
if (bioUserData->buffer == NULL || bioUserData->bufferLength == 0) {
BIO_set_retry_write(bio); /* no buffer to write into */
return -1;
}
// First check if we need to drain data queued in the internal SSL buffer.
if (bioUserData->nonApplicationBufferLength != 0) {
writeAmount = tcn_flush_sslbuffer_to_bytebuffer(bioUserData);
}
// Next write "in" into what ever space the ByteBuffer has available.
writeChunk = TCN_MIN(bioUserData->bufferLength, (jint) inl) * sizeof(char);
#ifdef NETTY_TCNATIVE_BIO_DEBUG
fprintf(stderr, "tcn_write_to_bytebuffer2 writeChunk %d\n", writeChunk);
#endif
memcpy(bioUserData->buffer, in, (size_t) writeChunk);
bioUserData->bufferLength -= writeChunk;
bioUserData->buffer += writeChunk; // Pointer arithmetic based on char* type
return writeAmount + writeChunk;
}
static jint tcn_read_from_bytebuffer(BIO* bio, char *out, int outl) {
jint readAmount;
struct TCN_bio_bytebuffer* bioUserData = (struct TCN_bio_bytebuffer*) BIO_get_data(bio);
TCN_ASSERT(bioUserData != NULL);
#ifdef NETTY_TCNATIVE_BIO_DEBUG
fprintf(stderr, "tcn_read_from_bytebuffer bioUserData->bufferIsSSLWriteSink %d outl %d [%.*s]\n", bioUserData->bufferIsSSLWriteSink, outl, outl, out);
#endif
if (out == NULL || outl <= 0) {
return 0;
}
if (bioUserData->bufferIsSSLWriteSink || bioUserData->buffer == NULL || bioUserData->bufferLength == 0) {
// During handshake this may happen, and it means we are not setup to read yet.
BIO_set_retry_read(bio);
return -1;
}
readAmount = TCN_MIN(bioUserData->bufferLength, (jint) outl) * sizeof(char);
#ifdef NETTY_TCNATIVE_BIO_DEBUG
fprintf(stderr, "tcn_read_from_bytebuffer readAmount %d\n", readAmount);
#endif
memcpy(out, bioUserData->buffer, (size_t) readAmount);
bioUserData->bufferLength -= readAmount;
bioUserData->buffer += readAmount; // Pointer arithmetic based on char* type
return readAmount;
}
static int bio_java_bytebuffer_create(BIO* bio) {
struct TCN_bio_bytebuffer* bioUserData = (struct TCN_bio_bytebuffer*) OPENSSL_malloc(sizeof(struct TCN_bio_bytebuffer));
if (bioUserData == NULL) {
return 0;
}
// The actual ByteBuffer is set from java and may be swapped out for each operation.
bioUserData->buffer = NULL;
bioUserData->bufferLength = 0;
bioUserData->bufferIsSSLWriteSink = false;
bioUserData->nonApplicationBuffer = NULL;
bioUserData->nonApplicationBufferSize = 0;
bioUserData->nonApplicationBufferOffset = 0;
bioUserData->nonApplicationBufferLength = 0;
BIO_set_data(bio, bioUserData);
// In order to for OpenSSL to properly manage the lifetime of a BIO it relies on some shutdown and init state.
// The behavior expected by OpenSSL can be found here: https://www.openssl.org/docs/man1.1.0/crypto/BIO_set_data.html
BIO_set_shutdown(bio, 1);
BIO_set_init(bio, 1);
return 1;
}
static int bio_java_bytebuffer_destroy(BIO* bio) {
struct TCN_bio_bytebuffer* bioUserData;
if (bio == NULL) {
return 0;
}
bioUserData = (struct TCN_bio_bytebuffer*) BIO_get_data(bio);
if (bioUserData == NULL) {
return 1;
}
if (bioUserData->nonApplicationBuffer != NULL) {
OPENSSL_free(bioUserData->nonApplicationBuffer);
bioUserData->nonApplicationBuffer = NULL;
}
// The buffer is not owned by tcn, so just free the native memory.
OPENSSL_free(bioUserData);
BIO_set_data(bio, NULL);
return 1;
}
static int bio_java_bytebuffer_write(BIO* bio, const char* in, int inl) {
BIO_clear_retry_flags(bio);
return (int) tcn_write_to_bytebuffer(bio, in, inl);
}
static int bio_java_bytebuffer_read(BIO* bio, char* out, int outl) {
BIO_clear_retry_flags(bio);
return (int) tcn_read_from_bytebuffer(bio, out, outl);
}
static int bio_java_bytebuffer_puts(BIO* bio, const char *in) {
BIO_clear_retry_flags(bio);
return (int) tcn_write_to_bytebuffer(bio, in, strlen(in));
}
static int bio_java_bytebuffer_gets(BIO* b, char* out, int outl) {
// Not supported https://www.openssl.org/docs/man1.0.2/crypto/BIO_write.html
return -2;
}
static long bio_java_bytebuffer_ctrl(BIO* bio, int cmd, long num, void* ptr) {
// see https://www.openssl.org/docs/man1.0.1/crypto/BIO_ctrl.html
switch (cmd) {
case BIO_CTRL_GET_CLOSE:
return (long) BIO_get_shutdown(bio);
case BIO_CTRL_SET_CLOSE:
BIO_set_shutdown(bio, (int) num);
return 1;
case BIO_CTRL_FLUSH:
return 1;
default:
return 0;
}
}
// This code is based on libcurl:
// https://github.com/curl/curl/blob/curl-7_61_0/lib/vtls/openssl.c#L521
#ifndef OPENSSL_NO_ENGINE
/*
* Supply default password to the engine user interface conversation.
* The password is passed by OpenSSL engine from ENGINE_load_private_key()
* last argument to the ui and can be obtained by UI_get0_user_data(ui) here.
*/
static int ssl_ui_reader(UI *ui, UI_STRING *uis)
{
const char *password;
switch (UI_get_string_type(uis)) {
case UIT_PROMPT:
case UIT_VERIFY:
password = (const char *) UI_get0_user_data(ui);
if (password != NULL && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD) != 0) {
UI_set_result(ui, uis, password);
return 1;
}
// fall-through
default:
return (UI_method_get_reader(UI_OpenSSL()))(ui, uis);
}
}
/*
* Suppress interactive request for a default password if available.
*/
static int ssl_ui_writer(UI *ui, UI_STRING *uis)
{
switch(UI_get_string_type(uis)) {
case UIT_PROMPT:
case UIT_VERIFY:
if (UI_get0_user_data(ui) != NULL && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD) != 0) {
return 1;
}
// fall-through
default:
return (UI_method_get_writer(UI_OpenSSL()))(ui, uis);
}
}
#endif // OPENSSL_NO_ENGINE
TCN_IMPLEMENT_CALL(jint, SSL, bioLengthByteBuffer)(TCN_STDARGS, jlong bioAddress) {
BIO* bio = J2P(bioAddress, BIO*);
struct TCN_bio_bytebuffer* bioUserData;
TCN_CHECK_NULL(bio, bioAddress, 0);
bioUserData = (struct TCN_bio_bytebuffer*) BIO_get_data(bio);
return bioUserData == NULL ? 0 : bioUserData->bufferLength;
}
TCN_IMPLEMENT_CALL(jint, SSL, bioLengthNonApplication)(TCN_STDARGS, jlong bioAddress) {
BIO* bio = J2P(bioAddress, BIO*);
struct TCN_bio_bytebuffer* bioUserData;
TCN_CHECK_NULL(bio, bioAddress, 0);
bioUserData = (struct TCN_bio_bytebuffer*) BIO_get_data(bio);
return bioUserData == NULL ? 0 : bioUserData->nonApplicationBufferLength;
}
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
static BIO_METHOD bio_java_bytebuffer_methods = {
BIO_TYPE_MEM,
"Java ByteBuffer",
bio_java_bytebuffer_write,
bio_java_bytebuffer_read,
bio_java_bytebuffer_puts,
bio_java_bytebuffer_gets,
bio_java_bytebuffer_ctrl,
bio_java_bytebuffer_create,
bio_java_bytebuffer_destroy,
NULL
};
#else
static BIO_METHOD* bio_java_bytebuffer_methods = NULL;
static void init_bio_methods(void) {
bio_java_bytebuffer_methods = BIO_meth_new(BIO_TYPE_MEM, "Java ByteBuffer");
BIO_meth_set_write(bio_java_bytebuffer_methods, &bio_java_bytebuffer_write);
BIO_meth_set_read(bio_java_bytebuffer_methods, &bio_java_bytebuffer_read);
BIO_meth_set_puts(bio_java_bytebuffer_methods, &bio_java_bytebuffer_puts);
BIO_meth_set_gets(bio_java_bytebuffer_methods, &bio_java_bytebuffer_gets);
BIO_meth_set_ctrl(bio_java_bytebuffer_methods, &bio_java_bytebuffer_ctrl);
BIO_meth_set_create(bio_java_bytebuffer_methods, &bio_java_bytebuffer_create);
BIO_meth_set_destroy(bio_java_bytebuffer_methods, &bio_java_bytebuffer_destroy);
}
static void free_bio_methods(void) {
BIO_meth_free(bio_java_bytebuffer_methods);
}
#endif
static BIO_METHOD* BIO_java_bytebuffer() {
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
return &bio_java_bytebuffer_methods;
#else
return bio_java_bytebuffer_methods;
#endif
}
static int ssl_tmp_key_init_dh(int bits, int idx)
{
return (SSL_temp_keys[idx] = tcn_SSL_dh_get_tmp_param(bits)) ? 0 : 1;
}
TCN_IMPLEMENT_CALL(jint, SSL, version)(TCN_STDARGS)
{
UNREFERENCED_STDARGS;
return OpenSSL_version_num();
}
TCN_IMPLEMENT_CALL(jstring, SSL, versionString)(TCN_STDARGS)
{
UNREFERENCED(o);
return AJP_TO_JSTRING(OpenSSL_version(OPENSSL_VERSION));
}
/*
* the various processing hooks
*/
static apr_status_t ssl_init_cleanup(void *data)
{
UNREFERENCED(data);
if (!ssl_initialized)
return APR_SUCCESS;
ssl_initialized = 0;
SSL_TMP_KEYS_FREE(DH);
/*
* Try to kill the internals of the SSL library.
*/
#if OPENSSL_VERSION_NUMBER >= 0x00907001 && !defined(OPENSSL_IS_BORINGSSL)
/* Corresponds to OPENSSL_load_builtin_modules():
* XXX: borrowed from apps.h, but why not CONF_modules_free()
* which also invokes CONF_modules_finish()?
*/
CONF_modules_unload(1);
#endif
/* Corresponds to SSL_library_init: */
EVP_cleanup();
#if OPENSSL_VERSION_NUMBER >= 0x00907001
CRYPTO_cleanup_all_ex_data();
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000L
ERR_remove_thread_state(NULL);
#endif
#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
free_bio_methods();
#endif
// Reset fips mode to the default.
#ifdef OPENSSL_FIPS
FIPS_mode_set(0);
#endif
#ifndef OPENSSL_NO_ENGINE
/* Free our "structural" reference. */
if (tcn_ssl_engine != NULL) {
ENGINE_free(tcn_ssl_engine);
tcn_ssl_engine = NULL;
}
if (ui_method != NULL) {
UI_destroy_method(ui_method);
ui_method = NULL;
}
// In case we loaded any engine we should also call cleanup. This is especialy important in openssl < 1.1.
#ifndef OPENSSL_IS_BORINGSSL
// This is deprecated since openssl 1.1 but does not exist at all in BoringSSL.
ENGINE_cleanup();
#endif // OPENSSL_IS_BORINGSSL
#endif // OPENSSL_NO_ENGINE
/* Don't call ERR_free_strings here; ERR_load_*_strings only
* actually load the error strings once per process due to static
* variable abuse in OpenSSL. */
/*
* TODO: determine somewhere we can safely shove out diagnostics
* (when enabled) at this late stage in the game:
* CRYPTO_mem_leaks_fp(stderr);
*/
return APR_SUCCESS;
}
#ifndef OPENSSL_NO_ENGINE
/* Try to load an engine in a shareable library */
static ENGINE *ssl_try_load_engine(const char *engine)
{
ENGINE *e = ENGINE_by_id("dynamic");
if (e) {
if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
|| !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
ENGINE_free(e);
e = NULL;
}
}
return e;
}
#endif
/*
* To ensure thread-safetyness in OpenSSL
*/
static apr_thread_mutex_t **ssl_lock_cs;
static int ssl_lock_num_locks;
static void ssl_thread_lock(int mode, int type,
const char *file, int line)
{
UNREFERENCED(file);
UNREFERENCED(line);
if (type < ssl_lock_num_locks) {
if (mode & CRYPTO_LOCK) {
apr_thread_mutex_lock(ssl_lock_cs[type]);
}
else {
apr_thread_mutex_unlock(ssl_lock_cs[type]);
}
}
}
static unsigned long ssl_thread_id(void)
{
/* OpenSSL needs this to return an unsigned long. On OS/390, the pthread
* id is a structure twice that big. Use the TCB pointer instead as a
* unique unsigned long.
*/
#ifdef __MVS__
struct PSA {
char unmapped[540];
unsigned long PSATOLD;
} *psaptr = 0;
return psaptr->PSATOLD;
#elif defined(_WIN32)
return (unsigned long)GetCurrentThreadId();
#else
return (unsigned long)(apr_os_thread_current());
#endif
}
static void ssl_set_thread_id(CRYPTO_THREADID *id)
{
CRYPTO_THREADID_set_numeric(id, ssl_thread_id());
}
static apr_status_t ssl_thread_cleanup(void *data)
{
UNREFERENCED(data);
CRYPTO_set_locking_callback(NULL);
CRYPTO_THREADID_set_callback(NULL);
CRYPTO_set_dynlock_create_callback(NULL);
CRYPTO_set_dynlock_lock_callback(NULL);
CRYPTO_set_dynlock_destroy_callback(NULL);
dynlockpool = NULL;
/* Let the registered mutex cleanups do their own thing
*/
return APR_SUCCESS;
}
/*
* Dynamic lock creation callback
*/
static struct CRYPTO_dynlock_value *ssl_dyn_create_function(const char *file,
int line)
{
struct CRYPTO_dynlock_value *value;
apr_pool_t *p;
apr_status_t rv;
/*
* We need a pool to allocate our mutex. Since we can't clear
* allocated memory from a pool, create a subpool that we can blow
* away in the destruction callback.
*/
rv = apr_pool_create(&p, dynlockpool);
if (rv != APR_SUCCESS) {
/* TODO log that fprintf(stderr, "Failed to create subpool for dynamic lock"); */
return NULL;
}
value = (struct CRYPTO_dynlock_value *)apr_palloc(p,
sizeof(struct CRYPTO_dynlock_value));
if (!value) {
/* TODO log that fprintf(stderr, "Failed to allocate dynamic lock structure"); */
return NULL;
}
value->pool = p;
/* Keep our own copy of the place from which we were created,
using our own pool. */
value->file = apr_pstrdup(p, file);
value->line = line;
rv = apr_thread_mutex_create(&(value->mutex), APR_THREAD_MUTEX_DEFAULT,
p);
if (rv != APR_SUCCESS) {
/* TODO log that fprintf(stderr, "Failed to create thread mutex for dynamic lock"); */
apr_pool_destroy(p);
return NULL;
}
return value;
}
/*
* Dynamic locking and unlocking function
*/
static void ssl_dyn_lock_function(int mode, struct CRYPTO_dynlock_value *l,
const char *file, int line)
{
if (mode & CRYPTO_LOCK) {
apr_thread_mutex_lock(l->mutex);
}
else {
apr_thread_mutex_unlock(l->mutex);
}
}
/*
* Dynamic lock destruction callback
*/
static void ssl_dyn_destroy_function(struct CRYPTO_dynlock_value *l,
const char *file, int line)
{
apr_status_t rv;
rv = apr_thread_mutex_destroy(l->mutex);
if (rv != APR_SUCCESS) {
/* TODO log that fprintf(stderr, "Failed to destroy mutex for dynamic lock %s:%d", l->file, l->line); */
}
/* Trust that whomever owned the CRYPTO_dynlock_value we were
* passed has no future use for it...
*/
apr_pool_destroy(l->pool);
}
static void ssl_thread_setup(apr_pool_t *p)
{
int i;
ssl_lock_num_locks = CRYPTO_num_locks();
ssl_lock_cs = apr_palloc(p, ssl_lock_num_locks * sizeof(*ssl_lock_cs));
for (i = 0; i < ssl_lock_num_locks; i++) {
apr_thread_mutex_create(&(ssl_lock_cs[i]),
APR_THREAD_MUTEX_DEFAULT, p);
}
CRYPTO_THREADID_set_callback(ssl_set_thread_id);
CRYPTO_set_locking_callback(ssl_thread_lock);
/* Set up dynamic locking scaffolding for OpenSSL to use at its
* convenience.
*/
dynlockpool = p;
CRYPTO_set_dynlock_create_callback(ssl_dyn_create_function);
CRYPTO_set_dynlock_lock_callback(ssl_dyn_lock_function);
CRYPTO_set_dynlock_destroy_callback(ssl_dyn_destroy_function);
apr_pool_cleanup_register(p, NULL, ssl_thread_cleanup,
apr_pool_cleanup_null);
}
TCN_IMPLEMENT_CALL(jint, SSL, initialize)(TCN_STDARGS, jstring engine)
{
int r = 0;
TCN_ALLOC_CSTRING(engine);
UNREFERENCED(o);
if (!tcn_global_pool) {
TCN_FREE_CSTRING(engine);
tcn_ThrowAPRException(e, APR_EINVAL);
return (jint)APR_EINVAL;
}
/* Check if already initialized */
if (ssl_initialized++) {
TCN_FREE_CSTRING(engine);
return (jint)APR_SUCCESS;
}
#if OPENSSL_VERSION_NUMBER < 0x10100000L
if (OpenSSL_version_num() < 0x0090700L) {
TCN_FREE_CSTRING(engine);
tcn_ThrowAPRException(e, APR_EINVAL);
ssl_initialized = 0;
return (jint)APR_EINVAL;
}
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
/* We must register the library in full, to ensure our configuration
* code can successfully test the SSL environment.
*/
OPENSSL_malloc_init();
#endif
ERR_load_crypto_strings();
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
#if OPENSSL_VERSION_NUMBER >= 0x00907001
OPENSSL_load_builtin_modules();
#endif
/* Initialize thread support */
ssl_thread_setup(tcn_global_pool);
apr_status_t err = APR_SUCCESS;
#ifndef OPENSSL_NO_ENGINE
if (J2S(engine)) {
// Let us load the builtin engines as we want to use a specific one. This will also allow us
// to use OPENSSL_ENGINES to define where a custom engine is located.
ENGINE_load_builtin_engines();
if(strcmp(J2S(engine), "auto") == 0) {
ENGINE_register_all_complete();
}
else {
// ssl_init_cleanup will take care of free the engine (tcn_ssl_engine) if needed.
if ((tcn_ssl_engine = ENGINE_by_id(J2S(engine))) == NULL
&& (tcn_ssl_engine = ssl_try_load_engine(J2S(engine))) == NULL)
err = APR_ENOTIMPL;
else {
#ifdef ENGINE_CTRL_CHIL_SET_FORKCHECK
if (strcmp(J2S(engine), "chil") == 0)
ENGINE_ctrl(tcn_ssl_engine, ENGINE_CTRL_CHIL_SET_FORKCHECK, 1, 0, 0);
#endif
if (!ENGINE_set_default(tcn_ssl_engine, ENGINE_METHOD_ALL))
err = APR_ENOTIMPL;
}
if (err == APR_SUCCESS) {
// This code is based on libcurl:
// https://github.com/curl/curl/blob/curl-7_61_0/lib/vtls/openssl.c#L521
ui_method = UI_create_method((char *)"netty-tcnative user interface");
if (ui_method != NULL) {
if (UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL())) != 0) {
err = APR_EINVAL;
goto error;
}
if (UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL())) != 0) {
err = APR_EINVAL;
goto error;
}
if (UI_method_set_reader(ui_method, ssl_ui_reader) != 0) {
err = APR_EINVAL;
goto error;
}
if (UI_method_set_writer(ui_method, ssl_ui_writer) != 0) {
err = APR_EINVAL;
goto error;
}
} else {
err = APR_EINVAL;
goto error;
}
} else {
goto error;
}
}
}
#endif
// For tcn_SSL_get_app_data*() at request time
tcn_SSL_init_app_data_idx();
#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
init_bio_methods();
#endif
SSL_TMP_KEYS_INIT(r);
if (r) {
// TODO: Should we really do this as the user may want to inspect the error stack ?
ERR_clear_error();
err = APR_ENOTIMPL;
goto error;
}
/*
* Let us cleanup the ssl library when the library is unloaded
*/
apr_pool_cleanup_register(tcn_global_pool, NULL,
ssl_init_cleanup,
apr_pool_cleanup_null);
TCN_FREE_CSTRING(engine);
return (jint)APR_SUCCESS;
error:
TCN_FREE_CSTRING(engine);
ssl_init_cleanup(NULL);
tcn_ThrowAPRException(e, err);
return (jint)err;
}
TCN_IMPLEMENT_CALL(jlong, SSL, newMemBIO)(TCN_STDARGS)
{
BIO *bio = NULL;
UNREFERENCED(o);
// TODO: Use BIO_s_secmem() once included in stable release
if ((bio = BIO_new(BIO_s_mem())) == NULL) {
tcn_ThrowException(e, "Create BIO failed");
return 0;
}
return P2J(bio);
}
TCN_IMPLEMENT_CALL(jstring, SSL, getLastError)(TCN_STDARGS)
{
char buf[ERR_LEN];
UNREFERENCED(o);
ERR_error_string(ERR_get_error(), buf);
return tcn_new_string(e, buf);
}
/*** Begin Twitter 1:1 API addition ***/
TCN_IMPLEMENT_CALL(jint, SSL, getLastErrorNumber)(TCN_STDARGS) {
UNREFERENCED_STDARGS;
return ERR_get_error();
}
static void ssl_info_callback(const SSL *ssl, int where, int ret) {
int *handshakeCount = NULL;
if (0 != (where & SSL_CB_HANDSHAKE_START)) {
handshakeCount = (int*) tcn_SSL_get_app_data3((SSL*) ssl);
if (handshakeCount != NULL) {
++(*handshakeCount);
}
}
}
TCN_IMPLEMENT_CALL(jlong /* SSL * */, SSL, newSSL)(TCN_STDARGS,
jlong ctx /* tcn_ssl_ctxt_t * */,
jboolean server) {
SSL *ssl = NULL;
int *handshakeCount = NULL;
tcn_ssl_ctxt_t *c = J2P(ctx, tcn_ssl_ctxt_t *);
TCN_CHECK_NULL(c, ctx, 0);
UNREFERENCED_STDARGS;
ssl = SSL_new(c->ctx);
if (ssl == NULL) {
tcn_ThrowException(e, "cannot create new ssl");
return 0;
}
// Set the app_data2 before all the others because it may be used in SSL_free.
tcn_SSL_set_app_data2(ssl, c);
// Initially we will share the configuration from the SSLContext.
// Set this before other app_data because there is no chance of failure, and if other app_data initialization fails
// SSL_free maybe called and the state of this variable is assumed to be initalized.
tcn_SSL_set_app_data4(ssl, &c->verify_config);
// Store the handshakeCount in the SSL instance.
handshakeCount = (int*) OPENSSL_malloc(sizeof(int));
if (handshakeCount == NULL) {
SSL_free(ssl);
tcn_ThrowException(e, "cannot create handshakeCount user data");
return 0;
}
*handshakeCount = 0;
tcn_SSL_set_app_data3(ssl, handshakeCount);
// Add callback to keep track of handshakes.
SSL_CTX_set_info_callback(c->ctx, ssl_info_callback);
if (server) {
SSL_set_accept_state(ssl);
} else {
SSL_set_connect_state(ssl);
}
return P2J(ssl);
}
TCN_IMPLEMENT_CALL(jint, SSL, getError)(TCN_STDARGS,
jlong ssl /* SSL * */,
jint ret) {
SSL *ssl_ = J2P(ssl, SSL *);
TCN_CHECK_NULL(ssl_, ssl, 0);
UNREFERENCED_STDARGS;
return SSL_get_error(ssl_, ret);
}
// Write wlen bytes from wbuf into bio
TCN_IMPLEMENT_CALL(jint /* status */, SSL, bioWrite)(TCN_STDARGS,
jlong bioAddress /* BIO* */,
jlong wbufAddress /* char* */,
jint wlen /* sizeof(wbuf) */) {
BIO* bio = J2P(bioAddress, BIO*);
void* wbuf = J2P(wbufAddress, void*);
TCN_CHECK_NULL(bio, bioAddress, 0);
TCN_CHECK_NULL(wbuf, wbufAddress, 0);
UNREFERENCED_STDARGS;
return BIO_write(bio, wbuf, wlen);
}
TCN_IMPLEMENT_CALL(void, SSL, bioSetByteBuffer)(TCN_STDARGS,
jlong bioAddress /* BIO* */,
jlong bufferAddress /* Address for direct memory */,
jint maxUsableBytes /* max number of bytes to use */,
jboolean isSSLWriteSink) {
BIO* bio = J2P(bioAddress, BIO*);
char* buffer = J2P(bufferAddress, char*);
struct TCN_bio_bytebuffer* bioUserData = NULL;
TCN_CHECK_NULL(bio, bioAddress, /* void */);
TCN_CHECK_NULL(buffer, bufferAddress, /* void */);
bioUserData = (struct TCN_bio_bytebuffer*) BIO_get_data(bio);
TCN_ASSERT(bioUserData != NULL);
bioUserData->buffer = buffer;
bioUserData->bufferLength = maxUsableBytes;
bioUserData->bufferIsSSLWriteSink = (bool) isSSLWriteSink;
}
TCN_IMPLEMENT_CALL(void, SSL, bioClearByteBuffer)(TCN_STDARGS, jlong bioAddress) {
BIO* bio = J2P(bioAddress, BIO*);
struct TCN_bio_bytebuffer* bioUserData = NULL;
if (bio == NULL || (bioUserData = (struct TCN_bio_bytebuffer*) BIO_get_data(bio)) == NULL) {
return;
}
bioUserData->buffer = NULL;
bioUserData->bufferLength = 0;
bioUserData->bufferIsSSLWriteSink = false;
}
TCN_IMPLEMENT_CALL(jint, SSL, bioFlushByteBuffer)(TCN_STDARGS, jlong bioAddress) {
BIO* bio = J2P(bioAddress, BIO*);
struct TCN_bio_bytebuffer* bioUserData;