-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Copy pathpal_sslstream.c
1277 lines (1059 loc) · 44.9 KB
/
pal_sslstream.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "pal_sslstream.h"
#include "pal_ssl.h"
#include "pal_trust_manager.h"
// javax/net/ssl/SSLEngineResult$HandshakeStatus
enum
{
HANDSHAKE_STATUS__NOT_HANDSHAKING = 0,
HANDSHAKE_STATUS__FINISHED = 1,
HANDSHAKE_STATUS__NEED_TASK = 2,
HANDSHAKE_STATUS__NEED_WRAP = 3,
HANDSHAKE_STATUS__NEED_UNWRAP = 4,
};
// javax/net/ssl/SSLEngineResult$Status
// Android API 24+
enum
{
STATUS__BUFFER_UNDERFLOW = 0,
STATUS__BUFFER_OVERFLOW = 1,
STATUS__OK = 2,
STATUS__CLOSED = 3,
};
// javax/net/ssl/SSLEngineResult$Status
// Android API 21-23
enum
{
LEGACY__STATUS__BUFFER_OVERFLOW = 0,
LEGACY__STATUS__BUFFER_UNDERFLOW = 1,
LEGACY__STATUS__OK = 3,
LEGACY__STATUS__CLOSED = 2,
};
struct ApplicationProtocolData_t
{
uint8_t* data;
int32_t length;
};
ARGS_NON_NULL(1) static uint16_t* AllocateString(JNIEnv* env, jstring source);
ARGS_NON_NULL_ALL static PAL_SSLStreamStatus DoHandshake(JNIEnv* env, SSLStream* sslStream);
ARGS_NON_NULL_ALL static PAL_SSLStreamStatus DoWrap(JNIEnv* env, SSLStream* sslStream, int* handshakeStatus, int* bytesConsumed);
ARGS_NON_NULL_ALL static PAL_SSLStreamStatus DoUnwrap(JNIEnv* env, SSLStream* sslStream, int* handshakeStatus);
ARGS_NON_NULL_ALL static int GetHandshakeStatus(JNIEnv* env, SSLStream* sslStream)
{
// int handshakeStatus = sslEngine.getHandshakeStatus().ordinal();
int handshakeStatus = GetEnumAsInt(env, (*env)->CallObjectMethod(env, sslStream->sslEngine, g_SSLEngineGetHandshakeStatus));
if (CheckJNIExceptions(env))
return -1;
return handshakeStatus;
}
static bool IsHandshaking(int handshakeStatus)
{
return handshakeStatus != HANDSHAKE_STATUS__NOT_HANDSHAKING && handshakeStatus != HANDSHAKE_STATUS__FINISHED;
}
ARGS_NON_NULL(1, 2) static jobject GetSslSession(JNIEnv* env, SSLStream* sslStream, int handshakeStatus)
{
// During the initial handshake our sslStream->sslSession doesn't have access to the peer certificates
// which we need for hostname verification. There are different ways to access the handshake session
// in different Android API levels.
// SSLEngine.getHandshakeSession() is available since API 24.
// In older Android versions (API 21-23) we need to access the handshake session by accessing
// a private field instead.
if (g_SSLEngineGetHandshakeSession != NULL)
{
jobject sslSession = IsHandshaking(handshakeStatus)
? (*env)->CallObjectMethod(env, sslStream->sslEngine, g_SSLEngineGetHandshakeSession)
: (*env)->CallObjectMethod(env, sslStream->sslEngine, g_SSLEngineGetSession);
if (CheckJNIExceptions(env))
return NULL;
return sslSession;
}
else if (g_ConscryptOpenSSLEngineImplHandshakeSessionField != NULL)
{
jobject sslSession = IsHandshaking(handshakeStatus)
? (*env)->GetObjectField(env, sslStream->sslEngine, g_ConscryptOpenSSLEngineImplHandshakeSessionField)
: (*env)->CallObjectMethod(env, sslStream->sslEngine, g_SSLEngineGetSession);
if (CheckJNIExceptions(env))
return NULL;
return sslSession;
}
else
{
LOG_ERROR("Unable to get the current SSLSession from SSLEngine.");
assert(false && "Unable to get the current SSLSession from SSLEngine.");
return NULL;
}
}
ARGS_NON_NULL_ALL static jobject GetCurrentSslSession(JNIEnv* env, SSLStream* sslStream)
{
int handshakeStatus = GetHandshakeStatus(env, sslStream);
if (handshakeStatus == -1)
return NULL;
return GetSslSession(env, sslStream, handshakeStatus);
}
ARGS_NON_NULL_ALL static PAL_SSLStreamStatus Close(JNIEnv* env, SSLStream* sslStream)
{
// Call wrap to clear any remaining data before closing
int unused;
PAL_SSLStreamStatus ret = DoWrap(env, sslStream, &unused, &unused);
// sslEngine.closeOutbound();
(*env)->CallVoidMethod(env, sslStream->sslEngine, g_SSLEngineCloseOutbound);
if (ret != SSLStreamStatus_OK)
return ret;
// Flush any remaining data (e.g. sending close notification)
return DoWrap(env, sslStream, &unused, &unused);
}
ARGS_NON_NULL_ALL static PAL_SSLStreamStatus Flush(JNIEnv* env, SSLStream* sslStream)
{
/*
netOutBuffer.flip();
byte[] data = new byte[netOutBuffer.limit()];
netOutBuffer.get(data);
streamWriter(data, 0, data.length);
netOutBuffer.compact();
*/
PAL_SSLStreamStatus ret = SSLStreamStatus_Error;
IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->netOutBuffer, g_ByteBufferFlip));
int32_t bufferLimit = (*env)->CallIntMethod(env, sslStream->netOutBuffer, g_ByteBufferLimit);
jbyteArray data = make_java_byte_array(env, bufferLimit);
IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->netOutBuffer, g_ByteBufferGet, data));
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
uint8_t* dataPtr = (uint8_t*)xmalloc((size_t)bufferLimit);
(*env)->GetByteArrayRegion(env, data, 0, bufferLimit, (jbyte*)dataPtr);
sslStream->streamWriter(sslStream->managedContextHandle, dataPtr, bufferLimit);
free(dataPtr);
IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->netOutBuffer, g_ByteBufferCompact));
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
ret = SSLStreamStatus_OK;
cleanup:
(*env)->DeleteLocalRef(env, data);
return ret;
}
ARGS_NON_NULL_ALL static jobject ExpandBuffer(JNIEnv* env, jobject oldBuffer, int32_t newCapacity)
{
// oldBuffer.flip();
// ByteBuffer newBuffer = ByteBuffer.allocate(newCapacity);
// newBuffer.put(oldBuffer);
IGNORE_RETURN((*env)->CallObjectMethod(env, oldBuffer, g_ByteBufferFlip));
jobject newBuffer =
ToGRef(env, (*env)->CallStaticObjectMethod(env, g_ByteBuffer, g_ByteBufferAllocate, newCapacity));
IGNORE_RETURN((*env)->CallObjectMethod(env, newBuffer, g_ByteBufferPutBuffer, oldBuffer));
ReleaseGRef(env, oldBuffer);
return newBuffer;
}
ARGS_NON_NULL_ALL static jobject EnsureRemaining(JNIEnv* env, jobject oldBuffer, int32_t newRemaining)
{
IGNORE_RETURN((*env)->CallObjectMethod(env, oldBuffer, g_ByteBufferCompact));
int32_t oldPosition = (*env)->CallIntMethod(env, oldBuffer, g_ByteBufferPosition);
int32_t oldRemaining = (*env)->CallIntMethod(env, oldBuffer, g_ByteBufferRemaining);
if (oldRemaining < newRemaining)
{
// After compacting the oldBuffer, the oldPosition is equal to the number of bytes in the buffer at the moment
// we need to change the capacity to the oldPosition + newRemaining
return ExpandBuffer(env, oldBuffer, oldPosition + newRemaining);
}
else
{
return oldBuffer;
}
}
// There has been a change in the SSLEngineResult.Status enum between API 23 and 24 that changed
// the order/interger values of the enum options.
static int MapLegacySSLEngineResultStatus(int legacyStatus)
{
switch (legacyStatus)
{
case LEGACY__STATUS__BUFFER_OVERFLOW:
return STATUS__BUFFER_OVERFLOW;
case LEGACY__STATUS__BUFFER_UNDERFLOW:
return STATUS__BUFFER_UNDERFLOW;
case LEGACY__STATUS__CLOSED:
return STATUS__CLOSED;
case LEGACY__STATUS__OK:
return STATUS__OK;
default:
LOG_ERROR("Unknown legacy SSLEngineResult status: %d", legacyStatus);
assert(false && "Unknown SSLEngineResult status");
return -1;
}
}
ARGS_NON_NULL_ALL static PAL_SSLStreamStatus WrapAndProcessResult(JNIEnv* env, SSLStream* sslStream, int* handshakeStatus, int* bytesConsumed, bool* repeat)
{
// SSLEngineResult result = sslEngine.wrap(appOutBuffer, netOutBuffer);
jobject result = (*env)->CallObjectMethod(
env, sslStream->sslEngine, g_SSLEngineWrap, sslStream->appOutBuffer, sslStream->netOutBuffer);
if (CheckJNIExceptions(env))
return SSLStreamStatus_Error;
// handshakeStatus = result.getHandshakeStatus();
// bytesConsumed = result.bytesConsumed();
// SSLEngineResult.Status status = result.getStatus();
*handshakeStatus = GetEnumAsInt(env, (*env)->CallObjectMethod(env, result, g_SSLEngineResultGetHandshakeStatus));
*bytesConsumed = (*env)->CallIntMethod(env, result, g_SSLEngineResultBytesConsumed);
int status = GetEnumAsInt(env, (*env)->CallObjectMethod(env, result, g_SSLEngineResultGetStatus));
(*env)->DeleteLocalRef(env, result);
if (g_SSLEngineResultStatusLegacyOrder)
{
status = MapLegacySSLEngineResultStatus(status);
}
switch (status)
{
case STATUS__OK:
{
return Flush(env, sslStream);
}
case STATUS__CLOSED:
{
(void)Flush(env, sslStream);
(*env)->CallVoidMethod(env, sslStream->sslEngine, g_SSLEngineCloseOutbound);
return SSLStreamStatus_Closed;
}
case STATUS__BUFFER_OVERFLOW:
{
// Expand buffer and repeat the wrap
int32_t packetBufferSize = (*env)->CallIntMethod(env, sslStream->sslSession, g_SSLSessionGetPacketBufferSize);
sslStream->netOutBuffer = ExpandBuffer(env, sslStream->netOutBuffer, packetBufferSize);
*repeat = true;
return SSLStreamStatus_OK;
}
default:
{
LOG_ERROR("Unknown SSLEngineResult status: %d", status);
return SSLStreamStatus_Error;
}
}
}
ARGS_NON_NULL_ALL static PAL_SSLStreamStatus DoWrap(JNIEnv* env, SSLStream* sslStream, int* handshakeStatus, int* bytesConsumed)
{
// appOutBuffer.flip();
IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->appOutBuffer, g_ByteBufferFlip));
bool repeat = false;
PAL_SSLStreamStatus status = WrapAndProcessResult(env, sslStream, handshakeStatus, bytesConsumed, &repeat);
if (repeat)
{
repeat = false;
status = WrapAndProcessResult(env, sslStream, handshakeStatus, bytesConsumed, &repeat);
if (repeat)
{
LOG_ERROR("Unexpected repeat in DoWrap");
return SSLStreamStatus_Error;
}
}
// appOutBuffer.compact();
IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->appOutBuffer, g_ByteBufferCompact));
return status;
}
ARGS_NON_NULL_ALL static PAL_SSLStreamStatus DoUnwrap(JNIEnv* env, SSLStream* sslStream, int* handshakeStatus)
{
// if (netInBuffer.position() == 0)
// {
// int netInBufferLimit = netInBuffer.limit();
// ByteBuffer tmp = ByteBuffer.allocateDirect(netInBufferLimit);
// int count = streamReader(tmp, 0, netInBufferLimit);
// netInBuffer.put(tmp);
// }
if ((*env)->CallIntMethod(env, sslStream->netInBuffer, g_ByteBufferPosition) == 0)
{
int netInBufferLimit = (*env)->CallIntMethod(env, sslStream->netInBuffer, g_ByteBufferLimit);
uint8_t* tmpNative = (uint8_t*)xmalloc((size_t)netInBufferLimit);
int count = netInBufferLimit;
// todo assert streamReader != 0 ?
PAL_SSLStreamStatus status = sslStream->streamReader(sslStream->managedContextHandle, tmpNative, &count);
if (status != SSLStreamStatus_OK)
{
free(tmpNative);
return status;
}
jobject tmp = (*env)->NewDirectByteBuffer(env, tmpNative, count);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
IGNORE_RETURN(
(*env)->CallObjectMethod(env, sslStream->netInBuffer, g_ByteBufferPutBuffer, tmp));
cleanup:
free(tmpNative);
(*env)->DeleteLocalRef(env, tmp);
}
// netInBuffer.flip();
// SSLEngineResult result = sslEngine.unwrap(netInBuffer, appInBuffer);
IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->netInBuffer, g_ByteBufferFlip));
jobject result = (*env)->CallObjectMethod(
env, sslStream->sslEngine, g_SSLEngineUnwrap, sslStream->netInBuffer, sslStream->appInBuffer);
if (CheckJNIExceptions(env))
return SSLStreamStatus_Error;
// netInBuffer.compact();
IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->netInBuffer, g_ByteBufferCompact));
// handshakeStatus = result.getHandshakeStatus();
// SSLEngineResult.Status status = result.getStatus();
*handshakeStatus = GetEnumAsInt(env, (*env)->CallObjectMethod(env, result, g_SSLEngineResultGetHandshakeStatus));
int status = GetEnumAsInt(env, (*env)->CallObjectMethod(env, result, g_SSLEngineResultGetStatus));
(*env)->DeleteLocalRef(env, result);
if (g_SSLEngineResultStatusLegacyOrder)
{
status = MapLegacySSLEngineResultStatus(status);
}
switch (status)
{
case STATUS__OK:
{
return SSLStreamStatus_OK;
}
case STATUS__CLOSED:
{
return Close(env, sslStream);
}
case STATUS__BUFFER_UNDERFLOW:
{
// Expand buffer
// int newRemaining = sslSession.getPacketBufferSize();
int32_t newRemaining = (*env)->CallIntMethod(env, sslStream->sslSession, g_SSLSessionGetPacketBufferSize);
sslStream->netInBuffer = EnsureRemaining(env, sslStream->netInBuffer, newRemaining);
return SSLStreamStatus_OK;
}
case STATUS__BUFFER_OVERFLOW:
{
// Expand buffer
// int newCapacity = sslSession.getApplicationBufferSize() + appInBuffer.remaining();
int32_t newCapacity =
(*env)->CallIntMethod(env, sslStream->sslSession, g_SSLSessionGetApplicationBufferSize) +
(*env)->CallIntMethod(env, sslStream->appInBuffer, g_ByteBufferRemaining);
sslStream->appInBuffer = ExpandBuffer(env, sslStream->appInBuffer, newCapacity);
return SSLStreamStatus_OK;
}
default:
{
LOG_ERROR("Unknown SSLEngineResult status: %d", status);
return SSLStreamStatus_Error;
}
}
}
ARGS_NON_NULL_ALL static PAL_SSLStreamStatus DoHandshake(JNIEnv* env, SSLStream* sslStream)
{
PAL_SSLStreamStatus status = SSLStreamStatus_OK;
int handshakeStatus = GetHandshakeStatus(env, sslStream);
assert(handshakeStatus >= 0);
int bytesConsumed;
while (IsHandshaking(handshakeStatus) && status == SSLStreamStatus_OK)
{
switch (handshakeStatus)
{
case HANDSHAKE_STATUS__NEED_WRAP:
status = DoWrap(env, sslStream, &handshakeStatus, &bytesConsumed);
break;
case HANDSHAKE_STATUS__NEED_UNWRAP:
status = DoUnwrap(env, sslStream, &handshakeStatus);
break;
case HANDSHAKE_STATUS__NOT_HANDSHAKING:
case HANDSHAKE_STATUS__FINISHED:
status = SSLStreamStatus_OK;
break;
case HANDSHAKE_STATUS__NEED_TASK:
assert(0 && "unexpected NEED_TASK handshake status");
}
}
return status;
}
ARGS_NON_NULL_ALL static void FreeSSLStream(JNIEnv* env, SSLStream* sslStream)
{
ReleaseGRef(env, sslStream->sslContext);
ReleaseGRef(env, sslStream->sslEngine);
ReleaseGRef(env, sslStream->sslSession);
ReleaseGRef(env, sslStream->appOutBuffer);
ReleaseGRef(env, sslStream->netOutBuffer);
ReleaseGRef(env, sslStream->netInBuffer);
ReleaseGRef(env, sslStream->appInBuffer);
free(sslStream);
}
ARGS_NON_NULL_ALL static jobject GetSSLContextInstance(JNIEnv* env)
{
jobject sslContext = NULL;
// sslContext = SSLContext.getInstance("TLSv1.3");
jstring tls13 = make_java_string(env, "TLSv1.3");
sslContext = (*env)->CallStaticObjectMethod(env, g_SSLContext, g_SSLContextGetInstanceMethod, tls13);
if (TryClearJNIExceptions(env))
{
// TLSv1.3 is only supported on API level 29+ - fall back to TLSv1.2 (which is supported on API level 16+)
// sslContext = SSLContext.getInstance("TLSv1.2");
jstring tls12 = make_java_string(env, "TLSv1.2");
sslContext = (*env)->CallStaticObjectMethod(env, g_SSLContext, g_SSLContextGetInstanceMethod, tls12);
ReleaseLRef(env, tls12);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
}
cleanup:
ReleaseLRef(env, tls13);
return sslContext;
}
ARGS_NON_NULL_ALL static jobject GetKeyStoreInstance(JNIEnv* env)
{
jobject keyStore = NULL;
jstring ksType = NULL;
// String ksType = KeyStore.getDefaultType();
// KeyStore keyStore = KeyStore.getInstance(ksType);
// keyStore.load(null, null);
// return keyStore;
ksType = (*env)->CallStaticObjectMethod(env, g_KeyStoreClass, g_KeyStoreGetDefaultType);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
keyStore = (*env)->CallStaticObjectMethod(env, g_KeyStoreClass, g_KeyStoreGetInstance, ksType);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
(*env)->CallVoidMethod(env, keyStore, g_KeyStoreLoad, NULL, NULL);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
cleanup:
ReleaseLRef(env, ksType);
return keyStore;
}
SSLStream* AndroidCryptoNative_SSLStreamCreate(intptr_t sslStreamProxyHandle)
{
abort_unless(sslStreamProxyHandle != 0, "invalid pointer to the .NET SslStream proxy");
SSLStream* sslStream = NULL;
JNIEnv* env = GetJNIEnv();
INIT_LOCALS(loc, sslContext, trustManagers);
loc[sslContext] = GetSSLContextInstance(env);
if (!loc[sslContext])
goto cleanup;
loc[trustManagers] = GetTrustManagers(env, sslStreamProxyHandle);
if (!loc[trustManagers])
goto cleanup;
// sslContext.init(null, trustManagers, null);
(*env)->CallVoidMethod(env, loc[sslContext], g_SSLContextInitMethod, NULL, loc[trustManagers], NULL);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
sslStream = xcalloc(1, sizeof(SSLStream));
sslStream->sslContext = ToGRef(env, loc[sslContext]);
loc[sslContext] = NULL;
cleanup:
RELEASE_LOCALS(loc, env);
return sslStream;
}
ARGS_NON_NULL_ALL
static int32_t AddCertChainToStore(JNIEnv* env,
jobject store,
uint8_t* pkcs8PrivateKey,
int32_t pkcs8PrivateKeyLen,
PAL_KeyAlgorithm algorithm,
jobject* /*X509Certificate[]*/ certs,
int32_t certsLen)
{
abort_if_invalid_pointer_argument (pkcs8PrivateKey);
abort_if_invalid_pointer_argument (certs);
int32_t ret = FAIL;
INIT_LOCALS(loc, keyBytes, keySpec, algorithmName, keyFactory, privateKey, certArray, alias);
// byte[] keyBytes = new byte[] { <pkcs8PrivateKey> };
// PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
loc[keyBytes] = make_java_byte_array(env, pkcs8PrivateKeyLen);
(*env)->SetByteArrayRegion(env, loc[keyBytes], 0, pkcs8PrivateKeyLen, (jbyte*)pkcs8PrivateKey);
loc[keySpec] = (*env)->NewObject(env, g_PKCS8EncodedKeySpec, g_PKCS8EncodedKeySpecCtor, loc[keyBytes]);
switch (algorithm)
{
case PAL_DSA:
loc[algorithmName] = make_java_string(env, "DSA");
break;
case PAL_EC:
loc[algorithmName] = make_java_string(env, "EC");
break;
case PAL_RSA:
loc[algorithmName] = make_java_string(env, "RSA");
break;
default:
LOG_ERROR("Unknown key algorithm: %d", algorithm);
goto cleanup;
}
// KeyFactory keyFactory = KeyFactory.getInstance(algorithmName);
// PrivateKey privateKey = keyFactory.generatePrivate(spec);
loc[keyFactory] =
(*env)->CallStaticObjectMethod(env, g_KeyFactoryClass, g_KeyFactoryGetInstanceMethod, loc[algorithmName]);
loc[privateKey] = (*env)->CallObjectMethod(env, loc[keyFactory], g_KeyFactoryGenPrivateMethod, loc[keySpec]);
// X509Certificate[] certArray = new X509Certificate[certsLen];
loc[certArray] = make_java_object_array(env, certsLen, g_X509CertClass, NULL);
for (int32_t i = 0; i < certsLen; ++i)
{
(*env)->SetObjectArrayElement(env, loc[certArray], i, certs[i]);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
}
// store.setKeyEntry("SSLCertificateContext", privateKey, null, certArray);
loc[alias] = make_java_string(env, "SSLCertificateContext");
(*env)->CallVoidMethod(env, store, g_KeyStoreSetKeyEntry, loc[alias], loc[privateKey], NULL, loc[certArray]);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
ret = SUCCESS;
cleanup:
RELEASE_LOCALS(loc, env);
return ret;
}
SSLStream* AndroidCryptoNative_SSLStreamCreateWithCertificates(intptr_t sslStreamProxyHandle,
uint8_t* pkcs8PrivateKey,
int32_t pkcs8PrivateKeyLen,
PAL_KeyAlgorithm algorithm,
jobject* /*X509Certificate[]*/ certs,
int32_t certsLen)
{
abort_unless(sslStreamProxyHandle != 0, "invalid pointer to the .NET SslStream proxy");
SSLStream* sslStream = NULL;
JNIEnv* env = GetJNIEnv();
INIT_LOCALS(loc, sslContext, keyStore, kmfType, kmf, keyManagers, trustManagers);
loc[sslContext] = GetSSLContextInstance(env);
if (!loc[sslContext])
goto cleanup;
loc[keyStore] = GetKeyStoreInstance(env);
if (!loc[keyStore])
goto cleanup;
int32_t status =
AddCertChainToStore(env, loc[keyStore], pkcs8PrivateKey, pkcs8PrivateKeyLen, algorithm, certs, certsLen);
if (status != SUCCESS)
goto cleanup;
// String kmfType = "PKIX";
// KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfType);
loc[kmfType] = make_java_string(env, "PKIX");
loc[kmf] = (*env)->CallStaticObjectMethod(env, g_KeyManagerFactory, g_KeyManagerFactoryGetInstance, loc[kmfType]);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
// kmf.init(keyStore, null);
(*env)->CallVoidMethod(env, loc[kmf], g_KeyManagerFactoryInit, loc[keyStore], NULL);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
// KeyManager[] keyManagers = kmf.getKeyManagers();
loc[keyManagers] = (*env)->CallObjectMethod(env, loc[kmf], g_KeyManagerFactoryGetKeyManagers);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
// TrustManager[] trustManagers = GetTrustManagers(sslStreamProxyHandle);
loc[trustManagers] = GetTrustManagers(env, sslStreamProxyHandle);
if (!loc[trustManagers])
goto cleanup;
// sslContext.init(keyManagers, trustManagers, null);
(*env)->CallVoidMethod(env, loc[sslContext], g_SSLContextInitMethod, loc[keyManagers], loc[trustManagers], NULL);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
sslStream = xcalloc(1, sizeof(SSLStream));
sslStream->sslContext = ToGRef(env, loc[sslContext]);
loc[sslContext] = NULL;
cleanup:
RELEASE_LOCALS(loc, env);
return sslStream;
}
SSLStream* AndroidCryptoNative_SSLStreamCreateWithKeyStorePrivateKeyEntry(intptr_t sslStreamProxyHandle, jobject privateKeyEntry)
{
abort_unless(sslStreamProxyHandle != 0, "invalid pointer to the .NET SslStream proxy");
SSLStream* sslStream = NULL;
JNIEnv* env = GetJNIEnv();
INIT_LOCALS(loc, sslContext, dotnetX509KeyManager, keyManagers, trustManagers);
loc[sslContext] = GetSSLContextInstance(env);
if (!loc[sslContext])
goto cleanup;
loc[dotnetX509KeyManager] = (*env)->NewObject(env, g_DotnetX509KeyManager, g_DotnetX509KeyManagerCtor, privateKeyEntry);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
loc[keyManagers] = make_java_object_array(env, 1, g_KeyManager, loc[dotnetX509KeyManager]);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
// TrustManager[] trustManagers = GetTrustManagers(sslStreamProxyHandle);
loc[trustManagers] = GetTrustManagers(env, sslStreamProxyHandle);
if (!loc[trustManagers])
goto cleanup;
// sslContext.init(keyManagers, trustManagers, null);
(*env)->CallVoidMethod(env, loc[sslContext], g_SSLContextInitMethod, loc[keyManagers], loc[trustManagers], NULL);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
sslStream = xcalloc(1, sizeof(SSLStream));
sslStream->sslContext = ToGRef(env, loc[sslContext]);
loc[sslContext] = NULL;
cleanup:
RELEASE_LOCALS(loc, env);
return sslStream;
}
int32_t AndroidCryptoNative_SSLStreamInitialize(
SSLStream* sslStream, bool isServer, ManagedContextHandle managedContextHandle, STREAM_READER streamReader, STREAM_WRITER streamWriter, int32_t appBufferSize, char* peerHost)
{
abort_if_invalid_pointer_argument (sslStream);
abort_unless(sslStream->sslContext != NULL, "sslContext is NULL in SSL stream");
abort_unless(sslStream->sslEngine == NULL, "sslEngine is NOT NULL in SSL stream");
abort_unless(sslStream->sslSession == NULL, "sslSession is NOT NULL in SSL stream");
int32_t ret = FAIL;
JNIEnv* env = GetJNIEnv();
jobject sslEngine = NULL;
if (peerHost)
{
// SSLEngine sslEngine = sslContext.createSSLEngine(peerHost, -1);
jstring peerHostStr = make_java_string(env, peerHost);
sslEngine = (*env)->CallObjectMethod(env, sslStream->sslContext, g_SSLContextCreateSSLEngineMethodWithHostAndPort, peerHostStr, -1);
ReleaseLRef(env, peerHostStr);
ON_EXCEPTION_PRINT_AND_GOTO(exit);
}
else
{
// SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine = (*env)->CallObjectMethod(env, sslStream->sslContext, g_SSLContextCreateSSLEngineMethod);
ON_EXCEPTION_PRINT_AND_GOTO(exit);
}
// sslEngine.setUseClientMode(!isServer);
sslStream->sslEngine = ToGRef(env, sslEngine);
(*env)->CallVoidMethod(env, sslStream->sslEngine, g_SSLEngineSetUseClientMode, !isServer);
ON_EXCEPTION_PRINT_AND_GOTO(exit);
// SSLSession sslSession = sslEngine.getSession();
sslStream->sslSession = ToGRef(env, (*env)->CallObjectMethod(env, sslStream->sslEngine, g_SSLEngineGetSession));
// int applicationBufferSize = sslSession.getApplicationBufferSize();
// int packetBufferSize = sslSession.getPacketBufferSize();
int32_t applicationBufferSize = (*env)->CallIntMethod(env, sslStream->sslSession, g_SSLSessionGetApplicationBufferSize);
int32_t packetBufferSize = (*env)->CallIntMethod(env, sslStream->sslSession, g_SSLSessionGetPacketBufferSize);
// ByteBuffer appInBuffer = ByteBuffer.allocate(Math.max(applicationBufferSize, appBufferSize));
// ByteBuffer appOutBuffer = ByteBuffer.allocate(appBufferSize);
// ByteBuffer netOutBuffer = ByteBuffer.allocate(packetBufferSize);
// ByteBuffer netInBuffer = ByteBuffer.allocate(packetBufferSize);
int32_t appInBufferSize = applicationBufferSize > appBufferSize ? applicationBufferSize : appBufferSize;
sslStream->appInBuffer =
ToGRef(env, (*env)->CallStaticObjectMethod(env, g_ByteBuffer, g_ByteBufferAllocate, appInBufferSize));
sslStream->appOutBuffer =
ToGRef(env, (*env)->CallStaticObjectMethod(env, g_ByteBuffer, g_ByteBufferAllocate, appBufferSize));
sslStream->netOutBuffer =
ToGRef(env, (*env)->CallStaticObjectMethod(env, g_ByteBuffer, g_ByteBufferAllocate, packetBufferSize));
sslStream->netInBuffer =
ToGRef(env, (*env)->CallStaticObjectMethod(env, g_ByteBuffer, g_ByteBufferAllocate, packetBufferSize));
sslStream->managedContextHandle = managedContextHandle;
sslStream->streamReader = streamReader;
sslStream->streamWriter = streamWriter;
ret = SUCCESS;
exit:
return ret;
}
// This method calls internal Android APIs that are specific to Android API 21-23 and it won't work
// on newer API levels. By calling the sslEngine.sslParameters.useSni(true) method, the SSLEngine
// will include the peerHost that was passed in to the SSLEngine factory method in the client hello
// message.
ARGS_NON_NULL_ALL static int32_t ApplyLegacyAndroidSNIWorkaround(JNIEnv* env, SSLStream* sslStream)
{
if (g_ConscryptOpenSSLEngineImplClass == NULL || !(*env)->IsInstanceOf(env, sslStream->sslEngine, g_ConscryptOpenSSLEngineImplClass))
return FAIL;
int32_t ret = FAIL;
INIT_LOCALS(loc, sslParameters);
loc[sslParameters] = (*env)->GetObjectField(env, sslStream->sslEngine, g_ConscryptOpenSSLEngineImplSslParametersField);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
if (!loc[sslParameters])
goto cleanup;
(*env)->CallVoidMethod(env, loc[sslParameters], g_ConscryptSSLParametersImplSetUseSni, true);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
ret = SUCCESS;
cleanup:
RELEASE_LOCALS(loc, env);
return ret;
}
int32_t AndroidCryptoNative_SSLStreamSetTargetHost(SSLStream* sslStream, char* targetHost)
{
abort_if_invalid_pointer_argument (sslStream);
abort_if_invalid_pointer_argument (targetHost);
JNIEnv* env = GetJNIEnv();
if (g_SNIHostName == NULL || g_SSLParametersSetServerNames == NULL)
{
// SNIHostName is only available since API 24
// on APIs 21-23 we use a workaround to force the SSLEngine to use SNI
return ApplyLegacyAndroidSNIWorkaround(env, sslStream);
}
int32_t ret = FAIL;
INIT_LOCALS(loc, hostStr, nameList, hostName, params);
// ArrayList<SNIServerName> nameList = new ArrayList<SNIServerName>();
// SNIHostName hostName = new SNIHostName(targetHost);
// nameList.add(hostName);
loc[hostStr] = make_java_string(env, targetHost);
loc[nameList] = (*env)->NewObject(env, g_ArrayListClass, g_ArrayListCtor);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
loc[hostName] = (*env)->NewObject(env, g_SNIHostName, g_SNIHostNameCtor, loc[hostStr]);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
(*env)->CallBooleanMethod(env, loc[nameList], g_ArrayListAdd, loc[hostName]);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
// SSLParameters params = sslEngine.getSSLParameters();
// params.setServerNames(nameList);
// sslEngine.setSSLParameters(params);
loc[params] = (*env)->CallObjectMethod(env, sslStream->sslEngine, g_SSLEngineGetSSLParameters);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
(*env)->CallVoidMethod(env, loc[params], g_SSLParametersSetServerNames, loc[nameList]);
(*env)->CallVoidMethod(env, sslStream->sslEngine, g_SSLEngineSetSSLParameters, loc[params]);
ret = SUCCESS;
cleanup:
RELEASE_LOCALS(loc, env);
return ret;
}
PAL_SSLStreamStatus AndroidCryptoNative_SSLStreamHandshake(SSLStream* sslStream)
{
abort_if_invalid_pointer_argument (sslStream);
JNIEnv* env = GetJNIEnv();
int handshakeStatus = GetHandshakeStatus(env, sslStream);
if (handshakeStatus == -1)
return SSLStreamStatus_Error;
if (!IsHandshaking(handshakeStatus))
{
// sslEngine.beginHandshake();
(*env)->CallVoidMethod(env, sslStream->sslEngine, g_SSLEngineBeginHandshake);
if (CheckJNIExceptions(env))
return SSLStreamStatus_Error;
}
return DoHandshake(env, sslStream);
}
PAL_SSLStreamStatus
AndroidCryptoNative_SSLStreamRead(SSLStream* sslStream, uint8_t* buffer, int32_t length, int32_t* read)
{
abort_if_invalid_pointer_argument (sslStream);
abort_if_invalid_pointer_argument (read);
jbyteArray data = NULL;
JNIEnv* env = GetJNIEnv();
PAL_SSLStreamStatus ret = SSLStreamStatus_Error;
*read = 0;
/*
appInBuffer.flip();
if (appInBuffer.remaining() == 0) {
appInBuffer.compact();
DoUnwrap();
appInBuffer.flip();
}
if (appInBuffer.remaining() > 0) {
byte[] data = new byte[appInBuffer.remaining()];
appInBuffer.get(data);
appInBuffer.compact();
return SSLStreamStatus_OK;
} else {
return SSLStreamStatus_NeedData;
}
*/
IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->appInBuffer, g_ByteBufferFlip));
int32_t rem = (*env)->CallIntMethod(env, sslStream->appInBuffer, g_ByteBufferRemaining);
if (rem == 0)
{
IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->appInBuffer, g_ByteBufferCompact));
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
int handshakeStatus;
PAL_SSLStreamStatus unwrapStatus = DoUnwrap(env, sslStream, &handshakeStatus);
if (unwrapStatus != SSLStreamStatus_OK)
{
ret = unwrapStatus;
goto cleanup;
}
IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->appInBuffer, g_ByteBufferFlip));
if (IsHandshaking(handshakeStatus))
{
ret = SSLStreamStatus_Renegotiate;
goto cleanup;
}
rem = (*env)->CallIntMethod(env, sslStream->appInBuffer, g_ByteBufferRemaining);
}
if (rem > 0)
{
int32_t bytes_to_read = rem < length ? rem : length;
data = make_java_byte_array(env, bytes_to_read);
IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->appInBuffer, g_ByteBufferGet, data));
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->appInBuffer, g_ByteBufferCompact));
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
(*env)->GetByteArrayRegion(env, data, 0, bytes_to_read, (jbyte*)buffer);
*read = bytes_to_read;
ret = SSLStreamStatus_OK;
}
else
{
ret = SSLStreamStatus_NeedData;
}
cleanup:
ReleaseLRef(env, data);
return ret;
}
PAL_SSLStreamStatus AndroidCryptoNative_SSLStreamWrite(SSLStream* sslStream, uint8_t* buffer, int32_t length)
{
abort_if_invalid_pointer_argument (sslStream);
JNIEnv* env = GetJNIEnv();
PAL_SSLStreamStatus ret = SSLStreamStatus_Error;
// ByteBuffer bufferByteBuffer = ...;
jobject bufferByteBuffer = (*env)->NewDirectByteBuffer(env, buffer, length);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
// appOutBuffer.compact();
// appOutBuffer = EnsureRemaining(appOutBuffer, length);
// appOutBuffer.put(bufferByteBuffer);
IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->appOutBuffer, g_ByteBufferCompact));
sslStream->appOutBuffer = EnsureRemaining(env, sslStream->appOutBuffer, length);
IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->appOutBuffer, g_ByteBufferPutBuffer, bufferByteBuffer));
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
int32_t written = 0;
while (written < length)
{
int handshakeStatus;
int bytesConsumed;
ret = DoWrap(env, sslStream, &handshakeStatus, &bytesConsumed);
if (ret != SSLStreamStatus_OK)
{
goto cleanup;
}
else if (IsHandshaking(handshakeStatus))
{
ret = SSLStreamStatus_Renegotiate;
goto cleanup;
}
written += bytesConsumed;
}
cleanup:
(*env)->DeleteLocalRef(env, bufferByteBuffer);
return ret;
}
void AndroidCryptoNative_SSLStreamRelease(SSLStream* sslStream)
{
if (sslStream == NULL)
return;
JNIEnv* env = GetJNIEnv();
FreeSSLStream(env, sslStream);
}
int32_t AndroidCryptoNative_SSLStreamGetApplicationProtocol(SSLStream* sslStream, uint8_t* out, int32_t* outLen)
{
if (g_SSLEngineGetApplicationProtocol == NULL)
{
// SSLEngine.getApplicationProtocol() is only supported from API level 29 and above
return FAIL;
}
abort_if_invalid_pointer_argument (sslStream);
abort_if_invalid_pointer_argument (outLen);
JNIEnv* env = GetJNIEnv();
int32_t ret = FAIL;
// String protocol = sslEngine.getApplicationProtocol();
jstring protocol = (*env)->CallObjectMethod(env, sslStream->sslEngine, g_SSLEngineGetApplicationProtocol);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
if (protocol == NULL)
goto cleanup;
jsize len = (*env)->GetStringUTFLength(env, protocol);
bool insufficientBuffer = *outLen < len;
*outLen = len;
if (insufficientBuffer)
return INSUFFICIENT_BUFFER;
(*env)->GetStringUTFRegion(env, protocol, 0, len, (char*)out);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
ret = SUCCESS;
cleanup:
(*env)->DeleteLocalRef(env, protocol);
return ret;
}
int32_t AndroidCryptoNative_SSLStreamGetCipherSuite(SSLStream* sslStream, uint16_t** out)
{
abort_if_invalid_pointer_argument (sslStream);
abort_if_invalid_pointer_argument (out);
JNIEnv* env = GetJNIEnv();
int32_t ret = FAIL;
*out = NULL;
INIT_LOCALS(loc, sslSession, cipherSuite);
loc[sslSession] = GetCurrentSslSession(env, sslStream);
if (loc[sslSession] == NULL)
goto cleanup;
// String cipherSuite = sslSession.getCipherSuite();
loc[cipherSuite] = (*env)->CallObjectMethod(env, loc[sslSession], g_SSLSessionGetCipherSuite);
ON_EXCEPTION_PRINT_AND_GOTO(cleanup);
*out = AllocateString(env, loc[cipherSuite]);
ret = SUCCESS;
cleanup:
RELEASE_LOCALS(loc, env);
return ret;
}
int32_t AndroidCryptoNative_SSLStreamGetProtocol(SSLStream* sslStream, uint16_t** out)
{
abort_if_invalid_pointer_argument (sslStream);
abort_if_invalid_pointer_argument (out);