From 49cabd92d5a90627be71e05361118c396f860d9c Mon Sep 17 00:00:00 2001 From: Matt Strapp Date: Mon, 14 Feb 2022 16:01:45 -0600 Subject: replace exec with spawn Signed-off-by: Matt Strapp --- src/routes/api.ts | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) (limited to 'src/routes') diff --git a/src/routes/api.ts b/src/routes/api.ts index c538751..eb20963 100644 --- a/src/routes/api.ts +++ b/src/routes/api.ts @@ -5,7 +5,7 @@ import fileUpload, { UploadedFile } from 'express-fileupload'; import rateLimit from 'express-rate-limit'; import { access, stat } from 'fs/promises'; import { quote } from 'shell-quote'; -import { exec } from 'child_process'; +import { spawn } from 'child_process'; const api = express.Router(); @@ -85,18 +85,25 @@ api.route('/actuate') if (stats.isDirectory()) return res.status(403).json({ error: 'File is a directory.' }); - const escaped = quote([ 'python', req.body.path]); + const escaped = quote( [ req.body.path ] ); // Run the code /* TODO: MAKE THIS MORE SECURE - Execing random things is probably a bad idea, and snyk is complaining that it isn't escaped properly. */ - exec(escaped, (err, stdout, stderr) => { - if (err) - return res.status(500).json({ error: 'An unknown error occurred while executing the file.', error_msg: stderr }); - - // Return the output - res.status(200).json({ output: stdout }); + let output = ''; + // NOT PORTABLE: ASSUMES PYTHON 3 IS THERE AS WELL AS ON UNIX + // TODO: MAKE PORTABLE + const actuation = spawn('/usr/bin/python', escaped.split(' ')); + actuation.stdout.on('data', (data: Buffer) => { + output += data.toString(); + }); + actuation.stderr.on('data', (data: Buffer) => { + output += `STDERR: ${data.toString()}`; + }); + actuation.on('close', (code: number) => { + if (code !== 0) + res.status(500).json({ error: 'An unknown error occurred while running the file.', error_msg: output }); + res.status(200).json({ stdout: output }); }); }) // Fallback -- cgit v1.2.3