def threadSMIME(): # Seed the PRNG. Rand.load_file('randpool.dat', -1) # Instantiate an SMIME object. s = SMIME.SMIME() # Load target cert to encrypt to. x509 = X509.load_cert('recipient.pem') sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) # Set cipher: 3-key triple-DES in CBC mode. s.set_cipher(SMIME.Cipher('des_ede3_cbc')) # Encrypt the buffer. p7 = s.encrypt(buf) # Output p7 in mail-friendly format. out = BIO.MemoryBuffer() out.write('From: [email protected]\n') out.write('To: [email protected]\n') out.write('Subject: M2Crypto S/MIME testing\n') s.write(out, p7) print out.read() # Save the PRNG's state. Rand.save_file('randpool.dat')
def main(keylen, hashalg): global rsa, dgst # this exists ONLY for speed testing Rand.load_file('randpool.dat', -1) pvtkeyfilename = 'rsa%dpvtkey.pem' % (keylen) pubkeyfilename = 'rsa%dpubkey.pem' % (keylen) if makenewkey: print ' making and saving a new key' rsa = RSA.gen_key(keylen, exponent) rsa.save_key(pvtkeyfilename, None ) # no pswd callback rsa.save_pub_key(pubkeyfilename) else: print ' loading an existing key' rsa = RSA.load_key(pvtkeyfilename) print ' rsa key length:', len(rsa) if not rsa.check_key(): raise 'key is not initialised' # since we are testing signing and verification, let's not # be fussy about the digest. Just make one. md = EVP.MessageDigest(hashalg) md.update('can you spell subliminal channel?') dgst = md.digest() print ' hash algorithm: %s' % hashalg if showdigest: print ' %s digest: \n%s' % (hashalg, base64.encodestring(dgst)) test(rsa, dgst) # test_asn1(rsa, dgst) test_speed(rsa, dgst) Rand.save_file('randpool.dat')
def get_ssl_context(): from M2Crypto import Rand Rand.load_file('randpool.dat', -1) ctx = init_context('sslv23', 'server.pem', 'ca.pem', SSL.verify_none) #SSL.verify_peer | SSL.verify_fail_if_no_peer_cert) ctx.set_tmp_dh('dh1024.pem') Rand.save_file('randpool.dat') return ctx
def shutdown(profileDir): """ Shut down the cryptographic services. You must call startup() before doing cryptographic operations again. @param profileDir: The profile directory. A snapshot of current entropy state will be saved into a file in this directory. It is not a fatal error if the file cannot be created. """ Rand.save_file(_randpoolPath(profileDir)) m2threading.cleanup()
def __init__(self, handler, host='localhost', port=8000): threading.init() Rand.load_file('../randpool.dat', -1) ctx=echod_lib.init_context('sslv3','server.pem', 'ca.pem', SSL.verify_peer) ctx.set_tmp_dh('dh1024.pem') config = Config() server = TCPServer.__connection(self, host, port) while 1: server.OpenConnection() server.HandleConnection(handler,config.config,ctx) server.CloseConnection() Rand.save_file('../randpool.dat') threading.cleanup()
def test_load_save(self): try: os.remove('tests/randpool.dat') except OSError: pass self.assertIn(Rand.load_file('tests/randpool.dat', -1), [0, -1]) self.assertEqual(Rand.save_file('tests/randpool.dat'), 1024) self.assertEqual(Rand.load_file('tests/randpool.dat', -1), 1024)
def test_load_save(self): try: os.remove("test/randpool.dat") except OSError: pass assert Rand.load_file("test/randpool.dat", -1) == 0 assert Rand.save_file("test/randpool.dat") == 1024 assert Rand.load_file("test/randpool.dat", -1) == 1024
def main(curve, hashalg): global ec, dgst # this exists ONLY for speed testing Rand.load_file('randpool.dat', -1) if curve in curves2: curve = 'X9_62_' + curve ec_curve = eval('EC.NID_%s' % curve) pvtkeyfilename = '%spvtkey.pem' % (curve) pubkeyfilename = '%spubkey.pem' % (curve) if makenewkey: print ' making and saving a new key' ec = EC.gen_params(ec_curve) ec.gen_key() ec.save_key(pvtkeyfilename, None ) ec.save_pub_key(pubkeyfilename) else: print ' loading an existing key' ec=EC.load_key(pvtkeyfilename) print ' ecdsa key length:', len(ec) print ' curve: %s' % curve if not ec.check_key(): raise 'key is not initialised' if showpubkey: ec_pub = ec.pub() pub_der = ec_pub.get_der() pub_pem = base64.encodestring(pub_der) print ' PEM public key is: \n',pub_pem # since we are testing signing and verification, let's not # be fussy about the digest. Just make one. md = EVP.MessageDigest(hashalg) md.update('can you spell subliminal channel?') dgst = md.digest() print ' hash algorithm: %s' % hashalg if showdigest: print ' %s digest: \n%s' % (base64.encodestring(dgst)) test(ec, dgst) # test_asn1(ec, dgst) test_speed(ec, dgst) Rand.save_file('randpool.dat')
def runall(report_leaks=0): report_leaks = report_leaks if report_leaks: import gc gc.enable() gc.set_debug(gc.DEBUG_LEAK & ~gc.DEBUG_SAVEALL) import os, unittest from M2Crypto import Rand try: Rand.load_file('tests/randpool.dat', -1) unittest.TextTestRunner(verbosity=2).run(suite()) Rand.save_file('tests/randpool.dat') finally: if os.name == 'posix': from test_ssl import zap_servers zap_servers() if report_leaks: dump_garbage()
def stopCrypto(profileDir): """ Shut down the cryptographic services. You must call startup() before doing cryptographic operations again. @param profileDir: The profile directory. A snapshot of current entropy state will be saved into a file in this directory. It is not a fatal error if the file cannot be created. @return: The number of bytes saved to file. """ from osaf.framework.certstore import utils ret = 0 if utils.entropyInitialized: ret = Rand.save_file(_randpoolPath(profileDir)) m2threading.cleanup() return ret
def init(data_dir): """Sets the directory in which to store crypto data/randfile @param data_dir: path to directory @type data_dir: string """ threading.init() global get_rand global global_cryptodir, global_randfile, global_dd, global_certpath if None not in (global_cryptodir, global_randfile): log.warning("Crypto already initialized with root directory: %s. Not using %s." % (global_dd, data_dir)) return # Initialize directory structure global_dd = data_dir global_cryptodir = os.path.join(data_dir, 'crypto') if not os.path.exists(data_dir): os.mkdir(data_dir, 0700) if not os.path.exists(global_cryptodir): os.mkdir(global_cryptodir, 0700) # Copy the default certificates into the user's crypto dir global_certpath = os.path.join(global_cryptodir, 'default_certificates') if not os.path.exists(global_certpath): from Anomos import app_root shutil.copytree(os.path.join(app_root, 'default_certificates'), global_certpath) # Initialize randfile global_randfile = os.path.join(global_cryptodir, 'randpool.dat') if Rand.save_file(global_randfile) == 0: raise CryptoError('Rand file not writable') @use_rand_file def randfunc(numBytes=32): rb = Rand.rand_bytes(numBytes); return rb get_rand = randfunc # Make Crypto objects accessible now that init has been called. global AESKey, Certificate, PeerCert import _AESKey, _Certificate, _PeerCert AESKey = _AESKey.AESKey Certificate = _Certificate.Certificate PeerCert = _PeerCert.PeerCert
class HTTPS_Server(SSLServer): def __init__(self, ME, HandlerClass, sslctx): SSLServer.__init__(self, ME, HandlerClass, sslctx) self.tracefile = None def finish(self): self.request.set_shutdown(SSL.SSL_RECEIVED_SHUTDOWN | SSL.SSL_SENT_SHUTDOWN) self.request.close() def init_ssl_context(dir, debug=None): ctx = SSL.Context('sslv23') if debug: ctx.set_info_callback() ctx.load_cert(certfile=dir+'/cert.pem', keyfile=dir+'/plainkey.pem') ctx.set_verify(SSL.verify_none, 1) ctx.set_allow_unknown_ca(1) ctx.set_session_id_ctx('xkms_srv') return ctx dir = os.environ.get('XKMSHOME', '/opt/xkms') + '/openssl/ssl' randfile = dir + '/xkms-ca/.rand' Rand.load_file(randfile, -1) sslctx = init_ssl_context(dir, 1) s = HTTPS_Server(('', 9999), XKMSRequestHandler, sslctx) s.tracefile=sys.stderr try: s.serve_forever() except KeyboardInterrupt: print "Quitting..." pass Rand.save_file(randfile)
# openssl must be started in the tests directory for it # to find the .pem files os.chdir('tests') try: hproc, _, _, _ = win32process.CreateProcess( self.openssl, ' '.join(args), None, None, 0, win32process.DETACHED_PROCESS, None, None, self.startupinfo) finally: os.chdir('..') time.sleep(0.3) return hproc def stop_server(self, hproc): win32process.TerminateProcess(hproc, 0) def suite(): return unittest.makeSuite(SSLWinClientTestCase) def zap_servers(): pass if __name__ == '__main__': try: if find_openssl() is not None: Rand.load_file('randpool.dat', -1) unittest.TextTestRunner().run(suite()) Rand.save_file('randpool.dat') finally: zap_servers()
ctx = SSL.Context('sslv3') ctx.load_cert('client.pem') #ctx.load_verify_info('ca.pem') ctx.set_verify(SSL.verify_peer, 10) ctx.set_info_callback() s = SSL.Connection(ctx) s.connect((host, port)) print 'Host =', gethostname() print 'Cipher =', s.get_cipher().name() peer = s.get_peer_cert() print 'Server =', peer.get_subject().CN while 1: data = s.recv() if not data: break sys.stdout.write(data) sys.stdout.flush() buf = sys.stdin.readline() if not buf: break s.send(buf) s.close() Rand.save_file('../randpool.dat')
def send_mail_ssl(server, sender, to, to_cert, subject, text, files=[], attachments={}, send=False): """ Sends SSL signed mail server - mailserver domain name eg. smtp.foo.bar sender - content of From field eg. "No Reply" <*****@*****.**> to - string with email addresses of recipent subject - subject of a mail text - text of email files - list of strings with paths to file to be attached attachmets - dict where keys are file names and values are content of files to be attached send - bool whether message should really be sent """ # create multipart message msg = MIMEMultipart() # attach message text as first attachment msg.attach(MIMEText(text)) # attach files to be read from file system for file in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(file, "rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) # attach filest read from dictionary for name in attachments: part = MIMEBase('application', "octet-stream") part.set_payload(attachments[name]) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % name) msg.attach(part) msg_str = msg.as_string() # Make a MemoryBuffer of the message. buf = BIO.MemoryBuffer(msg_str) # Seed the PRNG. Rand.load_file('randpool.dat', -1) # Instantiate an SMIME object. s = SMIME.SMIME() # Load target cert to encrypt to. x509 = X509.load_cert_string(to_cert) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) # Set cipher: 3-key triple-DES in CBC mode. s.set_cipher(SMIME.Cipher('des_ede3_cbc')) # Encrypt the buffer. p7 = s.encrypt(buf) # Output p7 in mail-friendly format. out = BIO.MemoryBuffer() out.write('From: %s\n' % sender) out.write('To: %s\n' % to) out.write('Subject: %s\n' % subject) # append signed message and original message to mail header s.write(out, p7) # Save the PRNG's state. Rand.save_file('randpool.dat') # finally send mail if send: # print("would have sent") smtp = smtplib.SMTP(server) smtp.sendmail(sender, to, out.read() ) smtp.close() else: print("sending is disabled (use --send)")
hss = https_server.https_server('', HTTPS_PORT, ssl_ctx) fs = filesys.os_filesystem(os.path.abspath(os.curdir)) #fs=filesys.os_filesystem('/usr/local/pkg/apache/htdocs') #fs=filesys.os_filesystem('c:/pkg/jdk130/docs') dh = default_handler.default_handler(fs) hs.install_handler(dh) hss.install_handler(dh) #class rpc_demo (xmlrpc_handler.xmlrpc_handler): # def call (self, method, params): # print 'method="%s" params=%s' % (method, params) # return "Sure, that works" #rpch = rpc_demo() #hs.install_handler(rpch) #hss.install_handler(rpch) ph = poison_handler.poison_handler(10) hs.install_handler(ph) hss.install_handler(ph) fauthz = ftp_server.anon_authorizer('/usr/local/pkg/apache/htdocs') ftps = ftps_server.ftp_tls_server(fauthz, ssl_ctx, port=FTP_PORT) sh = status_handler.status_extension([hs, hss, ftps]) hs.install_handler(sh) hss.install_handler(sh) asyncore.loop() Rand.save_file('../randpool.dat')
# XXX Cleanup the stack and store. msg = """ S/MIME - Secure Multipurpose Internet Mail Extensions [RFC 2311, RFC 2312] - provides a consistent way to send and receive secure MIME data. Based on the popular Internet MIME standard, S/MIME provides the following cryptographic security services for electronic messaging applications - authentication, message integrity and non-repudiation of origin (using digital signatures) and privacy and data security (using encryption). S/MIME is built on the PKCS #7 standard. [PKCS7] S/MIME is implemented in Netscape Messenger and Microsoft Outlook. """ if __name__ == "__main__": Rand.load_file("../randpool.dat", -1) sendsmime( from_addr="*****@*****.**", to_addrs=["*****@*****.**"], subject="S/MIME testing", msg=msg, # from_key = 'signer.pem', from_key=None, # to_certs = None) to_certs=["recipient.pem"], ) Rand.save_file("../randpool.dat")
# Buffer buf = BIO.MemoryBuffer(json) # Seed the PRNG Rand.load_file(rand, -1) # S/MIME object s = SMIME.SMIME() # Load certificate x509 = X509.load_cert(cert) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) #Set cipher: 3-key triple-DES in CBC mode. s.set_cipher(SMIME.Cipher('des_ede3_cbc')) # Encrypt the buffer. p7 = s.encrypt(buf) #p7 = s.sign(buf) out = BIO.MemoryBuffer() s.write(out, p7) smime = out.read() print smime headers, body = smime.split('\n\n', 1) # Rand.save_file(rand)
pass except: raise # Check umask sanity if we're on posix. if os.name == 'posix' and not os.environ.get('Z_DEBUG_MODE'): # umask is silly, blame POSIX. We have to set it to get its value. current_umask = os.umask(0) os.umask(current_umask) if current_umask != 077: current_umask = '%03o' % current_umask zLOG.LOG("z2", zLOG.INFO, ( 'Your umask of %s may be too permissive; for the security of ' 'your Zope data, it is recommended you use 077' % current_umask )) except: # Log startup exception and tell zdaemon not to restart us. try: zLOG.LOG("z2", zLOG.PANIC, "Startup exception", error=sys.exc_info()) except: pass sys.exit(0) # Start Medusa, Ye Hass! Rand.load_file('%s/randpool.dat' % INSTANCE_HOME, -1) sys.ZServerExitCode=0 asyncore.loop() Rand.save_file('%s/randpool.dat' % INSTANCE_HOME) sys.exit(sys.ZServerExitCode)
def retfun(*args, **kwargs): Rand.load_file(global_randfile, -1) r = function(*args, **kwargs) Rand.save_file(global_randfile) return r
# Load target cert to encrypt the signed message to. x509 = X509.load_cert("recipient.pem") sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) # Set cipher: 3-key triple-DES in CBC mode. s.set_cipher(SMIME.Cipher("des_ede3_cbc")) # Create a temporary buffer. tmp = BIO.MemoryBuffer() # Write the signed message into the temporary buffer. s.write(tmp, p7) # Encrypt the temporary buffer. p7 = s.encrypt(tmp) # Output p7 in mail-friendly format. out = BIO.MemoryBuffer() out.write("From: [email protected]\n") out.write("To: [email protected]\n") out.write("Subject: M2Crypto S/MIME testing\n") s.write(out, p7) print out.read() # Save the PRNG's state. Rand.save_file("randpool.dat")
buf = BIO.MemoryBuffer(json) # Seed the PRNG Rand.load_file(rand,-1) # S/MIME object s = SMIME.SMIME() # Load certificate x509 = X509.load_cert(cert) sk=X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) #Set cipher: 3-key triple-DES in CBC mode. s.set_cipher(SMIME.Cipher('des_ede3_cbc')) # Encrypt the buffer. p7 = s.encrypt(buf) #p7 = s.sign(buf) out = BIO.MemoryBuffer() s.write(out, p7) smime = out.read() print smime headers, body = smime.split('\n\n', 1) # Rand.save_file(rand)
r = BN.rand_range(1) assert r == 0 for x in range(loops): r = BN.rand_range(4) assert 0 <= r < 4 # large range r512 = BN.rand(512, top=0) for x in range(loops): r = BN.rand_range(r512) assert 0 <= r < r512 def test_randfname(self): m = re.compile('^[a-zA-Z0-9]{8}$') for x in range(loops): r = BN.randfname(8) assert m.match(r) def suite(): return unittest.makeSuite(BNTestCase) if __name__ == '__main__': Rand.load_file('randpool.dat', -1) unittest.TextTestRunner().run(suite()) Rand.save_file('randpool.dat')
def sign_and_attachment(self): server = 'mail.example.dom' sender = '*****@*****.**' to = [ '*****@*****.**', ] subject = 'test' text = 'test message' files = ['m2-demo.py'] attachments = {} bcc = [] if isinstance(to, str): to = [to] # create multipart message msg = MIMEMultipart() # attach message text as first attachment msg.attach(MIMEText(text)) # attach files to be read from file system for file in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(file, "rb").read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) # attach filest read from dictionary for name in attachments: part = MIMEBase('application', "octet-stream") part.set_payload(attachments[name]) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % name) msg.attach(part) # put message with attachments into into SSL' I/O buffer msg_str = msg.as_string() buf = BIO.MemoryBuffer(msg_str) # load seed file for PRNG Rand.load_file(randpool, -1) smime = SMIME.SMIME() # load certificate smime.load_key(signer_key, signer_cert) # sign whole message p7 = smime.sign(buf, SMIME.PKCS7_DETACHED) # create buffer for final mail and write header out = BIO.MemoryBuffer() out.write('From: %s\n' % sender) out.write('To: %s\n' % COMMASPACE.join(to)) out.write('Date: %s\n' % formatdate(localtime=True)) out.write('Subject: %s\n' % subject) out.write('Auto-Submitted: %s\n' % 'auto-generated') # convert message back into string buf = BIO.MemoryBuffer(msg_str) # append signed message and original message to mail header smime.write(out, p7, buf) # load save seed file for PRNG Rand.save_file(randpool) # extend list of recipents with bcc adresses to.extend(bcc) result = out.read() open('smime-m2-attachment.txt', 'wt').write(result) return # finaly send mail smtp = smtplib.SMTP(server) smtp.sendmail(sender, to, result) smtp.close()