Onionr/onionr/api.py

207 lines
7.5 KiB
Python
Raw Normal View History

2017-12-26 07:25:29 +00:00
'''
Onionr - P2P Microblogging Platform & Social network
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/>.
'''
2017-12-27 05:00:02 +00:00
import flask
from flask import request, Response, abort
from multiprocessing import Process
import configparser, sys, random, threading, hmac, hashlib, base64, time, math, gnupg, os, logger
from core import Core
2018-01-20 09:22:07 +00:00
import onionrutils
2017-12-26 07:25:29 +00:00
class API:
'''
Main HTTP API (Flask)
'''
def validateToken(self, token):
'''
Validate that the client token (hmac) matches the given token
'''
if self.clientToken != token:
return False
else:
return True
def __init__(self, config, debug):
'''
Initialize the api server, preping variables for later use
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-10 03:50:38 +00:00
if os.path.exists('dev-enabled'):
self._developmentMode = True
2018-01-26 07:22:48 +00:00
logger.set_level(logger.LEVEL_DEBUG)
logger.warn('DEVELOPMENT MODE ENABLED (THIS IS LESS SECURE!)')
2018-01-10 03:50:38 +00:00
else:
self._developmentMode = False
2018-01-26 07:22:48 +00:00
logger.set_level(logger.LEVEL_INFO)
self.config = config
2017-12-27 05:00:02 +00:00
self.debug = debug
self._privateDelayTime = 3
self._core = 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__)
bindPort = int(self.config['CLIENT']['PORT'])
self.bindPort = bindPort
self.clientToken = self.config['CLIENT']['CLIENT HMAC']
2018-01-26 07:22:48 +00:00
logger.debug('Your HMAC token: ' + logger.colors.underline + self.clientToken)
if not debug and not self._developmentMode:
hostNums = [random.randint(1, 255), random.randint(1, 255), random.randint(1, 255)]
self.host = '127.' + str(hostNums[0]) + '.' + str(hostNums[1]) + '.' + str(hostNums[2])
else:
2018-01-26 07:22:48 +00:00
self.host = '127.0.0.1'
hostFile = open('data/host.txt', 'w')
hostFile.write(self.host)
hostFile.close()
@app.before_request
def beforeReq():
'''
Simply define the request as not having yet failed, before every request.
'''
self.requestFailed = False
return
2017-12-27 05:00:02 +00:00
@app.after_request
def afterReq(resp):
if not self.requestFailed:
resp.headers['Access-Control-Allow-Origin'] = '*'
else:
resp.headers['server'] = 'Onionr'
2018-01-26 07:22:48 +00:00
resp.headers['Content-Type'] = 'text/plain'
2017-12-27 05:00:02 +00:00
resp.headers["Content-Security-Policy"] = "default-src 'none'"
2018-01-26 07:22:48 +00:00
resp.headers['X-Frame-Options'] = 'deny'
2018-01-28 01:53:24 +00:00
resp.headers['X-Content-Type-Options'] = "nosniff"
2017-12-27 05:00:02 +00:00
return resp
2018-01-26 07:22:48 +00:00
@app.route('/client/')
def private_handler():
startTime = math.floor(time.time())
# we should keep a hash DB of requests (with hmac) to prevent replays
action = request.args.get('action')
#if not self.debug:
token = request.args.get('token')
if not self.validateToken(token):
abort(403)
self.validateHost('private')
if action == 'hello':
resp = Response('Hello, World! ' + request.host)
elif action == 'shutdown':
request.environ.get('werkzeug.server.shutdown')()
resp = Response('Goodbye')
elif action == 'stats':
2018-01-26 07:22:48 +00:00
resp = Response('me_irl')
else:
resp = Response('(O_o) Dude what? (invalid command)')
endTime = math.floor(time.time())
elapsed = endTime - startTime
if elapsed < self._privateDelayTime:
time.sleep(self._privateDelayTime - elapsed)
2017-12-27 05:00:02 +00:00
return resp
@app.route('/public/')
def public_handler():
# Public means it is publicly network accessible
self.validateHost('public')
action = request.args.get('action')
2018-01-11 09:04:12 +00:00
requestingPeer = request.args.get('myID')
2018-01-18 07:49:13 +00:00
data = request.args.get('data')
2018-01-10 03:50:38 +00:00
if action == 'firstConnect':
pass
2018-01-18 07:49:13 +00:00
elif action == 'ping':
resp = Response("pong!")
elif action == 'setHMAC':
pass
2018-01-26 06:28:11 +00:00
elif action == 'getDBHash':
resp = Response(self._utils.getBlockDBHash())
elif action == 'getBlockHashes':
resp = Response(self._core.getBlockList())
2018-01-20 07:23:09 +00:00
elif action == 'getPGP':
2018-01-20 09:22:07 +00:00
resp = Response(self._utils.exportMyPubkey())
2018-01-25 22:39:09 +00:00
# setData should be something the communicator initiates, not this api
elif action == 'getData':
2018-01-27 21:49:48 +00:00
resp = self._core.getData(data)
if resp == False:
abort(404)
resp = ""
resp = Response(resp)
else:
resp = Response("")
2018-01-18 07:49:13 +00:00
return resp
2017-12-27 05:00:02 +00:00
@app.errorhandler(404)
def notfound(err):
self.requestFailed = True
resp = Response("")
return resp
@app.errorhandler(403)
def authFail(err):
self.requestFailed = True
resp = Response("403")
2017-12-27 05:00:02 +00:00
return resp
@app.errorhandler(401)
def clientError(err):
self.requestFailed = True
resp = Response("Invalid request")
return resp
2018-01-26 07:22:48 +00:00
logger.info('Starting client on ' + self.host + ':' + str(bindPort) + '...')
logger.debug('Client token: ' + logger.colors.underline + self.clientToken)
app.run(host=self.host, port=bindPort, debug=True, threaded=True)
2018-01-26 07:22:48 +00:00
def validateHost(self, hostType):
'''
Validate various features of the request including:
If private (/client/), is the host header local?
If public (/public/), is the host header onion or i2p?
2018-01-26 07:22:48 +00:00
Was X-Request-With used?
'''
2017-12-27 05:00:02 +00:00
if self.debug:
return
# Validate host header, to protect against DNS rebinding attacks
host = self.host
if hostType == 'private':
if not request.host.startswith('127') and not self._utils.checkIsIP(request.host):
abort(403)
elif hostType == 'public':
2018-01-18 07:49:13 +00:00
if not request.host.endswith('onion') and not request.host.endswith('i2p'):
abort(403)
# Validate x-requested-with, to protect against CSRF/metadata leaks
2018-01-12 09:06:24 +00:00
if not self._developmentMode:
2018-01-10 03:50:38 +00:00
try:
2018-01-26 07:22:48 +00:00
request.headers['X-Requested-With']
2018-01-10 03:50:38 +00:00
except:
# we exit rather than abort to avoid fingerprinting
2018-01-26 07:22:48 +00:00
logger.debug('Avoiding fingerprinting, exiting...')
sys.exit(1)