Skip to content
Browse files

crypto abstractions

  • Loading branch information...
1 parent 3d6d49d commit 317cfbbb588760ea95218b7755d8e6f33f4501f2 @rep committed
Showing with 89 additions and 43 deletions.
  1. +48 −0 py/pwrcall/crypto.py
  2. +15 −15 py/pwrcall/gev.py
  3. +26 −28 py/pwrcall/util.py
View
48 py/pwrcall/crypto.py
@@ -0,0 +1,48 @@
+
+import os
+
+def encrypt_openssl(*args, **kwargs): raise Exception("Function not available, install needed dependencies!")
+def decrypt_openssl(*args, **kwargs): raise Exception("Function not available, install needed dependencies!")
+def encrypt_nacl(*args, **kwargs): raise Exception("Function not available, install needed dependencies!")
+def decrypt_nacl(*args, **kwargs): raise Exception("Function not available, install needed dependencies!")
+def encrypt(*args, **kwargs): raise Exception("Function not available, install needed dependencies!")
+def decrypt(*args, **kwargs): raise Exception("Function not available, install needed dependencies!")
+
+
+try:
+ import Crypto.Cipher.AES
+ import OpenSSL.crypto
+except:
+ pass
+else:
+ def encrypt_openssl(data, secret):
+ a = Crypto.Cipher.AES.new(secret, Crypto.Cipher.AES.MODE_CFB, IV=secret)
+ return a.encrypt(data)
+
+ def decrypt_openssl(data, secret):
+ a = Crypto.Cipher.AES.new(secret, Crypto.Cipher.AES.MODE_CFB, IV=secret)
+ return a.decrypt(data)
+
+ encrypt = encrypt_openssl
+ decrypt = decrypt_openssl
+
+
+try:
+ import nacl
+except:
+ pass
+else:
+ def secretboxnonce():
+ return os.urandom(nacl.crypto_secretbox_NONCEBYTES)
+
+ def encrypt_nacl(data, secret):
+ n = secretboxnonce()
+ return secretboxnonce + nacl.crypto_secretbox(data, n, secret)
+
+ def decrypt_nacl(data, secret):
+ n, data = data[:nacl.crypto_secretbox_NONCEBYTES], data[nacl.crypto_secretbox_NONCEBYTES:]
+ return nacl.crypto_secretbox_open(data, n, secret)
+
+ encrypt = encrypt_nacl
+ encrypt = encrypt_nacl
+
View
30 py/pwrcall/gev.py
@@ -46,24 +46,21 @@ def __init__(self, sock):
def read(self):
try:
return self.sock.recv(BUFSIZE)
- except pwrtls.pwrtls_closed:
- return ''
- except socket.error:
- self.close()
+ except Exception as e:
+ self._close('recv exception: {0}'.format(e))
return ''
def write(self, data):
try: return self.sock.send(data)
- except pwrtls.pwrtls_closed:
+ except Exception as e:
+ self._close('send exception: {0}'.format(e))
return ''
- except socket.error:
- self.close()
- return 0
def _close(self, e):
- if self.sock: self.sock.close()
- self._closed = True
- self._event('close', e)
+ if not self._closed:
+ if self.sock: self.sock.close()
+ self._closed = True
+ self._event('close', e)
def close(self):
- if not self._closed: self._close(EVException('Connection closed.'))
+ self._close(EVException('Connection closed.'))
class Node(rpcnode.Node):
@@ -105,8 +102,9 @@ def listenPTLS(self, host='', port=0, backlog_limit=5, statepath=None):
if not statepath: raise NodeException('listenPTLS needs statepath!')
def handle(socket, addr):
socket = pwrtls.wrap_socket(socket, server_side=True, **pwrtls.state_file(statepath))
- socket.do_handshake()
- self._new_conn(socket, addr)
+ try: socket.do_handshake()
+ except Exception as e: logging.warn('PTLS Client handshake failure. Closing')
+ else: self._new_conn(socket, addr)
l = StreamServer((host, port), handle)
self.listeners.add(l)
@@ -211,7 +209,9 @@ def wait_for_banner(self):
tmp = ''
while not '\n' in tmp:
if len(tmp) > 100: return self.logclose('Invalid info string received. Dropping connection.')
- tmp += self.conn.read()
+ tmp2 = self.conn.read()
+ if not tmp2: return self.logclose('Closed before banner.')
+ tmp += tmp2
self.remote_info, tmp = tmp.split('\n', 1)
self.ready()
View
54 py/pwrcall/util.py
@@ -6,9 +6,9 @@
import urlparse
import hashlib
-from Crypto.Cipher import AES
-from OpenSSL import crypto
-import msgpack
+import info
+import crypto
+
class NodeException(Exception):
"""Base for Node Exceptions"""
@@ -60,13 +60,11 @@ def rand32():
return struct.unpack('I', os.urandom(4))[0]
def gen_forwarder(secret, obj, nonce, options={}):
- a = AES.new(secret, AES.MODE_CFB, IV=secret)
- return a.encrypt( msgpack.packb((nonce, id(obj), options)) )
+ return crypto.encrypt( msgpack.packb((nonce, id(obj), options)), secret )
# returns (fp, obj, nonce)
def cap_from_forwarder(secret, fwd):
- a = AES.new(secret, AES.MODE_CFB, IV=secret)
- return msgpack.unpackb( a.decrypt(fwd) )
+ return msgpack.unpackb( crypto.decrypt(fwd, secret) )
def parse_url(url):
up = urlparse.urlparse(url)
@@ -80,7 +78,7 @@ def load_cert(cert):
if not cert:
return None,''
if os.path.exists(cert):
- x509 = crypto.load_certificate(crypto.FILETYPE_PEM, open(cert, 'r').read())
+ x509 = crypto.OpenSSL.crypto.load_certificate(crypto.OpenSSL.crypto.FILETYPE_PEM, open(cert, 'r').read())
fp = x509.digest('sha1').replace(':','').lower()
return x509, fp
return None, ''
@@ -116,26 +114,26 @@ def WeakMethod(f):
def gen_selfsigned_cert(c='DE', st='NRW', l='Aachen', o='ITsec', ou='pwrcall', cn=os.urandom(10).encode('hex')):
- k = crypto.PKey()
- k.generate_key(crypto.TYPE_RSA, 1024)
-
- # create a self-signed cert
- cert = crypto.X509()
- cert.get_subject().C = c
- cert.get_subject().ST = st
- cert.get_subject().L = l
- cert.get_subject().O = o
- cert.get_subject().OU = ou
- cert.get_subject().CN = cn
- cert.set_serial_number(1000)
- cert.gmtime_adj_notBefore(0)
- cert.gmtime_adj_notAfter(10*365*24*60*60)
- cert.set_issuer(cert.get_subject())
- cert.set_pubkey(k)
- cert.sign(k, 'sha1')
-
- crtpem = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
- keypem = crypto.dump_privatekey(crypto.FILETYPE_PEM, k)
+ k = crypto.OpenSSL.crypto.PKey()
+ k.generate_key(crypto.OpenSSL.crypto.TYPE_RSA, 1024)
+
+ # create a self-signed cert
+ cert = crypto.OpenSSL.crypto.X509()
+ cert.get_subject().C = c
+ cert.get_subject().ST = st
+ cert.get_subject().L = l
+ cert.get_subject().O = o
+ cert.get_subject().OU = ou
+ cert.get_subject().CN = cn
+ cert.set_serial_number(1000)
+ cert.gmtime_adj_notBefore(0)
+ cert.gmtime_adj_notAfter(10*365*24*60*60)
+ cert.set_issuer(cert.get_subject())
+ cert.set_pubkey(k)
+ cert.sign(k, 'sha1')
+
+ crtpem = crypto.OpenSSL.crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
+ keypem = crypto.OpenSSL.crypto.dump_privatekey(crypto.FILETYPE_PEM, k)
return '\n'.join([keypem, crtpem])

0 comments on commit 317cfbb

Please sign in to comment.
Something went wrong with that request. Please try again.