From 065b1815309cd654ca59850905ec906d8b275d2f Mon Sep 17 00:00:00 2001 From: Eduard Urbach Date: Tue, 18 Mar 2025 22:12:46 +0100 Subject: [PATCH] Added a check for malformed request paths --- README.md | 1 + Server.go | 9 ++++++++- Server_test.go | 21 +++++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index fcfe006..149eb93 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ PASS: TestRun PASS: TestBadRequest PASS: TestBadRequestHeader PASS: TestBadRequestMethod +PASS: TestBadRequestPath PASS: TestBadRequestProtocol PASS: TestConnectionClose PASS: TestEarlyClose diff --git a/Server.go b/Server.go index ece9024..ba163a0 100644 --- a/Server.go +++ b/Server.go @@ -157,7 +157,14 @@ func (s *server) handleConnection(conn net.Conn) { lastSpace = len(message) - len("\r\n") } - url = message[space+1 : lastSpace] + space += 1 + + if space > lastSpace { + io.WriteString(conn, "HTTP/1.1 400 Bad Request\r\n\r\n") + return + } + + url = message[space:lastSpace] // Add headers until we meet an empty line for { diff --git a/Server_test.go b/Server_test.go index 013ca9b..f2c142b 100644 --- a/Server_test.go +++ b/Server_test.go @@ -110,6 +110,27 @@ func TestBadRequestMethod(t *testing.T) { s.Run(":8080") } +func TestBadRequestPath(t *testing.T) { + s := web.NewServer() + + go func() { + defer syscall.Kill(syscall.Getpid(), syscall.SIGTERM) + + conn, err := net.Dial("tcp", ":8080") + assert.Nil(t, err) + defer conn.Close() + + _, err = io.WriteString(conn, "GET \n") + assert.Nil(t, err) + + response, err := io.ReadAll(conn) + assert.Nil(t, err) + assert.Equal(t, string(response), "HTTP/1.1 400 Bad Request\r\n\r\n") + }() + + s.Run(":8080") +} + func TestBadRequestProtocol(t *testing.T) { s := web.NewServer()