Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

We’re showing branches in this repository, but you can also compare across forks.

base fork: rep/pwrcall
base: fedca34a1a
...
head fork: rep/pwrcall
compare: master
  • 19 commits
  • 9 files changed
  • 0 commit comments
  • 1 contributor
1  py/pwrcall/__init__.py
View
@@ -4,4 +4,3 @@
from .util import Referenced
from .evloop import loop, unloop, schedule
-from .sp import Process
48 py/pwrcall/crypto.py
View
@@ -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
+
8 py/pwrcall/evloop.py
View
@@ -21,7 +21,13 @@ def shutdown_callback(*args, **kwargs):
return current_evloop.shutdown_callback(*args, **kwargs)
def listenplain(*args, **kwargs):
return current_evloop.listenplain(*args, **kwargs)
+def connectplain(*args, **kwargs):
+ return current_evloop.connectplain(*args, **kwargs)
+def listenssl(*args, **kwargs):
+ return current_evloop.listenssl(*args, **kwargs)
+def connectssl(*args, **kwargs):
+ return current_evloop.connectssl(*args, **kwargs)
def later(*args, **kwargs):
return current_evloop.later(*args, **kwargs)
-hints = []
+hints = []
301 py/pwrcall/gev.py
View
@@ -0,0 +1,301 @@
+
+import socket
+import time
+import logging
+import traceback
+
+import gevent.server
+import gevent.socket
+import gevent.event
+import gevent.local
+
+from . import rpcnode
+from . import util
+from . import serialize
+from .util import NodeException, CallException, EventGen, Referenced
+from .rpcnode import RPC_REQUEST, RPC_RESPONSE, RPC_NOTIFY
+
+try: import pwrtls
+except: pwrtls = None
+
+BUFSIZE = 16*1024
+
+class EVException(Exception):
+ """Eventloop Exceptions"""
+
+
+class ConnTimeout(EVException):
+ """Eventloop Exceptions"""
+
+
+class StreamServer(gevent.server.StreamServer):
+ def close(self, *args, **kwargs):
+ self.stop(*args, **kwargs)
+
+
+class geventLoopAdapter:
+ @classmethod
+ def later(seconds, cb, *args, **kwargs):
+ gevent.core.timer(seconds, cb, *args, **kwargs)
+
+ @classmethod
+ def shutdown_callback(*args, **kwargs):
+ logging.warn('shutdown callback not implemented for gevent, yet.')
+
+
+class SockWrap(EventGen):
+ def __init__(self, sock):
+ EventGen.__init__(self)
+ self.sock = sock
+ self._closed = False
+ def read(self):
+ try:
+ return self.sock.recv(BUFSIZE)
+ except Exception as e:
+ self._close('recv exception: {0}'.format(e))
+ return ''
+ def write(self, data):
+ try: return self.sock.send(data)
+ except Exception as e:
+ self._close('send exception: {0}'.format(e))
+ return ''
+ def _close(self, e):
+ if not self._closed:
+ if self.sock: self.sock.close()
+ self._closed = True
+ self._event('close', e)
+ def close(self):
+ self._close(EVException('Connection closed.'))
+
+
+class Node(rpcnode.Node):
+ local = gevent.local.local()
+
+ def __init__(self, *args, **kwargs):
+ rpcnode.Node.__init__(self, *args, eventloop=geventLoopAdapter, **kwargs)
+
+ def refurl(self, ref):
+ return 'pwrcall://{0}@{1}/{2}'.format(self.fp, '', ref.encode('base64').strip())
+
+ def connect(self, host, port):
+ logging.info('Connecting to, {0}:{1}'.format(host, port))
+
+ c = gevent.socket.create_connection((host, port))
+
+ return self._new_conn(c, (host, port))
+
+ def connectPTLS(self, host, port, statepath=None):
+ logging.info('Connecting to, {0}:{1}'.format(host, port))
+ if not statepath: raise NodeException('PTLS needs statepath!')
+
+ c = gevent.socket.create_connection((host, port))
+ c = pwrtls.wrap_socket(c, **pwrtls.state_file(statepath))
+ c.do_handshake()
+
+ return self._new_conn(c, (host, port))
+
+ def listen(self, host='', port=0, backlog_limit=5):
+ def handle(sock, addr):
+ self._new_conn(sock, addr)
+
+ l = StreamServer((host, port), handle)
+ self.listeners.add(l)
+ l.start()
+
+ 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))
+ 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)
+ l.start()
+
+ def _new_conn(self, c, addr):
+ rc = RPCConnection(c, addr, self)
+ self._event('connection', rc, addr)
+ logging.info('New connection: {0}'.format(addr))
+ return rc
+
+ def establish(self, url):
+ try:
+ fp, hints, cap = util.parse_url(url)
+ except:
+ logging.critical('Could not parse pwrcall:// URL.')
+ raise NodeException('Could not parse pwrcall:// URL.')
+
+ # look up fingerprint in connections
+ # TODO: keep hashmap to find connections more efficiently
+ for c in self.connections:
+ if c.peerfp == fp:
+ logging.debug('Had a connection to that Node, reusing to get obj.')
+ return Referenced(c, cap)
+
+ for ip, port in hints:
+ try: c = self.connect(ip, port)
+ except socket.error:
+ continue
+
+ if c.peerfp == fp: return Referenced(c, cap)
+ else: raise NodeException('Peer public key mismatch: {0}.'.format(c.peerfp))
+
+ raise NodeException('Could not establish object connection.')
+
+ def serve_forever(self):
+ for l in self.listeners:
+ l._stopped_event.wait()
+
+class RPCConnection(rpcnode.RPCConnection):
+ def __init__(self, conn, addr, node):
+ EventGen.__init__(self)
+ self.conn = SockWrap(conn)
+ self.addr = addr
+ self.node = node
+
+ self.out_requests = {}
+ self.exports = {}
+ self.last_msgid = 0
+ self.livesign = time.time()
+ self.remote_info = ''
+ self.peerfp = 'none'
+ self.buf = ''
+
+ self.unpacker = serialize.PwrUnpacker(self)
+ self.packer = serialize.PwrPacker(self, self.gen_cap)
+ self.node.connections.add(self)
+
+ self.conn._on('close', self.closed)
+ self.negotiate()
+ self.wait_for_banner()
+
+ def ready(self):
+ self.negotiated = True
+ logging.info("Connected to remote {0} ({1}).".format(self.peerfp, self.remote_info))
+ self._event('ready')
+ self.alivegreenlet = gevent.spawn(self.keepalive)
+ self.handlegreenlet = gevent.spawn(self.handle)
+
+ def keepalive(self):
+ while True:
+ with gevent.Timeout(self.node.timeoutseconds, ConnTimeout) as timeout:
+ try:
+ r = self.call('%ping', 'ping')
+ except ConnTimeout:
+ return self.logclose('Connection timeout.')
+ except CallException:
+ # this is normal, as ping does not exist
+ pass
+ except NodeException as e:
+ # maybe connection was already closed
+ logging.info('Keepalive: {0}'.format(e))
+ break
+ except Exception as e:
+ logging.debug('Exception in keepalive: {0}'.format(e))
+ traceback.print_exc()
+ break
+ finally:
+ gevent.sleep(self.node.timeoutseconds-2)
+ if self.conn._closed: break
+
+ def call(self, ref, method, *params):
+ self.last_msgid += 1
+ callid = self.last_msgid
+ ar = gevent.event.AsyncResult()
+ self.out_requests[callid] = ar
+ self.send_request(callid, ref, method, params)
+ r = ar.get()
+ return r
+
+ def wait_for_banner(self):
+ tmp = ''
+ while not '\n' in tmp:
+ if len(tmp) > 100: return self.logclose('Invalid info string received. Dropping connection.')
+ 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()
+ self.buf += tmp
+
+ def handle(self):
+ data = self.conn.read()
+ while data:
+ try: self.unpacker.feed(data)
+ except NodeException as e: return self.close(e)
+ for item in self.unpacker:
+ if not type(item) in (list, tuple) or len(item) < 4:
+ return self.logclose('Invalid data received. Dropping connection.')
+
+ opcode, rest = item[0], item[1:]
+ handler = None
+ if opcode == RPC_REQUEST:
+ g = gevent.spawn(self.request, *rest)
+ g.link_exception(self.handler_exception)
+ elif opcode == RPC_RESPONSE:
+ self.response(*rest)
+ elif opcode == RPC_NOTIFY:
+ gevent.spawn(self.notify, *rest)
+ g.link_exception(self.handler_exception)
+ else:
+ return self.logclose('Invalid opcode. Dropping connection.')
+
+ data = self.conn.read()
+ return self.logclose('handle finished.')
+
+ def handler_exception(self, *args, **kwargs):
+ print 'handler exception:', args, kwargs
+ return self.logclose('Invalid item received. {0}'.format(args))
+
+ def request(self, msgid, ref, method, params=[]):
+ try:
+ obj = self.node.lookup(ref)
+ except NodeException as e:
+ self.send_response(msgid, str(e), None)
+ return
+
+ if isinstance(obj, Referenced):
+ # now this means we exported a referenced, that came from someone else
+ # ask him to fulfill the request
+ try: r = obj.call(method, *params)
+ except CallException as e: self.send_response(msgid, str(e), None)
+ else: self.send_response(msgid, None, r)
+ else:
+ obj.conn = self
+ Node.local.conn = self
+ try:
+ r = self.do_call(obj, method, params)
+ except NodeException as e:
+ self.send_response(msgid, str(e), None)
+ except Exception as e:
+ self.send_response(msgid, 'An exception occurred.', None)
+ traceback.print_exc()
+ else:
+ self.send_response(msgid, None, r)
+
+ def response(self, msgid, error, result):
+ if msgid in self.out_requests:
+ ar = self.out_requests.pop(msgid)
+ if error: ar.set_exception(CallException(error))
+ else: ar.set(result)
+ else:
+ logging.warn('WEIRD! msgid from response not in out_requests')
+ logging.info('Result on msgid {0}: err {1}, result {2}'.format(msgid,error,result))
+
+ def close(self, reason=None):
+ if not self.conn._closed:
+ if reason: self.conn._close(reason)
+ else: self.conn.close()
+
+ def closed(self, reason):
+ self.node._remove_connection(self)
+ logging.info('Connection closed, {0}'.format(reason))
+ ne = NodeException('Connection closed, {0}'.format(reason))
+ for ar in self.out_requests.values():
+ ar.set_exception(ne)
+ #gevent.kill(self.alivegreenlet, exception=ne)
+ self._event('close', reason)
+
16 py/pwrcall/rpcnode.py
View
@@ -75,6 +75,7 @@ def __init__(self, cert=None, eventloop=None):
self.listeners = set()
self._closing = False
self._shutdown = False
+ self.timeoutseconds = 7.0
self.exports = {}
self.directcaps = {}
self.revoked = set()
@@ -84,12 +85,6 @@ def __init__(self, cert=None, eventloop=None):
self.register(nodeFunctions(self), cap='$node')
- def connstats(self):
- print '---connstats---'
- for i in self.connections:
- print i, i.exports, i.out_requests, i.last_msgid, i.conn.buf.size, i.conn.readbytes, i.conn.writebytes
- self.eventloop.later(5, self.connstats)
-
def verify_peer(self, ok, store, *args, **kwargs):
if self.verify_hook: return self.verify_hook(ok, store, *args, **kwargs)
return True
@@ -167,7 +162,8 @@ def _shutdown_request(self):
def _remove_connection(self, c):
if not self._closing:
- self.connections.remove(c)
+ if c in self.connections: self.connections.remove(c)
+ else: logging.critical('connection to be removed not in self.connections!')
if c.peerfp:
self.peers.pop(c.peerfp, None)
logging.info('Disconnect by {0}'.format(c.addr))
@@ -276,7 +272,7 @@ def onready(self):
def node(self):
return Referenced(self, '$node')
- def negotiate(self, conn):
+ def negotiate(self, conn=None):
self.peerfp = self.conn.peerfp if hasattr(self.conn, 'peerfp') else 'plain'
self.conn.write(info.gen_banner())
@@ -292,12 +288,12 @@ def ping_response(r):
self.livesign = time.time()
if not self.conn._closed:
- if time.time() - self.livesign > 7.0:
+ if time.time() - self.livesign > self.node.timeoutseconds:
self.logclose('Connection timeout.')
else:
p = self.call('%ping', 'ping')
p._except(ping_response)
- self.node.eventloop.later(5.0, self.keepalive)
+ self.node.eventloop.later(self.node.timeoutseconds-2, self.keepalive)
def closed(self, reason):
self.node._remove_connection(self)
5 py/pwrcall/serialize.py
View
@@ -7,6 +7,7 @@
from .info import addio, choose_ioproto
# import serializers
+import serialize_bson
import serialize_msgpack
# json is python stdlib \o/
@@ -63,6 +64,8 @@ def realunpacker(self):
if not ioproto: raise NodeException('no ioproto possible?')
if ioproto == 'msgpack':
self._realunpacker = serialize_msgpack.MsgUnpacker(self.array_cb)
+ elif ioproto == 'bson':
+ self._realunpacker = serialize_bson.BsonUnpacker()
elif ioproto == 'json':
self._realunpacker = JsonUnpacker(self.array_cb)
else:
@@ -125,6 +128,8 @@ def realpacker(self):
if not ioproto: raise NodeException('no ioproto possible?')
if ioproto == 'msgpack':
self._realpacker = serialize_msgpack.MsgPacker(self.default)
+ elif ioproto == 'bson':
+ self._realpacker = serialize_bson.BsonPacker()
elif ioproto == 'json':
self._realpacker = JsonPacker(self.default)
else:
39 py/pwrcall/serialize_bson.py
View
@@ -0,0 +1,39 @@
+
+import struct
+import logging
+
+from .info import addio
+
+try: import bson
+except:
+ # msgpack not installed, do not add to supported serializers
+ pass
+else:
+ addio('bson')
+
+ class BsonUnpacker(object):
+ def __init__(self, arraycb=None):
+ self.arraycb = arraycb
+ self.buf = ''
+
+ def feed(self, data):
+ self.buf += data
+
+ def unpack(self):
+ if len(self.buf) < 4: raise StopIteration('stop')
+ framelen = struct.unpack('<i', self.buf[:4])[0]
+
+ if len(self.buf) < framelen: raise StopIteration('stop')
+
+ rest, self.buf = self.buf[:framelen], self.buf[framelen:]
+ if not bson.is_valid(rest):
+ logging.critical('Invalid BSON in frame from remote! content: {0}'.format(repr(rest)))
+ return self.unpack()
+
+ dec = bson.BSON(rest).decode()
+ return dec['data']
+
+ class BsonPacker(object):
+ def pack(self, o):
+ return bson.BSON.encode({'data': o})
+
178 py/pwrcall/sp.py
View
@@ -1,178 +0,0 @@
-
-from evnet import loop, unloop, pyev, default_loop, EVException, EventGen, later
-
-import sys
-import os
-import subprocess
-import traceback
-import fcntl
-import errno
-
-def fdnonblock(fd):
- fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)
-
-class Process(EventGen):
- def __init__(self, args):
- EventGen.__init__(self)
-
- self.buf = bytearray()
- self._writing = False
- self._closed = False
- self.retval = None
- try:
- self.p = subprocess.Popen(args, stdin=subprocess.PIPE,
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
- except Exception, e:
- self._closed = True
- self.retval = 3
- self._event('close', e)
- else:
- self.cw = pyev.Child(self.p.pid, False, default_loop, self.cw_cb)
- self.orw = pyev.Io(self.p.stdout, pyev.EV_READ, default_loop, self.orw_cb, priority=pyev.EV_MINPRI)
- self.erw = pyev.Io(self.p.stderr, pyev.EV_READ, default_loop, self.erw_cb, priority=pyev.EV_MINPRI)
- self.iww = pyev.Io(self.p.stdin, pyev.EV_WRITE, default_loop, self.iww_cb, priority=pyev.EV_MINPRI)
- fdnonblock(self.p.stdin.fileno())
- fdnonblock(self.p.stdout.fileno())
- fdnonblock(self.p.stderr.fileno())
-
- self.cw.start()
- self.orw.start()
- self.erw.start()
-
- def kill(self):
- try: self.p.kill()
- except OSError, e: self._close(e)
- def terminate(self):
- try: self.p.terminate()
- except OSError, e: self._close(e)
-
- def write(self, data):
- if self._closed: raise EVException('Already closed.')
- if not isinstance(data, bytes): data = bytes(data)
- self.buf.extend(data)
- if not self.iww.active and not self._writing: self._writeloop()
-
- def forward(self, fd, ed, watcher):
- count = 0
- while not self._closed and count < 5:
- count += 1
- try: data = fd.read(16384)
- except IOError as e:
- if e.errno == errno.EAGAIN: return
- else:
- watcher.stop()
- self._close(EVException('Exception {0}'.format(e)))
- except Exception as e:
- watcher.stop()
- self._close(EVException('Exception {0}'.format(e)))
- else:
- if not data: watcher.stop()
- else:
- try: self._event(ed, data)
- except: traceback.print_exc()
-
- def cw_cb(self, watcher, events):
- if os.WIFSIGNALED(watcher.rstatus): self.retval = -os.WTERMSIG(watcher.rstatus)
- elif os.WIFEXITED(watcher.rstatus): self.retval = os.WEXITSTATUS(watcher.rstatus)
- self._close(EVException('Child exit.'))
-
- def orw_cb(self, watcher, events):
- self.forward(self.p.stdout, 'read', watcher)
-
- def erw_cb(self, watcher, events):
- self.forward(self.p.stderr, 'readerr', watcher)
-
- def iww_cb(self, watcher, events):
- if self.iww.active: self.iww.stop()
-
- try: self._writeloop()
- except:
- traceback.print_exc()
- self._close(EVException('DEBUGWRAP'))
-
- def _writeloop(self):
- self._writing = True
- count = 0
- while not self._closed and len(self.buf)>0 and count < 5:
- count += 1
- try:
- self.p.stdin.write(self.buf[:16384])
- except IOError as e:
- if e.errno == errno.EAGAIN:
- self.iww.start()
- return
- else: self._close(EVException('Exception {0}'.format(e)))
- except Exception as e:
- self._close(EVException('Exception {0}'.format(e)))
- else:
- del self.buf[:16384]
- if len(self.buf) < 16384*2:
- self._event('writable')
-
- if len(self.buf)>0 and not self.iww.active:
- self.iww.start()
-
- self._writing = False
-
- def _close(self, e):
- if self.orw.active:
- self.orw.invoke(pyev.EV_READ)
- self.orw.stop()
- if self.erw.active:
- self.erw.invoke(pyev.EV_READ)
- self.erw.stop()
- self.p.stdout.close()
- self.p.stderr.close()
- self.p.stdin.close()
- self._closed = True
- self._event('close', e)
-
-if __name__ == '__main__':
- def incoming(data):
- print 'stdout:', data
- def incominge(data):
- print 'stderr:', data
-
- def writeto(p):
- p.write('test test test\n')
- p.write('test test test\n')
-
- def killp(p):
- print 'sending TERM'
- p.p.terminate()
- def killp2(p):
- print 'sending KILL'
- p.p.kill()
-
- def poll(p):
- print 'poll', p.p.poll(), p.p.returncode
- later(1.0, poll, p)
-
- def closed(e):
- print 'subprocess closed', e
- #unloop()
-
- def end():
- print 'end.'
- unloop()
-
- def status(p):
- print 'status', p
-
- p = Process(['/bin/nc', '-vvn', '127.0.0.1', '50000'])
- p._on('read', incoming)
- p._on('readerr', incominge)
- p._on('close', closed)
- p.write('abcdef\n')
- #later(5.0, status, p)
- later(1.0, poll, p)
-
- #later(5.0, writeto, p)
- #later(5.0, killp, p)
- #later(7.0, killp, p)
- later(15.0, end)
- loop()
- print 'sys.exit'
- sys.exit(0)
-
-
59 py/pwrcall/util.py
View
@@ -6,13 +6,18 @@
import urlparse
import hashlib
-from Crypto.Cipher import AES
-from OpenSSL import crypto
-import msgpack
+import info
+import crypto
+
+try: import msgpack
+except: pass
class NodeException(Exception):
"""Base for Node Exceptions"""
+class CallException(Exception):
+ """Call Exception"""
+
class EventGen(object):
def __init__(self):
@@ -57,13 +62,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)
@@ -77,7 +80,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, ''
@@ -113,26 +116,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.OpenSSL.crypto.FILETYPE_PEM, cert)
+ keypem = crypto.OpenSSL.crypto.dump_privatekey(crypto.OpenSSL.crypto.FILETYPE_PEM, k)
return '\n'.join([keypem, crtpem])

No commit comments for this range

Something went wrong with that request. Please try again.