== How to fix it in SSH2

=== Code examples

include::../../common/fix/code-rationale.adoc[]

==== Noncompliant code example

[source,javascript,diff-id=1,diff-type=noncompliant]
----
const { Client } = require('ssh2')

const conn = new Client()
    
conn.on('ready', () => {
    conn.exec(req.query.cmd, (err, stream) => {}) // Noncompliant
})

conn.connect({
    host: 'example.org',
    username: 'user',
    password: 'password'
})
----

==== Compliant solution

[source,javascript,diff-id=1,diff-type=compliant]
----
const { Client } = require('ssh2')
const shell = require('shell-escape-tag')

const cmdId = parseInt(req.query.cmdId)
let host = req.query.host
host = typeof host === "string"? host : "example.org"
host = shell.escape(host)

const allowedCommands = ["/bin/ping -c 1 --", "/bin/host --"]
const cmd = `${allowedCommands[cmdId]} ${host}`

const conn = new Client()

conn.on('ready', () => {
    conn.exec(cmd, (err, stream) => {})
})

conn.connect({
    host: 'example.org',
    username: 'user',
    password: 'password'
})
----

=== How does this work?

include::../../common/fix/introduction.adoc[]

include::../../common/fix/pre-approved-list.adoc[]

In the example compliant code, a static list of trusted commands is used. Users are only allowed to
submit an index in this array in place of a full command name.

:sanitizationLib: shell-escape-tag

include::../../common/fix/sanitize-meta-characters.adoc[]

In the example compliant code, the `escape` function from the `shell-escape-tag` is used to properly
escape the user-supplied command argument. It can then safely be used in the
trusted command template.

=== Pitfalls

include::../common/pitfalls/loose-typing.adoc[]

In the above compliant code example, the `shell.escape` function has this
behavior. However, a type check has been introduced to prevent any unexpected
issue.
