forked from redballoonsecurity/ofrak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build_image.py
221 lines (196 loc) · 7.31 KB
/
build_image.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
217
218
219
220
221
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional
import argparse
import os
import subprocess
import sys
import yaml
BASE_DOCKERFILE = "base.Dockerfile"
FINISH_DOCKERFILE = "finish.Dockerfile"
GIT_COMMIT_HASH = (
subprocess.check_output(["git", "rev-parse", "--short=8", "HEAD"]).decode("ascii").strip()
)
class InstallTarget(Enum):
INSTALL = "install"
DEVELOP = "develop"
@dataclass
class OfrakImageConfig:
registry: str
base_image_name: str
image_name: str
packages_paths: List[str]
build_base: bool
build_finish: bool
# Whether to supply --no-cache to docker build commands
no_cache: bool
extra_build_args: Optional[List[str]]
install_target: InstallTarget
def validate_serial_txt_existence(self):
"""
Check that the potential serial.txt file in `extra_build_args` exists on the filesystem.
Otherwise, raise an explicit error message.
"""
if (
self.extra_build_args is not None
and "id=serial,src=serial.txt" in self.extra_build_args
and not os.path.exists("serial.txt")
):
print(
"Error: file serial.txt not found.\n"
"You need a valid BinaryNinja license file, and to extract the serial number from that file "
"into a file named serial.txt in this directory.\n"
"Refer to the documentation for more details."
)
sys.exit(1)
def main():
config = parse_args()
print(
f"Building {BASE_DOCKERFILE}, {FINISH_DOCKERFILE} for {config.image_name} from: "
f"{', '.join(config.packages_paths)}."
)
for package_path in config.packages_paths:
check_package_contents(package_path)
dockerfile_base = create_dockerfile_base(config)
with open(BASE_DOCKERFILE, "w") as f:
f.write(dockerfile_base)
print(f"{BASE_DOCKERFILE} built.")
dockerfile_finish = create_dockerfile_finish(config)
with open(FINISH_DOCKERFILE, "w") as f:
f.write(dockerfile_finish)
print(f"{FINISH_DOCKERFILE} built.")
if config.build_base:
full_base_image_name = "/".join((config.registry, config.base_image_name))
base_command = [
"docker",
"build",
"--build-arg",
"BUILDKIT_INLINE_CACHE=1",
"--cache-from",
f"{full_base_image_name}:master",
"-t",
f"{full_base_image_name}:{GIT_COMMIT_HASH}",
"-t",
f"{full_base_image_name}:latest",
"-f",
BASE_DOCKERFILE,
".",
]
if config.no_cache:
base_command.extend(["--no-cache"])
# For secure build arguments
if config.extra_build_args:
base_command.extend(config.extra_build_args)
try:
subprocess.run(base_command, check=True)
except subprocess.CalledProcessError as error:
print(f"Error running command: '{' '.join(error.cmd)}'")
print(f"Exit status: {error.returncode}")
sys.exit(error.returncode)
if config.build_finish:
full_image_name = "/".join((config.registry, config.image_name))
finish_command = [
"docker",
"build",
"-t",
f"{full_image_name}:{GIT_COMMIT_HASH}",
"-t",
f"{full_image_name}:latest",
"-f",
FINISH_DOCKERFILE,
"--build-arg",
f"INSTALL_TARGET={config.install_target.value}",
".",
]
if config.no_cache:
finish_command.extend(["--no-cache"])
try:
subprocess.run(finish_command, check=True)
except subprocess.CalledProcessError as error:
print(f"Error running command: '{' '.join(error.cmd)}'")
print(f"Exit status: {error.returncode}")
sys.exit(error.returncode)
def parse_args() -> OfrakImageConfig:
parser = argparse.ArgumentParser()
parser.add_argument("--config", required=True)
parser.add_argument("--base", action="store_true")
parser.add_argument("--finish", action="store_true")
parser.add_argument("--no-cache", action="store_true")
parser.add_argument(
"--target",
choices=[InstallTarget.DEVELOP.value, InstallTarget.INSTALL.value],
default=InstallTarget.DEVELOP.value,
)
args = parser.parse_args()
with open(args.config) as file_handle:
config_dict = yaml.safe_load(file_handle)
image_config = OfrakImageConfig(
config_dict["registry"],
config_dict["base_image_name"],
config_dict["image_name"],
config_dict["packages_paths"],
args.base,
args.finish,
args.no_cache,
config_dict.get("extra_build_args"),
InstallTarget(args.target),
)
image_config.validate_serial_txt_existence()
return image_config
def check_package_contents(package_path: str):
required_contents = [
package_path,
os.path.join(package_path, "Dockerstub"),
os.path.join(package_path, "Makefile"),
]
if not all([os.path.exists(content) for content in required_contents]):
raise ValueError(
f"Package or required files (Dockerstub, Makefile) do not exist for "
f"{os.path.abspath(package_path)}"
)
return
def create_dockerfile_base(config: OfrakImageConfig) -> str:
dockerfile_base_parts = []
# Support multi-stage builds
for package_path in config.packages_paths:
if not os.path.exists(os.path.join(package_path, "Dockerstage")):
continue
with open(os.path.join(package_path, "Dockerstage")) as file_handle:
dockerstub = file_handle.read()
dockerfile_base_parts.append(dockerstub)
dockerfile_base_parts += [
"# syntax = docker/dockerfile:1.3",
"FROM python:3.7-bullseye@sha256:338ead05c1a0aa8bd8fcba8e4dbbe2afd0283b4732fd30cf9b3bfcfcbc4affab",
]
for package_path in config.packages_paths:
with open(os.path.join(package_path, "Dockerstub")) as file_handle:
dockerstub = file_handle.read()
dockerfile_base_parts.append(dockerstub)
return "\n".join(dockerfile_base_parts)
def create_dockerfile_finish(config: OfrakImageConfig) -> str:
full_base_image_name = "/".join((config.registry, config.base_image_name))
dockerfile_finish_parts = [f"FROM {full_base_image_name}:{GIT_COMMIT_HASH}\n\n"]
package_names = list()
for package_path in config.packages_paths:
package_name = os.path.basename(package_path)
package_names.append(package_name)
finish_stub_parts = [
f"ARG OFRAK_SRC_DIR=/{package_name}",
"WORKDIR $OFRAK_SRC_DIR",
f"ADD {package_path} $OFRAK_SRC_DIR",
"ARG INSTALL_TARGET",
"RUN make $INSTALL_TARGET\n\n",
]
dockerfile_finish_parts.append("\n".join(finish_stub_parts))
dockerfile_finish_parts.append("WORKDIR /\n")
finish_makefile = "\\n\\\n".join(
[
"test:",
"\\n\\\n".join([f"\tmake -C {package_name} test" for package_name in package_names]),
"",
]
)
dockerfile_finish_parts.append(f"RUN printf '{finish_makefile}' >> Makefile")
return "".join(dockerfile_finish_parts)
if __name__ == "__main__":
main()