-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathsecure_random.py
More file actions
61 lines (55 loc) · 2.05 KB
/
Copy pathsecure_random.py
File metadata and controls
61 lines (55 loc) · 2.05 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
from codemodder.codemods.libcst_transformer import (
LibcstResultTransformer,
LibcstTransformerPipeline,
)
from codemodder.codemods.semgrep import SemgrepRuleDetector
from codemodder.codemods.utils_mixin import NameResolutionMixin
from core_codemods.api import CoreCodemod, Metadata, Reference, ReviewGuidance
class SecureRandomTransformer(LibcstResultTransformer, NameResolutionMixin):
change_description = (
"Replace random.{func} with more secure secrets library functions."
)
def on_result_found(self, original_node, updated_node):
self.remove_unused_import(original_node)
self.add_needed_import("secrets")
if self.find_base_name(original_node.func) == "random.choice":
return self.update_call_target(updated_node, "secrets")
return self.update_call_target(updated_node, "secrets.SystemRandom()")
SecureRandom = CoreCodemod(
metadata=Metadata(
name="secure-random",
review_guidance=ReviewGuidance.MERGE_AFTER_CURSORY_REVIEW,
summary="Secure Source of Randomness",
references=[
Reference(
url="https://owasp.org/www-community/vulnerabilities/Insecure_Randomness",
),
Reference(
url="https://docs.python.org/3/library/random.html",
),
Reference(
url="https://cwe.mitre.org/data/definitions/338",
),
Reference(
url="https://cwe.mitre.org/data/definitions/330",
),
Reference(
url="https://cwe.mitre.org/data/definitions/326",
),
Reference(
url="https://cwe.mitre.org/data/definitions/1241",
),
],
),
detector=SemgrepRuleDetector(
"""
- patterns:
- pattern: random.$F(...)
- pattern-not: random.SystemRandom()
- pattern-inside: |
import random
...
"""
),
transformer=LibcstTransformerPipeline(SecureRandomTransformer),
)