flawopen.com/command-injection/Swift
Learn how to fix Command Injection (CWE-78) in Swift. Side-by-side vulnerable vs secure code examples for Foundation Process() with argument arrays.
Imagine pedir a um assistente de escritório para imprimir um documento chamado 'relatorio.pdf'. A injeção de comando ocorre quando alguém fornece o nome 'relatorio.pdf; whoami', e o assistente entrega o bilhete inteiro ao terminal, fazendo-o imprimir o relatório e ler o crachá de administrador.
Web Application SecurityCWE-918.CWE-918Defense-in-DepthO aplicativo aceita nomes de host diagnósticos, nomes de arquivo ou flags diretamente de uma requisição HTTP ou formulário de usuário.
O backend constrói uma string de comando shell usando concatenação direta ou formatação em vez de um vetor de argumentos separado.
O invasor injeta metacaracteres shell como ';', '&&', '|' ou crases (ex: '127.0.0.1; id') para quebrar o contexto pretendido do comando.
O shell do sistema operacional executa o comando anexado com todos os privilégios do processo web em execução.
// Calling /bin/sh with string interpolation
import Foundation
func ping(host: String) {
// Attacker input: "127.0.0.1; whoami"
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/sh")
process.arguments = ["-c", "ping -c 1 \(host)"]
try? process.run()
}
// Calling binary directly with isolated arguments array
import Foundation
func ping(host: String) {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/sbin/ping")
// host is strictly an argument, never parsed as a shell command
process.arguments = ["-c", "1", host]
try? process.run()
}
system() function in Swift.