首页 > 解决方案 > 试图通过套接字获取 403 错误代码

问题描述

我有一个 python 套接字编程作业。其中一项任务是通过阻止包含 /../ 的任何 URL 来防止恶意攻击

在下面的代码中,我注释掉了我希望返回 403 Forbidden 错误的代码行。但是当那行代码处于活动状态时,什么都没有发生。我正在使用 curl (--path-as-is) 从命令行执行代码,以确保 /../ 不会被剥离(例如,像 Chrome 那样)。但是,当这行代码处于活动状态时,命令提示符中不会返回任何内容。如果这行代码被注释掉,那么 curl 返回一个 52 错误代码。但最终我想返回一个 403 错误代码。

while True:
    print('Ready to serve....')
    connectionSocket, addr = serverSocket.accept() #Fill in code to get a connection
    try:
        message = connectionSocket.recv(1024).decode() #Fill in code to read GET request
        filename = message.split()[1]
        if("/../" in filename): #security code to see if there is a /../ in the filename URL
            #connectionSocket.send('HTTP/1.0 403 Forbidden\r\n'.encode()) # Send HTTP header line(s) into socket
            connectionSocket.close()
            continue;

标签: python-3.xsockets

解决方案


我的猜测是,当您激活该线路时,它会发送 403 错误并关闭套接字连接。但是,您并没有跳出循环,因此这将在您的 while 循环中继续运行而没有任何输出。尝试更改continuebreak

while True:
    print('Ready to serve....')
    connectionSocket, addr = serverSocket.accept() #Fill in code to get a connection
    try:
        message = connectionSocket.recv(1024).decode() #Fill in code to read GET request
        filename = message.split()[1]
        if("/../" in filename): #security code to see if there is a /../ in the filename URL
            connectionSocket.send('HTTP/1.0 403 Forbidden\r\n'.encode()) # Send HTTP header line(s) into socket
            connectionSocket.close()
            break;#exits the while loop

CURL 返回的错误 52

当没有来自服务器的回复时,Curl 会给出此错误,因为 HTTP 不响应任何请求是错误的。这是有道理的,因为当该行被注释掉时,您没有通过套接字发送/接收任何内容。


推荐阅读