CVE-2021-23348: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') (CWE-78)
value: This affects the package portprocesses before 1.0.5. If (attacker-controlled) user input is given to the killProcess function, it is possible for an attacker to execute arbitrary commands. This is due to use of the child_process exec function without input sanitization.
CWE description: The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
CVSS v3 base score: 8.8
Published: 2021-03-31T15:15Z
Repository: https://github.com/rrainn/PortProcesses
Language: JavaScript
Files changed: .gitignore, LICENSE, README.md, cli.js, exec.js, index.js, package.json
Commit date: 2021-03-30 21:45:27 -0600
Commit message: Merge pull request from GHSA-vm67-7vmg-66vm

Adding check to ensure function arguments are numbers
Diff: diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..3a4c858
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,73 @@
+# Logs
+logs
+*.log
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+
+# Runtime data
+pids
+*.pid
+*.seed
+*.pid.lock
+
+# Directory for instrumented libs generated by jscoverage/JSCover
+lib-cov
+
+# Coverage directory used by tools like istanbul
+coverage
+
+# nyc test coverage
+.nyc_output
+
+# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
+.grunt
+
+# Bower dependency directory (https://bower.io/)
+bower_components
+
+# node-waf configuration
+.lock-wscript
+
+# Compiled binary addons (https://nodejs.org/api/addons.html)
+build/Release
+
+# Dependency directories
+node_modules/
+jspm_packages/
+
+# TypeScript v1 declaration files
+typings/
+
+# Optional npm cache directory
+.npm
+
+# Optional eslint cache
+.eslintcache
+
+# Optional REPL history
+.node_repl_history
+
+# Output of 'npm pack'
+*.tgz
+
+# Yarn Integrity file
+.yarn-integrity
+
+# dotenv environment variables file
+.env
+
+# parcel-bundler cache (https://parceljs.org/)
+.cache
+
+# next.js build output
+.next
+
+# nuxt.js build output
+.nuxt
+
+# vuepress build output
+.vuepress/dist
+
+# Serverless directories
+.serverless
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..95da755
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2018 rrainn, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..f68dfb9
--- /dev/null
+++ b/README.md
@@ -0,0 +1,58 @@
+# PortProcesses
+
+## Install
+
+    npm install -g portprocesses
+
+## Usage
+
+### CLI
+
+The following command will list all processes running on port `8000`. You can replace `8000` with any port to get the processes running on that port. The output will be in JSON format.
+
+    portprocesses list 8000
+
+The following command will kill all processes running on port `8000`. You can replace `8000` with any port to kill the processes running on that port.
+
+    portprocesses kill 8000
+
+### Node.js
+
+The following code will list all processes running on port `8000`. You can replace `8000` with any port to get the processes running on that port.
+
+```js
+const portprocesses = require('portprocesses');
+const promise = portprocesses.listProcessesOnPort(8000); // this returns a promise
+promise.then((result) => {
+	console.log(result); // JSON array
+	// [ { command: 'node',
+	// pid: '123',
+	// user: 'user',
+	// fd: '22u',
+	// type: 'IPv4',
+	// device: '0x01abc3456d789012',
+	// 'size/off': '0t0',
+	// node: 'TCP',
+	// name: '10.0.0.1:12345->123.456.7.89:http (CLOSE_WAIT)' } ]
+});
+promise.catch((err) => {
+	console.error(err);
+});
+```
+
+The following code will kill all processes running on port `8000`. You can replace `8000` with any port to kill the processes running on that port.
+
+```js
+const portprocesses = require('portprocesses');
+const promise = portprocesses.killAllProcessesOnPort(8000); // this returns a promise
+promise.then((result) => {
+	console.log(result); // JSON array
+	// [ { pid: '123'
+	// success: true } ]
+});
+promise.catch((err) => {
+	console.error(err);
+});
+```
+
+In this case success for a given process can be false without the process throwing an error. Therefor upon success of the promise it's recommended to check the array for any items that have `success` set to `false`.
diff --git a/cli.js b/cli.js
new file mode 100644
index 0000000..f8a5eb4
--- /dev/null
+++ b/cli.js
@@ -0,0 +1,22 @@
+const main = require('./index');
+
+async function task() {
+	const argv = [...process.argv];
+	const port = process.argv.pop();
+	const command = process.argv.pop();
+
+	let result;
+	switch (command) {
+		case "kill":
+			result = await main.killAllProcessesOnPort(port);
+			console.log(result.filter(item => !item.success).map(item => `Failed to kill process ${item.pid}`).join('\n'));
+			break;
+		case "list":
+			result = await main.listProcessesOnPort(port);
+			console.log(result);
+			break;
+		default:
+			console.error("Command not found");
+	}
+}
+task();
diff --git a/exec.js b/exec.js
new file mode 100644
index 0000000..5034ad4
--- /dev/null
+++ b/exec.js
@@ -0,0 +1,13 @@
+const { exec } = require('child_process');
+
+module.exports = cmd => {
+	return new Promise((resolve, reject) => {
+		exec(cmd, (err, stdout, stderr) => {
+			if (err) {
+				reject(err);
+			} else {
+				resolve({output: stdout, error: stderr});
+			}
+		});
+	});
+};
diff --git a/index.js b/index.js
new file mode 100644
index 0000000..4812a18
--- /dev/null
+++ b/index.js
@@ -0,0 +1,51 @@
+const exec = require('./exec');
+const listProcessesOnPort = module.exports.listProcessesOnPort = async port => {
+	const portNumber = parseInt(port, 10);
+	if (Number.isNaN(portNumber)) {
+		console.error("Must provide number for port.");
+		return;
+	}
+	try {
+		const result = (await exec(`lsof -i :${portNumber}`)).output.split('\n');
+		const headers = result.shift().split(' ').filter(item => !!item.trim() && item.trim() !== "").map(item => item.toLowerCase());
+		return result.filter(item => !!item.trim() && item.trim() !== "").reduce((accumulator, currentValue) => {
+			accumulator.push(currentValue.split(' ').filter(item => !!item.trim() && item.trim() !== "").reduce((accumulator, currentValue, index) => {
+				if (index > headers.length - 1) {
+					accumulator[headers[headers.length - 1]] = (!!accumulator[headers[headers.length - 1]].trim() && accumulator[headers[headers.length - 1]].trim() !== "") ? `${accumulator[headers[headers.length - 1]]} ${currentValue}` : currentValue;
+				} else {
+					accumulator[headers[index]] = currentValue;
+				}
+				return accumulator;
+			}, {}));
+			return accumulator;
+		}, []);
+	} catch (e) {
+		console.error(e);
+	}
+};
+const killProcess = module.exports.killProcess = async pid => {
+	const pidNumber = parseInt(pid, 10);
+	if (Number.isNaN(pidNumber)) {
+		console.error("Must provide number for process identifier.");
+		return false;
+	}
+
+	try {
+		await exec(`kill ${pidNumber}`);
+		return true;
+	} catch (e) {
+		return false;
+	}
+};
+const killAllProcessesOnPort = module.exports.killAllProcessesOnPort = async port => {
+	try {
+		const processesOnPort = await listProcessesOnPort(port);
+		const killProcessResult = processesOnPort.map(theProcess => {
+			const success = killProcess(theProcess.pid);
+			return {pid: theProcess.pid, success};
+		});
+		return killProcessResult;
+	} catch (e) {
+		console.log(e);
+	}
+};
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..b4df24c
--- /dev/null
+++ b/package.json
@@ -0,0 +1,28 @@
+{
+  "name": "portprocesses",
+  "version": "1.0.4",
+  "description": "This tool letes you list and kill processes on a specified port.",
+  "main": "index.js",
+  "scripts": {
+    "test": "echo \"Error: no test specified\" && exit 1",
+    "postversion": "git push -u && git push --tags && npm publish"
+  },
+  "bin": {
+    "portprocesses": "cli.js"
+  },
+  "keywords": [
+    "process",
+    "port",
+    "manager"
+  ],
+  "author": "rrainn, Inc.",
+  "license": "MIT",
+  "repository": {
+    "type": "git",
+    "url": "git+https://github.com/rrainn/PortProcesses.git"
+  },
+  "bugs": {
+    "url": "https://github.com/rrainn/PortProcesses/issues"
+  },
+  "homepage": "https://github.com/rrainn/PortProcesses#readme"
+}

