forked from Timi16/soroban-debugger
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorig_sec.rs
More file actions
1757 lines (1576 loc) · 129 KB
/
Copy pathorig_sec.rs
File metadata and controls
1757 lines (1576 loc) · 129 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
use crate::runtime::executor::ContractExecutor;
use crate::server::protocol::{DynamicTraceEvent, DynamicTraceEventKind};
use crate::utils::wasm::{parse_instructions, WasmInstruction};
use crate::Result;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use wasmparser::{Operator, Parser, Payload};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
Low,
Medium,
High,
}
impl Default for Severity {
fn default() -> Self {
Severity::Low
}
}
#[derive(Debug, Default, Clone)]
pub struct AnalyzerFilter {
pub enable_rules: Vec<String>,
pub disable_rules: Vec<String>,
pub min_severity: Severity,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityFinding {
pub rule_id: String,
pub severity: Severity,
pub location: String,
pub description: String,
pub remediation: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub confidence: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rationale: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SecurityReport {
pub findings: Vec<SecurityFinding>,
}
pub trait SecurityRule {
fn name(&self) -> &str;
fn description(&self) -> &str;
fn analyze_static(&self, _wasm_bytes: &[u8]) -> Result<Vec<SecurityFinding>> {
Ok(vec![])
}
fn analyze_dynamic(
&self,
_executor: Option<&ContractExecutor>,
_trace: &[DynamicTraceEvent],
) -> Result<Vec<SecurityFinding>> {
Ok(vec![])
}
}
pub struct SecurityAnalyzer {
rules: Vec<Box<dyn SecurityRule>>,
}
impl SecurityAnalyzer {
pub fn new() -> Self {
Self {
rules: vec![
Box::new(HardcodedAddressRule),
Box::new(ArithmeticCheckRule),
Box::new(AuthorizationCheckRule),
Box::new(ReentrancyPatternRule),
Box::new(CrossContractImportRule),
Box::new(UnboundedIterationRule),
],
}
}
pub fn analyze(
&self,
wasm_bytes: &[u8],
executor: Option<&ContractExecutor>,
trace: Option<&[DynamicTraceEvent]>,
filter: &AnalyzerFilter,
) -> Result<SecurityReport> {
let mut report = SecurityReport::default();
for rule in &self.rules {
let name = rule.name();
if !filter.enable_rules.is_empty() && !filter.enable_rules.iter().any(|r| r == name) {
continue;
}
if filter.disable_rules.iter().any(|r| r == name) {
continue;
}
let static_findings = rule.analyze_static(wasm_bytes)?;
report.findings.extend(
static_findings
.into_iter()
.filter(|f| f.severity >= filter.min_severity),
);
if let Some(tr) = trace {
let dynamic_findings = rule.analyze_dynamic(executor, tr)?;
report.findings.extend(
dynamic_findings
.into_iter()
.filter(|f| f.severity >= filter.min_severity),
);
}
}
Ok(report)
}
}
impl Default for SecurityAnalyzer {
fn default() -> Self {
Self::new()
}
}
// ---------------------------------------------------------------------------
// StrKey validation helpers
// ---------------------------------------------------------------------------
/// CRC-16/XModem (poly = 0x1021, init = 0x0000, no reflection).
/// Used by Stellar StrKey to protect against transcription errors.
fn strkey_crc16(data: &[u8]) -> u16 {
let mut crc: u16 = 0x0000;
for &byte in data {
crc ^= (byte as u16) << 8;
for _ in 0..8 {
crc = if (crc & 0x8000) != 0 {
(crc << 1) ^ 0x1021
} else {
crc << 1
};
}
}
crc
}
/// Returns `true` only when `s` is a cryptographically valid Stellar StrKey.
///
/// Validation steps (SEP-0023):
/// 1. Must be exactly 56 characters, all from the base32 alphabet (AΓÇôZ, 2ΓÇô7).
/// 2. Base32-decode to exactly 35 bytes.
/// 3. `decoded[0]` must be a recognised version byte:
/// • `0x30` (6 << 3) → ED25519 public key → 'G' prefix
/// • `0x10` (2 << 3) → contract address → 'C' prefix
/// 4. CRC-16/XModem over `decoded[0..33]` must equal the little-endian u16
/// stored in `decoded[33..35]`.
///
/// Any 56-char string that fails even one of these steps is **not** a valid
/// address ΓÇö it is, for example, an error-message fragment, a base64 blob, or
/// a random identifier that merely happens to start with 'G' or 'C'.
fn is_valid_strkey(s: &str) -> bool {
if s.len() != 56 {
return false;
}
// --- Base32 decode (RFC 4648, no padding) ---
// 56 chars × 5 bits = 280 bits = 35 bytes exactly.
let mut decoded = [0u8; 35];
let mut bits: u64 = 0;
let mut bit_count: u32 = 0;
let mut byte_idx: usize = 0;
for ch in s.bytes() {
let val: u64 = match ch {
b'A'..=b'Z' => (ch - b'A') as u64,
b'2'..=b'7' => (ch - b'2' + 26) as u64,
_ => {
return false;
} // character outside base32 alphabet
};
bits = (bits << 5) | val;
bit_count += 5;
if bit_count >= 8 {
bit_count -= 8;
if byte_idx >= 35 {
return false;
}
decoded[byte_idx] = ((bits >> bit_count) & 0xff) as u8;
byte_idx += 1;
}
}
if byte_idx != 35 {
return false;
}
// --- Version byte ---
let version = decoded[0];
if version != (6u8 << 3) && version != (2u8 << 3) {
return false;
}
// --- Checksum ---
let expected = u16::from_le_bytes([decoded[33], decoded[34]]);
let computed = strkey_crc16(&decoded[..33]);
computed == expected
}
// ---------------------------------------------------------------------------
// Rules
// ---------------------------------------------------------------------------
struct HardcodedAddressRule;
impl SecurityRule for HardcodedAddressRule {
fn name(&self) -> &str {
"hardcoded-address"
}
fn description(&self) -> &str {
"Detects hardcoded Stellar addresses in WASM data sections."
}
fn analyze_static(&self, wasm_bytes: &[u8]) -> Result<Vec<SecurityFinding>> {
let mut findings = Vec::new();
for payload in Parser::new(0).parse_all(wasm_bytes).flatten() {
if let Payload::DataSection(reader) = payload {
for data in reader.into_iter().flatten() {
let content = String::from_utf8_lossy(data.data);
for word in content.split(|c: char| !c.is_alphanumeric()) {
// Guard 1 ΓÇô fast pre-filter (cheap): right length and prefix.
// Guard 2 ΓÇô full StrKey validation (base32 + version byte + CRC-16).
//
// Without guard 2, arbitrary 56-char constants such as error
// message fragments or base64 blobs that happen to start with
// 'G' or 'C' would be mis-classified as addresses.
if (word.starts_with('G') || word.starts_with('C'))
&& word.len() == 56
&& is_valid_strkey(word)
{
findings.push(SecurityFinding {
rule_id: self.name().to_string(),
severity: Severity::Medium,
location: "Data Section".to_string(),
description: format!("Found potential hardcoded address: {}", word),
remediation:
"Use Address::from_str from configuration or function \
arguments instead of hardcoding."
.to_string(),
confidence: None,
rationale: None,
});
}
}
}
}
}
Ok(findings)
}
}
struct ArithmeticCheckRule;
impl SecurityRule for ArithmeticCheckRule {
fn name(&self) -> &str {
"arithmetic-overflow"
}
fn description(&self) -> &str {
"Detects potential for unchecked arithmetic overflow."
}
fn analyze_static(&self, wasm_bytes: &[u8]) -> Result<Vec<SecurityFinding>> {
let mut findings = Vec::new();
let instructions = parse_instructions(wasm_bytes);
for (i, instr) in instructions.iter().enumerate() {
if Self::is_arithmetic(instr) && !Self::is_guarded(&instructions, i) {
findings.push(SecurityFinding {
rule_id: self.name().to_string(),
severity: Severity::Medium,
location: format!("Instruction {}", i),
description: format!("Unchecked arithmetic operation detected: {:?}", instr),
remediation: "Ensure arithmetic operations are guarded with proper bounds checks or overflow handling.".to_string(),
confidence: None,
context: None,
});
}
}
Ok(findings)
}
}
impl ArithmeticCheckRule {
fn is_arithmetic(instr: &WasmInstruction) -> bool {
matches!(
instr,
WasmInstruction::I32Add
| WasmInstruction::I32Sub
| WasmInstruction::I32Mul
| WasmInstruction::I64Add
| WasmInstruction::I64Sub
| WasmInstruction::I64Mul
)
}
}
struct AuthorizationCheckRule;
impl SecurityRule for AuthorizationCheckRule {
fn name(&self) -> &str {
"missing-auth"
}
fn description(&self) -> &str {
"Detects sensitive flows missing authorization checks."
}
fn analyze_dynamic(
&self,
_executor: Option<&ContractExecutor>,
trace: &[DynamicTraceEvent],
) -> Result<Vec<SecurityFinding>> {
let mut findings = Vec::new();
let mut auth_sequence = None;
let mut problematic_storage_writes = Vec::new();
// First pass: find the earliest authorization event and any storage writes before it
for entry in trace {
if entry.kind == DynamicTraceEventKind::Authorization {
// Record the earliest authorization event
match auth_sequence {
None => auth_sequence = Some(entry.sequence),
Some(current_auth_seq) => {
if entry.sequence < current_auth_seq {
auth_sequence = Some(entry.sequence);
}
}
}
} else if entry.kind == DynamicTraceEventKind::StorageWrite {
// Check if this storage write happens before any authorization
if let Some(auth_seq) = auth_sequence {
if entry.sequence < auth_seq {
problematic_storage_writes.push(entry.sequence);
}
} else {
// No auth seen yet, this storage write is problematic
problematic_storage_writes.push(entry.sequence);
}
}
}
// If we have storage writes without preceding auth, report a finding
if !problematic_storage_writes.is_empty() {
findings.push(SecurityFinding {
rule_id: self.name().to_string(),
severity: Severity::High,
location: "Dynamic trace".to_string(),
description: format!(
"Storage mutation detected without preceding authorization. Found {} storage write(s) occurring before any authorization event.",
problematic_storage_writes.len()
),
remediation: "Ensure all sensitive functions call `address.require_auth()` before mutating state.".to_string(),
confidence: None,
rationale: None,
});
}
Ok(findings)
}
}
struct ReentrancyPatternRule;
impl SecurityRule for ReentrancyPatternRule {
fn name(&self) -> &str {
"reentrancy-pattern"
}
fn description(&self) -> &str {
"Detects cross-contract calls followed by storage writes in the same call frame."
}
fn analyze_dynamic(
&self,
_executor: Option<&ContractExecutor>,
trace: &[DynamicTraceEvent],
) -> Result<Vec<SecurityFinding>> {
Ok(analyze_reentrancy_pattern_dynamic(trace))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct FrameKey {
function: Option<String>,
call_depth: Option<usize>,
}
#[derive(Debug, Clone)]
struct PendingCrossCall {
frame: Option<FrameKey>,
sequence: usize,
pre_call_write_seen: bool,
inferred: bool,
}
struct CrossContractImportRule;
impl SecurityRule for CrossContractImportRule {
fn name(&self) -> &str {
"cross-contract-import"
}
fn description(&self) -> &str {
"Detects cross-contract host function imports with robust name matching."
}
fn analyze_static(&self, wasm_bytes: &[u8]) -> Result<Vec<SecurityFinding>> {
let mut matches = Vec::new();
for payload in Parser::new(0).parse_all(wasm_bytes) {
let Ok(payload) = payload else {
// Many unit tests feed non-module bytes into the analyzer. Degrade gracefully.
return Ok(Vec::new());
};
if let Payload::ImportSection(reader) = payload {
for import in reader.into_iter() {
let Ok(import) = import else {
continue;
};
if !matches!(import.ty, wasmparser::TypeRef::Func(_)) {
continue;
}
if is_cross_contract_host_import(import.module, import.name) {
matches.push(format!("{}::{}", import.module, import.name));
}
}
}
}
if matches.is_empty() {
return Ok(Vec::new());
}
Ok(vec![SecurityFinding {
rule_id: self.name().to_string(),
severity: Severity::Low,
location: "Import Section".to_string(),
description: format!(
"Cross-contract host imports detected: {}",
matches.join(", ")
),
remediation: "Review external call sites for reentrancy and authorization checks."
.to_string(),
confidence: None,
context: None,
}])
}
}
fn canonicalize_ascii(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for ch in s.chars() {
if ch.is_ascii_alphanumeric() {
out.push(ch.to_ascii_lowercase());
}
}
out
}
fn is_env_like_module(module: &str) -> bool {
let m = canonicalize_ascii(module);
m == "env" || m.starts_with("sorobanenv")
}
fn is_cross_contract_host_function_name(name: &str) -> bool {
const BASES: &[&str] = &[
"invokecontract",
"tryinvokecontract",
"callcontract",
"trycallcontract",
"trycall",
];
let n = canonicalize_ascii(name);
for base in BASES {
if n == *base {
return true;
}
if let Some(suffix) = n.strip_prefix(base) {
if suffix.is_empty() {
return true;
}
if let Some(rest) = suffix.strip_prefix('v') {
if !rest.is_empty() && rest.chars().all(|c| c.is_ascii_digit()) {
return true;
}
}
}
}
false
}
fn is_cross_contract_host_import(module: &str, name: &str) -> bool {
is_env_like_module(module) && is_cross_contract_host_function_name(name)
}
struct UnboundedIterationRule;
impl SecurityRule for UnboundedIterationRule {
fn name(&self) -> &str {
"unbounded-iteration"
}
fn description(&self) -> &str {
"Detects storage-driven loops and unbounded read patterns."
}
fn analyze_static(&self, wasm_bytes: &[u8]) -> Result<Vec<SecurityFinding>> {
let analysis = analyze_unbounded_iteration_static(wasm_bytes);
if !analysis.suspicious {
return Ok(Vec::new());
}
let mut finding = SecurityFinding {
rule_id: self.name().to_string(),
severity: Severity::High,
location: "WASM code section".to_string(),
description: format!(
"Detected loop(s) with storage-read host calls ({} storage calls while inside loop).",
analysis.storage_calls_inside_loops
),
remediation: "Bound iteration over storage-backed collections (pagination, explicit limits, or capped batch size).".to_string(),
confidence: analysis.confidence,
context: analysis.context,
};
// Enhance description with additional context if available
if let Some(context) = &finding.context {
if let Some(pattern) = &context.storage_call_pattern {
if pattern.calls_outside_loops > 0 {
finding.description = format!(
"{} Also found {} storage calls outside loops (may indicate mixed access patterns).",
finding.description,
pattern.calls_outside_loops
);
}
}
if let Some(depth) = context.loop_nesting_depth {
if depth > 1 {
finding.description = format!(
"{} Loop nesting depth: {} (increased complexity).",
finding.description, depth
);
}
}
}
Ok(vec![finding])
}
fn analyze_dynamic(
&self,
_executor: Option<&ContractExecutor>,
trace: &[DynamicTraceEvent],
) -> Result<Vec<SecurityFinding>> {
Ok(analyze_unbounded_iteration_dynamic(trace)
.into_iter()
.map(|mut finding| {
finding.rule_id = self.name().to_string();
finding
})
.collect())
}
}
#[derive(Debug, Default)]
struct UnboundedStaticSignal {
suspicious: bool,
storage_calls_inside_loops: usize,
confidence: Option<f32>,
rationale: Option<String>,
loop_types: Vec<String>,
max_nesting_depth: usize,
}
#[derive(Debug, Clone)]
enum ControlFlowFrame {
Loop { loop_type: String },
Block,
If,
}
impl ControlFlowFrame {
fn is_loop(&self) -> bool {
matches!(self, ControlFlowFrame::Loop { .. })
}
fn loop_type(&self) -> Option<&str> {
match self {
ControlFlowFrame::Loop { loop_type, .. } => Some(loop_type),
_ => None,
}
}
}
fn analyze_unbounded_iteration_static(wasm_bytes: &[u8]) -> UnboundedStaticSignal {
let mut storage_import_indices = HashSet::new();
let mut imported_func_count = 0u32;
let mut control_flow_stack: Vec<ControlFlowFrame> = Vec::new();
let mut signal = UnboundedStaticSignal::default();
let mut storage_calls_in_loops = 0usize;
let mut storage_calls_outside_loops = 0usize;
let mut loop_types_with_calls: HashSet<String> = HashSet::new();
let mut loop_types_seen: HashSet<String> = HashSet::new();
let mut conditional_branches = 0usize;
for payload in Parser::new(0).parse_all(wasm_bytes) {
let Ok(payload) = payload else {
return signal;
};
match payload {
Payload::ImportSection(reader) => {
for import in reader.into_iter().flatten() {
if let wasmparser::TypeRef::Func(_) = import.ty {
if is_storage_read_import(import.module, import.name) {
storage_import_indices.insert(imported_func_count);
}
imported_func_count += 1;
}
}
}
Payload::CodeSectionEntry(body) => {
let Ok(mut operators) = body.get_operators_reader() else {
continue;
};
while !operators.eof() {
let Ok(op) = operators.read() else {
break;
};
match op {
Operator::Loop { .. } => {
let current_depth =
control_flow_stack.iter().filter(|f| f.is_loop()).count();
let loop_type = (if current_depth > 0 {
"nested_loop"
} else {
"top_level_loop"
})
.to_string();
loop_types_seen.insert(loop_type.clone());
control_flow_stack.push(ControlFlowFrame::Loop {
loop_type: loop_type.clone(),
});
signal.max_nesting_depth =
signal.max_nesting_depth.max(current_depth + 1);
}
Operator::Block { .. } => {
control_flow_stack.push(ControlFlowFrame::Block);
}
Operator::If { .. } => {
conditional_branches += 1;
control_flow_stack.push(ControlFlowFrame::If);
}
Operator::Else => {}
Operator::End => {
if let Some(_frame) = control_flow_stack.pop() {
// max_nesting_depth tracks the peak depth and shouldn't be decremented
}
}
Operator::Call { function_index } => {
let is_storage_call = storage_import_indices.contains(&function_index);
let current_loop_depth =
control_flow_stack.iter().filter(|f| f.is_loop()).count();
if is_storage_call {
if current_loop_depth > 0 {
storage_calls_in_loops += 1;
if let Some(loop_frame) =
control_flow_stack.iter().rev().find(|f| f.is_loop())
{
if let Some(loop_type) = loop_frame.loop_type() {
loop_types_with_calls.insert(loop_type.to_string());
}
}
} else {
storage_calls_outside_loops += 1;
}
}
}
Operator::BrIf { .. } => {
conditional_branches += 1;
}
_ => {}
}
}
}
_ => {}
}
}
signal.storage_calls_inside_loops = storage_calls_in_loops;
signal.loop_types = loop_types_seen.into_iter().collect();
// Calculate confidence based on multiple factors
let confidence = if storage_calls_in_loops > 0 {
if signal.max_nesting_depth >= 2 && storage_calls_in_loops >= 3 {
0.9
} else if signal.max_nesting_depth > 1 || storage_calls_in_loops > 1 {
0.7
} else {
0.5
}
} else {
0.2
};
signal.rationale = Some(format!(
"Storage calls in loops: {}, max nesting depth: {}, loop types with calls: {:?}",
storage_calls_in_loops, signal.max_nesting_depth, loop_types_with_calls
));
signal.confidence = Some(confidence);
signal.suspicious = storage_calls_in_loops > 0;
signal
signal.suspicious = storage_calls_in_loops > 0;
signal
}
fn is_storage_read_import(module: &str, name: &str) -> bool {
const BASES: &[&str] = &[
"storageget",
"storagehas",
"storagenext",
"storageiter",
"getcontractdata",
"hascontractdata",
"mapget",
"vecget",
"contractstorageget",
"sorobanstoragehas",
];
if !is_env_like_module(module) {
return false;
}
let n = canonicalize_ascii(name);
for base in BASES {
if n == *base {
return true;
}
// Handle prefix-qualified names like "contract_storage_get" or "soroban_storage_has"
if n.ends_with(base) {
return true;
}
if n.starts_with(base) {
let _suffix = &n[base.len()..];
}
if let Some(suffix) = n.strip_prefix(base) {
if suffix.is_empty() {
return true;
}
if let Some(rest) = suffix.strip_prefix('v') {
if !rest.is_empty() && rest.chars().all(|c| c.is_ascii_digit()) {
return true;
}
}
}
// Handle prefix-qualified names like "contract_storage_get".
if n.ends_with(base) {
return true;
}
}
false
}
fn analyze_unbounded_iteration_dynamic(trace: &[DynamicTraceEvent]) -> Option<SecurityFinding> {
let mut read_key_counts: HashMap<&str, usize> = HashMap::new();
let mut total_reads = 0usize;
for entry in trace {
if entry.kind == DynamicTraceEventKind::StorageRead {
total_reads += 1;
if let Some(key) = entry.storage_key.as_deref() {
*read_key_counts.entry(key).or_insert(0) += 1;
}
}
}
if total_reads == 0 {
return None;
}
let unique_keys = read_key_counts.len();
let max_reads_for_one_key = read_key_counts.values().copied().max().unwrap_or(0);
let likely_unbounded = total_reads >= 64
&& (unique_keys <= total_reads / 4 || max_reads_for_one_key >= 32 || total_reads >= 128);
if !likely_unbounded {
return None;
}
Some(SecurityFinding {
rule_id: "unbounded-iteration".to_string(),
severity: Severity::High,
location: "Dynamic trace".to_string(),
description: format!(
"Observed high storage-read pressure (reads={}, unique_keys={}, max_reads_single_key={}). This pattern is consistent with unbounded or storage-driven iteration.",
total_reads,
unique_keys,
max_reads_for_one_key
),
remediation: "Use explicit iteration bounds and pagination for storage traversal to avoid gas-denial risks.".to_string(),
confidence: None,
rationale: None,
})
}
fn analyze_reentrancy_pattern_dynamic(trace: &[DynamicTraceEvent]) -> Vec<SecurityFinding> {
let mut entries = trace.to_vec();
entries.sort_by_key(|entry| entry.sequence);
let mut findings = Vec::new();
let mut writes_seen_by_frame: HashMap<FrameKey, usize> = HashMap::new();
let mut last_known_frame: Option<FrameKey> = None;
let mut pending_cross_call: Option<PendingCrossCall> = None;
for entry in &entries {
let explicit_frame = frame_key_for(entry);
let active_frame = explicit_frame.clone().or_else(|| last_known_frame.clone());
match entry.kind {
DynamicTraceEventKind::FunctionCall => {
if let Some(frame) = explicit_frame {
last_known_frame = Some(frame);
}
}
DynamicTraceEventKind::StorageWrite => {
if let Some(frame) = active_frame.clone() {
*writes_seen_by_frame.entry(frame.clone()).or_insert(0) += 1;
last_known_frame = Some(frame.clone());
}
let Some(pending) = pending_cross_call.as_ref() else {
continue;
};
let same_frame = match (&pending.frame, &active_frame) {
(Some(expected), Some(actual)) => expected == actual,
_ => false,
};
let inferred_match =
pending.inferred && pending.frame.is_none() && active_frame.is_none();
if !(same_frame || inferred_match) {
continue;
}
if pending.pre_call_write_seen {
pending_cross_call = None;
continue;
}
let (confidence, rationale) = if same_frame {
(
0.92,
format!(
"Observed an external interaction at trace event {} and a later \
storage write in the same call frame. This matches the classic \
checks-effects-interactions violation shape.",
pending.sequence
),
)
} else {
(
0.42,
format!(
"Observed a global sequence of external call at trace event {} \
followed by a storage write, but the trace lacked frame metadata. \
Treat this as a low-confidence signal.",
pending.sequence
),
)
};
findings.push(SecurityFinding {
rule_id: "reentrancy-pattern".to_string(),
severity: if confidence >= 0.8 {
Severity::High
} else {
Severity::Low
},
location: format!("Trace event {}", entry.sequence),
description: "Storage write detected after an external contract call in the same execution frame. Possible reentrancy risk.".to_string(),
remediation: "Follow checks-effects-interactions: finalize critical state before external calls, or isolate post-call writes to benign bookkeeping.".to_string(),
confidence: Some(confidence),
rationale: Some(rationale),
});
pending_cross_call = None;
}
DynamicTraceEventKind::CrossContractCall => {
let frame = active_frame.clone();
let pre_call_write_seen = frame
.as_ref()
.and_then(|key| writes_seen_by_frame.get(key).copied())
.unwrap_or(0)
> 0;
pending_cross_call = Some(PendingCrossCall {
frame,
sequence: entry.sequence,
pre_call_write_seen,
inferred: active_frame.is_none(),
});
}
_ => {
if let Some(frame) = active_frame {
last_known_frame = Some(frame);
}
}
}
}
findings
}
fn frame_key_for(entry: &DynamicTraceEvent) -> Option<FrameKey> {
if entry.function.is_none() && entry.call_depth.is_none() {
return None;
}
Some(FrameKey {
function: entry.function.clone(),
call_depth: entry.call_depth,
})
}
#[cfg(test)]
mod tests {
use super::*;
// -----------------------------------------------------------------------
// Helpers shared across StrKey tests
// -----------------------------------------------------------------------
/// Build a syntactically and cryptographically valid StrKey from raw parts.
///
/// `version` must be `6 << 3` (ED25519 / 'G') or `2 << 3` (contract / 'C').
/// `key_bytes` must be exactly 32 bytes.
fn build_strkey(version: u8, key_bytes: &[u8; 32]) -> String {
// 1. Assemble the 33-byte payload and compute CRC.
let mut payload = [0u8; 33];
payload[0] = version;
payload[1..].copy_from_slice(key_bytes);
let crc = strkey_crc16(&payload);
// 2. Concatenate payload + CRC (little-endian) → 35 bytes.
let mut raw = [0u8; 35];
raw[..33].copy_from_slice(&payload);
raw[33..].copy_from_slice(&crc.to_le_bytes());
// 3. Base32-encode (RFC 4648, A-Z / 2-7).
const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
let mut out = String::with_capacity(56);
let mut bits: u64 = 0;
let mut bit_count: u32 = 0;
for &byte in &raw {
bits = (bits << 8) | (byte as u64);
bit_count += 8;
while bit_count >= 5 {
bit_count -= 5;
out.push(ALPHABET[((bits >> bit_count) & 0x1f) as usize] as char);
}
}
debug_assert_eq!(out.len(), 56, "StrKey must be exactly 56 chars");
out
}
// -----------------------------------------------------------------------
// is_valid_strkey ΓÇö unit tests
// -----------------------------------------------------------------------
/// A programmatically constructed StrKey (version 0x30, all-zero key) must
/// be accepted. This is the canonical regression guard: if the CRC logic or
/// base32 decode regresses, this test fails immediately.
#[test]
fn strkey_accepts_well_formed_g_address() {
let addr = build_strkey(6 << 3, &[0u8; 32]);
assert!(
addr.starts_with('G'),
"sanity: version 0x30 encodes to 'G' prefix"
);