forked from raymanfx/android-cve-checker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cve_check.py
216 lines (165 loc) · 5.94 KB
/
cve_check.py
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
import getopt
import os
import subprocess
import sys
from stats_engine import collect_stats
"""
Builds a list of git patches under a given path.
Args:
path: The path containing the patchfiles.
Returns:
A list with absolute paths to the patchfiles.
"""
def load_patches(path):
patches = []
patch_suffix = ".patch"
for node in os.listdir(path):
if node.endswith(patch_suffix):
patches.append(os.path.abspath(path) + '/' + node)
return sorted(patches)
"""
Reads the Linux version from the kernel Makefile.
Args:
kernel_repo The path to the kernel repository
Returns
Linux version string (e.g. "3.10.9").
"""
def parse_linux_version(kernel_repo):
kernel_version = ""
makefile_name = "Makefile"
version_components = ["VERSION", "PATCHLEVEL", "SUBLEVEL", "EXTRAVERSION"]
with open(kernel_repo + '/' + makefile_name) as mk:
for line in mk:
for component in version_components:
if component in line:
number = ""
try:
number = line.split('=')[1].strip()
except IndexError:
pass
kernel_version += (number + '.')
# check if we read everything
if kernel_version.count('.') == len(version_components):
# remove trailing version delimiters ('.')
while kernel_version.endswith('.'):
kernel_version = kernel_version[:-1]
return kernel_version
"""
Check if a git patch applies either cleanly or in reverse.
Args:
kernel_repo: The kernel git repository.
cve_patch: The CVE git patch to check.
Returns:
0 - patch applies cleanly
1 - patch applies in reverse (already applied?)
2 - patch does not apply
"""
def basic_check(kernel_repo, cve_patch):
# try to apply the patch in reverse
cmd = ["git", "-C", kernel_repo, "apply", "--3way", "--check", "--reverse",
cve_patch]
try:
with open(os.devnull, 'w') as silence:
subprocess.check_output(cmd, stderr=silence)
return 1
except subprocess.CalledProcessError:
# not already applied, attempt to apply it
pass
# try to apply the patch normally
cmd = ["git", "-C", kernel_repo, "apply", "--3way", "--check", cve_patch]
try:
with open(os.devnull, 'w') as silence:
subprocess.check_output(cmd, stderr=silence)
return 0
except subprocess.CalledProcessError:
# we ran out of options, probably need the advanced check..
return 2
"""
Print usage information about this program.
"""
def print_usage():
print("usage: cve_check.py <OPTIONS> cve_dir kernel_repo")
print("\noutput:")
print("\t<AC> The CVE patch applies cleanly.")
print("\t<AR> The CVE patch applies in reverse.")
print("\t<!!> The CVE patch does not apply.")
"""
Entrypoint to the Python CVE checker.
The output looks like this:
<AC> The CVE patch applies cleanly.
<AR> The CVE patch applies in reverse.
<!!> The CVE patch does not apply.
"""
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])
except getopt.GetoptError as err:
# print help information and exit
print(str(err))
print_usage()
sys.exit(2)
# check for required args
if len(sys.argv) != 3:
print("[E] Invalid number of args (required: 3, found: "
+ str(len(sys.argv)) + ")!")
print_usage()
sys.exit(2)
# directory containing the CVE patches
input_dir = sys.argv[-2]
# directory containing the kernel repo to be patched
kernel_repo = sys.argv[-1]
for o, a in opts:
if o in ("-h", "--help"):
print_usage()
sys.exit()
else:
print("[E] unhandled option: " + o)
sys.exit(2)
if not input_dir or not os.path.isdir(input_dir):
print("[E] invalid CVE input directory: " + input_dir)
return
if not kernel_repo or not os.path.isdir(kernel_repo):
print("[E] invalid kernel directory: " + kernel_repo)
return
if ".git" not in os.listdir(kernel_repo):
print("[E] kernel directory does not seem to be a git repository")
return
# read the kernel version
linux_version = parse_linux_version(kernel_repo)
# we only want VERSION + PATCHLEVEL
while linux_version.count('.') > 1:
linux_version = linux_version[:linux_version.rfind('.')]
# load the version specific patches
version_specifc_patches_dir = input_dir
if not input_dir.endswith('/'):
version_specifc_patches_dir += '/'
version_specifc_patches_dir += linux_version
patches = load_patches(version_specifc_patches_dir)
# perform the actual checking and log to console
for cve_patch in patches:
res = basic_check(kernel_repo, cve_patch)
# in case a patch does not apply, collect diff stats
if res > 1:
print("<!!> " + os.path.basename(cve_patch))
# print stats
(added, removed) = collect_stats(kernel_repo, cve_patch)
print(" stats: ", end='')
if added is not None:
(actual_plus, total_plus) = added
print(str(actual_plus) + '/' + str(total_plus)
+ " insertions(+)", end='')
if removed is not None:
# print a separator if needed
if added is not None:
print(", ", end='')
(actual_minus, total_minus) = removed
print(str(actual_minus) + '/' + str(total_minus)
+ " deletions(-)", end='')
# new line
print('')
elif res == 1:
print("<AR> " + os.path.basename(cve_patch))
elif res == 0:
print("<AC> " + os.path.basename(cve_patch))
if __name__ == "__main__":
main()