Fixed code: # Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

# parcel-bundler cache (https://parceljs.org/)
.cache

# next.js build output
.next

# nuxt.js build output
.nuxt

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless
MIT License

Copyright (c) 2018 rrainn, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# PortProcesses

## Install

    npm install -g portprocesses

## Usage

### CLI

The following command will list all processes running on port `8000`. You can replace `8000` with any port to get the processes running on that port. The output will be in JSON format.

    portprocesses list 8000

The following command will kill all processes running on port `8000`. You can replace `8000` with any port to kill the processes running on that port.

    portprocesses kill 8000

### Node.js

The following code will list all processes running on port `8000`. You can replace `8000` with any port to get the processes running on that port.

```js
const portprocesses = require('portprocesses');
const promise = portprocesses.listProcessesOnPort(8000); // this returns a promise
promise.then((result) => {
	console.log(result); // JSON array
	// [ { command: 'node',
	// pid: '123',
	// user: 'user',
	// fd: '22u',
	// type: 'IPv4',
	// device: '0x01abc3456d789012',
	// 'size/off': '0t0',
	// node: 'TCP',
	// name: '10.0.0.1:12345->123.456.7.89:http (CLOSE_WAIT)' } ]
});
promise.catch((err) => {
	console.error(err);
});
```

The following code will kill all processes running on port `8000`. You can replace `8000` with any port to kill the processes running on that port.

