-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathJCA.qll
More file actions
2301 lines (1850 loc) · 82.1 KB
/
JCA.qll
File metadata and controls
2301 lines (1850 loc) · 82.1 KB
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
overlay[local?]
module;
import java
import semmle.code.java.dataflow.DataFlow
import semmle.code.java.dataflow.TaintTracking
import semmle.code.java.controlflow.Dominance
module JCAModel {
import Language
import codeql.quantum.experimental.Standardization::Types::KeyOpAlg as KeyOpAlg
abstract class CipherAlgorithmValueConsumer extends Crypto::AlgorithmValueConsumer { }
abstract class EllipticCurveAlgorithmValueConsumer extends Crypto::AlgorithmValueConsumer { }
abstract class HashAlgorithmValueConsumer extends Crypto::AlgorithmValueConsumer { }
abstract class KeyAgreementAlgorithmValueConsumer extends Crypto::AlgorithmValueConsumer { }
abstract class SignatureAlgorithmValueConsumer extends Crypto::AlgorithmValueConsumer { }
abstract class MacAlgorithmValueConsumer extends Crypto::AlgorithmValueConsumer { }
// TODO: Verify that the PBEWith% case works correctly
bindingset[algo]
predicate cipher_names(string algo) {
algo.toUpperCase()
.matches([
"AES", "AESWrap", "AESWrapPad", "ARCFOUR", "ARIA", "Blowfish", "Camellia", "ChaCha20",
"ChaCha20-Poly1305", "DES", "DESede", "DESedeWrap", "ECIES", "PBEWith%", "RC2", "RC4",
"RC5", "RSA", "Salsa20", "SEED", "Skipjack", "Idea", "Twofish"
].toUpperCase())
}
// TODO: Verify that the OAEPWith% case works correctly
bindingset[padding]
predicate cipher_padding(string padding) {
padding
.toUpperCase()
.matches([
"NoPadding", "ISO10126Padding", "OAEPPadding", "OAEPWith%", "PKCS1Padding",
"PKCS5Padding", "SSL3Padding"
].toUpperCase())
}
bindingset[hash]
predicate hash_names(string hash) { exists(hash_name_to_type_known(hash, _)) }
bindingset[kdf]
predicate kdf_names(string kdf) {
kdf.toUpperCase().matches(["PBKDF2With%", "PBEWith%"].toUpperCase())
}
bindingset[name]
predicate elliptic_curve_names(string name) {
// Note: as a one-off exception, we use the internal Crypto module implementation of `isEllipticCurveAlgorithmName`
Crypto::isEllipticCurveAlgorithmName(name)
}
/*
* TODO:
*
* MAC Algorithms possible (JCA Default + BouncyCastle Extensions)
*
* Name Type Description
* ---------------------------------------------------------------------------
* "HmacMD5" HMAC HMAC with MD5 (not recommended)
* "HmacSHA1" HMAC HMAC with SHA-1 (not recommended)
* "HmacSHA224" HMAC HMAC with SHA-224
* "HmacSHA256" HMAC HMAC with SHA-256
* "HmacSHA384" HMAC HMAC with SHA-384
* "HmacSHA512" HMAC HMAC with SHA-512
*
* (BouncyCastle and Other Provider Extensions)
* "AESCMAC" CMAC Cipher-based MAC using AES
* "DESCMAC" CMAC CMAC with DES (legacy)
* "GMAC" GCM-based MAC Authenticates AAD only (GCM-style)
* "Poly1305" AEAD-style MAC Used with ChaCha20
* "SipHash" Hash-based MAC Fast MAC for short inputs
* "BLAKE2BMAC" HMAC-style BLAKE2b MAC (cryptographic hash)
* "HmacRIPEMD160" HMAC HMAC with RIPEMD160 hash
*/
bindingset[name]
predicate mac_names(string name) {
name.toUpperCase()
.matches([
"HMAC%", "AESCMAC", "DESCMAC", "GMAC", "Poly1305", "SipHash", "BLAKE2BMAC",
"HMACRIPEMD160", "%CMAC"
].toUpperCase())
}
/**
* Names that match known signature algorithms.
* https://docs.oracle.com/en/java/javase/25/docs/specs/security/standard-names.html
*/
bindingset[name]
predicate signature_names(string name) {
name.toUpperCase().splitAt("WITH", 1).matches(["RSA%", "ECDSA%", "DSA%"])
or
name.toUpperCase()
.matches(["RSASSA-PSS", "ED25519", "ED448", "EDDSA", "ML-DSA%", "HSS/LMS", "DSA"])
}
bindingset[name]
predicate key_agreement_names(string name) {
name.toUpperCase()
.matches(["DH", "EDH", "ECDH", "ECMQV", "X25519", "X448", "ML-KEM%", "XDH"].toUpperCase())
}
bindingset[name]
Crypto::TKeyDerivationType kdf_name_to_kdf_type(string name, string withSubstring) {
name.matches("PBKDF2With%") and
result instanceof Crypto::PBKDF2 and
withSubstring = name.regexpCapture("PBKDF2With(.*)", 1)
or
name.matches("PBEWith%") and
result instanceof Crypto::PBES and
withSubstring = name.regexpCapture("PBEWith(.*)", 1)
// TODO: add additional
}
bindingset[nameRaw]
Crypto::HashType hash_name_to_type_known(string nameRaw, int digestLength) {
exists(string name | name = nameRaw.toUpperCase() |
name in ["SHA-1", "SHA1"] and result instanceof Crypto::SHA1 and digestLength = 160
or
name in ["SHA-256", "SHA-224", "SHA-384", "SHA-512", "SHA224", "SHA256", "SHA384", "SHA512"] and
result instanceof Crypto::SHA2 and
digestLength = name.replaceAll("-", "").splitAt("SHA", 1).toInt()
or
name in ["SHA-512/224", "SHA-512/256", "SHA512/224", "SHA512/256"] and
result instanceof Crypto::SHA2 and
digestLength = name.replaceAll("-", "").splitAt("SHA-512/", 1).toInt()
or
name in ["SHA3-224", "SHA3-256", "SHA3-384", "SHA3-512", "SHA3256", "SHA3384", "SHA3512"] and
result instanceof Crypto::SHA3 and
digestLength = name.replaceAll("-", "").splitAt("SHA3", 1).toInt()
or
(
name.toUpperCase().matches("BLAKE2B%") and
result instanceof Crypto::BLAKE2B
or
name.toUpperCase() = "BLAKE2S" and result instanceof Crypto::BLAKE2S
) and
(
if exists(name.indexOf("-"))
then name.splitAt("-", 1).toInt() = digestLength
else digestLength = 512
)
or
name = "MD5" and
result instanceof Crypto::MD5 and
digestLength = 128
or
name = "RIPEMD160" and
result instanceof Crypto::RIPEMD160 and
digestLength = 160
or
name = "WHIRLPOOL" and
result instanceof Crypto::WHIRLPOOL and
digestLength = 512 // TODO: verify
)
}
bindingset[name]
private predicate mode_name_to_type_known(KeyOpAlg::ModeOfOperationType type, string name) {
type = KeyOpAlg::ECB() and name = "ECB"
or
type = KeyOpAlg::CBC() and name = "CBC"
or
type = KeyOpAlg::GCM() and name = "GCM"
or
type = KeyOpAlg::CTR() and name = "CTR"
or
type = KeyOpAlg::XTS() and name = "XTS"
or
type = KeyOpAlg::CCM() and name = "CCM"
or
type = KeyOpAlg::SIV() and name = "SIV"
or
type = KeyOpAlg::OCB() and name = "OCB"
or
type = KeyOpAlg::CFB() and name = "CFB"
or
type = KeyOpAlg::OFB() and name = "OFB"
or
type = KeyOpAlg::PCBC() and name = "PCBC"
or
type = KeyOpAlg::KWP() and name = "KWP"
or
type = KeyOpAlg::LRW() and name = "LRW"
}
bindingset[name]
private predicate cipher_name_to_type_known(KeyOpAlg::TAlgorithm type, string name) {
exists(string upper | upper = name.toUpperCase() |
upper.matches("AES%") and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::AES())
or
// NOTE: DESede (TripleDES) must be matched before DES% to avoid misclassification
upper.matches("DESEDE%") and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::TRIPLE_DES())
or
not upper.matches("DESEDE%") and
upper.matches("DES%") and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::DES())
or
upper = "TRIPLEDES" and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::TRIPLE_DES())
or
upper = "ARIA" and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::ARIA())
or
upper = "CAMELLIA" and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::CAMELLIA())
or
upper = "TWOFISH" and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::TWOFISH())
or
upper = "SEED" and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::SEED())
or
upper = "SALSA20" and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::SALSA20())
or
upper = "IDEA" and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::IDEA())
or
upper = "CAST5" and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::CAST5())
or
upper = "CHACHA20" and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::CHACHA20())
or
upper = "RC2" and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::RC2())
or
upper = "RC4" and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::RC4())
or
upper = "RC5" and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::RC5())
or
upper = "RSA" and
type = KeyOpAlg::TAsymmetricCipher(KeyOpAlg::RSA())
or
upper = "SKIPJACK" and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::SKIPJACK())
or
upper = "BLOWFISH" and
type = KeyOpAlg::TSymmetricCipher(KeyOpAlg::BLOWFISH())
)
}
bindingset[name]
predicate key_agreement_name_to_type_known(Crypto::TKeyAgreementType type, string name) {
type = Crypto::DH() and
name.toUpperCase() = "DH"
or
type = Crypto::EDH() and
name.toUpperCase() = "EDH"
or
type = Crypto::ECDH() and
name.toUpperCase() in ["ECDH", "X25519", "X448", "XDH"]
or
type = Crypto::ECMQV() and
name.toUpperCase() = "ECMQV"
or
type = Crypto::OtherKeyAgreementType() and
name.toUpperCase().matches("ML-KEM%")
}
/**
* Maps a signature algorithm name to its type, if known.
* see https://docs.oracle.com/en/java/javase/25/docs/specs/security/standard-names.html
*/
bindingset[name]
predicate signature_name_to_type_known(Crypto::KeyOpAlg::TAlgorithm type, string name) {
name.toUpperCase().splitAt("with".toUpperCase(), 1).matches("RSA%") and
type = KeyOpAlg::TAsymmetricCipher(KeyOpAlg::RSA())
or
name.toUpperCase().splitAt("with".toUpperCase(), 1).matches("ECDSA%") and
type = KeyOpAlg::TSignature(KeyOpAlg::ECDSA())
or
name.toUpperCase().splitAt("with".toUpperCase(), 1).matches("DSA%") and
type = KeyOpAlg::TSignature(KeyOpAlg::DSA())
or
name.toUpperCase() = "RSASSA-PSS" and type = KeyOpAlg::TAsymmetricCipher(KeyOpAlg::RSA())
or
name.toUpperCase().matches(["EDDSA", "ED25519", "ED448"]) and
type = KeyOpAlg::TSignature(KeyOpAlg::EDDSA())
or
name.toUpperCase().matches("ML-DSA%") and type = KeyOpAlg::TSignature(KeyOpAlg::DSA())
or
name.toUpperCase() = "HSS/LMS" and type = KeyOpAlg::TSignature(KeyOpAlg::HSS_LMS())
or
name.toUpperCase() = "DSA" and type = KeyOpAlg::TSignature(KeyOpAlg::DSA())
}
bindingset[name]
Crypto::HashType signature_name_to_hash_type_known(string name, int digestLength) {
result = hash_name_to_type_known(name.splitAt("with", 0), digestLength)
}
/**
* A `JavaConstant` in the `"ALG/MODE/PADDING"` or `"ALG"` format
*/
class CipherStringLiteral extends JavaConstant {
CipherStringLiteral() { cipher_names(this.getValue().splitAt("/")) }
string getAlgorithmName() { result = this.getValue().splitAt("/", 0) }
string getMode() { result = this.getValue().splitAt("/", 1) }
string getPadding() { result = this.getValue().splitAt("/", 2) }
}
class CipherGetInstanceCall extends MethodCall {
CipherGetInstanceCall() {
this.getCallee().hasQualifiedName(javaxOrJakarta() + ".crypto", "Cipher", "getInstance")
}
Expr getAlgorithmArg() { result = this.getArgument(0) }
Expr getProviderArg() { result = this.getArgument(1) }
}
// TODO: handle key artifact produced by unwrap
private class CipherOperationCall extends MethodCall {
CipherOperationCall() {
this.getMethod()
.hasQualifiedName(javaxOrJakarta() + ".crypto", "Cipher",
["update", "doFinal", "wrap", "unwrap"])
}
predicate isIntermediate() { this.getMethod().getName() = "update" }
Expr getInput() { result = this.getArgument(0) }
Expr getOutput() {
exists(int outputIndex | this.getMethod().getParameter(outputIndex).getName() = "output" |
result = this.getArgument(outputIndex)
)
or
this.getMethod().getReturnType().hasName("byte[]") and result = this
}
DataFlow::Node getMessageArg() { result.asExpr() = this.getInput() }
}
/**
* Data-flow configuration modeling flow from a cipher string literal to a cipher algorithm consumer.
*/
private module CipherAlgorithmStringToCipherConsumerConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node src) { src.asExpr() instanceof CipherStringLiteral }
predicate isSink(DataFlow::Node sink) {
sink = any(CipherAlgorithmValueConsumer call).getInputNode()
}
}
module CipherAlgorithmStringToFetchFlow =
TaintTracking::Global<CipherAlgorithmStringToCipherConsumerConfig>;
/**
* Note: padding and a mode of operation will only exist when the padding / mode (*and its type*) are determinable.
* This is because the mode will always be specified alongside the algorithm and never independently.
* Therefore, we can always assume that a determinable algorithm will have a determinable mode.
*
* In the case that only an algorithm is specified, e.g., "AES", the provider provides a default mode.
*
* TODO: Model the case of relying on a provider default, but alert on it as a bad practice.
*/
class CipherStringLiteralPaddingAlgorithmInstance extends CipherStringLiteralAlgorithmInstance,
Crypto::PaddingAlgorithmInstance instanceof CipherStringLiteral
{
CipherStringLiteralPaddingAlgorithmInstance() { exists(super.getPadding()) } // TODO: provider defaults
override string getRawPaddingAlgorithmName() { result = super.getPadding() }
bindingset[name]
private predicate paddingToNameMappingKnown(KeyOpAlg::PaddingSchemeType type, string name) {
type instanceof KeyOpAlg::NoPadding and name = "NOPADDING"
or
type instanceof KeyOpAlg::PKCS7 and name = ["PKCS5Padding", "PKCS7Padding"] // TODO: misnomer in the JCA?
or
type instanceof KeyOpAlg::OAEP and name.matches("OAEP%") // TODO: handle OAEPWith%
or
type instanceof KeyOpAlg::PKCS1_V1_5 and name = "PKCS1Padding"
or
type instanceof KeyOpAlg::PSS and name = "PSS"
}
override KeyOpAlg::PaddingSchemeType getPaddingType() {
if this.paddingToNameMappingKnown(_, super.getPadding())
then this.paddingToNameMappingKnown(result, super.getPadding())
else result instanceof KeyOpAlg::OtherPadding
}
}
class CipherStringLiteralModeAlgorithmInstance extends CipherStringLiteralPaddingAlgorithmInstance,
Crypto::ModeOfOperationAlgorithmInstance instanceof CipherStringLiteral
{
CipherStringLiteralModeAlgorithmInstance() { exists(super.getMode()) } // TODO: provider defaults
override string getRawModeAlgorithmName() { result = super.getMode() }
override KeyOpAlg::ModeOfOperationType getModeType() {
if mode_name_to_type_known(_, super.getMode())
then mode_name_to_type_known(result, super.getMode())
else result instanceof KeyOpAlg::OtherMode
}
}
class CipherStringLiteralAlgorithmInstance extends Crypto::KeyOperationAlgorithmInstance instanceof CipherStringLiteral
{
CipherAlgorithmValueConsumer consumer;
CipherStringLiteralAlgorithmInstance() {
CipherAlgorithmStringToFetchFlow::flow(DataFlow::exprNode(this), consumer.getInputNode())
}
CipherAlgorithmValueConsumer getConsumer() { result = consumer }
override Crypto::ModeOfOperationAlgorithmInstance getModeOfOperationAlgorithm() {
result = this // TODO: provider defaults
}
override Crypto::PaddingAlgorithmInstance getPaddingAlgorithm() {
result = this // TODO: provider defaults
}
override string getRawAlgorithmName() { result = super.getValue() }
override KeyOpAlg::AlgorithmType getAlgorithmType() {
if cipher_name_to_type_known(_, super.getAlgorithmName())
then cipher_name_to_type_known(result, super.getAlgorithmName())
else result instanceof KeyOpAlg::TOtherKeyOperationAlgorithmType
}
override int getKeySizeFixed() {
none() // TODO: implement to handle variants such as AES-128
}
override Crypto::ConsumerInputDataFlowNode getKeySizeConsumer() { none() }
}
bindingset[input]
predicate oaep_padding_string_components(string input, string hash, string mfg) {
exists(string regex |
regex = "OAEPWith(.*)And(.*)Padding" and
hash = input.regexpCapture(regex, 1) and
mfg = input.regexpCapture(regex, 2)
)
}
predicate oaep_padding_string_components_eval(string hash, string mfg) {
oaep_padding_string_components(any(CipherStringLiteral s).getPadding(), hash, mfg)
}
class OaepPaddingHashAlgorithmInstance extends OaepPaddingAlgorithmInstance,
Crypto::HashAlgorithmInstance instanceof CipherStringLiteral
{
string hashName;
OaepPaddingHashAlgorithmInstance() {
oaep_padding_string_components(super.getPadding(), hashName, _)
}
override string getRawHashAlgorithmName() { result = super.getPadding() }
override Crypto::THashType getHashType() { result = hash_name_to_type_known(hashName, _) }
override int getFixedDigestLength() { exists(hash_name_to_type_known(hashName, result)) }
}
class OaepPaddingAlgorithmInstance extends Crypto::OaepPaddingAlgorithmInstance,
CipherStringLiteralPaddingAlgorithmInstance
{
override Crypto::HashAlgorithmInstance getOaepEncodingHashAlgorithm() { result = this }
override Crypto::HashAlgorithmInstance getMgf1HashAlgorithm() { none() } // TODO
}
/**
* The cipher algorithm argument to a `CipherGetInstanceCall`.
*
* For example, in `Cipher.getInstance(algorithm)`, this class represents `algorithm`.
*/
class CipherGetInstanceAlgorithmArg extends CipherAlgorithmValueConsumer instanceof Expr {
CipherGetInstanceAlgorithmArg() { this = any(CipherGetInstanceCall call).getAlgorithmArg() }
override Crypto::ConsumerInputDataFlowNode getInputNode() { result.asExpr() = this }
override Crypto::AlgorithmInstance getAKnownAlgorithmSource() {
result.(CipherStringLiteralAlgorithmInstance).getConsumer() = this
}
}
/**
* An access to the `javax.crypto.Cipher` class.
*/
private class CipherAccess extends TypeAccess {
CipherAccess() {
this.getType().(Class).hasQualifiedName(javaxOrJakarta() + ".crypto", "Cipher")
}
}
/**
* An access to a cipher mode field of the `javax.crypto.Cipher` class,
* specifically `ENCRYPT_MODE`, `DECRYPT_MODE`, `WRAP_MODE`, or `UNWRAP_MODE`.
*/
private class JavaxCryptoCipherOperationModeAccess extends FieldAccess {
JavaxCryptoCipherOperationModeAccess() {
this.getQualifier() instanceof CipherAccess and
this.getField().getName().toUpperCase() in [
"ENCRYPT_MODE", "DECRYPT_MODE", "WRAP_MODE", "UNWRAP_MODE"
]
}
}
signature class GetInstanceCallSig instanceof MethodCall;
signature class InitCallSig instanceof MethodCall;
signature class UseCallSig instanceof MethodCall {
/**
* Holds if the use is not a final use, such as an `update()` call before `doFinal()`
*/
predicate isIntermediate();
}
/**
* An generic analysis module for analyzing the `getInstance` to `initialize` to `doOperation` pattern in the JCA.
*
* For example:
* ```
* kpg = KeyPairGenerator.getInstance();
* kpg.initialize(...);
* kpg.generate(...);
* ```
*/
module GetInstanceInitUseFlowAnalysis<
GetInstanceCallSig GetInstance, InitCallSig Init, UseCallSig Use>
{
newtype TFlowState =
TUninitialized() or
TInitialized(Init call) or
TIntermediateUse(Use call)
abstract class InitFlowState extends TFlowState {
string toString() {
this = TUninitialized() and result = "Uninitialized"
or
this = TInitialized(_) and result = "Initialized"
// TODO: add intermediate use
}
}
class UninitializedFlowState extends InitFlowState, TUninitialized { }
class InitializedFlowState extends InitFlowState, TInitialized {
Init call;
DataFlow::Node node1;
DataFlow::Node node2;
InitializedFlowState() {
this = TInitialized(call) and
node2.asExpr() = call.(MethodCall).getQualifier() and
DataFlow::localFlowStep(node1, node2) and
node1 != node2
}
Init getInitCall() { result = call }
DataFlow::Node getFstNode() { result = node1 }
DataFlow::Node getSndNode() { result = node2 }
}
class IntermediateUseState extends InitFlowState, TIntermediateUse {
Use call;
DataFlow::Node node1;
DataFlow::Node node2;
IntermediateUseState() {
this = TIntermediateUse(call) and
call.isIntermediate() and
node1.asExpr() = call.(MethodCall).getQualifier() and
node2 = node1
}
Use getUseCall() { result = call }
DataFlow::Node getFstNode() { result = node1 }
DataFlow::Node getSndNode() { result = node2 }
}
module GetInstanceToInitToUseConfig implements DataFlow::StateConfigSig {
class FlowState = InitFlowState;
predicate isSource(DataFlow::Node src, FlowState state) {
state instanceof UninitializedFlowState and
src.asExpr() instanceof GetInstance
or
src = state.(InitializedFlowState).getSndNode()
or
src = state.(IntermediateUseState).getSndNode()
}
// TODO: document this, but this is intentional (avoid cross products?)
predicate isSink(DataFlow::Node sink, FlowState state) { none() }
predicate isSink(DataFlow::Node sink) {
exists(Init c | c.(MethodCall).getQualifier() = sink.asExpr())
or
exists(Use c | not c.isIntermediate() and c.(MethodCall).getQualifier() = sink.asExpr())
}
predicate isAdditionalFlowStep(
DataFlow::Node node1, FlowState state1, DataFlow::Node node2, FlowState state2
) {
state1 = state1 and
(
node1 = state2.(InitializedFlowState).getFstNode() and
node2 = state2.(InitializedFlowState).getSndNode()
or
node1 = state2.(IntermediateUseState).getFstNode() and
node2 = state2.(IntermediateUseState).getSndNode()
)
}
predicate isBarrier(DataFlow::Node node, FlowState state) {
exists(Init call | node.asExpr() = call.(MethodCall).getQualifier() |
state instanceof UninitializedFlowState
or
state.(InitializedFlowState).getInitCall() != call
)
}
}
module GetInstanceToInitToUseFlow = DataFlow::GlobalWithState<GetInstanceToInitToUseConfig>;
GetInstance getInstantiationFromUse(Use use, DataFlow::Node src, DataFlow::Node sink) {
src.asExpr() = result and
sink.asExpr() = use.(MethodCall).getQualifier() and
GetInstanceToInitToUseFlow::flow(src, sink)
}
GetInstance getInstantiationFromInit(Init init, DataFlow::Node src, DataFlow::Node sink) {
src.asExpr() = result and
sink.asExpr() = init.(MethodCall).getQualifier() and
GetInstanceToInitToUseFlow::flow(src, sink)
}
Init getInitFromUse(Use use, DataFlow::Node src, DataFlow::Node sink) {
src.asExpr() = result.(MethodCall).getQualifier() and
sink.asExpr() = use.(MethodCall).getQualifier() and
GetInstanceToInitToUseFlow::flow(src, sink)
}
predicate hasInit(Use use) { exists(getInitFromUse(use, _, _)) }
Use getAnIntermediateUseFromFinalUse(Use final, DataFlow::Node src, DataFlow::Node sink) {
not final.isIntermediate() and
result.isIntermediate() and
src.asExpr() = result.(MethodCall).getQualifier() and
sink.asExpr() = final.(MethodCall).getQualifier() and
GetInstanceToInitToUseFlow::flow(src, sink)
}
}
module CipherFlowAnalysisImpl =
GetInstanceInitUseFlowAnalysis<CipherGetInstanceCall, CipherInitCall, CipherOperationCall>;
module CipherFlow = CipherFlowAnalysisImpl::GetInstanceToInitToUseFlow;
Crypto::KeyOperationSubtype getKeyOperationSubtypeFromState(
CipherFlowAnalysisImpl::InitFlowState state
) {
state instanceof CipherFlowAnalysisImpl::UninitializedFlowState and
result = Crypto::TUnknownKeyOperationMode()
or
exists(CipherInitCall call | state = CipherFlowAnalysisImpl::TInitialized(call) |
result = call.getCipherOperationModeType()
)
}
class CipherOperationInstance extends Crypto::KeyOperationInstance instanceof CipherOperationCall {
CipherOperationInstance() { not this.isIntermediate() }
override Crypto::KeyOperationSubtype getKeyOperationSubtype() {
if CipherFlowAnalysisImpl::hasInit(this)
then result = CipherFlowAnalysisImpl::getInitFromUse(this, _, _).getCipherOperationModeType()
else result = Crypto::TUnknownKeyOperationMode()
}
CipherGetInstanceCall getInstantiationCall() {
result = CipherFlowAnalysisImpl::getInstantiationFromUse(this, _, _)
}
CipherInitCall getInitCall() { result = CipherFlowAnalysisImpl::getInitFromUse(this, _, _) }
override Crypto::ConsumerInputDataFlowNode getNonceConsumer() {
result.asExpr() = this.getInitCall().getNonceArg()
}
override Crypto::ConsumerInputDataFlowNode getInputConsumer() {
result = super.getMessageArg() or
result = CipherFlowAnalysisImpl::getAnIntermediateUseFromFinalUse(this, _, _).getMessageArg()
}
override Crypto::ConsumerInputDataFlowNode getKeyConsumer() {
result.asExpr() = this.getInitCall().getKeyArg()
}
override Crypto::AlgorithmValueConsumer getAnAlgorithmValueConsumer() {
result = this.getInstantiationCall().getAlgorithmArg()
}
override Crypto::ArtifactOutputDataFlowNode getOutputArtifact() {
result.asExpr() = super.getOutput()
}
}
/**
* Initialization vectors and other nonce artifacts
*/
abstract class NonceParameterInstantiation extends ClassInstanceExpr {
DataFlow::Node getOutputNode() { result.asExpr() = this }
abstract DataFlow::Node getInputNode();
}
// TODO: for all parametert specs, I think they can be set through the constructor
// and through setter methods
class IvParameterSpecInstance extends NonceParameterInstantiation {
IvParameterSpecInstance() {
super
.getConstructedType()
.hasQualifiedName(javaxOrJakarta() + ".crypto.spec", "IvParameterSpec")
}
override DataFlow::Node getInputNode() { result.asExpr() = super.getArgument(0) }
}
// TODO: this also specifies the tag length for GCM
class GCMParameterSpecInstance extends NonceParameterInstantiation {
GCMParameterSpecInstance() {
super
.getConstructedType()
.hasQualifiedName(javaxOrJakarta() + ".crypto.spec", "GCMParameterSpec")
}
override DataFlow::Node getInputNode() { result.asExpr() = super.getArgument(1) }
}
class IvParameterSpecGetIvCall extends MethodCall {
IvParameterSpecGetIvCall() {
this.getMethod()
.hasQualifiedName(javaxOrJakarta() + ".crypto.spec", "IvParameterSpec", "getIV")
}
}
class KeyAdditionalFlowSteps extends MethodCall {
KeyAdditionalFlowSteps() {
this.getCallee().hasQualifiedName("java.security", "KeyPair", "getPublic")
or
this.getCallee().hasQualifiedName("java.security", "KeyPair", "getPrivate")
or
this.getCallee().hasQualifiedName("java.security", "Key", "getEncoded")
}
DataFlow::Node getInputNode() { result.asExpr() = this.getQualifier() }
DataFlow::Node getOutputNode() { result.asExpr() = this }
}
predicate additionalFlowSteps(DataFlow::Node node1, DataFlow::Node node2) {
exists(IvParameterSpecGetIvCall m |
node1.asExpr() = m.getQualifier() and
node2.asExpr() = m
)
or
exists(NonceParameterInstantiation n |
node1 = n.getInputNode() and
node2 = n.getOutputNode()
)
or
exists(KeyAdditionalFlowSteps call |
node1 = call.getInputNode() and
node2 = call.getOutputNode()
)
}
class ArtifactAdditionalFlowStep extends AdditionalFlowInputStep {
DataFlow::Node output;
ArtifactAdditionalFlowStep() { additionalFlowSteps(this, output) }
override DataFlow::Node getOutput() { result = output }
}
/**
* A data-flow configuration to track flow from a mode field access to
* the mode argument of the `init` method of the `javax.crypto.Cipher` class.
*/
private module JavaxCipherModeAccessToInitConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node src) {
src.asExpr() instanceof JavaxCryptoCipherOperationModeAccess
}
predicate isSink(DataFlow::Node sink) {
exists(CipherInitCall c | c.getModeArg() = sink.asExpr())
}
}
module JavaxCipherModeAccessToInitFlow = DataFlow::Global<JavaxCipherModeAccessToInitConfig>;
private predicate cipher_mode_str_to_cipher_mode_known(
string mode, Crypto::KeyOperationSubtype cipher_mode
) {
mode = "ENCRYPT_MODE" and cipher_mode = Crypto::TEncryptMode()
or
mode = "WRAP_MODE" and cipher_mode = Crypto::TWrapMode()
or
mode = "DECRYPT_MODE" and cipher_mode = Crypto::TDecryptMode()
or
mode = "UNWRAP_MODE" and cipher_mode = Crypto::TUnwrapMode()
}
class CipherInitCall extends MethodCall {
CipherInitCall() {
this.getCallee().hasQualifiedName(javaxOrJakarta() + ".crypto", "Cipher", "init")
}
/**
* Returns the mode argument to the `init` method
* that is used to determine the cipher operation mode.
* Note this is the raw expr and not necessarily a direct access
* of a mode. Use `getModeOrigin()` to get the field access origin
* flowing to this argument, if one exists (is known).
*/
Expr getModeArg() { result = this.getArgument(0) }
JavaxCryptoCipherOperationModeAccess getModeOrigin() {
exists(DataFlow::Node src, DataFlow::Node sink |
JavaxCipherModeAccessToInitFlow::flow(src, sink) and
src.asExpr() = result and
this.getModeArg() = sink.asExpr()
)
}
Crypto::KeyOperationSubtype getCipherOperationModeType() {
if cipher_mode_str_to_cipher_mode_known(this.getModeOrigin().getField().getName(), _)
then cipher_mode_str_to_cipher_mode_known(this.getModeOrigin().getField().getName(), result)
else result = Crypto::TUnknownKeyOperationMode()
}
Expr getKeyArg() {
result = this.getArgument(1) and this.getMethod().getParameterType(1).hasName("Key")
}
Expr getNonceArg() {
result = this.getArgument(2) and
this.getMethod().getParameterType(2).hasName("AlgorithmParameterSpec")
}
}
class CipherInitCallKeyConsumer extends Crypto::ArtifactConsumer {
CipherInitCallKeyConsumer() { this = any(CipherInitCall call).getKeyArg() }
override Crypto::ConsumerInputDataFlowNode getInputNode() { result.asExpr() = this }
}
/*
* Hash Functions
*/
/**
* Flow from a known hash algorithm name to a `MessageDigest.getInstance(sink)` call.
*/
module KnownHashAlgorithmLiteralToMessageDigestConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node src) { hash_names(src.asExpr().(JavaConstant).getValue()) }
predicate isSink(DataFlow::Node sink) {
exists(HashAlgorithmValueConsumer consumer | sink = consumer.getInputNode())
}
}
module KnownHashAlgorithmLiteralToMessageDigestFlow =
DataFlow::Global<KnownHashAlgorithmLiteralToMessageDigestConfig>;
class KnownHashAlgorithm extends Crypto::HashAlgorithmInstance instanceof JavaConstant {
HashAlgorithmValueConsumer consumer;
KnownHashAlgorithm() {
hash_names(super.getValue()) and
KnownHashAlgorithmLiteralToMessageDigestFlow::flow(DataFlow::exprNode(this),
consumer.getInputNode())
}
HashAlgorithmValueConsumer getConsumer() { result = consumer }
override string getRawHashAlgorithmName() { result = super.getValue() }
override Crypto::THashType getHashType() {
result = hash_name_to_type_known(this.getRawHashAlgorithmName(), _)
}
override int getFixedDigestLength() {
exists(hash_name_to_type_known(this.getRawHashAlgorithmName(), result))
}
}
module MessageDigestFlowAnalysisImpl =
GetInstanceInitUseFlowAnalysis<MessageDigestGetInstanceCall, DUMMY_UNUSED_METHODCALL, DigestCall>;
class MessageDigestGetInstanceAlgorithmValueConsumer extends HashAlgorithmValueConsumer {
MessageDigestGetInstanceCall call;
MessageDigestGetInstanceAlgorithmValueConsumer() { this = call.getAlgorithmArg() }
MessageDigestGetInstanceCall getInstantiationCall() { result = call }
override Crypto::ConsumerInputDataFlowNode getInputNode() { result.asExpr() = this }
override Crypto::AlgorithmInstance getAKnownAlgorithmSource() {
exists(KnownHashAlgorithm l | l.getConsumer() = this and result = l)
}
}
class MessageDigestGetInstanceCall extends MethodCall {
MessageDigestGetInstanceCall() {
this.getCallee().hasQualifiedName("java.security", "MessageDigest", "getInstance")
}
Expr getAlgorithmArg() { result = this.getArgument(0) }
}
class DigestCall extends MethodCall {
DigestCall() {
this.getCallee().hasQualifiedName("java.security", "MessageDigest", ["update", "digest"])
}
Expr getDigestArtifactOutput() { result = this }
Expr getInputArg() { result = this.getArgument(0) }
predicate isIntermediate() { this.getMethod().getName() = "update" }
}
// flow config from MessageDigest.getInstance to MessageDigest.digest
module DigestGetInstanceToDigestConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node src) { src.asExpr() instanceof MessageDigestGetInstanceCall }
predicate isSink(DataFlow::Node sink) {
exists(DigestCall c | c.getQualifier() = sink.asExpr())
}
}
module DigestGetInstanceToDigestFlow = DataFlow::Global<DigestGetInstanceToDigestConfig>;
class DigestHashOperation extends Crypto::HashOperationInstance instanceof DigestCall {
DigestHashOperation() { not super.isIntermediate() }
override Crypto::ArtifactOutputDataFlowNode getOutputArtifact() {
result.asExpr() = super.getDigestArtifactOutput()
}
override Crypto::AlgorithmValueConsumer getAnAlgorithmValueConsumer() {
MessageDigestFlowAnalysisImpl::getInstantiationFromUse(this, _, _) =
result.(MessageDigestGetInstanceAlgorithmValueConsumer).getInstantiationCall()
}
override Crypto::ConsumerInputDataFlowNode getInputConsumer() {
result.asExpr() = super.getInputArg() or
result.asExpr() =
MessageDigestFlowAnalysisImpl::getAnIntermediateUseFromFinalUse(this, _, _).getInputArg()
}
}
/*
* Key Generation
*/
module KeyGeneratorFlowAnalysisImpl =
GetInstanceInitUseFlowAnalysis<KeyGeneratorGetInstanceCall, KeyGeneratorInitCall,
KeyGeneratorGenerateCall>;
module KeyGeneratorFlow = KeyGeneratorFlowAnalysisImpl::GetInstanceToInitToUseFlow;
abstract class KeyGeneratorParameterSpecClassInstanceExpr extends ClassInstanceExpr {
KeyGeneratorInitCall getAnInitCallUse() {
exists(DataFlow::Node sink |
KeyGeneratorParameterSpecToInitializeFlow::flow(DataFlow::exprNode(this), sink) and
result.getAlgorithmParameterSpecArg() = sink.asExpr()