Advertisement
hollerith

dodgybottle

Apr 16th, 2019
430
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 KB | None | 0 0
  1. import random
  2. import json
  3. import hashlib
  4. import binascii
  5. from ecdsa import VerifyingKey, SigningKey, NIST384p
  6. from bottle import route, run, request, debug
  7. from bottle import hook
  8. from bottle import response as resp
  9.  
  10.  
  11. def secure_rng(seed):
  12.     # Taken from the internet - probably secure
  13.     p = 2147483647
  14.     g = 2255412
  15.  
  16.     keyLength = 32
  17.     ret = 0
  18.     ths = round((p-1)/2)
  19.     for i in range(keyLength*8):
  20.         seed = pow(g,seed,p)
  21.         if seed > ths:
  22.             ret += 2**i
  23.     return ret
  24.  
  25. # Set up the keys
  26. seed = random.getrandbits(128)
  27. rand = secure_rng(seed) + 1
  28. sk = SigningKey.from_secret_exponent(rand, curve=NIST384p)
  29. vk = sk.get_verifying_key()
  30.  
  31. def verify(msg, sig):
  32.     try:
  33.         return vk.verify(binascii.unhexlify(sig), msg)
  34.     except:
  35.         return False
  36.  
  37. def sign(msg):
  38.     return binascii.hexlify(sk.sign(msg))
  39.  
  40. @route('/', method='GET')
  41. def web_root():
  42.     response = {'response':
  43.                 {
  44.                     'Application': 'Kryptos Test Web Server',
  45.                     'Status': 'running'
  46.                 }
  47.                 }
  48.     return json.dumps(response, sort_keys=True, indent=2)
  49.  
  50. @route('/eval', method='POST')
  51. def evaluate():
  52.     try:
  53.         req_data = request.json
  54.         expr = req_data['expr']
  55.         sig = req_data['sig']
  56.         # Only signed expressions will be evaluated
  57.         if not verify(str.encode(expr), str.encode(sig)):
  58.             return "Bad signature"
  59.         result = eval(expr, {'__builtins__':None}) # Builtins are removed, this should be pretty safe
  60.         response = {'response':
  61.                     {
  62.                         'Expression': expr,
  63.                         'Result': str(result)
  64.                     }
  65.                     }
  66.         return json.dumps(response, sort_keys=True, indent=2)
  67.     except:
  68.         return "Error"
  69.  
  70. # Generate a sample expression and signature for debugging purposes
  71. @route('/debug', method='GET')
  72. def debug():
  73.     expr = '2+2'
  74.     sig = sign(str.encode(expr))
  75.     response = {'response':
  76.                 {
  77.                     'Expression': expr,
  78.                     'Signature': sig.decode()
  79.                 }
  80.                 }
  81.     return json.dumps(response, sort_keys=True, indent=2)
  82.  
  83. run(host='127.0.0.1', port=81, reloader=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement