forked from onstatus/0x0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfhost.py
executable file
·554 lines (436 loc) · 15.5 KB
/
fhost.py
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright © 2020 Mia Herkt
Licensed under the EUPL, Version 1.2 or - as soon as approved
by the European Commission - subsequent versions of the EUPL
(the "License");
You may not use this work except in compliance with the License.
You may obtain a copy of the license at:
https://joinup.ec.europa.eu/software/page/eupl
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied.
See the License for the specific language governing permissions
and limitations under the License.
"""
from flask import Flask, abort, make_response, redirect, request, send_file, send_from_directory, url_for, Response, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from jinja2.exceptions import *
from jinja2 import ChoiceLoader, FileSystemLoader, Template
from hashlib import sha256
from magic import Magic
from mimetypes import guess_extension
import click
import os
import requests
import subprocess
import sys
from validators import url as url_valid
from pathlib import Path
app = Flask(__name__, instance_relative_config=True)
app.config.update(
SQLALCHEMY_TRACK_MODIFICATIONS = False,
PREFERRED_URL_SCHEME = "https", # nginx users: make sure to have 'uwsgi_param UWSGI_SCHEME $scheme;' in your config
MAX_CONTENT_LENGTH = 256 * 1024 * 1024,
MAX_URL_LENGTH = 4096,
USE_X_SENDFILE = False,
FHOST_USE_X_ACCEL_REDIRECT = True, # expect nginx by default
FHOST_STORAGE_PATH = "up",
FHOST_MAX_EXT_LENGTH = 9,
FHOST_EXT_OVERRIDE = {
"audio/flac" : ".flac",
"image/gif" : ".gif",
"image/jpeg" : ".jpg",
"image/png" : ".png",
"image/svg+xml" : ".svg",
"video/webm" : ".webm",
"video/x-matroska" : ".mkv",
"application/octet-stream" : ".bin",
"text/plain" : ".log",
"text/plain" : ".txt",
"text/x-diff" : ".diff",
},
FHOST_MIME_BLACKLIST = [
"application/x-dosexec",
"application/java-archive",
"application/java-vm"
],
FHOST_UPLOAD_BLACKLIST = None,
NSFW_DETECT = False,
NSFW_THRESHOLD = 0.608,
URL_ALPHABET = "DEQhd2uFteibPwq0SWBInTpA_jcZL5GKz3YCR14Ulk87Jors9vNHgfaOmMXy6Vx-",
)
if not app.config["TESTING"]:
app.config.from_pyfile("config.py")
app.jinja_loader = ChoiceLoader([
FileSystemLoader(str(Path(app.instance_path) / "templates")),
app.jinja_loader
])
if app.config["DEBUG"]:
app.config["FHOST_USE_X_ACCEL_REDIRECT"] = False
if app.config["NSFW_DETECT"]:
from nsfw_detect import NSFWDetector
nsfw = NSFWDetector()
try:
mimedetect = Magic(mime=True, mime_encoding=False)
except:
print("""Error: You have installed the wrong version of the 'magic' module.
Please install python-magic.""")
sys.exit(1)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
class URL(db.Model):
id = db.Column(db.Integer, primary_key=True)
url = db.Column(db.UnicodeText, unique=True)
def __init__(self, url):
self.url = url
def __repr__(self):
return (
f"id: {self.id}, name: {self.getname()}\n"
f"url: {self.url}\n"
)
def getname(self):
return su.enbase(self.id)
def geturl(self):
return url_for("get", path=self.getname(), _external=True) + "\n"
def get(url):
u = URL.query.filter_by(url=url).first()
if not u:
u = URL(url)
db.session.add(u)
db.session.commit()
return u
class File(db.Model):
id = db.Column(db.Integer, primary_key=True)
sha256 = db.Column(db.String, unique=True)
ext = db.Column(db.UnicodeText)
mime = db.Column(db.UnicodeText)
addr = db.Column(db.UnicodeText)
removed = db.Column(db.Boolean, default=False)
nsfw_score = db.Column(db.Float)
def __init__(self, sha256, ext, mime, addr):
self.sha256 = sha256
self.ext = ext
self.mime = mime
self.addr = addr
def __repr__(self):
# using jinja here to get the filesizeformat() filter
return Template((
"id: {{ f.id }}, name: {{ su.enbase(f.id) }}, ext: {{ f.ext }}, mime: {{ f.mime }}\n"
"addr: {{ f.addr }}, removed: {{ f.removed }}, nsfw_score: {{ f.nsfw_score }}\n"
"hash: {{ f.sha256 }}\n"
"size: {% if f.getpath().is_file() %}{{ f.getpath().stat().st_size | filesizeformat(True) }}{% else %}0{% endif %}\n"
)).render(f=self, su=su)
def getname(self):
return u"{0}{1}".format(su.enbase(self.id), self.ext)
def geturl(self):
n = self.getname()
if self.nsfw_score and self.nsfw_score > app.config["NSFW_THRESHOLD"]:
return url_for("get", path=n, _external=True, _anchor="nsfw") + "\n"
else:
return url_for("get", path=n, _external=True) + "\n"
def getpath(self):
return Path(app.config["FHOST_STORAGE_PATH"]) / self.sha256
def store(file_, addr):
data = file_.stream.read()
digest = sha256(data).hexdigest()
def get_mime():
guess = mimedetect.from_buffer(data)
app.logger.debug(f"MIME - specified: '{file_.content_type}' - detected: '{guess}'")
if not file_.content_type or not "/" in file_.content_type or file_.content_type == "application/octet-stream":
mime = guess
else:
mime = file_.content_type
if mime in app.config["FHOST_MIME_BLACKLIST"] or guess in app.config["FHOST_MIME_BLACKLIST"]:
abort(415)
if mime.startswith("text/") and not "charset" in mime:
mime += "; charset=utf-8"
return mime
def get_ext(mime):
ext = "".join(Path(file_.filename).suffixes[-2:])
gmime = mime.split(";")[0]
guess = guess_extension(gmime)
app.logger.debug(f"extension - specified: '{ext}' - detected: '{guess}'")
if not ext:
if gmime in app.config["FHOST_EXT_OVERRIDE"]:
ext = app.config["FHOST_EXT_OVERRIDE"][gmime]
else:
ext = guess
return ext[:app.config["FHOST_MAX_EXT_LENGTH"]] or ".bin"
f = File.query.filter_by(sha256=digest).first()
if f:
if f.removed:
abort(451)
else:
mime = get_mime()
ext = get_ext(mime)
# strip all exif tags, saving orientation
# requires exiftool available on PATH
if app.config["STRIP_IMAGE_EXIF"] and mime.startswith("image/"):
p = subprocess.Popen(
[
"exiftool",
"-stay_open",
"true",
"-all=",
"-tagsfromfile",
"@",
"-Orientation",
"-",
],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
)
p.stdin.write(data)
p.stdin.close()
data = p.stdout.read()
digest = sha256(data).hexdigest()
f = File.query.filter_by(sha256=digest).first()
if f:
return f
f = File(digest, ext, mime, addr)
f.addr = addr
storage = Path(app.config["FHOST_STORAGE_PATH"])
storage.mkdir(parents=True, exist_ok=True)
p = storage / digest
if p.is_file():
p.touch()
else:
with open(p, "wb") as file:
file.write(data)
if not f.nsfw_score and app.config["NSFW_DETECT"]:
f.nsfw_score = nsfw.detect(p)
db.session.add(f)
db.session.commit()
return f
class UrlEncoder(object):
def __init__(self,alphabet, min_length):
self.alphabet = alphabet
self.min_length = min_length
def enbase(self, x):
n = len(self.alphabet)
str = ""
while x > 0:
str = (self.alphabet[int(x % n)]) + str
x = int(x // n)
padding = self.alphabet[0] * (self.min_length - len(str))
return '%s%s' % (padding, str)
def debase(self, x):
n = len(self.alphabet)
result = 0
for i, c in enumerate(reversed(x)):
result += self.alphabet.index(c) * (n ** i)
return result
su = UrlEncoder(alphabet=app.config["URL_ALPHABET"], min_length=1)
def fhost_url(scheme=None):
if not scheme:
return url_for(".fhost", _external=True).rstrip("/")
else:
return url_for(".fhost", _external=True, _scheme=scheme).rstrip("/")
def is_fhost_url(url):
return url.startswith(fhost_url()) or url.startswith(fhost_url("https"))
def shorten(url):
if len(url) > app.config["MAX_URL_LENGTH"]:
abort(414)
# resolve redirects
r = requests.head(url)
if 300 < r.status_code < 400:
url = r.headers['location']
if not url_valid(url) or is_fhost_url(url) or "\n" in url:
abort(400)
u = URL.get(url)
return u.geturl()
def in_upload_bl(addr):
if app.config["FHOST_UPLOAD_BLACKLIST"]:
with app.open_instance_resource(app.config["FHOST_UPLOAD_BLACKLIST"]) as bl:
check = addr.lstrip("::ffff:")
for l in bl.readlines():
if not l.startswith(b"#"):
if check == l.rstrip():
return True
return False
def store_file(f, addr):
if in_upload_bl(addr):
return "Your host is blocked from uploading files.\n", 451
sf = File.store(f, addr)
return sf.geturl()
def store_url(url, addr):
if is_fhost_url(url):
abort(400)
h = { "Accept-Encoding" : "identity" }
r = requests.get(url, stream=True, verify=False, headers=h)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
return str(e) + "\n"
if "content-length" in r.headers:
l = int(r.headers["content-length"])
if l < app.config["MAX_CONTENT_LENGTH"]:
def urlfile(**kwargs):
return type('', (), kwargs)()
f = urlfile(stream=r.raw, content_type=r.headers["content-type"], filename="")
return store_file(f, addr)
else:
abort(413)
else:
abort(411)
@app.route("/<path:path>")
def get(path):
path = Path(path.split("/", 1)[0])
sufs = "".join(path.suffixes[-2:])
name = path.name[:-len(sufs) or None]
id = su.debase(name)
if sufs:
f = File.query.get(id)
if f and f.ext == sufs:
if f.removed:
abort(451)
fpath = Path(app.config["FHOST_STORAGE_PATH"]) / f.sha256
if not fpath.is_file():
abort(404)
if app.config["FHOST_USE_X_ACCEL_REDIRECT"]:
response = make_response()
response.headers["Content-Type"] = f.mime
response.headers["Content-Length"] = fpath.stat().st_size
response.headers["X-Accel-Redirect"] = "/" + str(fpath)
return response
else:
return send_from_directory(app.config["FHOST_STORAGE_PATH"], f.sha256, mimetype=f.mime)
else:
u = URL.query.get(id)
if u:
return redirect(u.url)
abort(404)
@app.route("/", methods=["GET", "POST"])
def fhost():
if request.method == "POST":
sf = None
if "file" in request.files:
out = store_file(request.files["file"], request.remote_addr)
elif "url" in request.form:
out = store_url(request.form["url"], request.remote_addr)
elif "shorten" in request.form:
out = shorten(request.form["shorten"])
if out is not None:
return Response(out, mimetype="text/plain")
abort(400)
else:
return render_template("index.html")
@app.route("/robots.txt")
def robots():
return """User-agent: *
Disallow: /
"""
@app.route("/favicon.ico")
def favicon():
return send_file("favicon.ico")
@app.errorhandler(400)
@app.errorhandler(404)
@app.errorhandler(411)
@app.errorhandler(413)
@app.errorhandler(414)
@app.errorhandler(415)
@app.errorhandler(451)
def ehandler(e):
try:
return render_template(f"{e.code}.html", id=id), e.code
except TemplateNotFound:
return "Segmentation fault\n", e.code
# cli commands
@app.cli.command("permadelete")
@click.argument("name")
def permadelete(name):
f = File.query.get(su.debase(name))
if f:
fpath = f.getpath()
if fpath.is_file():
fpath.unlink()
f.removed = True
db.session.commit()
@app.cli.command("query")
@click.argument("name")
def query(name):
f = File.query.get(su.debase(name))
if f:
print(f)
@app.cli.command("queryhash")
@click.argument("hash")
def queryhash(hash):
f = File.query.filter_by(sha256=hash).first()
if f:
print(f)
@app.cli.command("queryaddr")
@click.argument("address")
@click.option("--nsfw", is_flag=True, default=False)
@click.option("--removed", is_flag=True, default=False)
def queryaddr(address, nsfw, removed):
res = File.query.filter_by(addr=address)
if not removed:
res = res.filter(File.removed != True)
if nsfw:
res = res.filter(File.nsfw_score > app.config["NSFW_THRESHOLD"])
for f in res:
print(f)
@app.cli.command("queryurl")
@click.argument("url")
def queryurl(url):
u = URL.query.get(su.debase(url))
if u:
print(u)
@app.cli.command("delurl")
@click.argument("url")
def delurl(url):
u = URL.query.get(su.debase(url))
if u:
print("deleting url", u)
db.session.delete(u)
db.session.commit()
@app.cli.command("deladdr")
@click.argument("address")
def deladdr(address):
res = File.query.filter_by(addr=address).filter(File.removed != True)
for f in res:
fpath = f.getpath()
if fpath.is_file():
fpath.unlink()
f.removed = True
db.session.commit()
@app.cli.command("update_nsfw")
def update_nsfw():
if not app.config["NSFW_DETECT"]:
print("NSFW detection is disabled in app config")
return 1
from multiprocessing import Pool
import tqdm
res = File.query.filter_by(nsfw_score=None, removed=False)
with Pool() as p:
results = []
work = [{"path": f.getpath(), "id": f.id} for f in res]
for r in tqdm.tqdm(p.imap_unordered(nsfw_detect, work), total=len(work)):
if r:
results.append({"id": r["id"], "nsfw_score": r["nsfw_score"]})
db.session.bulk_update_mappings(File, results)
db.session.commit()
@app.cli.command("querybl")
@click.option("--nsfw", is_flag=True, default=False)
@click.option("--removed", is_flag=True, default=False)
def querybl(nsfw, removed):
blist = []
if os.path.isfile(app.config["FHOST_UPLOAD_BLACKLIST"]):
with open(app.config["FHOST_UPLOAD_BLACKLIST"], "r") as bl:
for l in bl.readlines():
if not l.startswith("#"):
if not ":" in l:
blist.append("::ffff:" + l.rstrip())
else:
blist.append(l.strip())
res = File.query.filter(File.addr.in_(blist))
if not removed:
res = res.filter(File.removed != True)
if nsfw:
res = res.filter(File.nsfw_score > app.config["NSFW_THRESHOLD"])
for f in res:
print(f)