Repository navigation
Expand file tree
/
Copy pathtransform.py
More file actions
76 lines (63 loc) · 2.34 KB
/
Copy pathtransform.py
File metadata and controls
76 lines (63 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import os
import logging
from bs4 import BeautifulSoup as Soup
logging.basicConfig(
format="%(asctime)s [%(name)s] [%(levelname)s] %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p",
)
logger = logging.getLogger(os.path.basename(__file__))
if os.environ.get("LOG_LEVEL", "").lower() == "debug":
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
def get_static(web_root, fpath):
if fpath.split("?")[0] == "/":
fpath = "index.html"
if fpath.startswith("/"):
fpath = fpath[1:]
freq = os.path.join(web_root, fpath)
# Prevent path traversal attacks by validating resolved path stays within web_root
real_path = os.path.realpath(freq)
real_web_root = os.path.realpath(web_root)
if not real_path.startswith(real_web_root + os.sep) and real_path != real_web_root:
logger.warning(f"Path traversal attempt detected: {fpath}")
return None, None
if os.path.exists(freq):
if freq.lower().endswith(".js"):
ftype = "application/javascript"
elif freq.lower().endswith(".css"):
ftype = "text/css"
elif freq.lower().endswith(".png"):
ftype = "image/png"
elif freq.lower().endswith(".html"):
ftype = "text/html"
elif freq.lower().endswith(".otf"):
ftype = "font/opentype"
elif freq.lower().endswith(".woff"):
ftype = "font/woff"
elif freq.lower().endswith(".woff2"):
ftype = "font/woff2"
elif freq.lower().endswith(".ttf"):
ftype = "font/ttf"
elif freq.lower().endswith(".svg"):
ftype = "image/svg+xml"
elif freq.lower().endswith(".eot"):
ftype = "application/vnd.ms-fontobject"
elif freq.lower().endswith(".json"):
ftype = "application/json"
elif freq.lower().endswith(".xml"):
ftype = "application/xml"
else:
ftype = "text/plain"
with open(freq, "rb") as f:
return f.read(), ftype
return None, None
def inject_js(htmlsrc, *args):
soup = Soup(htmlsrc, "html.parser")
for fpath in args:
logger.debug("Inserting Javascript file: {}".format(fpath))
script = soup.new_tag("script")
script["type"] = "text/javascript"
script["src"] = fpath
soup.body.append(script)
return str(soup)