Skip to content

Commit 2d7c32c

Browse files
Remove the usage of shell=True when running commands using subprocess (#1443)
* fix(bandit b602): remove the usage of shell=True when running commands using subprocess Signed-off-by: Pant, Akshay <[email protected]> * fix(execute): keyword argument name Signed-off-by: Pant, Akshay <[email protected]> * fix(execute): value type in dict Signed-off-by: Pant, Akshay <[email protected]> * fix(dockerize): command args Signed-off-by: Pant, Akshay <[email protected]> --------- Signed-off-by: Pant, Akshay <[email protected]>
1 parent 0c065b5 commit 2d7c32c

File tree

2 files changed

+91
-43
lines changed

2 files changed

+91
-43
lines changed

openfl/interface/workspace.py

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ def dockerize_(context, save: bool, rebuild: bool, enclave_key: str, base_image:
404404
options = " ".join(options)
405405
logging.info(f"Using base image: {base_image}")
406406
if enclave_key is None:
407-
_execute("openssl genrsa -out key.pem -3 3072")
407+
_execute(["openssl", "genrsa", "-out", "key.pem", "-3", "3072"])
408408
enclave_key = os.path.abspath("key.pem")
409409
logging.info(f"Generated new enclave key: {enclave_key}")
410410
else:
@@ -414,28 +414,27 @@ def dockerize_(context, save: bool, rebuild: bool, enclave_key: str, base_image:
414414
logging.info(f"Using enclave key: {enclave_key}")
415415

416416
logging.info("Building workspace image")
417-
ws_image_build_cmd = (
418-
"DOCKER_BUILDKIT=1 docker build {options} "
419-
"--build-arg WORKSPACE_NAME={workspace_name} "
420-
"--secret id=signer-key,src={enclave_key} "
421-
"-t {image_name} "
422-
"-f {dockerfile} "
423-
"{build_context}"
424-
).format(
425-
options=options,
426-
image_name=workspace_name,
427-
workspace_name=workspace_name,
428-
enclave_key=enclave_key,
429-
dockerfile=os.path.join(SITEPACKS, "openfl-docker", "Dockerfile.workspace"),
430-
build_context=".",
431-
)
432-
_execute(ws_image_build_cmd)
417+
ws_image_build_cmd = [
418+
"docker",
419+
"build",
420+
*options.split(),
421+
"--build-arg",
422+
f"WORKSPACE_NAME={workspace_name}",
423+
"--secret",
424+
f"id=signer-key,src={enclave_key}",
425+
"-t",
426+
workspace_name,
427+
"-f",
428+
os.path.join(SITEPACKS, "openfl-docker", "Dockerfile.workspace"),
429+
".",
430+
]
431+
_execute(ws_image_build_cmd, env_var={"DOCKER_BUILDKIT": "1"})
433432

434433
# Export workspace as tarball (optional)
435434
if save:
436435
logging.info("Saving workspace docker image...")
437-
save_image_cmd = "docker save {image_name} -o {image_name}.tar"
438-
_execute(save_image_cmd.format(image_name=workspace_name))
436+
save_image_cmd = ["docker", "save", workspace_name, "-o", f"{workspace_name}.tar"]
437+
_execute(save_image_cmd)
439438
logging.info(f"Docker image saved to file: {workspace_name}.tar")
440439

441440

@@ -455,7 +454,7 @@ def apply_template_plan(prefix, template):
455454
Plan.dump(prefix / "plan" / "plan.yaml", template_plan.config)
456455

457456

458-
def _execute(cmd: str, verbose=True) -> None:
457+
def _execute(cmd: str, env_var: dict = {}, verbose=True) -> None:
459458
"""Executes `cmd` as a subprocess
460459
461460
Args:
@@ -468,7 +467,7 @@ def _execute(cmd: str, verbose=True) -> None:
468467
`stdout` of the command as list of messages
469468
"""
470469
logging.info(f"Executing: {cmd}")
471-
process = subprocess.Popen(cmd, shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
470+
process = subprocess.Popen(cmd, env=env_var, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
472471
stdout_log = []
473472
for line in process.stdout:
474473
msg = line.rstrip().decode("utf-8")

openfl/utilities/ca/ca.py

Lines changed: 71 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -53,11 +53,20 @@ def get_token(name, ca_url, ca_path="."):
5353
root_crt = step_config_dir / "certs" / "root_ca.crt"
5454
try:
5555
token = subprocess.check_output(
56-
f"{step_path} ca token {name} "
57-
f"--key {priv_json} --root {root_crt} "
58-
f"--password-file {pass_file} "
59-
f"--ca-url {ca_url}",
60-
shell=True,
56+
[
57+
step_path,
58+
"ca",
59+
"token",
60+
name,
61+
"--key",
62+
priv_json,
63+
"--root",
64+
root_crt,
65+
"--password-file",
66+
pass_file,
67+
"--ca-url",
68+
ca_url,
69+
]
6170
)
6271
except subprocess.CalledProcessError as exc:
6372
logger.error("Error code %s: %s", exc.returncode, exc.output)
@@ -131,9 +140,21 @@ def certify(name, cert_path: Path, token_with_cert, ca_path: Path):
131140
with open(f"{cert_path}/root_ca.crt", mode="wb") as file:
132141
file.write(root_certificate)
133142
check_call(
134-
f"{step_path} ca certificate {name} {cert_path}/{name}.crt "
135-
f"{cert_path}/{name}.key --kty EC --curve P-384 -f --token {token}",
136-
shell=True,
143+
[
144+
step_path,
145+
"ca",
146+
"certificate",
147+
name,
148+
f"{cert_path}/{name}.crt",
149+
f"{cert_path}/{name}.key",
150+
"--kty",
151+
"EC",
152+
"--curve",
153+
"P-384",
154+
"-f",
155+
"--token",
156+
token,
157+
]
137158
)
138159

139160

@@ -186,7 +207,7 @@ def run_ca(step_ca, pass_file, ca_json):
186207
"""
187208
if _check_kill_process("step-ca", confirmation=True):
188209
logger.info("Up CA server")
189-
check_call(f"{step_ca} --password-file {pass_file} {ca_json}", shell=True)
210+
check_call([step_ca, "--password-file", pass_file, ca_json])
190211

191212

192213
def _check_kill_process(pstring, confirmation=False):
@@ -202,11 +223,22 @@ def _check_kill_process(pstring, confirmation=False):
202223
"""
203224
pids = []
204225
proc = subprocess.Popen(
205-
f"ps ax | grep {pstring} | grep -v grep",
206-
shell=True,
226+
["ps", "ax"],
227+
stdout=subprocess.PIPE,
228+
)
229+
grep_proc = subprocess.Popen(
230+
["grep", pstring],
231+
stdin=proc.stdout,
232+
stdout=subprocess.PIPE,
233+
)
234+
proc.stdout.close()
235+
grep_proc_2 = subprocess.Popen(
236+
["grep", "-v", "grep"],
237+
stdin=grep_proc.stdout,
207238
stdout=subprocess.PIPE,
208239
)
209-
text = proc.communicate()[0].decode("utf-8")
240+
grep_proc.stdout.close()
241+
text = grep_proc_2.communicate()[0].decode("utf-8")
210242

211243
for line in text.splitlines():
212244
fields = line.split()
@@ -249,21 +281,38 @@ def _create_ca(ca_path: Path, ca_url: str, password: str):
249281
shutil.rmtree(step_config_dir, ignore_errors=True)
250282
name = ca_url.split(":")[0]
251283
check_call(
252-
f"{step_path} ca init --name name --dns {name} "
253-
f"--address {ca_url} --provisioner prov "
254-
f"--password-file {pki_dir}/pass_file",
255-
shell=True,
284+
[
285+
step_path,
286+
"ca",
287+
"init",
288+
"--name",
289+
"name",
290+
"--dns",
291+
name,
292+
"--address",
293+
ca_url,
294+
"--provisioner",
295+
"prov",
296+
"--password-file",
297+
f"{pki_dir}/pass_file",
298+
]
256299
)
257300

258-
check_call(f"{step_path} ca provisioner remove prov --all", shell=True)
301+
check_call([step_path, "ca", "provisioner", "remove", "prov", "--all"])
302+
259303
check_call(
260-
f"{step_path} crypto jwk create {step_config_dir}/certs/pub.json "
261-
f"{step_config_dir}/secrets/priv.json --password-file={pki_dir}/pass_file",
262-
shell=True,
304+
[
305+
step_path,
306+
"crypto",
307+
"jwk",
308+
"create",
309+
f"{step_config_dir}/certs/pub.json",
310+
f"{step_config_dir}/secrets/priv.json",
311+
f"--password-file={pki_dir}/pass_file",
312+
]
263313
)
264314
check_call(
265-
f"{step_path} ca provisioner add provisioner {step_config_dir}/certs/pub.json",
266-
shell=True,
315+
[step_path, "ca", "provisioner", "add", "provisioner", f"{step_config_dir}/certs/pub.json"]
267316
)
268317

269318

0 commit comments

Comments
 (0)