2012-01-06 3 views
2

로컬 네트워크에서 내 가족을위한 간단한 http 서버를 만들었습니다. html 파일과 PNG 그림을 추가하고 HTML 파일을 보려고했는데 이미지를로드 할 수 없습니다.
은 말한다 :
"이미지"에 http : // :... 255/header.png가 ".이 오류를 포함하고 있기 때문에 표시 할 수 없습니다"
여기 내 코드python http 웹 서버

 elif self.path.endswith(".bm"): #our dynamic content 
      self.send_response(200) 
      self.send_header('Content-type', 'text/html') 
      self.end_headers() 
      f= open(curdir + sep + self.path) 
      ren = self.render(f.read()) 
      self.wfile.write(ren) 
      return 
     elif self.path.endswith('.png'): 
      print "IMAGE WANTED!" 
      self.send_response(200) 
      self.send_header('Content-type', 'image/png') 
      self.end_headers() 
      f = open(curdir + sep + self.path) 
      self.wfile.write(f.read()) 
      return 
     elif self.path.endswith('.jpg'): 
      print "IMAGE WANTED!" 
      self.send_response(200) 
      self.send_header('Content-type', 'image/jpeg') 
      self.end_headers() 
      f= open(curdir + sep + self.path) 
      print f.read() 
      self.wfile.write(f.read()) 
      return 
     elif self.path.endswith(".esp"): 
      self.send_response(200) 
      self.send_header('Content-type', 'text/plain') 
      self.end_headers() 
      self.wfile.write("This Format Is Not Supported Any More, Upgrade To BM Script") 
      return 

의 비트입니다 그들은 PNG 및 JPEG 부분을 제외한 모든 작업. BM 스크립트 나 자신을 esp와 동일하게 만들었습니다.

+2

넓은 보안 구멍이 열려 있기 때문에 인터넷에서 접근 할 수 없다는 것을 알려주세요 (../../../ etc/passwd \ 0'와 같은 상대 경로 허용) –

+5

왜 내장 된'python -m SimpleHTTPServer'를 사용하지 마십시오. 이것은 현재 디렉토리를 제공합니다. – wim

답변

7

기본값 모드 open'r'으로, 텍스트 데이터를 읽는 것을 의미하며 Windows에서 자동 EOL 변환을 수행합니다.

fn = os.path.normpath(os.path.join(curdir, self.path)) 
if not fn.startswith(abspath + os.path.sep): 
    raise Exception('Path traversal attempt') 
with open(fn, 'rb') as f: 
    self.wfile.write(f.read()) 

f = open(curdir + sep + self.path); self.wfile.write(f.read())를 교체 with 문은 파일 핸들의 누수를 해결합니다. 또는 (파이썬 < 2.5에서) f.close()을 수동으로 호출 할 수 있습니다.

os.path.join (파일의 시작 부분에 import os.path이 필요할 수 있음)은 문자열 연결보다 파일 이름 생성 메커니즘이 뛰어납니다. 결과 파일 이름이 예상 디렉토리에 있는지 확인하면 누구나 시스템의 모든 파일을 읽을 수있는 path traversal vulnerability을 사용할 수 없게됩니다.

+0

내가 누락되었지만, * normpath *가 경로 통과를 어떻게 방지합니까? 나의 이해는 단지 경로를 "표준화"하고, 기본적으로 그냥 정리하는 것이다. A // B, A/B /, A /./B 및 A/foo /../ B는 모두 A/B가됩니다. – monkut

+0

@monkut - normpath를 사용하여 웹 루트와 사용자 경로를 결합한 다음 웹 루트로 실제로 시작하는지 확인하십시오.'import os; root = "/ web/root"; path_from_client = "../../etc/passwd"; os.path.normpath (os.path.join (root, path_from_client)). startswith (root)' – jdi

+0

@jdi 의미가 있지만 여기서 대답은 명확하지 않습니다. * normpath *에 대한 호출만으로는 경로 통과로부터 사용자를 보호하지 못합니다. – monkut