/
native_crypto.cc
11394 lines (9950 loc) · 447 KB
/
native_crypto.cc
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 (C) 2007-2008 The Android Open Source Project
*
* Licensed 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 <conscrypt/NetFd.h>
#include <conscrypt/app_data.h>
#include <conscrypt/bio_input_stream.h>
#include <conscrypt/bio_output_stream.h>
#include <conscrypt/bio_stream.h>
#include <conscrypt/compat.h>
#include <conscrypt/compatibility_close_monitor.h>
#include <conscrypt/jniutil.h>
#include <conscrypt/logging.h>
#include <conscrypt/macros.h>
#include <conscrypt/native_crypto.h>
#include <conscrypt/netutil.h>
#include <conscrypt/scoped_ssl_bio.h>
#include <conscrypt/ssl_error.h>
#include <limits.h>
#include <nativehelper/scoped_primitive_array.h>
#include <nativehelper/scoped_utf_chars.h>
#include <openssl/aead.h>
#include <openssl/asn1.h>
#include <openssl/bn.h>
#include <openssl/chacha.h>
#include <openssl/cmac.h>
#include <openssl/crypto.h>
#include <openssl/curve25519.h>
#include <openssl/engine.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/hpke.h>
#include <openssl/pkcs7.h>
#include <openssl/pkcs8.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#include <limits>
#include <optional>
#include <type_traits>
#include <vector>
using conscrypt::AppData;
using conscrypt::BioInputStream;
using conscrypt::BioOutputStream;
using conscrypt::BioStream;
using conscrypt::CompatibilityCloseMonitor;
using conscrypt::NativeCrypto;
using conscrypt::SslError;
/**
* Helper function that grabs the casts an ssl pointer and then checks for nullness.
* If this function returns nullptr and <code>throwIfNull</code> is
* passed as <code>true</code>, then this function will call
* <code>throwSSLExceptionStr</code> before returning, so in this case of
* nullptr, a caller of this function should simply return and allow JNI
* to do its thing.
*
* @param env the JNI environment
* @param ssl_address; the ssl_address pointer as an integer
* @param throwIfNull whether to throw if the SSL pointer is nullptr
* @returns the pointer, which may be nullptr
*/
static SSL_CTX* to_SSL_CTX(JNIEnv* env, jlong ssl_ctx_address, bool throwIfNull) {
SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address));
if ((ssl_ctx == nullptr) && throwIfNull) {
JNI_TRACE("ssl_ctx == null");
conscrypt::jniutil::throwNullPointerException(env, "ssl_ctx == null");
}
return ssl_ctx;
}
static SSL* to_SSL(JNIEnv* env, jlong ssl_address, bool throwIfNull) {
SSL* ssl = reinterpret_cast<SSL*>(static_cast<uintptr_t>(ssl_address));
if ((ssl == nullptr) && throwIfNull) {
JNI_TRACE("ssl == null");
conscrypt::jniutil::throwNullPointerException(env, "ssl == null");
}
return ssl;
}
static BIO* to_BIO(JNIEnv* env, jlong bio_address) {
BIO* bio = reinterpret_cast<BIO*>(static_cast<uintptr_t>(bio_address));
if (bio == nullptr) {
JNI_TRACE("bio == null");
conscrypt::jniutil::throwNullPointerException(env, "bio == null");
}
return bio;
}
static SSL_SESSION* to_SSL_SESSION(JNIEnv* env, jlong ssl_session_address, bool throwIfNull) {
SSL_SESSION* ssl_session =
reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address));
if ((ssl_session == nullptr) && throwIfNull) {
JNI_TRACE("ssl_session == null");
conscrypt::jniutil::throwNullPointerException(env, "ssl_session == null");
}
return ssl_session;
}
static SSL_CIPHER* to_SSL_CIPHER(JNIEnv* env, jlong ssl_cipher_address, bool throwIfNull) {
SSL_CIPHER* ssl_cipher =
reinterpret_cast<SSL_CIPHER*>(static_cast<uintptr_t>(ssl_cipher_address));
if ((ssl_cipher == nullptr) && throwIfNull) {
JNI_TRACE("ssl_cipher == null");
conscrypt::jniutil::throwNullPointerException(env, "ssl_cipher == null");
}
return ssl_cipher;
}
template <typename T>
static T* fromContextObject(JNIEnv* env, jobject contextObject) {
if (contextObject == nullptr) {
JNI_TRACE("contextObject == null");
conscrypt::jniutil::throwNullPointerException(env, "contextObject == null");
return nullptr;
}
T* ref = reinterpret_cast<T*>(
env->GetLongField(contextObject, conscrypt::jniutil::nativeRef_address));
if (ref == nullptr) {
JNI_TRACE("ref == null");
conscrypt::jniutil::throwNullPointerException(env, "ref == null");
return nullptr;
}
return ref;
}
/**
* Converts a Java byte[] two's complement to an OpenSSL BIGNUM. This will
* allocate the BIGNUM if *dest == nullptr. Returns true on success. If the
* return value is false, there is a pending exception.
*/
static bool arrayToBignum(JNIEnv* env, jbyteArray source, BIGNUM** dest) {
JNI_TRACE("arrayToBignum(%p, %p)", source, dest);
if (dest == nullptr) {
JNI_TRACE("arrayToBignum(%p, %p) => dest is null!", source, dest);
conscrypt::jniutil::throwNullPointerException(env, "dest == null");
return false;
}
JNI_TRACE("arrayToBignum(%p, %p) *dest == %p", source, dest, *dest);
ScopedByteArrayRO sourceBytes(env, source);
if (sourceBytes.get() == nullptr) {
JNI_TRACE("arrayToBignum(%p, %p) => null", source, dest);
return false;
}
const unsigned char* tmp = reinterpret_cast<const unsigned char*>(sourceBytes.get());
size_t tmpSize = sourceBytes.size();
/* if the array is empty, it is zero. */
if (tmpSize == 0) {
if (*dest == nullptr) {
*dest = BN_new();
}
BN_zero(*dest);
return true;
}
std::unique_ptr<unsigned char[]> twosComplement;
bool negative = (tmp[0] & 0x80) != 0;
if (negative) {
// Need to convert to two's complement.
twosComplement.reset(new unsigned char[tmpSize]);
unsigned char* twosBytes = reinterpret_cast<unsigned char*>(twosComplement.get());
memcpy(twosBytes, tmp, tmpSize);
tmp = twosBytes;
bool carry = true;
for (ssize_t i = static_cast<ssize_t>(tmpSize - 1); i >= 0; i--) {
twosBytes[i] ^= 0xFF;
if (carry) {
carry = (++twosBytes[i]) == 0;
}
}
}
BIGNUM* ret = BN_bin2bn(tmp, tmpSize, *dest);
if (ret == nullptr) {
conscrypt::jniutil::throwRuntimeException(env, "Conversion to BIGNUM failed");
ERR_clear_error();
JNI_TRACE("arrayToBignum(%p, %p) => threw exception", source, dest);
return false;
}
BN_set_negative(ret, negative ? 1 : 0);
*dest = ret;
JNI_TRACE("arrayToBignum(%p, %p) => *dest = %p", source, dest, ret);
return true;
}
static bssl::UniquePtr<BIGNUM> arrayToBignum(JNIEnv* env, jbyteArray source) {
BIGNUM *bn = nullptr;
if (!arrayToBignum(env, source, &bn)) {
return nullptr;
}
return bssl::UniquePtr<BIGNUM>(bn);
}
/**
* Converts an OpenSSL BIGNUM to a Java byte[] array in two's complement.
*/
static jbyteArray bignumToArray(JNIEnv* env, const BIGNUM* source, const char* sourceName) {
JNI_TRACE("bignumToArray(%p, %s)", source, sourceName);
if (source == nullptr) {
conscrypt::jniutil::throwNullPointerException(env, sourceName);
return nullptr;
}
size_t numBytes = BN_num_bytes(source) + 1;
jbyteArray javaBytes = env->NewByteArray(static_cast<jsize>(numBytes));
ScopedByteArrayRW bytes(env, javaBytes);
if (bytes.get() == nullptr) {
JNI_TRACE("bignumToArray(%p, %s) => null", source, sourceName);
return nullptr;
}
unsigned char* tmp = reinterpret_cast<unsigned char*>(bytes.get());
if (BN_num_bytes(source) > 0 && BN_bn2bin(source, tmp + 1) <= 0) {
conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "bignumToArray");
return nullptr;
}
// Set the sign and convert to two's complement if necessary for the Java code.
if (BN_is_negative(source)) {
bool carry = true;
for (ssize_t i = static_cast<ssize_t>(numBytes - 1); i >= 0; i--) {
tmp[i] ^= 0xFF;
if (carry) {
carry = (++tmp[i]) == 0;
}
}
*tmp |= 0x80;
} else {
*tmp = 0x00;
}
JNI_TRACE("bignumToArray(%p, %s) => %p", source, sourceName, javaBytes);
return javaBytes;
}
/**
* Converts various OpenSSL ASN.1 types to a jbyteArray with DER-encoded data
* inside. The "i2d_func" function pointer is a function of the "i2d_<TYPE>"
* from the OpenSSL ASN.1 API. Note i2d_func may take a const parameter, so we
* use a separate type parameter.
*
* TODO(https://crbug.com/boringssl/407): When all BoringSSL i2d functions are
* const, switch back to a single template parameter.
*/
template <typename T, typename U>
jbyteArray ASN1ToByteArray(JNIEnv* env, T* obj, int (*i2d_func)(U*, unsigned char**)) {
// T and U should be the same type, but may differ in const.
static_assert(std::is_same<typename std::remove_const<T>::type,
typename std::remove_const<U>::type>::value,
"obj and i2d_func have incompatible types");
if (obj == nullptr) {
conscrypt::jniutil::throwNullPointerException(env, "ASN1 input == null");
JNI_TRACE("ASN1ToByteArray(%p) => null input", obj);
return nullptr;
}
int derLen = i2d_func(obj, nullptr);
if (derLen < 0) {
conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "ASN1ToByteArray");
JNI_TRACE("ASN1ToByteArray(%p) => measurement failed", obj);
return nullptr;
}
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(derLen));
if (byteArray.get() == nullptr) {
JNI_TRACE("ASN1ToByteArray(%p) => creating byte array failed", obj);
return nullptr;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == nullptr) {
JNI_TRACE("ASN1ToByteArray(%p) => using byte array failed", obj);
return nullptr;
}
unsigned char* p = reinterpret_cast<unsigned char*>(bytes.get());
int ret = i2d_func(obj, &p);
if (ret < 0) {
conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "ASN1ToByteArray");
JNI_TRACE("ASN1ToByteArray(%p) => final conversion failed", obj);
return nullptr;
}
JNI_TRACE("ASN1ToByteArray(%p) => success (%d bytes written)", obj, ret);
return byteArray.release();
}
/**
* Finishes a pending CBB and returns a jbyteArray with the contents.
*/
jbyteArray CBBToByteArray(JNIEnv* env, CBB* cbb) {
uint8_t* data;
size_t len;
if (!CBB_finish(cbb, &data, &len)) {
conscrypt::jniutil::throwRuntimeException(env, "CBB_finish failed");
ERR_clear_error();
JNI_TRACE("creating byte array failed");
return nullptr;
}
bssl::UniquePtr<uint8_t> free_data(data);
ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(static_cast<jsize>(len)));
if (byteArray.get() == nullptr) {
JNI_TRACE("creating byte array failed");
return nullptr;
}
ScopedByteArrayRW bytes(env, byteArray.get());
if (bytes.get() == nullptr) {
JNI_TRACE("using byte array failed");
return nullptr;
}
memcpy(bytes.get(), data, len);
return byteArray.release();
}
jbyteArray CryptoBufferToByteArray(JNIEnv* env, const CRYPTO_BUFFER* buf) {
if (CRYPTO_BUFFER_len(buf) > INT_MAX) {
JNI_TRACE("buffer too large");
conscrypt::jniutil::throwRuntimeException(env, "buffer too large");
return nullptr;
}
int length = static_cast<int>(CRYPTO_BUFFER_len(buf));
jbyteArray ret = env->NewByteArray(length);
if (ret == nullptr) {
JNI_TRACE("allocating byte array failed");
return nullptr;
}
env->SetByteArrayRegion(ret, 0, length,
reinterpret_cast<const int8_t*>(CRYPTO_BUFFER_data(buf)));
return ret;
}
bssl::UniquePtr<CRYPTO_BUFFER> ByteArrayToCryptoBuffer(JNIEnv* env, const jbyteArray array,
CONSCRYPT_UNUSED CRYPTO_BUFFER_POOL* pool) {
if (array == nullptr) {
JNI_TRACE("array was null");
conscrypt::jniutil::throwNullPointerException(env, "array == null");
return nullptr;
}
ScopedByteArrayRO arrayRo(env, array);
if (arrayRo.get() == nullptr) {
JNI_TRACE("failed to get bytes");
return nullptr;
}
bssl::UniquePtr<CRYPTO_BUFFER> ret(CRYPTO_BUFFER_new(
reinterpret_cast<const uint8_t*>(arrayRo.get()), arrayRo.size(), nullptr));
if (!ret) {
JNI_TRACE("failed to allocate CRYPTO_BUFFER");
conscrypt::jniutil::throwOutOfMemory(env, "failed to allocate CRYPTO_BUFFER");
return nullptr;
}
return ret;
}
static jobjectArray CryptoBuffersToObjectArray(JNIEnv* env,
const STACK_OF(CRYPTO_BUFFER)* buffers) {
size_t numBuffers = sk_CRYPTO_BUFFER_num(buffers);
if (numBuffers > INT_MAX) {
JNI_TRACE("too many buffers");
conscrypt::jniutil::throwRuntimeException(env, "too many buffers");
return nullptr;
}
ScopedLocalRef<jobjectArray> array(
env, env->NewObjectArray(static_cast<int>(numBuffers),
conscrypt::jniutil::byteArrayClass, nullptr));
if (array.get() == nullptr) {
JNI_TRACE("failed to allocate array");
return nullptr;
}
for (size_t i = 0; i < numBuffers; ++i) {
CRYPTO_BUFFER* buffer = sk_CRYPTO_BUFFER_value(buffers, i);
ScopedLocalRef<jbyteArray> bArray(env, CryptoBufferToByteArray(env, buffer));
if (bArray.get() == nullptr) {
return nullptr;
}
env->SetObjectArrayElement(array.get(), i, bArray.get());
}
return array.release();
}
/**
* Converts ASN.1 BIT STRING to a jbooleanArray.
*/
jbooleanArray ASN1BitStringToBooleanArray(JNIEnv* env, const ASN1_BIT_STRING* bitStr) {
int size = ASN1_STRING_length(bitStr) * 8;
if (bitStr->flags & ASN1_STRING_FLAG_BITS_LEFT) {
size -= bitStr->flags & 0x07;
}
ScopedLocalRef<jbooleanArray> bitsRef(env, env->NewBooleanArray(size));
if (bitsRef.get() == nullptr) {
return nullptr;
}
ScopedBooleanArrayRW bitsArray(env, bitsRef.get());
for (size_t i = 0; i < bitsArray.size(); i++) {
bitsArray[i] = static_cast<jboolean>(ASN1_BIT_STRING_get_bit(bitStr, static_cast<int>(i)));
}
return bitsRef.release();
}
static int bio_stream_destroy(BIO* b) {
if (b == nullptr) {
return 0;
}
delete static_cast<BioStream*>(BIO_get_data(b));
BIO_set_data(b, nullptr);
BIO_set_init(b, 0);
return 1;
}
static int bio_stream_read(BIO* b, char* buf, int len) {
BIO_clear_retry_flags(b);
BioInputStream* stream = static_cast<BioInputStream*>(BIO_get_data(b));
int ret = stream->read(buf, len);
if (ret == 0) {
if (stream->isFinite()) {
return 0;
}
// If the BioInputStream is not finite then EOF doesn't mean that
// there's nothing more coming.
BIO_set_retry_read(b);
return -1;
}
return ret;
}
static int bio_stream_write(BIO* b, const char* buf, int len) {
BIO_clear_retry_flags(b);
BioOutputStream* stream = static_cast<BioOutputStream*>(BIO_get_data(b));
return stream->write(buf, len);
}
static int bio_stream_gets(BIO* b, char* buf, int len) {
BioInputStream* stream = static_cast<BioInputStream*>(BIO_get_data(b));
return stream->gets(buf, len);
}
static void bio_stream_assign(BIO* b, BioStream* stream) {
BIO_set_data(b, stream);
BIO_set_init(b, 1);
}
// NOLINTNEXTLINE(runtime/int)
static long bio_stream_ctrl(BIO* b, int cmd, long, void*) {
BioStream* stream = static_cast<BioStream*>(BIO_get_data(b));
switch (cmd) {
case BIO_CTRL_EOF:
return stream->isEof() ? 1 : 0;
case BIO_CTRL_FLUSH:
return stream->flush();
default:
return 0;
}
}
static const BIO_METHOD *stream_bio_method() {
static const BIO_METHOD* stream_method = []() -> const BIO_METHOD* {
BIO_METHOD* method = BIO_meth_new(0, nullptr);
if (!method || !BIO_meth_set_write(method, bio_stream_write) ||
!BIO_meth_set_read(method, bio_stream_read) ||
!BIO_meth_set_gets(method, bio_stream_gets) ||
!BIO_meth_set_ctrl(method, bio_stream_ctrl) ||
!BIO_meth_set_destroy(method, bio_stream_destroy)) {
BIO_meth_free(method);
return nullptr;
}
return method;
}();
return stream_method;
}
static jbyteArray ecSignDigestWithPrivateKey(JNIEnv* env, jobject privateKey, const char* message,
size_t message_len) {
JNI_TRACE("ecSignDigestWithPrivateKey(%p)", privateKey);
if (message_len > std::numeric_limits<jsize>::max()) {
JNI_TRACE("ecSignDigestWithPrivateKey(%p) => argument too large", privateKey);
return nullptr;
}
ScopedLocalRef<jbyteArray> messageArray(env,
env->NewByteArray(static_cast<jsize>(message_len)));
if (env->ExceptionCheck()) {
JNI_TRACE("ecSignDigestWithPrivateKey(%p) => threw exception", privateKey);
return nullptr;
}
{
ScopedByteArrayRW messageBytes(env, messageArray.get());
if (messageBytes.get() == nullptr) {
JNI_TRACE("ecSignDigestWithPrivateKey(%p) => using byte array failed", privateKey);
return nullptr;
}
memcpy(messageBytes.get(), message, message_len);
}
return reinterpret_cast<jbyteArray>(env->CallStaticObjectMethod(
conscrypt::jniutil::cryptoUpcallsClass,
conscrypt::jniutil::cryptoUpcallsClass_rawSignMethod,
privateKey, messageArray.get()));
}
static jbyteArray rsaSignDigestWithPrivateKey(JNIEnv* env, jobject privateKey, jint padding,
const char* message, size_t message_len) {
if (message_len > std::numeric_limits<jsize>::max()) {
JNI_TRACE("rsaSignDigestWithPrivateKey(%p) => argument too large", privateKey);
return nullptr;
}
ScopedLocalRef<jbyteArray> messageArray(env,
env->NewByteArray(static_cast<jsize>(message_len)));
if (env->ExceptionCheck()) {
JNI_TRACE("rsaSignDigestWithPrivateKey(%p) => threw exception", privateKey);
return nullptr;
}
{
ScopedByteArrayRW messageBytes(env, messageArray.get());
if (messageBytes.get() == nullptr) {
JNI_TRACE("rsaSignDigestWithPrivateKey(%p) => using byte array failed", privateKey);
return nullptr;
}
memcpy(messageBytes.get(), message, message_len);
}
return reinterpret_cast<jbyteArray>(
env->CallStaticObjectMethod(
conscrypt::jniutil::cryptoUpcallsClass,
conscrypt::jniutil::cryptoUpcallsClass_rsaSignMethod,
privateKey, padding, messageArray.get()));
}
// rsaDecryptWithPrivateKey uses privateKey to decrypt |ciphertext_len| bytes
// from |ciphertext|. The ciphertext is expected to be padded using the scheme
// given in |padding|, which must be one of |RSA_*_PADDING| constants from
// OpenSSL.
static jbyteArray rsaDecryptWithPrivateKey(JNIEnv* env, jobject privateKey, jint padding,
const char* ciphertext, size_t ciphertext_len) {
if (ciphertext_len > std::numeric_limits<jsize>::max()) {
JNI_TRACE("rsaDecryptWithPrivateKey(%p) => argument too large", privateKey);
return nullptr;
}
ScopedLocalRef<jbyteArray> ciphertextArray(
env, env->NewByteArray(static_cast<jsize>(ciphertext_len)));
if (env->ExceptionCheck()) {
JNI_TRACE("rsaDecryptWithPrivateKey(%p) => threw exception", privateKey);
return nullptr;
}
{
ScopedByteArrayRW ciphertextBytes(env, ciphertextArray.get());
if (ciphertextBytes.get() == nullptr) {
JNI_TRACE("rsaDecryptWithPrivateKey(%p) => using byte array failed", privateKey);
return nullptr;
}
memcpy(ciphertextBytes.get(), ciphertext, ciphertext_len);
}
return reinterpret_cast<jbyteArray>(
env->CallStaticObjectMethod(
conscrypt::jniutil::cryptoUpcallsClass,
conscrypt::jniutil::cryptoUpcallsClass_rsaDecryptMethod,
privateKey, padding, ciphertextArray.get()));
}
// *********************************************
// From keystore_openssl.cpp in Chromium source.
// *********************************************
namespace {
ENGINE* g_engine;
int g_rsa_exdata_index;
int g_ecdsa_exdata_index;
RSA_METHOD g_rsa_method;
ECDSA_METHOD g_ecdsa_method;
std::once_flag g_engine_once;
void init_engine_globals();
void ensure_engine_globals() {
std::call_once(g_engine_once, init_engine_globals);
}
// KeyExData contains the data that is contained in the EX_DATA of the RSA
// and ECDSA objects that are created to wrap Android system keys.
struct KeyExData {
// private_key contains a reference to a Java, private-key object.
jobject private_key;
};
// ExDataDup is called when one of the RSA or EC_KEY objects is duplicated. We
// don't support this and it should never happen.
int ExDataDup(CRYPTO_EX_DATA* /* to */,
const CRYPTO_EX_DATA* /* from */,
void** /* from_d */,
int /* index */,
long /* argl */ /* NOLINT(runtime/int) */,
void* /* argp */) {
return 0;
}
// ExDataFree is called when one of the RSA or EC_KEY objects is freed.
void ExDataFree(void* /* parent */,
void* ptr,
CRYPTO_EX_DATA* /* ad */,
int /* index */,
long /* argl */ /* NOLINT(runtime/int) */,
void* /* argp */) {
// Ensure the global JNI reference created with this wrapper is
// properly destroyed with it.
KeyExData* ex_data = reinterpret_cast<KeyExData*>(ptr);
if (ex_data != nullptr) {
JNIEnv* env = conscrypt::jniutil::getJNIEnv();
env->DeleteGlobalRef(ex_data->private_key);
delete ex_data;
}
}
KeyExData* RsaGetExData(const RSA* rsa) {
return reinterpret_cast<KeyExData*>(RSA_get_ex_data(rsa, g_rsa_exdata_index));
}
int RsaMethodSignRaw(RSA* rsa, size_t* out_len, uint8_t* out, size_t max_out, const uint8_t* in,
size_t in_len, int padding) {
if (padding != RSA_PKCS1_PADDING && padding != RSA_NO_PADDING) {
OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
return 0;
}
// Retrieve private key JNI reference.
const KeyExData* ex_data = RsaGetExData(rsa);
if (!ex_data || !ex_data->private_key) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
JNIEnv* env = conscrypt::jniutil::getJNIEnv();
if (env == nullptr) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
// For RSA keys, this function behaves as RSA_private_encrypt with
// the specified padding.
ScopedLocalRef<jbyteArray> signature(
env, rsaSignDigestWithPrivateKey(env, ex_data->private_key, padding,
reinterpret_cast<const char*>(in), in_len));
if (signature.get() == nullptr) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
ScopedByteArrayRO result(env, signature.get());
size_t expected_size = static_cast<size_t>(RSA_size(rsa));
if (result.size() > expected_size) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
if (max_out < expected_size) {
OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE);
return 0;
}
// Copy result to OpenSSL-provided buffer. rsaSignDigestWithPrivateKey
// should pad with leading 0s, but if it doesn't, pad the result.
size_t zero_pad = expected_size - result.size();
memset(out, 0, zero_pad);
memcpy(out + zero_pad, &result[0], result.size());
*out_len = expected_size;
return 1;
}
int RsaMethodDecrypt(RSA* rsa, size_t* out_len, uint8_t* out, size_t max_out, const uint8_t* in,
size_t in_len, int padding) {
// Retrieve private key JNI reference.
const KeyExData* ex_data = RsaGetExData(rsa);
if (!ex_data || !ex_data->private_key) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
JNIEnv* env = conscrypt::jniutil::getJNIEnv();
if (env == nullptr) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
// This function behaves as RSA_private_decrypt.
ScopedLocalRef<jbyteArray> cleartext(
env, rsaDecryptWithPrivateKey(env, ex_data->private_key, padding,
reinterpret_cast<const char*>(in), in_len));
if (cleartext.get() == nullptr) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
return 0;
}
ScopedByteArrayRO cleartextBytes(env, cleartext.get());
if (max_out < cleartextBytes.size()) {
OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE);
return 0;
}
// Copy result to OpenSSL-provided buffer.
memcpy(out, cleartextBytes.get(), cleartextBytes.size());
*out_len = cleartextBytes.size();
return 1;
}
// Custom ECDSA_METHOD that uses the platform APIs.
// Note that for now, only signing through ECDSA_sign() is really supported.
// all other method pointers are either stubs returning errors, or no-ops.
jobject EcKeyGetKey(const EC_KEY* ec_key) {
KeyExData* ex_data =
reinterpret_cast<KeyExData*>(EC_KEY_get_ex_data(ec_key, g_ecdsa_exdata_index));
return ex_data->private_key;
}
int EcdsaMethodSign(const uint8_t* digest, size_t digest_len, uint8_t* sig, unsigned int* sig_len,
EC_KEY* ec_key) {
// Retrieve private key JNI reference.
jobject private_key = EcKeyGetKey(ec_key);
if (!private_key) {
CONSCRYPT_LOG_ERROR("Null JNI reference passed to EcdsaMethodSign!");
return 0;
}
JNIEnv* env = conscrypt::jniutil::getJNIEnv();
if (env == nullptr) {
return 0;
}
// Sign message with it through JNI.
ScopedLocalRef<jbyteArray> signature(
env, ecSignDigestWithPrivateKey(env, private_key,
reinterpret_cast<const char*>(digest), digest_len));
if (signature.get() == nullptr) {
CONSCRYPT_LOG_ERROR("Could not sign message in EcdsaMethodDoSign!");
return 0;
}
ScopedByteArrayRO signatureBytes(env, signature.get());
// Note: With ECDSA, the actual signature may be smaller than
// ECDSA_size().
size_t max_expected_size = ECDSA_size(ec_key);
if (signatureBytes.size() > max_expected_size) {
CONSCRYPT_LOG_ERROR("ECDSA Signature size mismatch, actual: %zd, expected <= %zd",
signatureBytes.size(), max_expected_size);
return 0;
}
memcpy(sig, signatureBytes.get(), signatureBytes.size());
*sig_len = static_cast<unsigned int>(signatureBytes.size());
return 1;
}
void init_engine_globals() {
g_rsa_exdata_index = RSA_get_ex_new_index(0 /* argl */, nullptr /* argp */,
nullptr /* new_func */, ExDataDup, ExDataFree);
g_ecdsa_exdata_index = EC_KEY_get_ex_new_index(0 /* argl */, nullptr /* argp */,
nullptr /* new_func */, ExDataDup, ExDataFree);
g_rsa_method.common.is_static = 1;
g_rsa_method.sign_raw = RsaMethodSignRaw;
g_rsa_method.decrypt = RsaMethodDecrypt;
g_rsa_method.flags = RSA_FLAG_OPAQUE;
g_ecdsa_method.common.is_static = 1;
g_ecdsa_method.sign = EcdsaMethodSign;
g_ecdsa_method.flags = ECDSA_FLAG_OPAQUE;
g_engine = ENGINE_new();
ENGINE_set_RSA_method(g_engine, &g_rsa_method, sizeof(g_rsa_method));
ENGINE_set_ECDSA_method(g_engine, &g_ecdsa_method, sizeof(g_ecdsa_method));
}
} // anonymous namespace
#define THROW_SSLEXCEPTION (-2)
#define THROW_SOCKETTIMEOUTEXCEPTION (-3)
#define THROWN_EXCEPTION (-4)
/**
* Initialization phase for every OpenSSL job: Loads the Error strings, the
* crypto algorithms and reset the OpenSSL library
*/
static void NativeCrypto_clinit(JNIEnv*, jclass) {
CRYPTO_library_init();
}
/**
* private static native int EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q);
*/
static jlong NativeCrypto_EVP_PKEY_new_RSA(JNIEnv* env, jclass, jbyteArray n, jbyteArray e,
jbyteArray d, jbyteArray p, jbyteArray q,
jbyteArray dmp1, jbyteArray dmq1, jbyteArray iqmp) {
CHECK_ERROR_QUEUE_ON_RETURN;
JNI_TRACE("EVP_PKEY_new_RSA(n=%p, e=%p, d=%p, p=%p, q=%p, dmp1=%p, dmq1=%p, iqmp=%p)", n, e, d,
p, q, dmp1, dmq1, iqmp);
if (e == nullptr && d == nullptr) {
conscrypt::jniutil::throwException(env, "java/lang/IllegalArgumentException",
"e == null && d == null");
JNI_TRACE("NativeCrypto_EVP_PKEY_new_RSA => e == null && d == null");
return 0;
}
#if BORINGSSL_API_VERSION >= 20
bssl::UniquePtr<BIGNUM> nBN, eBN, dBN, pBN, qBN, dmp1BN, dmq1BN, iqmpBN;
nBN = arrayToBignum(env, n);
if (!nBN) {
return 0;
}
if (e != nullptr) {
eBN = arrayToBignum(env, e);
if (!eBN) {
return 0;
}
}
if (d != nullptr) {
dBN = arrayToBignum(env, d);
if (!dBN) {
return 0;
}
}
if (p != nullptr) {
pBN = arrayToBignum(env, p);
if (!pBN) {
return 0;
}
}
if (q != nullptr) {
qBN = arrayToBignum(env, q);
if (!qBN) {
return 0;
}
}
if (dmp1 != nullptr) {
dmp1BN = arrayToBignum(env, dmp1);
if (!dmp1BN) {
return 0;
}
}
if (dmq1 != nullptr) {
dmq1BN = arrayToBignum(env, dmq1);
if (!dmq1BN) {
return 0;
}
}
if (iqmp != nullptr) {
iqmpBN = arrayToBignum(env, iqmp);
if (!iqmpBN) {
return 0;
}
}
// Determine what kind of key this is.
//
// TODO(davidben): The caller already knows what kind of key they expect. Ideally we would have
// separate APIs for the caller. However, we currently tolerate, say, an RSAPrivateCrtKeySpec
// where most fields are null and silently make a public key out of it. This is probably a
// mistake, but would need to be a breaking change.
bssl::UniquePtr<RSA> rsa;
if (!dBN) {
rsa.reset(RSA_new_public_key(nBN.get(), eBN.get()));
} else if (!eBN) {
rsa.reset(RSA_new_private_key_no_e(nBN.get(), dBN.get()));
} else if (!pBN || !qBN || !dmp1BN || !dmq1BN || !iqmpBN) {
rsa.reset(RSA_new_private_key_no_crt(nBN.get(), eBN.get(), dBN.get()));
} else {
rsa.reset(RSA_new_private_key(nBN.get(), eBN.get(), dBN.get(), pBN.get(), qBN.get(),
dmp1BN.get(), dmq1BN.get(), iqmpBN.get()));
}
if (rsa == nullptr) {
conscrypt::jniutil::throwRuntimeException(env, "Creating RSA key failed");
return 0;
}
#else
bssl::UniquePtr<RSA> rsa(RSA_new());
if (rsa.get() == nullptr) {
conscrypt::jniutil::throwRuntimeException(env, "RSA_new failed");
return 0;
}
if (!arrayToBignum(env, n, &rsa->n)) {
return 0;
}
if (e != nullptr && !arrayToBignum(env, e, &rsa->e)) {
return 0;
}
if (d != nullptr && !arrayToBignum(env, d, &rsa->d)) {
return 0;
}
if (p != nullptr && !arrayToBignum(env, p, &rsa->p)) {
return 0;
}
if (q != nullptr && !arrayToBignum(env, q, &rsa->q)) {
return 0;
}
if (dmp1 != nullptr && !arrayToBignum(env, dmp1, &rsa->dmp1)) {
return 0;
}
if (dmq1 != nullptr && !arrayToBignum(env, dmq1, &rsa->dmq1)) {
return 0;
}
if (iqmp != nullptr && !arrayToBignum(env, iqmp, &rsa->iqmp)) {
return 0;
}
if (conscrypt::trace::kWithJniTrace) {
if (p != nullptr && q != nullptr) {
int check = RSA_check_key(rsa.get());
JNI_TRACE("EVP_PKEY_new_RSA(...) RSA_check_key returns %d", check);
}
}
if (rsa->n == nullptr || (rsa->e == nullptr && rsa->d == nullptr)) {
conscrypt::jniutil::throwRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
return 0;
}
/*
* If the private exponent is available, there is the potential to do signing
* operations. However, we can only do blinding if the public exponent is also
* available. Disable blinding if the public exponent isn't available.
*
* TODO[kroot]: We should try to recover the public exponent by trying
* some common ones such 3, 17, or 65537.
*/
if (rsa->d != nullptr && rsa->e == nullptr) {
JNI_TRACE("EVP_PKEY_new_RSA(...) disabling RSA blinding => %p", rsa.get());
rsa->flags |= RSA_FLAG_NO_BLINDING;
}
#endif
bssl::UniquePtr<EVP_PKEY> pkey(EVP_PKEY_new());
if (pkey.get() == nullptr) {
conscrypt::jniutil::throwRuntimeException(env, "EVP_PKEY_new failed");
return 0;
}
if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) != 1) {
conscrypt::jniutil::throwRuntimeException(env, "EVP_PKEY_new failed");
ERR_clear_error();
return 0;
}
OWNERSHIP_TRANSFERRED(rsa);
JNI_TRACE("EVP_PKEY_new_RSA(n=%p, e=%p, d=%p, p=%p, q=%p dmp1=%p, dmq1=%p, iqmp=%p) => %p", n,
e, d, p, q, dmp1, dmq1, iqmp, pkey.get());
return reinterpret_cast<uintptr_t>(pkey.release());
}