```js
const portprocesses = require('portprocesses');
const promise = portprocesses.killAllProcessesOnPort(8000); // this returns a promise
promise.then((result) => {
	console.log(result); // JSON array
	// [ { pid: '123'
	// success: true } ]
});
promise.catch((err) => {
	console.error(err);
});
```

In this case success for a given process can be false without the process throwing an error. Therefor upon success of the promise it's recommended to check the array for any items that have `success` set to `false`.
const main = require('./index');

async function task() {
	const argv = [...process.argv];
	const port = process.argv.pop();
	const command = process.argv.pop();

	let result;
	switch (command) {
		case "kill":
			result = await main.killAllProcessesOnPort(port);
			console.log(result.filter(item => !item.success).map(item => `Failed to kill process ${item.pid}`).join('\n'));
			break;
		case "list":
			result = await main.listProcessesOnPort(port);
			console.log(result);
			break;
		default:
			console.error("Command not found");
	}
}
task();
const { exec } = require('child_process');

module.exports = cmd => {
	return new Promise((resolve, reject) => {
		exec(cmd, (err, stdout, stderr) => {
			if (err) {
				reject(err);
			} else {
				resolve({output: stdout, error: stderr});
			}
		});
	});
};
const exec = require('./exec');
const listProcessesOnPort = module.exports.listProcessesOnPort = async port => {
	const portNumber = parseInt(port, 10);
	if (Number.isNaN(portNumber)) {
		console.error("Must provide number for port.");
		return;
	}
	try {
		const result = (await exec(`lsof -i :${portNumber}`)).output.split('\n');
		const headers = result.shift().split(' ').filter(item => !!item.trim() && item.trim() !== "").map(item => item.toLowerCase());
		return result.filter(item => !!item.trim() && item.trim() !== "").reduce((accumulator, currentValue) => {
			accumulator.push(currentValue.split(' ').filter(item => !!item.trim() && item.trim() !== "").reduce((accumulator, currentValue, index) => {
				if (index > headers.length - 1) {
					accumulator[headers[headers.length - 1]] = (!!accumulator[headers[headers.length - 1]].trim() && accumulator[headers[headers.length - 1]].trim() !== "") ? `${accumulator[headers[headers.length - 1]]} ${currentValue}` : currentValue;
				} else {
					accumulator[headers[index]] = currentValue;
				}
				return accumulator;
			}, {}));
			return accumulator;
		}, []);
	} catch (e) {
		console.error(e);
	}
};
const killProcess = module.exports.killProcess = async pid => {
	const pidNumber = parseInt(pid, 10);
	if (Number.isNaN(pidNumber)) {
		console.error("Must provide number for process identifier.");
		return false;
	}

	try {
		await exec(`kill ${pidNumber}`);
		return true;
	} catch (e) {
		return false;
	}
};
const killAllProcessesOnPort = module.exports.killAllProcessesOnPort = async port => {
	try {
		const processesOnPort = await listProcessesOnPort(port);
		const killProcessResult = processesOnPort.map(theProcess => {
			const success = killProcess(theProcess.pid);
			return {pid: theProcess.pid, success};
		});
		return killProcessResult;
	} catch (e) {
		console.log(e);
	}
};
{
  "name": "portprocesses",
  "version": "1.0.4",
  "description": "This tool letes you list and kill processes on a specified port.",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "postversion": "git push -u && git push --tags && npm publish"
  },
  "bin": {
    "portprocesses": "cli.js"
  },
  "keywords": [
    "process",
    "port",
    "manager"
  ],
  "author": "rrainn, Inc.",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/rrainn/PortProcesses.git"
  },
  "bugs": {
    "url": "https://github.com/rrainn/PortProcesses/issues"
  },
  "homepage": "https://github.com/rrainn/PortProcesses#readme"
}