2017-12-26 07:25:29 +00:00
|
|
|
'''
|
2018-11-04 16:06:24 +00:00
|
|
|
Onionr - P2P Anonymous Storage Network
|
2018-01-14 08:48:23 +00:00
|
|
|
|
|
|
|
This file handles all incoming http requests to the client, using Flask
|
|
|
|
'''
|
|
|
|
'''
|
2017-12-26 07:25:29 +00:00
|
|
|
This program is free software: you can redistribute it and/or modify
|
|
|
|
it under the terms of the GNU General Public License as published by
|
|
|
|
the Free Software Foundation, either version 3 of the License, or
|
|
|
|
(at your option) any later version.
|
|
|
|
|
|
|
|
This program is distributed in the hope that it will be useful,
|
|
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
GNU General Public License for more details.
|
|
|
|
|
|
|
|
You should have received a copy of the GNU General Public License
|
|
|
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
'''
|
2018-12-26 06:14:05 +00:00
|
|
|
import flask, cgi
|
2018-07-27 05:48:22 +00:00
|
|
|
from flask import request, Response, abort, send_from_directory
|
2018-09-03 15:28:08 +00:00
|
|
|
from gevent.pywsgi import WSGIServer
|
2018-08-04 03:47:56 +00:00
|
|
|
import sys, random, threading, hmac, hashlib, base64, time, math, os, json
|
2018-10-27 03:29:25 +00:00
|
|
|
import core
|
2018-05-19 22:11:51 +00:00
|
|
|
from onionrblockapi import Block
|
2018-11-11 03:25:40 +00:00
|
|
|
import onionrutils, onionrexceptions, onionrcrypto, blockimporter, onionrevents as events, logger, config, onionr
|
2018-05-19 22:11:51 +00:00
|
|
|
|
2018-12-18 23:48:17 +00:00
|
|
|
def guessMime(path):
|
2018-02-04 03:44:29 +00:00
|
|
|
'''
|
2018-12-19 06:06:25 +00:00
|
|
|
Guesses the mime type of a file from the input filename
|
2018-02-04 03:44:29 +00:00
|
|
|
'''
|
2018-12-18 23:48:17 +00:00
|
|
|
mimetypes = {
|
|
|
|
'html' : 'text/html',
|
|
|
|
'js' : 'application/javascript',
|
|
|
|
'css' : 'text/css',
|
|
|
|
'png' : 'image/png',
|
|
|
|
'jpg' : 'image/jpeg'
|
|
|
|
}
|
|
|
|
|
|
|
|
for mimetype in mimetypes:
|
|
|
|
if path.endswith('.%s' % mimetype):
|
|
|
|
return mimetypes[mimetype]
|
|
|
|
|
|
|
|
return 'text/plain'
|
|
|
|
|
|
|
|
def setBindIP(filePath):
|
|
|
|
'''Set a random localhost IP to a specified file (intended for private or public API localhost IPs)'''
|
|
|
|
hostOctets = [str(127), str(random.randint(0x02, 0xFF)), str(random.randint(0x02, 0xFF)), str(random.randint(0x02, 0xFF))]
|
|
|
|
data = '.'.join(hostOctets)
|
|
|
|
|
|
|
|
with open(filePath, 'w') as bindFile:
|
|
|
|
bindFile.write(data)
|
|
|
|
return data
|
|
|
|
|
|
|
|
class PublicAPI:
|
|
|
|
'''
|
|
|
|
The new client api server, isolated from the public api
|
|
|
|
'''
|
|
|
|
def __init__(self, clientAPI):
|
|
|
|
assert isinstance(clientAPI, API)
|
|
|
|
app = flask.Flask('PublicAPI')
|
|
|
|
self.i2pEnabled = config.get('i2p.host', False)
|
|
|
|
self.hideBlocks = [] # Blocks to be denied sharing
|
|
|
|
self.host = setBindIP(clientAPI._core.publicApiHostFile)
|
2018-12-20 06:01:53 +00:00
|
|
|
self.torAdder = clientAPI._core.hsAddress
|
|
|
|
self.i2pAdder = clientAPI._core.i2pAddress
|
|
|
|
self.bindPort = config.get('client.public.port')
|
2018-12-22 19:02:09 +00:00
|
|
|
logger.info('Running public api on %s:%s' % (self.host, self.bindPort))
|
2018-12-20 06:01:53 +00:00
|
|
|
|
|
|
|
@app.before_request
|
|
|
|
def validateRequest():
|
|
|
|
'''Validate request has the correct hostname'''
|
|
|
|
if type(self.torAdder) is None and type(self.i2pAdder) is None:
|
|
|
|
# abort if our hs addresses are not known
|
|
|
|
abort(403)
|
|
|
|
if request.host not in (self.i2pAdder, self.torAdder):
|
|
|
|
abort(403)
|
|
|
|
|
|
|
|
@app.after_request
|
|
|
|
def sendHeaders(resp):
|
|
|
|
'''Send api, access control headers'''
|
|
|
|
resp.headers['Date'] = 'Thu, 1 Jan 1970 00:00:00 GMT' # Clock info is probably useful to attackers. Set to unix epoch.
|
|
|
|
resp.headers["Content-Security-Policy"] = "default-src 'none'; script-src 'none'; object-src 'none'; style-src data: 'unsafe-inline'; img-src data:; media-src 'none'; frame-src 'none'; font-src 'none'; connect-src 'none'"
|
|
|
|
resp.headers['X-Frame-Options'] = 'deny'
|
|
|
|
resp.headers['X-Content-Type-Options'] = "nosniff"
|
2018-12-22 19:02:09 +00:00
|
|
|
resp.headers['X-API'] = onionr.API_VERSION
|
2018-12-20 06:01:53 +00:00
|
|
|
return resp
|
2018-07-30 00:37:12 +00:00
|
|
|
|
2018-12-18 23:48:17 +00:00
|
|
|
@app.route('/')
|
|
|
|
def banner():
|
|
|
|
try:
|
|
|
|
with open('static-data/index.html', 'r') as html:
|
|
|
|
resp = Response(html.read(), mimetype='text/html')
|
|
|
|
except FileNotFoundError:
|
|
|
|
resp = Response("")
|
|
|
|
return resp
|
2018-12-20 06:01:53 +00:00
|
|
|
|
|
|
|
@app.route('/getblocklist')
|
|
|
|
def getBlockList():
|
|
|
|
bList = clientAPI._core.getBlockList()
|
|
|
|
for b in self.hideBlocks:
|
|
|
|
if b in bList:
|
|
|
|
bList.remove(b)
|
|
|
|
return Response('\n'.join(bList))
|
|
|
|
|
|
|
|
@app.route('/getdata/<name>')
|
2018-12-22 19:02:09 +00:00
|
|
|
def getBlockData(name):
|
2018-12-20 06:01:53 +00:00
|
|
|
resp = ''
|
2018-12-22 19:02:09 +00:00
|
|
|
data = name
|
2018-12-20 06:01:53 +00:00
|
|
|
if clientAPI._utils.validateHash(data):
|
|
|
|
if data not in self.hideBlocks:
|
|
|
|
if os.path.exists(clientAPI._core.dataDir + 'blocks/' + data + '.dat'):
|
|
|
|
block = Block(hash=data.encode(), core=clientAPI._core)
|
|
|
|
resp = base64.b64encode(block.getRaw().encode()).decode()
|
|
|
|
if len(resp) == 0:
|
|
|
|
abort(404)
|
|
|
|
resp = ""
|
|
|
|
return Response(resp)
|
|
|
|
|
2018-12-22 19:02:09 +00:00
|
|
|
@app.route('/www/<path:path>')
|
|
|
|
def wwwPublic(path):
|
|
|
|
if not config.get("www.public.run", True):
|
|
|
|
abort(403)
|
|
|
|
return send_from_directory(config.get('www.public.path', 'static-data/www/public/'), path)
|
|
|
|
|
2018-12-20 06:01:53 +00:00
|
|
|
@app.route('/ping')
|
|
|
|
def ping():
|
|
|
|
return Response("pong!")
|
2018-12-22 19:02:09 +00:00
|
|
|
|
2018-12-20 06:01:53 +00:00
|
|
|
@app.route('/getdbhash')
|
|
|
|
def getDBHash():
|
|
|
|
return Response(clientAPI._utils.getBlockDBHash())
|
2018-12-22 19:02:09 +00:00
|
|
|
|
2018-12-20 06:01:53 +00:00
|
|
|
@app.route('/pex')
|
|
|
|
def peerExchange():
|
2018-12-22 19:02:09 +00:00
|
|
|
response = ','.join(clientAPI._core.listAdders())
|
2018-12-20 06:01:53 +00:00
|
|
|
if len(response) == 0:
|
|
|
|
response = 'none'
|
2018-12-22 19:02:09 +00:00
|
|
|
return Response(response)
|
|
|
|
|
|
|
|
@app.route('/announce', methods=['post'])
|
|
|
|
def acceptAnnounce():
|
|
|
|
resp = 'failure'
|
|
|
|
powHash = ''
|
|
|
|
randomData = ''
|
|
|
|
newNode = ''
|
|
|
|
ourAdder = clientAPI._core.hsAddress.encode()
|
|
|
|
try:
|
|
|
|
newNode = request.form['node'].encode()
|
|
|
|
except KeyError:
|
|
|
|
logger.warn('No block specified for upload')
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
randomData = request.form['random']
|
|
|
|
randomData = base64.b64decode(randomData)
|
|
|
|
except KeyError:
|
|
|
|
logger.warn('No random data specified for upload')
|
|
|
|
else:
|
|
|
|
nodes = newNode + clientAPI._core.hsAddress.encode()
|
|
|
|
nodes = clientAPI._core._crypto.blake2bHash(nodes)
|
|
|
|
powHash = clientAPI._core._crypto.blake2bHash(randomData + nodes)
|
|
|
|
try:
|
|
|
|
powHash = powHash.decode()
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
if powHash.startswith('0000'):
|
|
|
|
try:
|
|
|
|
newNode = newNode.decode()
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
if clientAPI._core.addAddress(newNode):
|
|
|
|
resp = 'Success'
|
|
|
|
else:
|
|
|
|
logger.warn(newNode.decode() + ' failed to meet POW: ' + powHash)
|
|
|
|
resp = Response(resp)
|
|
|
|
return resp
|
2018-12-20 06:01:53 +00:00
|
|
|
|
|
|
|
@app.route('/upload', methods=['post'])
|
|
|
|
def upload():
|
|
|
|
resp = 'failure'
|
|
|
|
try:
|
|
|
|
data = request.form['block']
|
|
|
|
except KeyError:
|
|
|
|
logger.warn('No block specified for upload')
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
if sys.getsizeof(data) < 100000000:
|
|
|
|
try:
|
|
|
|
if blockimporter.importBlockFromData(data, clientAPI._core):
|
|
|
|
resp = 'success'
|
|
|
|
else:
|
|
|
|
logger.warn('Error encountered importing uploaded block')
|
|
|
|
except onionrexceptions.BlacklistedBlock:
|
|
|
|
logger.debug('uploaded block is blacklisted')
|
|
|
|
pass
|
|
|
|
if resp == 'failure':
|
|
|
|
abort(400)
|
|
|
|
resp = Response(resp)
|
|
|
|
return resp
|
|
|
|
|
2018-12-18 23:48:17 +00:00
|
|
|
clientAPI.setPublicAPIInstance(self)
|
2018-12-22 19:02:09 +00:00
|
|
|
while self.torAdder == '':
|
|
|
|
clientAPI._core.refreshFirstStartVars()
|
|
|
|
self.torAdder = clientAPI._core.hsAddress
|
|
|
|
time.sleep(1)
|
2018-12-20 06:01:53 +00:00
|
|
|
self.httpServer = WSGIServer((self.host, self.bindPort), app, log=None)
|
2018-12-18 23:48:17 +00:00
|
|
|
self.httpServer.serve_forever()
|
2018-08-04 02:52:45 +00:00
|
|
|
|
2018-12-18 23:48:17 +00:00
|
|
|
class API:
|
|
|
|
'''
|
|
|
|
Client HTTP api
|
|
|
|
'''
|
2018-08-04 02:52:45 +00:00
|
|
|
|
2018-12-18 23:48:17 +00:00
|
|
|
callbacks = {'public' : {}, 'private' : {}}
|
2018-08-04 02:52:45 +00:00
|
|
|
|
2018-12-22 19:02:09 +00:00
|
|
|
def __init__(self, onionrInst, debug, API_VERSION):
|
2018-02-04 03:44:29 +00:00
|
|
|
'''
|
|
|
|
Initialize the api server, preping variables for later use
|
2018-01-14 08:48:23 +00:00
|
|
|
|
2018-02-04 03:44:29 +00:00
|
|
|
This initilization defines all of the API entry points and handlers for the endpoints and errors
|
|
|
|
This also saves the used host (random localhost IP address) to the data folder in host.txt
|
2018-01-14 08:48:23 +00:00
|
|
|
'''
|
2018-12-26 06:14:05 +00:00
|
|
|
# assert isinstance(onionrInst, onionr.Onionr)
|
2018-11-11 03:25:40 +00:00
|
|
|
# configure logger and stuff
|
|
|
|
onionr.Onionr.setupConfig('data/', self = self)
|
2018-01-26 07:22:48 +00:00
|
|
|
|
2017-12-27 05:00:02 +00:00
|
|
|
self.debug = debug
|
2018-01-05 09:16:21 +00:00
|
|
|
self._privateDelayTime = 3
|
2018-10-27 03:29:25 +00:00
|
|
|
self._core = core.Core()
|
2018-02-07 09:04:58 +00:00
|
|
|
self._crypto = onionrcrypto.OnionrCrypto(self._core)
|
2018-01-26 06:28:11 +00:00
|
|
|
self._utils = onionrutils.OnionrUtils(self._core)
|
2017-12-27 05:00:02 +00:00
|
|
|
app = flask.Flask(__name__)
|
2018-12-18 23:48:17 +00:00
|
|
|
bindPort = int(config.get('client.client.port', 59496))
|
2018-01-02 08:43:29 +00:00
|
|
|
self.bindPort = bindPort
|
2018-12-18 23:48:17 +00:00
|
|
|
|
2018-12-27 05:27:46 +00:00
|
|
|
self.whitelistEndpoints = ('site', 'www', 'onionrhome', 'board', 'boardContent', 'sharedContent')
|
2018-12-26 06:14:05 +00:00
|
|
|
|
2018-12-09 17:29:39 +00:00
|
|
|
self.clientToken = config.get('client.webpassword')
|
2018-04-16 02:22:19 +00:00
|
|
|
self.timeBypassToken = base64.b16encode(os.urandom(32)).decode()
|
|
|
|
|
2018-12-18 23:48:17 +00:00
|
|
|
self.publicAPI = None # gets set when the thread calls our setter... bad hack but kinda necessary with flask
|
2018-12-22 19:02:09 +00:00
|
|
|
#threading.Thread(target=PublicAPI, args=(self,)).start()
|
2018-12-18 23:48:17 +00:00
|
|
|
self.host = setBindIP(self._core.privateApiHostFile)
|
|
|
|
logger.info('Running api on %s:%s' % (self.host, self.bindPort))
|
|
|
|
self.httpServer = ''
|
2018-12-22 19:02:09 +00:00
|
|
|
onionrInst.setClientAPIInst(self)
|
2018-05-02 06:50:29 +00:00
|
|
|
|
2018-12-19 06:06:25 +00:00
|
|
|
@app.before_request
|
|
|
|
def validateRequest():
|
|
|
|
'''Validate request has set password and is the correct hostname'''
|
|
|
|
if request.host != '%s:%s' % (self.host, self.bindPort):
|
|
|
|
abort(403)
|
2018-12-26 06:14:05 +00:00
|
|
|
if request.endpoint in self.whitelistEndpoints:
|
|
|
|
return
|
2018-12-19 06:06:25 +00:00
|
|
|
try:
|
|
|
|
if not hmac.compare_digest(request.headers['token'], self.clientToken):
|
|
|
|
abort(403)
|
|
|
|
except KeyError:
|
|
|
|
abort(403)
|
2018-12-22 19:02:09 +00:00
|
|
|
|
2018-12-19 06:06:25 +00:00
|
|
|
@app.after_request
|
|
|
|
def afterReq(resp):
|
2018-12-26 06:14:05 +00:00
|
|
|
#resp.headers["Content-Security-Policy"] = "default-src 'none'; script-src 'none'; object-src 'none'; style-src data: 'unsafe-inline'; img-src data:; media-src 'none'; frame-src 'none'; font-src 'none'; connect-src 'none'"
|
|
|
|
resp.headers['Content-Security-Policy'] = "default-src 'none'; script-src 'self'; object-src 'none'; style-src 'self'; img-src 'self'; media-src 'none'; frame-src 'none'; font-src 'none'; connect-src 'self'"
|
2018-12-19 06:06:25 +00:00
|
|
|
resp.headers['X-Frame-Options'] = 'deny'
|
|
|
|
resp.headers['X-Content-Type-Options'] = "nosniff"
|
2018-12-22 19:02:09 +00:00
|
|
|
resp.headers['X-API'] = onionr.API_VERSION
|
|
|
|
resp.headers['Server'] = ''
|
2018-12-19 06:06:25 +00:00
|
|
|
resp.headers['Date'] = 'Thu, 1 Jan 1970 00:00:00 GMT' # Clock info is probably useful to attackers. Set to unix epoch.
|
|
|
|
return resp
|
|
|
|
|
2018-12-26 06:14:05 +00:00
|
|
|
@app.route('/board/', endpoint='board')
|
|
|
|
def loadBoard():
|
|
|
|
return send_from_directory('static-data/www/board/', "index.html")
|
|
|
|
|
|
|
|
@app.route('/board/<path:path>', endpoint='boardContent')
|
|
|
|
def boardContent(path):
|
|
|
|
return send_from_directory('static-data/www/board/', path)
|
2018-12-27 05:27:46 +00:00
|
|
|
@app.route('/shared/<path:path>', endpoint='sharedContent')
|
|
|
|
def sharedContent(path):
|
|
|
|
return send_from_directory('static-data/www/shared/', path)
|
2018-12-26 06:14:05 +00:00
|
|
|
|
|
|
|
@app.route('/www/<path:path>', endpoint='www')
|
|
|
|
def wwwPublic(path):
|
|
|
|
if not config.get("www.private.run", True):
|
|
|
|
abort(403)
|
|
|
|
return send_from_directory(config.get('www.private.path', 'static-data/www/private/'), path)
|
|
|
|
|
2018-12-19 06:06:25 +00:00
|
|
|
@app.route('/ping')
|
|
|
|
def ping():
|
2018-12-22 19:02:09 +00:00
|
|
|
return Response("pong!")
|
2018-12-19 06:06:25 +00:00
|
|
|
|
2018-12-26 06:14:05 +00:00
|
|
|
@app.route('/', endpoint='onionrhome')
|
2018-12-18 23:48:17 +00:00
|
|
|
def hello():
|
2018-12-26 06:14:05 +00:00
|
|
|
return Response("Welcome to Onionr")
|
|
|
|
|
|
|
|
@app.route('/getblocksbytype/<name>')
|
|
|
|
def getBlocksByType(name):
|
|
|
|
blocks = self._core.getBlocksByType(name)
|
|
|
|
return Response(','.join(blocks))
|
|
|
|
|
|
|
|
@app.route('/gethtmlsafeblockdata/<name>')
|
|
|
|
def getData(name):
|
|
|
|
resp = ''
|
|
|
|
if self._core._utils.validateHash(name):
|
|
|
|
try:
|
|
|
|
resp = cgi.escape(Block(name).bcontent, quote=True)
|
|
|
|
except TypeError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
abort(404)
|
|
|
|
return Response(resp)
|
2018-12-20 06:01:53 +00:00
|
|
|
|
2018-12-26 06:14:05 +00:00
|
|
|
@app.route('/site/<name>', endpoint='site')
|
|
|
|
def site(name):
|
|
|
|
bHash = name
|
2018-12-20 06:01:53 +00:00
|
|
|
resp = 'Not Found'
|
|
|
|
if self._core._utils.validateHash(bHash):
|
2018-12-26 06:14:05 +00:00
|
|
|
try:
|
|
|
|
resp = Block(bHash).bcontent
|
|
|
|
except TypeError:
|
|
|
|
pass
|
2018-12-20 06:01:53 +00:00
|
|
|
try:
|
|
|
|
resp = base64.b64decode(resp)
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
if resp == 'Not Found':
|
|
|
|
abourt(404)
|
|
|
|
return Response(resp)
|
|
|
|
|
|
|
|
@app.route('/waitforshare/<name>', methods=['post'])
|
2018-12-19 06:06:25 +00:00
|
|
|
def waitforshare():
|
|
|
|
assert name.isalnum()
|
|
|
|
if name in self.publicAPI.hideBlocks:
|
|
|
|
self.publicAPI.hideBlocks.remove(name)
|
|
|
|
return Response("removed")
|
|
|
|
else:
|
|
|
|
self.publicAPI.hideBlocks.append(name)
|
|
|
|
return Response("added")
|
|
|
|
|
2018-12-18 23:48:17 +00:00
|
|
|
@app.route('/shutdown')
|
|
|
|
def shutdown():
|
2018-07-23 07:43:10 +00:00
|
|
|
try:
|
2018-12-18 23:48:17 +00:00
|
|
|
self.publicAPI.httpServer.stop()
|
|
|
|
self.httpServer.stop()
|
|
|
|
except AttributeError:
|
2018-07-23 07:43:10 +00:00
|
|
|
pass
|
2018-12-18 23:48:17 +00:00
|
|
|
return Response("bye")
|
2018-12-22 19:02:09 +00:00
|
|
|
|
2018-12-18 23:48:17 +00:00
|
|
|
self.httpServer = WSGIServer((self.host, bindPort), app, log=None)
|
|
|
|
self.httpServer.serve_forever()
|
2018-12-22 19:02:09 +00:00
|
|
|
|
2018-12-18 23:48:17 +00:00
|
|
|
def setPublicAPIInstance(self, inst):
|
|
|
|
assert isinstance(inst, PublicAPI)
|
|
|
|
self.publicAPI = inst
|
2018-05-19 21:32:21 +00:00
|
|
|
|
2018-12-18 23:48:17 +00:00
|
|
|
def validateToken(self, token):
|
2018-12-09 17:29:39 +00:00
|
|
|
'''
|
2018-12-18 23:48:17 +00:00
|
|
|
Validate that the client token matches the given token
|
2018-12-09 17:29:39 +00:00
|
|
|
'''
|
2018-12-18 23:48:17 +00:00
|
|
|
if len(self.clientToken) == 0:
|
|
|
|
logger.error("client password needs to be set")
|
2018-07-30 00:37:12 +00:00
|
|
|
return False
|
2018-12-18 23:48:17 +00:00
|
|
|
try:
|
|
|
|
if not hmac.compare_digest(self.clientToken, token):
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
except TypeError:
|
2018-12-22 19:02:09 +00:00
|
|
|
return False
|