def execute(self): if not self.numArg: tack = Tack.createFromParameters(self.key.getPublicKey(), self.key.getPrivateKey(), self.min_generation, self.generation, self.expiration, self.certificate.key_sha256) self.outputFile.write(self.addPemComments(tack.serializeAsPem())) if self.isVerbose(): sys.stderr.write(str(tack) + "\n") else: (numTacks, interval) = self.numArg if not self.outputFileName: self.printError("-o required with -n") for x in range(numTacks): tack = Tack.createFromParameters(self.key.getPublicKey(), self.key, self.min_generation, self.generation, self.expiration, self.certificate.key_sha256) outputFile = open(self.outputFileName + "_%04d.pem" % x, "w") outputFile.write(self.addPemComments(tack.serializeAsPem())) outputFile.close() if self.isVerbose(): sys.stderr.write(str(tack) + "\n") self.expiration += interval
def execute(self): if not self.numArg: #We are only signing a single TACK (this is the typical mode) tack = Tack.create(self.keyfile.getPublicKey(), self.keyfile.getPrivateKey(), self.min_generation, self.generation, self.expiration, self.certificate.key_sha256) self.outputFile.write(self.addPemComments(tack.serializeAsPem())) self.printVerbose(str(tack)) else: # We are signing multiple TACKs, since "-n" was specified (numTacks, interval) = self.numArg if not self.outputFileName: self.printError("-o required with -n") for x in range(numTacks): tack = Tack.create(self.keyfile.getPublicKey(), self.keyfile.getPrivateKey(), self.min_generation, self.generation, self.expiration, self.certificate.key_sha256) try: outputFileName = self.outputFileName + "_%04d.pem" % x outputFile = open(outputFileName, "w") outputFile.write(self.addPemComments(tack.serializeAsPem())) outputFile.close() except IOError: self.printError("Error opening output file: %s" % outputFileName) self.expiration += interval self.printVerbose(str(tack))
def execute(self): text, binary = self._readFileTextAndBinary(self.argRemainder[0]) fileType = None try: if text: decoder = PEMDecoder(text) if decoder.containsEncoded("TACK PRIVATE KEY"): fileType = "Private Key" kf = TackKeyFile.createFromPem(text, None) sys.stdout.write(str(kf)) return elif decoder.containsEncoded("TACK"): fileType = "Tack" tack = Tack.createFromPem(text) sys.stdout.write(str(tack)) return elif decoder.containsEncoded("TACK EXTENSION"): fileType = "TACK Extension" tackExt = TackExtension.createFromPem(text, True) sys.stdout.write(str(tackExt)) return elif decoder.containsEncoded( "CERTIFICATE"): fileType = "Certificate" sslc = TlsCertificate.createFromPem(text) sys.stdout.write(str(sslc)) return # Is it a certificate? try: sslc = TlsCertificate(binary) sys.stdout.write(str(sslc)) except SyntaxError: self.printError("Unrecognized file type") except SyntaxError as e: self.printError("Error parsing %s: %s" % (fileType, e))
def _parseTack(self): tackLen = self.getInt(1) if tackLen != Tack.LENGTH: raise SyntaxError("TACK wrong size") return Tack(self.getBytes(tackLen))
def test_Tack(self): s = """ -----BEGIN TACK----- TAmsAZIpzR+MYwQrsujLhesvpu3dRc5ROhfgySqUVkU1p1hdXo+PwQrmaQo9B9+o hecRrWElh3yThwgYQRgbSwAAAY0cQDHeDLGfKtuw0c17GzHvjuPrWbdEWa75S0gL 7u64XGTJQUtzAwXIWOkQEQ0BRUlbzcGEa9a1PBhjmmWFNF+kGAswhLnXc5qL4y/Z PDUV0rzIIYjXP58T5pphGKRgLlK3Aw== -----END TACK-----""" t = Tack().createFromPem(s) assert (t.public_key.getRawKey() == a2b_hex( "4c09ac019229cd1f8c63042bb2e8" "cb85eb2fa6eddd45ce513a17e0c9" "2a94564535a7585d5e8f8fc10ae6" "690a3d07dfa885e711ad6125877c" "9387081841181b4b")) assert (Time.posixTimeToStr(t.expiration * 60) == "2019-06-25T22:24Z") assert (t.generation == 0) assert (t.target_hash == a2b_hex( "31de0cb19f2adbb0d1cd7b1b31ef8ee3eb59b74459aef94b480beeeeb85c64c9") ) assert (t.signature == a2b_hex("414b730305c858e910110d0145495" "bcdc1846bd6b53c18639a6585345f" "a4180b3084b9d7739a8be32fd93c3" "515d2bcc82188d73f9f13e69a6118" "a4602e52b703"))
def getTacks(self): fileName = self.argRemainder[0] try: contents = open(fileName, "r").read() return Tack.createFromPemList(contents) except IOError as e: self.printError("Error opening tacks: %s\n%s" % (fileName, e)) except SyntaxError as e: self.printError("Error parsing tacks: %s\n%s" % (fileName, e))
def _getInputTack(self): contents = self._getInputFileContents() if contents is None: return None if PEMDecoder(contents).containsEncoded("TACK"): return Tack.createFromPem(contents) return None
def getTacks(self): fileName = self._getOptionValue("-t") if fileName is None: return None try: contents = open(fileName, "r").read() return Tack.createFromPemList(contents) except IOError: self.printError("Error opening tacks: %s" % fileName) except SyntaxError: self.printError("Error parsing tacks: %s" % fileName)
def _parseTacks(self): tacksLen = self.getInt(2) if tacksLen > 2 * Tack.LENGTH or tacksLen < Tack.LENGTH or tacksLen == 0: raise SyntaxError("tacks wrong number: %d" % tacksLen) elif tacksLen % Tack.LENGTH != 0: raise SyntaxError("tacks wrong size: %d" % tacksLen) tacks = [] b2 = self.getBytes(tacksLen) while b2: tacks.append(Tack(b2[:Tack.LENGTH])) b2 = b2[Tack.LENGTH:] return tacks
def execute(self): if not self.numArg: #We are only signing a single TACK (this is the typical mode) tack = Tack.create(self.keyfile.getPublicKey(), self.keyfile.getPrivateKey(), self.min_generation, self.generation, self.expiration, self.certificate.key_sha256) self.outputFile.write(self.addPemComments(tack.serializeAsPem())) self.printVerbose(str(tack)) else: # We are signing multiple TACKs, since "-n" was specified (numTacks, interval) = self.numArg if not self.outputFileName: self.printError("-o required with -n") for x in range(numTacks): tack = Tack.create(self.keyfile.getPublicKey(), self.keyfile.getPrivateKey(), self.min_generation, self.generation, self.expiration, self.certificate.key_sha256) try: outputFileName = self.outputFileName + "_%04d.pem" % x outputFile = open(outputFileName, "w") outputFile.write(self.addPemComments( tack.serializeAsPem())) outputFile.close() except IOError: self.printError("Error opening output file: %s" % outputFileName) self.expiration += interval self.printVerbose(str(tack))
def execute(self): text, binary = self._readFile(self.argv) fileType = None try: if text: decoder = PEMDecoder(text) if decoder.containsEncoded("TACK PRIVATE KEY"): fileType = "Private Key" kf = TackKeyFile.createFromPem(text, None) print(str(kf)) return elif decoder.containsEncoded("TACK"): fileType = "TACK" tack = Tack.createFromPem(text) print(str(tack)) return elif decoder.containsEncoded("TACK BREAK SIG"): fileType = "Break Sig" tbsList = TackBreakSig.createFromPemList(text) s = "" for tbs in tbsList: s += str(tbs) print(s) return elif decoder.containsEncoded("CERTIFICATE"): fileType = "Certificate" sslc = TlsCertificate() sslc.parsePem(text) print(sslc.writeText()) return # Is it an SSL certificate? try: sslc = TlsCertificate() sslc.parse(binary) print(sslc.writeText()) except SyntaxError: self.printError("Unrecognized file type") except SyntaxError as e: self.printError("Error parsing %s: %s" % (fileType, e))
def _getInputFile(self): fileName = self._getOptionValue("-i") if fileName is None: self.printError("-i missing (Certificate or TACK)") try: text, binary = self._readFileTextAndBinary(fileName) if text: pem = PEMDecoder(text) if pem.containsEncoded("TACK"): return (Tack.createFromPem(text), None) elif pem.containsEncoded("CERTIFICATE"): return (None, TlsCertificate.createFromPem(text)) else: self.printError("Unrecognized input file: %s" % fileName) else: return (None, TlsCertificate(binary)) except IOError: self.printError("Error opening input file: %s" % fileName) except SyntaxError: self.printError("Error parsing input file: %s" % fileName)
def handleArgs(argv, argString, flagsList=[]): # Convert to getopt argstring format: # Add ":" after each arg, ie "abc" -> "a:b:c:" getOptArgString = ":".join(argString) + ":" try: opts, argv = getopt.getopt(argv, getOptArgString, flagsList) except getopt.GetoptError as e: printError(e) # Default values if arg not present privateKey = None certChain = None username = None password = None tacks = None verifierDB = None reqCert = False directory = None expLabel = None expLength = 20 alpn = [] dhparam = None for opt, arg in opts: if opt == "-k": s = open(arg, "rb").read() if sys.version_info[0] >= 3: s = str(s, 'utf-8') # OpenSSL/m2crypto does not support RSASSA-PSS certificates privateKey = parsePEMKey(s, private=True, implementations=["python"]) elif opt == "-c": s = open(arg, "rb").read() if sys.version_info[0] >= 3: s = str(s, 'utf-8') x509 = X509() x509.parse(s) certChain = X509CertChain([x509]) elif opt == "-u": username = arg elif opt == "-p": password = arg elif opt == "-t": if tackpyLoaded: s = open(arg, "rU").read() tacks = Tack.createFromPemList(s) elif opt == "-v": verifierDB = VerifierDB(arg) verifierDB.open() elif opt == "-d": directory = arg elif opt == "--reqcert": reqCert = True elif opt == "-l": expLabel = arg elif opt == "-L": expLength = int(arg) elif opt == "-a": alpn.append(bytearray(arg, 'utf-8')) elif opt == "--param": s = open(arg, "rb").read() if sys.version_info[0] >= 3: s = str(s, 'utf-8') dhparam = parseDH(s) else: assert (False) # when no names provided, don't return array if not alpn: alpn = None if not argv: printError("Missing address") if len(argv) > 1: printError("Too many arguments") #Split address into hostname/port tuple address = argv[0] address = address.split(":") if len(address) != 2: raise SyntaxError("Must specify <host>:<port>") address = (address[0], int(address[1])) # Populate the return list retList = [address] if "k" in argString: retList.append(privateKey) if "c" in argString: retList.append(certChain) if "u" in argString: retList.append(username) if "p" in argString: retList.append(password) if "t" in argString: retList.append(tacks) if "v" in argString: retList.append(verifierDB) if "d" in argString: retList.append(directory) if "reqcert" in flagsList: retList.append(reqCert) if "l" in argString: retList.append(expLabel) if "L" in argString: retList.append(expLength) if "a" in argString: retList.append(alpn) if "param=" in flagsList: retList.append(dhparam) return retList
def handleArgs(argv, argString, flagsList=[]): # Convert to getopt argstring format: # Add ":" after each arg, ie "abc" -> "a:b:c:" getOptArgString = ":".join(argString) + ":" try: opts, argv = getopt.getopt(argv, getOptArgString, flagsList) except getopt.GetoptError as e: printError(e) # Default values if arg not present privateKey = None certChain = None username = None password = None tacks = None verifierDB = None reqCert = False directory = None for opt, arg in opts: if opt == "-k": s = open(arg, "rb").read() privateKey = parsePEMKey(s, private=True) elif opt == "-c": s = open(arg, "rb").read() x509 = X509() x509.parse(s) certChain = X509CertChain([x509]) elif opt == "-u": username = arg elif opt == "-p": password = arg elif opt == "-t": if tackpyLoaded: s = open(arg, "rU").read() tacks = Tack.createFromPemList(s) elif opt == "-v": verifierDB = VerifierDB(arg) verifierDB.open() elif opt == "-d": directory = arg elif opt == "--reqcert": reqCert = True else: assert (False) if not argv: printError("Missing address") if len(argv) > 1: printError("Too many arguments") #Split address into hostname/port tuple address = argv[0] address = address.split(":") if len(address) != 2: raise SyntaxError("Must specify <host>:<port>") address = (address[0], int(address[1])) # Populate the return list retList = [address] if "k" in argString: retList.append(privateKey) if "c" in argString: retList.append(certChain) if "u" in argString: retList.append(username) if "p" in argString: retList.append(password) if "t" in argString: retList.append(tacks) if "v" in argString: retList.append(verifierDB) if "d" in argString: retList.append(directory) if "reqcert" in flagsList: retList.append(reqCert) return retList
def handleArgs(argv, argString, flagsList=[]): # Convert to getopt argstring format: # Add ":" after each arg, ie "abc" -> "a:b:c:" getOptArgString = ":".join(argString) + ":" try: opts, argv = getopt.getopt(argv, getOptArgString, flagsList) except getopt.GetoptError as e: printError(e) # Default values if arg not present privateKey = None certChain = None username = None password = None tacks = None verifierDB = None reqCert = False directory = None for opt, arg in opts: if opt == "-k": s = open(arg, "rb").read() privateKey = parsePEMKey(s, private=True) elif opt == "-c": s = open(arg, "rb").read() x509 = X509() x509.parse(s) certChain = X509CertChain([x509]) elif opt == "-u": username = arg elif opt == "-p": password = arg elif opt == "-t": if tackpyLoaded: s = open(arg, "rU").read() tacks = Tack.createFromPemList(s) elif opt == "-v": verifierDB = VerifierDB(arg) verifierDB.open() elif opt == "-d": directory = arg elif opt == "--reqcert": reqCert = True else: assert(False) if not argv: printError("Missing address") if len(argv)>1: printError("Too many arguments") #Split address into hostname/port tuple address = argv[0] address = address.split(":") if len(address) != 2: raise SyntaxError("Must specify <host>:<port>") address = ( address[0], int(address[1]) ) # Populate the return list retList = [address] if "k" in argString: retList.append(privateKey) if "c" in argString: retList.append(certChain) if "u" in argString: retList.append(username) if "p" in argString: retList.append(password) if "t" in argString: retList.append(tacks) if "v" in argString: retList.append(verifierDB) if "d" in argString: retList.append(directory) if "reqcert" in flagsList: retList.append(reqCert) return retList
def handleArgs(argv, argString, flagsList=[]): # Convert to getopt argstring format: # Add ":" after each arg, ie "abc" -> "a:b:c:" getOptArgString = ":".join(argString) + ":" try: opts, argv = getopt.getopt(argv, getOptArgString, flagsList) except getopt.GetoptError as e: printError(e) # Default values if arg not present privateKey = None cert_chain = None username = None password = None use_fido2 = False eph_user_name_out = None eph_user_name_in = None tacks = None verifierDB = None reqCert = False fido2_db = None fido2_db_encryption_key = None fido2_modes = None force_fido2 = False pre_share_eph_user_name = False directory = None expLabel = None expLength = 20 alpn = [] dhparam = None psk = None psk_ident = None psk_hash = 'sha256' resumption = False ssl3 = False max_ver = None tickets = None verbose = False for opt, arg in opts: if opt == "-k": s = open(arg, "rb").read() if sys.version_info[0] >= 3: s = str(s, 'utf-8') # OpenSSL/m2crypto does not support RSASSA-PSS certificates privateKey = parsePEMKey(s, private=True, implementations=["python"]) elif opt == "-c": s = open(arg, "rb").read() if sys.version_info[0] >= 3: s = str(s, 'utf-8') cert_chain = X509CertChain() cert_chain.parsePemList(s) elif opt == "-u": username = arg elif opt == "-p": password = arg elif opt == "--fido2": use_fido2 = True elif opt == "--eph-uname-out": eph_user_name_out = arg elif opt == "--eph-uname-in": eph_user_name_in = arg elif opt == "-t": if tackpyLoaded: s = open(arg, "rU").read() tacks = Tack.createFromPemList(s) elif opt == "-v": verifierDB = VerifierDB(arg) verifierDB.open() elif opt == "-d": directory = arg elif opt == "--reqcert": reqCert = True elif opt == "--fido2-db": fido2_db = arg elif opt == "--db-encryption-key": s = open(arg, "rb").read() if sys.version_info[0] >= 3: s = str(s, 'utf-8') fido2_db_encryption_key = parsePEMKey(s, private=True, implementations=["python"]) elif opt == "--fido2-modes": mode_string = arg fido2_modes = [] if "i" in mode_string: fido2_modes.append(FIDO2Mode.fido2_with_id) if "n" in mode_string: fido2_modes.append(FIDO2Mode.fido2_with_name) elif opt == "--force-fido2": force_fido2 = True elif opt == "--pre-share-euname": pre_share_eph_user_name = True elif opt == "-l": expLabel = arg elif opt == "-L": expLength = int(arg) elif opt == "-a": alpn.append(bytearray(arg, 'utf-8')) elif opt == "--param": s = open(arg, "rb").read() if sys.version_info[0] >= 3: s = str(s, 'utf-8') dhparam = parseDH(s) elif opt == "--psk": psk = a2b_hex(arg) elif opt == "--psk-ident": psk_ident = bytearray(arg, 'utf-8') elif opt == "--psk-sha384": psk_hash = 'sha384' elif opt == "--resumption": resumption = True elif opt == "--ssl3": ssl3 = True elif opt == "--max-ver": max_ver = ver_to_tuple(arg) elif opt == "--tickets": tickets = int(arg) elif opt == "--verbose": verbose = True else: assert (False) # when no names provided, don't return array if not alpn: alpn = None if (psk and not psk_ident) or (not psk and psk_ident): printError("PSK and IDENTITY must be set together") if not argv: printError("Missing address") if len(argv) > 1: printError("Too many arguments") # Split address into hostname/port tuple address = argv[0] address = address.split(":") if len(address) != 2: raise SyntaxError("Must specify <host>:<port>") address = (address[0], int(address[1])) # Populate the return list retList = [address] if "k" in argString: retList.append(privateKey) if "c" in argString: retList.append(cert_chain) if "u" in argString: retList.append(username) if "p" in argString: retList.append(password) if "fido2" in flagsList: retList.append(use_fido2) if "eph-uname-out=" in flagsList: retList.append(eph_user_name_out) if "eph-uname-in=" in flagsList: retList.append(eph_user_name_in) if "t" in argString: retList.append(tacks) if "v" in argString: retList.append(verifierDB) if "d" in argString: retList.append(directory) if "reqcert" in flagsList: retList.append(reqCert) if "fido2-db=" in flagsList: retList.append(fido2_db) if "db-encryption-key=" in flagsList: retList.append(fido2_db_encryption_key) if "fido2-modes=" in flagsList: retList.append(fido2_modes) if "force-fido2" in flagsList: retList.append(force_fido2) if "pre-share-euname" in flagsList: retList.append(pre_share_eph_user_name) if "l" in argString: retList.append(expLabel) if "L" in argString: retList.append(expLength) if "a" in argString: retList.append(alpn) if "param=" in flagsList: retList.append(dhparam) if "psk=" in flagsList: retList.append(psk) if "psk-ident=" in flagsList: retList.append(psk_ident) if "psk-sha384" in flagsList: retList.append(psk_hash) if "resumption" in flagsList: retList.append(resumption) if "ssl3" in flagsList: retList.append(ssl3) if "max-ver=" in flagsList: retList.append(max_ver) if "tickets=" in flagsList: retList.append(tickets) if "verbose" in flagsList: retList.append(verbose) return retList
def serverTestCmd(argv): address = argv[0] dir = argv[1] #Split address into hostname/port tuple address = address.split(":") address = ( address[0], int(address[1]) ) #Connect to server lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) lsock.bind(address) lsock.listen(5) def connect(): return TLSConnection(lsock.accept()[0]) print "Test 0 - Anonymous server handshake" connection = connect() connection.handshakeServer(anon=True) testConnServer(connection) connection.close() print "Test 1 - good X.509" x509Cert = X509().parse(open(os.path.join(dir, "serverX509Cert.pem")).read()) x509Chain = X509CertChain([x509Cert]) s = open(os.path.join(dir, "serverX509Key.pem")).read() x509Key = parsePEMKey(s, private=True) connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) assert(connection.session.serverName == address[0]) testConnServer(connection) connection.close() print "Test 1.a - good X.509, SSL v3" connection = connect() settings = HandshakeSettings() settings.minVersion = (3,0) settings.maxVersion = (3,0) connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) testConnServer(connection) connection.close() if tackpyLoaded: tack = Tack.createFromPem(open("./TACK1.pem", "rU").read()) tackUnrelated = Tack.createFromPem(open("./TACKunrelated.pem", "rU").read()) settings = HandshakeSettings() settings.useExperimentalTackExtension = True print "Test 2.a - good X.509, TACK" connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, tacks=[tack], activationFlags=1, settings=settings) testConnServer(connection) connection.close() print "Test 2.b - good X.509, TACK unrelated to cert chain" connection = connect() try: connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, tacks=[tackUnrelated], settings=settings) assert(False) except TLSRemoteAlert, alert: if alert.description != AlertDescription.illegal_parameter: raise
def serverTestCmd(argv): address = argv[0] dir = argv[1] #Split address into hostname/port tuple address = address.split(":") address = ( address[0], int(address[1]) ) #Create synchronisation FIFO synchroSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) synchroSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) synchroSocket.bind((address[0], address[1]-1)) synchroSocket.listen(2) #Connect to server lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) lsock.bind(address) lsock.listen(5) # following is blocking until the other side doesn't open synchro = synchroSocket.accept()[0] def connect(): return TLSConnection(lsock.accept()[0]) x509Cert = X509().parse(open(os.path.join(dir, "serverX509Cert.pem")).read()) x509Chain = X509CertChain([x509Cert]) s = open(os.path.join(dir, "serverX509Key.pem")).read() x509Key = parsePEMKey(s, private=True) print("Test 0 - Anonymous server handshake") synchro.send(b'R') connection = connect() connection.handshakeServer(anon=True) testConnServer(connection) connection.close() print("Test 1 - good X.509") synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) assert(connection.session.serverName == address[0]) testConnServer(connection) connection.close() print("Test 1.a - good X.509, SSL v3") synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.minVersion = (3,0) settings.maxVersion = (3,0) connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) testConnServer(connection) connection.close() print("Test 1.b - good X.509, RC4-MD5") synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.macNames = ["sha", "md5"] settings.cipherNames = ["rc4"] connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) testConnServer(connection) connection.close() if tackpyLoaded: tack = Tack.createFromPem(open("./TACK1.pem", "rU").read()) tackUnrelated = Tack.createFromPem(open("./TACKunrelated.pem", "rU").read()) settings = HandshakeSettings() settings.useExperimentalTackExtension = True print("Test 2.a - good X.509, TACK") synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, tacks=[tack], activationFlags=1, settings=settings) testConnServer(connection) connection.close() print("Test 2.b - good X.509, TACK unrelated to cert chain") synchro.send(b'R') connection = connect() try: connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, tacks=[tackUnrelated], settings=settings) assert(False) except TLSRemoteAlert as alert: if alert.description != AlertDescription.illegal_parameter: raise print("Test 3 - good SRP") verifierDB = VerifierDB() verifierDB.create() entry = VerifierDB.makeVerifier("test", "password", 1536) verifierDB["test"] = entry synchro.send(b'R') connection = connect() connection.handshakeServer(verifierDB=verifierDB) testConnServer(connection) connection.close() print("Test 4 - SRP faults") for fault in Fault.clientSrpFaults + Fault.genericFaults: synchro.send(b'R') connection = connect() connection.fault = fault connection.handshakeServer(verifierDB=verifierDB) connection.close() print("Test 6 - good SRP: with X.509 cert") synchro.send(b'R') connection = connect() connection.handshakeServer(verifierDB=verifierDB, \ certChain=x509Chain, privateKey=x509Key) testConnServer(connection) connection.close() print("Test 7 - X.509 with SRP faults") for fault in Fault.clientSrpFaults + Fault.genericFaults: synchro.send(b'R') connection = connect() connection.fault = fault connection.handshakeServer(verifierDB=verifierDB, \ certChain=x509Chain, privateKey=x509Key) connection.close() print("Test 11 - X.509 faults") for fault in Fault.clientNoAuthFaults + Fault.genericFaults: synchro.send(b'R') connection = connect() connection.fault = fault connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) connection.close() print("Test 14 - good mutual X.509") synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, reqCert=True) testConnServer(connection) assert(isinstance(connection.session.serverCertChain, X509CertChain)) connection.close() print("Test 14a - good mutual X.509, TLSv1.1") synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.minVersion = (3,2) settings.maxVersion = (3,2) connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, reqCert=True, settings=settings) testConnServer(connection) assert(isinstance(connection.session.serverCertChain, X509CertChain)) connection.close() print("Test 14b - good mutual X.509, SSLv3") synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.minVersion = (3,0) settings.maxVersion = (3,0) connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, reqCert=True, settings=settings) testConnServer(connection) assert(isinstance(connection.session.serverCertChain, X509CertChain)) connection.close() print("Test 15 - mutual X.509 faults") for fault in Fault.clientCertFaults + Fault.genericFaults: synchro.send(b'R') connection = connect() connection.fault = fault connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, reqCert=True) connection.close() print("Test 18 - good SRP, prepare to resume") synchro.send(b'R') sessionCache = SessionCache() connection = connect() connection.handshakeServer(verifierDB=verifierDB, sessionCache=sessionCache) assert(connection.session.serverName == address[0]) testConnServer(connection) connection.close() print("Test 19 - resumption") synchro.send(b'R') connection = connect() connection.handshakeServer(verifierDB=verifierDB, sessionCache=sessionCache) assert(connection.session.serverName == address[0]) testConnServer(connection) #Don't close! -- see next test print("Test 20 - invalidated resumption") synchro.send(b'R') try: connection.read(min=1, max=1) assert() #Client is going to close the socket without a close_notify except TLSAbruptCloseError as e: pass synchro.send(b'R') connection = connect() try: connection.handshakeServer(verifierDB=verifierDB, sessionCache=sessionCache) except TLSLocalAlert as alert: if alert.description != AlertDescription.bad_record_mac: raise connection.close() print("Test 21 - HTTPS test X.509") #Close the current listening socket lsock.close() #Create and run an HTTP Server using TLSSocketServerMixIn class MyHTTPServer(TLSSocketServerMixIn, HTTPServer): def handshake(self, tlsConnection): tlsConnection.handshakeServer(certChain=x509Chain, privateKey=x509Key) return True def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) HTTPServer.server_bind(self) cd = os.getcwd() os.chdir(dir) address = address[0], address[1]+1 httpd = MyHTTPServer(address, SimpleHTTPRequestHandler) for x in range(6): synchro.send(b'R') httpd.handle_request() httpd.server_close() cd = os.chdir(cd) #Re-connect the listening socket lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) address = address[0], address[1]+1 lsock.bind(address) lsock.listen(5) implementations = [] if m2cryptoLoaded: implementations.append("openssl") if pycryptoLoaded: implementations.append("pycrypto") implementations.append("python") print("Test 22 - different ciphers") for implementation in ["python"] * len(implementations): for cipher in ["aes128", "aes256", "rc4"]: print("Test 22:", end=' ') synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.cipherNames = [cipher] settings.cipherImplementations = [implementation, "python"] connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) print(connection.getCipherName(), connection.getCipherImplementation()) testConnServer(connection) connection.close() print("Test 23 - throughput test") for implementation in implementations: for cipher in ["aes128", "aes256", "3des", "rc4"]: if cipher == "3des" and implementation not in ("openssl", "pycrypto"): continue print("Test 23:", end=' ') synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.cipherNames = [cipher] settings.cipherImplementations = [implementation, "python"] connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) print(connection.getCipherName(), connection.getCipherImplementation()) h = connection.read(min=50000, max=50000) assert(h == b"hello"*10000) connection.write(h) connection.close() print("Test 24.a - Next-Protocol Server Negotiation") synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"http/1.1"]) testConnServer(connection) connection.close() print("Test 24.b - Next-Protocol Server Negotiation") synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"spdy/2", b"http/1.1"]) testConnServer(connection) connection.close() print("Test 24.c - Next-Protocol Server Negotiation") synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"http/1.1", b"spdy/2"]) testConnServer(connection) connection.close() print("Test 24.d - Next-Protocol Server Negotiation") synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"spdy/2", b"http/1.1"]) testConnServer(connection) connection.close() print("Test 24.e - Next-Protocol Server Negotiation") synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"http/1.1", b"spdy/2", b"spdy/3"]) testConnServer(connection) connection.close() print("Test 24.f - Next-Protocol Server Negotiation") synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"spdy/3", b"spdy/2"]) testConnServer(connection) connection.close() print("Test 24.g - Next-Protocol Server Negotiation") synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[]) testConnServer(connection) connection.close() print("Test 25.a - FALLBACK_SCSV") synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) testConnServer(connection) connection.close() print("Test 25.b - FALLBACK_SCSV") synchro.send(b'R') connection = connect() try: connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) assert() except TLSLocalAlert as alert: if alert.description != AlertDescription.inappropriate_fallback: raise connection.close() print("Test 26.a - server checks cipher version") synchro.send(b'R') connection = connect() try: connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) assert() except TLSLocalAlert as alert: # The server should reject the connection with a handshake_failure # because, after taking the version into account, no ciphers match. if alert.description != AlertDescription.handshake_failure: raise connection.close() print("Test 26.b - client checks cipher version") synchro.send(b'R') connection = connect() # Configure the server to illegally select SHA-256 ciphers at TLS 1.1. connection.fault = Fault.ignoreVersionForCipher settings = HandshakeSettings() settings.maxVersion = (3, 2) settings.macNames = ["sha256"] connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) connection.close() print("Tests 27-29 - XMLRPXC server") address = address[0], address[1]+1 class Server(TLSXMLRPCServer): def handshake(self, tlsConnection): try: tlsConnection.handshakeServer(certChain=x509Chain, privateKey=x509Key, sessionCache=sessionCache) tlsConnection.ignoreAbruptClose = True return True except TLSError as error: print("Handshake failure:", str(error)) return False class MyFuncs: def pow(self, x, y): return pow(x, y) def add(self, x, y): return x + y server = Server(address) server.register_instance(MyFuncs()) synchro.send(b'R') #sa = server.socket.getsockname() #print "Serving HTTPS on", sa[0], "port", sa[1] for i in range(6): synchro.send(b'R') server.handle_request() synchro.close() synchroSocket.close() print("Test succeeded")
def serverTestCmd(argv): address = argv[0] dir = argv[1] #Split address into hostname/port tuple address = address.split(":") address = ( address[0], int(address[1]) ) #Create synchronisation FIFO synchroSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) synchroSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) synchroSocket.bind((address[0], address[1]-1)) synchroSocket.listen(2) #Connect to server lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) lsock.bind(address) lsock.listen(5) # following is blocking until the other side doesn't open synchro = synchroSocket.accept()[0] def connect(): return TLSConnection(lsock.accept()[0]) x509Cert = X509().parse(open(os.path.join(dir, "serverX509Cert.pem")).read()) x509Chain = X509CertChain([x509Cert]) s = open(os.path.join(dir, "serverX509Key.pem")).read() x509Key = parsePEMKey(s, private=True) test_no = 0 print("Test {0} - Anonymous server handshake".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(anon=True) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - good X.509".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) assert(connection.session.serverName == address[0]) assert(connection.extendedMasterSecret) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - good X.509, SSL v3".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.minVersion = (3,0) settings.maxVersion = (3,0) connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) assert(not connection.extendedMasterSecret) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - good X.509, RC4-MD5".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.macNames = ["sha", "md5"] settings.cipherNames = ["rc4"] connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) testConnServer(connection) connection.close() if tackpyLoaded: tack = Tack.createFromPem(open("./TACK1.pem", "rU").read()) tackUnrelated = Tack.createFromPem(open("./TACKunrelated.pem", "rU").read()) settings = HandshakeSettings() settings.useExperimentalTackExtension = True test_no += 1 print("Test {0} - good X.509, TACK".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, tacks=[tack], activationFlags=1, settings=settings) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - good X.509, TACK unrelated to cert chain".\ format(test_no)) synchro.send(b'R') connection = connect() try: connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, tacks=[tackUnrelated], settings=settings) assert(False) except TLSRemoteAlert as alert: if alert.description != AlertDescription.illegal_parameter: raise else: test_no += 1 print("Test {0} - good X.509, TACK...skipped (no tackpy)".\ format(test_no)) test_no += 1 print("Test {0} - good X.509, TACK unrelated to cert chain" "...skipped (no tackpy)".format(test_no)) test_no += 1 print("Test {0} - good SRP".format(test_no)) verifierDB = VerifierDB() verifierDB.create() entry = VerifierDB.makeVerifier("test", "password", 1536) verifierDB[b"test"] = entry synchro.send(b'R') connection = connect() connection.handshakeServer(verifierDB=verifierDB) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - good SRP (db)".format(test_no)) try: (db_file, db_name) = mkstemp() os.close(db_file) # this is race'y but the interface dbm interface is stupid like that... os.remove(db_name) verifierDB = VerifierDB(db_name) verifierDB.create() entry = VerifierDB.makeVerifier("test", "password", 1536) verifierDB[b"test"] = entry synchro.send(b'R') connection = connect() connection.handshakeServer(verifierDB=verifierDB) testConnServer(connection) connection.close() finally: os.remove(db_name) test_no += 1 print("Test {0} - SRP faults".format(test_no)) for fault in Fault.clientSrpFaults + Fault.genericFaults: synchro.send(b'R') connection = connect() connection.fault = fault connection.handshakeServer(verifierDB=verifierDB) connection.close() test_no += 1 print("Test {0} - good SRP: with X.509 cert".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(verifierDB=verifierDB, \ certChain=x509Chain, privateKey=x509Key) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - X.509 with SRP faults".format(test_no)) for fault in Fault.clientSrpFaults + Fault.genericFaults: synchro.send(b'R') connection = connect() connection.fault = fault connection.handshakeServer(verifierDB=verifierDB, \ certChain=x509Chain, privateKey=x509Key) connection.close() test_no += 1 print("Test {0} - X.509 faults".format(test_no)) for fault in Fault.clientNoAuthFaults + Fault.genericFaults: synchro.send(b'R') connection = connect() connection.fault = fault connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) connection.close() test_no += 1 print("Test {0} - good mutual X.509".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, reqCert=True) testConnServer(connection) assert(isinstance(connection.session.clientCertChain, X509CertChain)) connection.close() test_no += 1 print("Test {0} - good mutual X.509, TLSv1.1".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.minVersion = (3,2) settings.maxVersion = (3,2) connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, reqCert=True, settings=settings) testConnServer(connection) assert(isinstance(connection.session.clientCertChain, X509CertChain)) connection.close() test_no += 1 print("Test {0} - good mutual X.509, SSLv3".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.minVersion = (3,0) settings.maxVersion = (3,0) connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, reqCert=True, settings=settings) testConnServer(connection) assert(isinstance(connection.session.clientCertChain, X509CertChain)) connection.close() test_no += 1 print("Test {0} - mutual X.509 faults".format(test_no)) for fault in Fault.clientCertFaults + Fault.genericFaults: synchro.send(b'R') connection = connect() connection.fault = fault connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, reqCert=True) connection.close() test_no += 1 print("Test {0} - good SRP, prepare to resume".format(test_no)) synchro.send(b'R') sessionCache = SessionCache() connection = connect() connection.handshakeServer(verifierDB=verifierDB, sessionCache=sessionCache) assert(connection.session.serverName == address[0]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - resumption".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(verifierDB=verifierDB, sessionCache=sessionCache) assert(connection.session.serverName == address[0]) testConnServer(connection) #Don't close! -- see next test test_no += 1 print("Test {0} - invalidated resumption".format(test_no)) synchro.send(b'R') try: connection.read(min=1, max=1) assert() #Client is going to close the socket without a close_notify except TLSAbruptCloseError as e: pass synchro.send(b'R') connection = connect() try: connection.handshakeServer(verifierDB=verifierDB, sessionCache=sessionCache) except TLSLocalAlert as alert: if alert.description != AlertDescription.bad_record_mac: raise connection.close() test_no += 1 print("Test {0} - HTTPS test X.509".format(test_no)) #Close the current listening socket lsock.close() #Create and run an HTTP Server using TLSSocketServerMixIn class MyHTTPServer(TLSSocketServerMixIn, HTTPServer): def handshake(self, tlsConnection): tlsConnection.handshakeServer(certChain=x509Chain, privateKey=x509Key) return True def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) HTTPServer.server_bind(self) cd = os.getcwd() os.chdir(dir) address = address[0], address[1]+1 httpd = MyHTTPServer(address, SimpleHTTPRequestHandler) for x in range(6): synchro.send(b'R') httpd.handle_request() httpd.server_close() cd = os.chdir(cd) #Re-connect the listening socket lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) address = address[0], address[1]+1 lsock.bind(address) lsock.listen(5) implementations = [] if m2cryptoLoaded: implementations.append("openssl") if pycryptoLoaded: implementations.append("pycrypto") implementations.append("python") test_no += 1 print("Test {0} - different ciphers".format(test_no)) for implementation in ["python"] * len(implementations): for cipher in ["aes128", "aes256", "rc4"]: test_no += 1 print("Test {0}:".format(test_no), end=' ') synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.cipherNames = [cipher] settings.cipherImplementations = [implementation, "python"] connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) print(connection.getCipherName(), connection.getCipherImplementation()) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - throughput test".format(test_no)) for implementation in implementations: for cipher in ["aes128gcm", "aes256gcm", "aes128", "aes256", "3des", "rc4", "chacha20-poly1305_draft00", "chacha20-poly1305"]: # skip tests with implementations that don't support them if cipher == "3des" and implementation not in ("openssl", "pycrypto"): continue if cipher in ("aes128gcm", "aes256gcm") and \ implementation not in ("pycrypto", "python"): continue if cipher in ("chacha20-poly1305_draft00", "chacha20-poly1305") \ and implementation not in ("python", ): continue test_no += 1 print("Test {0}:".format(test_no), end=' ') synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.cipherNames = [cipher] settings.cipherImplementations = [implementation, "python"] connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) print(connection.getCipherName(), connection.getCipherImplementation()) h = connection.read(min=50000, max=50000) assert(h == b"hello"*10000) connection.write(h) connection.close() test_no += 1 print("Test {0} - Next-Protocol Server Negotiation".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"http/1.1"]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - Next-Protocol Server Negotiation".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"spdy/2", b"http/1.1"]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - Next-Protocol Server Negotiation".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"http/1.1", b"spdy/2"]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - Next-Protocol Server Negotiation".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"spdy/2", b"http/1.1"]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - Next-Protocol Server Negotiation".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"http/1.1", b"spdy/2", b"spdy/3"]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - Next-Protocol Server Negotiation".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"spdy/3", b"spdy/2"]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - Next-Protocol Server Negotiation".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - FALLBACK_SCSV".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - FALLBACK_SCSV".format(test_no)) synchro.send(b'R') connection = connect() try: connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) assert() except TLSLocalAlert as alert: if alert.description != AlertDescription.inappropriate_fallback: raise connection.close() test_no += 1 print("Test {0} - no EtM server side".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.useEncryptThenMAC = False connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - no EtM client side".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - resumption with EtM".format(test_no)) synchro.send(b'R') sessionCache = SessionCache() connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, sessionCache=sessionCache) testConnServer(connection) connection.close() # resume synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, sessionCache=sessionCache) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - resumption with no EtM in 2nd handshake".format(test_no)) synchro.send(b'R') sessionCache = SessionCache() connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, sessionCache=sessionCache) testConnServer(connection) connection.close() # resume synchro.send(b'R') connection = connect() try: connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, sessionCache=sessionCache) except TLSLocalAlert as e: assert(str(e) == "handshake_failure") else: raise AssertionError("no exception raised") connection.close() test_no += 1 print("Tests {0}-{1} - XMLRPXC server".format(test_no, test_no + 2)) test_no += 2 address = address[0], address[1]+1 class Server(TLSXMLRPCServer): def handshake(self, tlsConnection): try: tlsConnection.handshakeServer(certChain=x509Chain, privateKey=x509Key, sessionCache=sessionCache) tlsConnection.ignoreAbruptClose = True return True except TLSError as error: print("Handshake failure:", str(error)) return False class MyFuncs: def pow(self, x, y): return pow(x, y) def add(self, x, y): return x + y server = Server(address) server.register_instance(MyFuncs()) synchro.send(b'R') #sa = server.socket.getsockname() #print "Serving HTTPS on", sa[0], "port", sa[1] for i in range(6): synchro.send(b'R') server.handle_request() synchro.close() synchroSocket.close() print("Test succeeded")
def serverTestCmd(argv): address = argv[0] dir = argv[1] #Split address into hostname/port tuple address = address.split(":") address = ( address[0], int(address[1]) ) #Connect to server lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) lsock.bind(address) lsock.listen(5) def connect(): return TLSConnection(lsock.accept()[0]) x509Cert = X509().parse(open(os.path.join(dir, "serverX509Cert.pem")).read()) x509Chain = X509CertChain([x509Cert]) s = open(os.path.join(dir, "serverX509Key.pem")).read() x509Key = parsePEMKey(s, private=True) print("Test 0 - Anonymous server handshake") connection = connect() connection.handshakeServer(anon=True) testConnServer(connection) connection.close() print("Test 1 - good X.509") connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) assert(connection.session.serverName == address[0]) testConnServer(connection) connection.close() print("Test 1.a - good X.509, SSL v3") connection = connect() settings = HandshakeSettings() settings.minVersion = (3,0) settings.maxVersion = (3,0) connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) testConnServer(connection) connection.close() print("Test 1.b - good X.509, RC4-MD5") connection = connect() settings = HandshakeSettings() settings.macNames = ["sha", "md5"] settings.cipherNames = ["rc4"] connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) testConnServer(connection) connection.close() if tackpyLoaded: tack = Tack.createFromPem(open("./TACK1.pem", "rU").read()) tackUnrelated = Tack.createFromPem(open("./TACKunrelated.pem", "rU").read()) settings = HandshakeSettings() settings.useExperimentalTackExtension = True print("Test 2.a - good X.509, TACK") connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, tacks=[tack], activationFlags=1, settings=settings) testConnServer(connection) connection.close() print("Test 2.b - good X.509, TACK unrelated to cert chain") connection = connect() try: connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, tacks=[tackUnrelated], settings=settings) assert(False) except TLSRemoteAlert as alert: if alert.description != AlertDescription.illegal_parameter: raise print("Test 3 - good SRP") verifierDB = VerifierDB() verifierDB.create() entry = VerifierDB.makeVerifier("test", "password", 1536) verifierDB["test"] = entry connection = connect() connection.handshakeServer(verifierDB=verifierDB) testConnServer(connection) connection.close() print("Test 4 - SRP faults") for fault in Fault.clientSrpFaults + Fault.genericFaults: connection = connect() connection.fault = fault try: connection.handshakeServer(verifierDB=verifierDB) assert() except: pass connection.close() print("Test 6 - good SRP: with X.509 cert") connection = connect() connection.handshakeServer(verifierDB=verifierDB, \ certChain=x509Chain, privateKey=x509Key) testConnServer(connection) connection.close() print("Test 7 - X.509 with SRP faults") for fault in Fault.clientSrpFaults + Fault.genericFaults: connection = connect() connection.fault = fault try: connection.handshakeServer(verifierDB=verifierDB, \ certChain=x509Chain, privateKey=x509Key) assert() except: pass connection.close() print("Test 11 - X.509 faults") for fault in Fault.clientNoAuthFaults + Fault.genericFaults: connection = connect() connection.fault = fault try: connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) assert() except: pass connection.close() print("Test 14 - good mutual X.509") connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, reqCert=True) testConnServer(connection) assert(isinstance(connection.session.serverCertChain, X509CertChain)) connection.close() print("Test 14a - good mutual X.509, SSLv3") connection = connect() settings = HandshakeSettings() settings.minVersion = (3,0) settings.maxVersion = (3,0) connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, reqCert=True, settings=settings) testConnServer(connection) assert(isinstance(connection.session.serverCertChain, X509CertChain)) connection.close() print("Test 15 - mutual X.509 faults") for fault in Fault.clientCertFaults + Fault.genericFaults: connection = connect() connection.fault = fault try: connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, reqCert=True) assert() except: pass connection.close() print("Test 18 - good SRP, prepare to resume") sessionCache = SessionCache() connection = connect() connection.handshakeServer(verifierDB=verifierDB, sessionCache=sessionCache) assert(connection.session.serverName == address[0]) testConnServer(connection) connection.close() print("Test 19 - resumption") connection = connect() connection.handshakeServer(verifierDB=verifierDB, sessionCache=sessionCache) assert(connection.session.serverName == address[0]) testConnServer(connection) #Don't close! -- see next test print("Test 20 - invalidated resumption") try: connection.read(min=1, max=1) assert() #Client is going to close the socket without a close_notify except TLSAbruptCloseError as e: pass connection = connect() try: connection.handshakeServer(verifierDB=verifierDB, sessionCache=sessionCache) except TLSLocalAlert as alert: if alert.description != AlertDescription.bad_record_mac: raise connection.close() print("Test 21 - HTTPS test X.509") #Close the current listening socket lsock.close() #Create and run an HTTP Server using TLSSocketServerMixIn class MyHTTPServer(TLSSocketServerMixIn, HTTPServer): def handshake(self, tlsConnection): tlsConnection.handshakeServer(certChain=x509Chain, privateKey=x509Key) return True cd = os.getcwd() os.chdir(dir) address = address[0], address[1]+1 httpd = MyHTTPServer(address, SimpleHTTPRequestHandler) for x in range(6): httpd.handle_request() httpd.server_close() cd = os.chdir(cd) #Re-connect the listening socket lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) address = address[0], address[1]+1 lsock.bind(address) lsock.listen(5) implementations = [] if m2cryptoLoaded: implementations.append("openssl") if pycryptoLoaded: implementations.append("pycrypto") implementations.append("python") print("Test 22 - different ciphers") for implementation in ["python"] * len(implementations): for cipher in ["aes128", "aes256", "rc4"]: print("Test 22:", end=' ') connection = connect() settings = HandshakeSettings() settings.cipherNames = [cipher] settings.cipherImplementations = [implementation, "python"] connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) print(connection.getCipherName(), connection.getCipherImplementation()) testConnServer(connection) connection.close() print("Test 23 - throughput test") for implementation in implementations: for cipher in ["aes128", "aes256", "3des", "rc4"]: if cipher == "3des" and implementation not in ("openssl", "pycrypto"): continue print("Test 23:", end=' ') connection = connect() settings = HandshakeSettings() settings.cipherNames = [cipher] settings.cipherImplementations = [implementation, "python"] connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) print(connection.getCipherName(), connection.getCipherImplementation()) h = connection.read(min=50000, max=50000) assert(h == b"hello"*10000) connection.write(h) connection.close() print("Test 24.a - Next-Protocol Server Negotiation") connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"http/1.1"]) testConnServer(connection) connection.close() print("Test 24.b - Next-Protocol Server Negotiation") connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"spdy/2", b"http/1.1"]) testConnServer(connection) connection.close() print("Test 24.c - Next-Protocol Server Negotiation") connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"http/1.1", b"spdy/2"]) testConnServer(connection) connection.close() print("Test 24.d - Next-Protocol Server Negotiation") connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"spdy/2", b"http/1.1"]) testConnServer(connection) connection.close() print("Test 24.e - Next-Protocol Server Negotiation") connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"http/1.1", b"spdy/2", b"spdy/3"]) testConnServer(connection) connection.close() print("Test 24.f - Next-Protocol Server Negotiation") connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"spdy/3", b"spdy/2"]) testConnServer(connection) connection.close() print("Test 24.g - Next-Protocol Server Negotiation") connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[]) testConnServer(connection) connection.close() print("Tests 25-27 - XMLRPXC server") address = address[0], address[1]+1 class Server(TLSXMLRPCServer): def handshake(self, tlsConnection): try: tlsConnection.handshakeServer(certChain=x509Chain, privateKey=x509Key, sessionCache=sessionCache) tlsConnection.ignoreAbruptClose = True return True except TLSError as error: print("Handshake failure:", str(error)) return False class MyFuncs: def pow(self, x, y): return pow(x, y) def add(self, x, y): return x + y server = Server(address) server.register_instance(MyFuncs()) #sa = server.socket.getsockname() #print "Serving HTTPS on", sa[0], "port", sa[1] for i in range(6): server.handle_request() print("Test succeeded")
def handleArgs(argv, argString, flagsList=[]): # Convert to getopt argstring format: # Add ":" after each arg, ie "abc" -> "a:b:c:" getOptArgString = ":".join(argString) + ":" try: opts, argv = getopt.getopt(argv, getOptArgString, flagsList) except getopt.GetoptError as e: printError(e) # Default values if arg not present privateKey = None cert_chain = None virtual_hosts = [] v_host_cert = None username = None password = None tacks = None verifierDB = None reqCert = False directory = None expLabel = None expLength = 20 alpn = [] dhparam = None psk = None psk_ident = None psk_hash = 'sha256' resumption = False ssl3 = False max_ver = None tickets = None ciphers = [] request_pha = False require_pha = False for opt, arg in opts: if opt == "-k": s = open(arg, "rb").read() if sys.version_info[0] >= 3: s = str(s, 'utf-8') # OpenSSL/m2crypto does not support RSASSA-PSS certificates if not privateKey: privateKey = parsePEMKey(s, private=True, implementations=["python"]) else: if not v_host_cert: raise ValueError("Virtual host certificate missing " "(must be listed before key)") p_key = parsePEMKey(s, private=True, implementations=["python"]) if not virtual_hosts: virtual_hosts.append(VirtualHost()) virtual_hosts[0].keys.append( Keypair(p_key, v_host_cert.x509List)) v_host_cert = None elif opt == "-c": s = open(arg, "rb").read() if sys.version_info[0] >= 3: s = str(s, 'utf-8') if not cert_chain: cert_chain = X509CertChain() cert_chain.parsePemList(s) else: v_host_cert = X509CertChain() v_host_cert.parsePemList(s) elif opt == "-u": username = arg elif opt == "-p": password = arg elif opt == "-t": if tackpyLoaded: s = open(arg, "rU").read() tacks = Tack.createFromPemList(s) elif opt == "-v": verifierDB = VerifierDB(arg) verifierDB.open() elif opt == "-d": directory = arg elif opt == "--reqcert": reqCert = True elif opt == "-l": expLabel = arg elif opt == "-L": expLength = int(arg) elif opt == "-a": alpn.append(bytearray(arg, 'utf-8')) elif opt == "--param": s = open(arg, "rb").read() if sys.version_info[0] >= 3: s = str(s, 'utf-8') dhparam = parseDH(s) elif opt == "--psk": psk = a2b_hex(arg) elif opt == "--psk-ident": psk_ident = bytearray(arg, 'utf-8') elif opt == "--psk-sha384": psk_hash = 'sha384' elif opt == "--resumption": resumption = True elif opt == "--ssl3": ssl3 = True elif opt == "--max-ver": max_ver = ver_to_tuple(arg) elif opt == "--tickets": tickets = int(arg) elif opt == "--cipherlist": ciphers.append(arg) elif opt == "--request-pha": request_pha = True elif opt == "--require-pha": require_pha = True else: assert (False) # when no names provided, don't return array if not alpn: alpn = None if (psk and not psk_ident) or (not psk and psk_ident): printError("PSK and IDENTITY must be set together") if not argv: printError("Missing address") if len(argv) > 1: printError("Too many arguments") #Split address into hostname/port tuple address = argv[0] address = address.split(":") if len(address) != 2: raise SyntaxError("Must specify <host>:<port>") address = (address[0], int(address[1])) # Populate the return list retList = [address] if "k" in argString: retList.append(privateKey) if "c" in argString: retList.append(cert_chain) retList.append(virtual_hosts) if "u" in argString: retList.append(username) if "p" in argString: retList.append(password) if "t" in argString: retList.append(tacks) if "v" in argString: retList.append(verifierDB) if "d" in argString: retList.append(directory) if "reqcert" in flagsList: retList.append(reqCert) if "l" in argString: retList.append(expLabel) if "L" in argString: retList.append(expLength) if "a" in argString: retList.append(alpn) if "param=" in flagsList: retList.append(dhparam) if "psk=" in flagsList: retList.append(psk) if "psk-ident=" in flagsList: retList.append(psk_ident) if "psk-sha384" in flagsList: retList.append(psk_hash) if "resumption" in flagsList: retList.append(resumption) if "ssl3" in flagsList: retList.append(ssl3) if "max-ver=" in flagsList: retList.append(max_ver) if "tickets=" in flagsList: retList.append(tickets) if "cipherlist=" in flagsList: retList.append(ciphers) if "request-pha" in flagsList: retList.append(request_pha) if "require-pha" in flagsList: retList.append(require_pha) return retList
def handleArgs(argv, argString, flagsList=[]): # Convert to getopt argstring format: # Add ":" after each arg, ie "abc" -> "a:b:c:" getOptArgString = ":".join(argString) + ":" try: opts, argv = getopt.getopt(argv, getOptArgString, flagsList) except getopt.GetoptError as e: printError(e) # Default values if arg not present privateKey = None cert_chain = None username = None password = None tacks = None verifierDB = None reqCert = False directory = None expLabel = None expLength = 20 alpn = [] dhparam = None psk = None psk_ident = None psk_hash = 'sha256' resumption = False ssl3 = False max_ver = None tickets = None for opt, arg in opts: if opt == "-k": s = open(arg, "rb").read() if sys.version_info[0] >= 3: s = str(s, 'utf-8') # OpenSSL/m2crypto does not support RSASSA-PSS certificates privateKey = parsePEMKey(s, private=True, implementations=["python"]) elif opt == "-c": s = open(arg, "rb").read() if sys.version_info[0] >= 3: s = str(s, 'utf-8') cert_chain = X509CertChain() cert_chain.parsePemList(s) elif opt == "-u": username = arg elif opt == "-p": password = arg elif opt == "-t": if tackpyLoaded: s = open(arg, "rU").read() tacks = Tack.createFromPemList(s) elif opt == "-v": verifierDB = VerifierDB(arg) verifierDB.open() elif opt == "-d": directory = arg elif opt == "--reqcert": reqCert = True elif opt == "-l": expLabel = arg elif opt == "-L": expLength = int(arg) elif opt == "-a": alpn.append(bytearray(arg, 'utf-8')) elif opt == "--param": s = open(arg, "rb").read() if sys.version_info[0] >= 3: s = str(s, 'utf-8') dhparam = parseDH(s) elif opt == "--psk": psk = a2b_hex(arg) elif opt == "--psk-ident": psk_ident = bytearray(arg, 'utf-8') elif opt == "--psk-sha384": psk_hash = 'sha384' elif opt == "--resumption": resumption = True elif opt == "--ssl3": ssl3 = True elif opt == "--max-ver": max_ver = ver_to_tuple(arg) elif opt == "--tickets": tickets = int(arg) else: assert(False) # when no names provided, don't return array if not alpn: alpn = None if (psk and not psk_ident) or (not psk and psk_ident): printError("PSK and IDENTITY must be set together") if not argv: printError("Missing address") if len(argv)>1: printError("Too many arguments") #Split address into hostname/port tuple address = argv[0] address = address.split(":") if len(address) != 2: raise SyntaxError("Must specify <host>:<port>") address = ( address[0], int(address[1]) ) # Populate the return list retList = [address] if "k" in argString: retList.append(privateKey) if "c" in argString: retList.append(cert_chain) if "u" in argString: retList.append(username) if "p" in argString: retList.append(password) if "t" in argString: retList.append(tacks) if "v" in argString: retList.append(verifierDB) if "d" in argString: retList.append(directory) if "reqcert" in flagsList: retList.append(reqCert) if "l" in argString: retList.append(expLabel) if "L" in argString: retList.append(expLength) if "a" in argString: retList.append(alpn) if "param=" in flagsList: retList.append(dhparam) if "psk=" in flagsList: retList.append(psk) if "psk-ident=" in flagsList: retList.append(psk_ident) if "psk-sha384" in flagsList: retList.append(psk_hash) if "resumption" in flagsList: retList.append(resumption) if "ssl3" in flagsList: retList.append(ssl3) if "max-ver=" in flagsList: retList.append(max_ver) if "tickets=" in flagsList: retList.append(tickets) return retList
def serverTestCmd(argv): address = argv[0] dir = argv[1] #Split address into hostname/port tuple address = address.split(":") address = ( address[0], int(address[1]) ) #Create synchronisation FIFO synchroSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) synchroSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) synchroSocket.bind((address[0], address[1]-1)) synchroSocket.listen(2) #Connect to server lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) lsock.bind(address) lsock.listen(5) # following is blocking until the other side doesn't open synchro = synchroSocket.accept()[0] def connect(): return TLSConnection(lsock.accept()[0]) x509Cert = X509().parse(open(os.path.join(dir, "serverX509Cert.pem")).read()) x509Chain = X509CertChain([x509Cert]) s = open(os.path.join(dir, "serverX509Key.pem")).read() x509Key = parsePEMKey(s, private=True) with open(os.path.join(dir, "serverRSAPSSSigCert.pem")) as f: x509CertRSAPSSSig = X509().parse(f.read()) x509ChainRSAPSSSig = X509CertChain([x509CertRSAPSSSig]) with open(os.path.join(dir, "serverRSAPSSSigKey.pem")) as f: x509KeyRSAPSSSig = parsePEMKey(f.read(), private=True) with open(os.path.join(dir, "serverRSAPSSCert.pem")) as f: x509CertRSAPSS = X509().parse(f.read()) x509ChainRSAPSS = X509CertChain([x509CertRSAPSS]) assert x509CertRSAPSS.certAlg == "rsa-pss" with open(os.path.join(dir, "serverRSAPSSKey.pem")) as f: x509KeyRSAPSS = parsePEMKey(f.read(), private=True, implementations=["python"]) test_no = 0 print("Test {0} - Anonymous server handshake".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(anon=True) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - good X.509".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) assert(connection.session.serverName == address[0]) assert(connection.extendedMasterSecret) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - good X.509/w RSA-PSS sig".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509ChainRSAPSSSig, privateKey=x509KeyRSAPSSSig) assert(connection.session.serverName == address[0]) assert(connection.extendedMasterSecret) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - good X.509/w RSA-PSS cert".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509ChainRSAPSS, privateKey=x509KeyRSAPSS) assert(connection.session.serverName == address[0]) assert(connection.extendedMasterSecret) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - good X.509, SSL v3".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.minVersion = (3,0) settings.maxVersion = (3,0) connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) assert(not connection.extendedMasterSecret) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - good X.509, RC4-MD5".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.macNames = ["sha", "md5"] settings.cipherNames = ["rc4"] connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) testConnServer(connection) connection.close() if tackpyLoaded: tack = Tack.createFromPem(open("./TACK1.pem", "rU").read()) tackUnrelated = Tack.createFromPem(open("./TACKunrelated.pem", "rU").read()) settings = HandshakeSettings() settings.useExperimentalTackExtension = True test_no += 1 print("Test {0} - good X.509, TACK".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, tacks=[tack], activationFlags=1, settings=settings) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - good X.509, TACK unrelated to cert chain".\ format(test_no)) synchro.send(b'R') connection = connect() try: connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, tacks=[tackUnrelated], settings=settings) assert(False) except TLSRemoteAlert as alert: if alert.description != AlertDescription.illegal_parameter: raise else: test_no += 1 print("Test {0} - good X.509, TACK...skipped (no tackpy)".\ format(test_no)) test_no += 1 print("Test {0} - good X.509, TACK unrelated to cert chain" "...skipped (no tackpy)".format(test_no)) test_no += 1 print("Test {0} - good SRP (db)".format(test_no)) try: (db_file, db_name) = mkstemp() os.close(db_file) # this is race'y but the interface dbm interface is stupid like that... os.remove(db_name) verifierDB = VerifierDB(db_name) verifierDB.create() entry = VerifierDB.makeVerifier("test", "password", 1536) verifierDB[b"test"] = entry synchro.send(b'R') connection = connect() connection.handshakeServer(verifierDB=verifierDB) testConnServer(connection) connection.close() finally: try: os.remove(db_name) except FileNotFoundError: # dbm module may create files with different names depending on # platform os.remove(db_name + ".dat") test_no += 1 print("Test {0} - good SRP".format(test_no)) verifierDB = VerifierDB() verifierDB.create() entry = VerifierDB.makeVerifier("test", "password", 1536) verifierDB[b"test"] = entry synchro.send(b'R') connection = connect() connection.handshakeServer(verifierDB=verifierDB) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - SRP faults".format(test_no)) for fault in Fault.clientSrpFaults + Fault.genericFaults: synchro.send(b'R') connection = connect() connection.fault = fault connection.handshakeServer(verifierDB=verifierDB) connection.close() test_no += 1 print("Test {0} - good SRP: with X.509 cert".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(verifierDB=verifierDB, \ certChain=x509Chain, privateKey=x509Key) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - X.509 with SRP faults".format(test_no)) for fault in Fault.clientSrpFaults + Fault.genericFaults: synchro.send(b'R') connection = connect() connection.fault = fault connection.handshakeServer(verifierDB=verifierDB, \ certChain=x509Chain, privateKey=x509Key) connection.close() test_no += 1 print("Test {0} - X.509 faults".format(test_no)) for fault in Fault.clientNoAuthFaults + Fault.genericFaults: synchro.send(b'R') connection = connect() connection.fault = fault connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) connection.close() test_no += 1 print("Test {0} - good mutual X.509".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, reqCert=True) testConnServer(connection) assert(isinstance(connection.session.clientCertChain, X509CertChain)) connection.close() test_no += 1 print("Test {0} - good mutual X.509, TLSv1.1".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.minVersion = (3,2) settings.maxVersion = (3,2) connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, reqCert=True, settings=settings) testConnServer(connection) assert(isinstance(connection.session.clientCertChain, X509CertChain)) connection.close() test_no += 1 print("Test {0} - good mutual X.509, SSLv3".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.minVersion = (3,0) settings.maxVersion = (3,0) connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, reqCert=True, settings=settings) testConnServer(connection) assert(isinstance(connection.session.clientCertChain, X509CertChain)) connection.close() test_no += 1 print("Test {0} - mutual X.509 faults".format(test_no)) for fault in Fault.clientCertFaults + Fault.genericFaults: synchro.send(b'R') connection = connect() connection.fault = fault connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, reqCert=True) connection.close() test_no += 1 print("Test {0} - good SRP, prepare to resume".format(test_no)) synchro.send(b'R') sessionCache = SessionCache() connection = connect() connection.handshakeServer(verifierDB=verifierDB, sessionCache=sessionCache) assert(connection.session.serverName == address[0]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - resumption".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(verifierDB=verifierDB, sessionCache=sessionCache) assert(connection.session.serverName == address[0]) testConnServer(connection) #Don't close! -- see next test test_no += 1 print("Test {0} - invalidated resumption".format(test_no)) synchro.send(b'R') try: connection.read(min=1, max=1) assert() #Client is going to close the socket without a close_notify except TLSAbruptCloseError as e: pass synchro.send(b'R') connection = connect() try: connection.handshakeServer(verifierDB=verifierDB, sessionCache=sessionCache) except TLSLocalAlert as alert: if alert.description != AlertDescription.bad_record_mac: raise connection.close() test_no += 1 print("Test {0} - HTTPS test X.509".format(test_no)) #Close the current listening socket lsock.close() #Create and run an HTTP Server using TLSSocketServerMixIn class MyHTTPServer(TLSSocketServerMixIn, HTTPServer): def handshake(self, tlsConnection): tlsConnection.handshakeServer(certChain=x509Chain, privateKey=x509Key) return True def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) HTTPServer.server_bind(self) cd = os.getcwd() os.chdir(dir) address = address[0], address[1]+1 httpd = MyHTTPServer(address, SimpleHTTPRequestHandler) for x in range(6): synchro.send(b'R') httpd.handle_request() httpd.server_close() cd = os.chdir(cd) #Re-connect the listening socket lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) address = address[0], address[1]+1 lsock.bind(address) lsock.listen(5) implementations = [] if m2cryptoLoaded: implementations.append("openssl") if pycryptoLoaded: implementations.append("pycrypto") implementations.append("python") test_no += 1 print("Test {0} - different ciphers".format(test_no)) for implementation in ["python"] * len(implementations): for cipher in ["aes128", "aes256", "rc4"]: test_no += 1 print("Test {0}:".format(test_no), end=' ') synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.cipherNames = [cipher] settings.cipherImplementations = [implementation, "python"] connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) print(connection.getCipherName(), connection.getCipherImplementation()) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - throughput test".format(test_no)) for implementation in implementations: for cipher in ["aes128gcm", "aes256gcm", "aes128", "aes256", "3des", "rc4", "chacha20-poly1305_draft00", "chacha20-poly1305"]: # skip tests with implementations that don't support them if cipher == "3des" and implementation not in ("openssl", "pycrypto"): continue if cipher in ("aes128gcm", "aes256gcm") and \ implementation not in ("pycrypto", "python"): continue if cipher in ("chacha20-poly1305_draft00", "chacha20-poly1305") \ and implementation not in ("python", ): continue test_no += 1 print("Test {0}:".format(test_no), end=' ') synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.cipherNames = [cipher] settings.cipherImplementations = [implementation, "python"] connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) print(connection.getCipherName(), connection.getCipherImplementation()) h = connection.read(min=50000, max=50000) assert(h == b"hello"*10000) connection.write(h) connection.close() test_no += 1 print("Test {0} - Next-Protocol Server Negotiation".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"http/1.1"]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - Next-Protocol Server Negotiation".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"spdy/2", b"http/1.1"]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - Next-Protocol Server Negotiation".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"http/1.1", b"spdy/2"]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - Next-Protocol Server Negotiation".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"spdy/2", b"http/1.1"]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - Next-Protocol Server Negotiation".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"http/1.1", b"spdy/2", b"spdy/3"]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - Next-Protocol Server Negotiation".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[b"spdy/3", b"spdy/2"]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - Next-Protocol Server Negotiation".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings, nextProtos=[]) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - FALLBACK_SCSV".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - FALLBACK_SCSV".format(test_no)) synchro.send(b'R') connection = connect() try: connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) assert() except TLSLocalAlert as alert: if alert.description != AlertDescription.inappropriate_fallback: raise connection.close() test_no += 1 print("Test {0} - no EtM server side".format(test_no)) synchro.send(b'R') connection = connect() settings = HandshakeSettings() settings.useEncryptThenMAC = False connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - no EtM client side".format(test_no)) synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - resumption with EtM".format(test_no)) synchro.send(b'R') sessionCache = SessionCache() connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, sessionCache=sessionCache) testConnServer(connection) connection.close() # resume synchro.send(b'R') connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, sessionCache=sessionCache) testConnServer(connection) connection.close() test_no += 1 print("Test {0} - resumption with no EtM in 2nd handshake".format(test_no)) synchro.send(b'R') sessionCache = SessionCache() connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, sessionCache=sessionCache) testConnServer(connection) connection.close() # resume synchro.send(b'R') connection = connect() try: connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, sessionCache=sessionCache) except TLSLocalAlert as e: assert(str(e) == "handshake_failure") else: raise AssertionError("no exception raised") connection.close() test_no += 1 print("Tests {0}-{1} - XMLRPXC server".format(test_no, test_no + 2)) test_no += 2 address = address[0], address[1]+1 class Server(TLSXMLRPCServer): def handshake(self, tlsConnection): try: tlsConnection.handshakeServer(certChain=x509Chain, privateKey=x509Key, sessionCache=sessionCache) tlsConnection.ignoreAbruptClose = True return True except TLSError as error: print("Handshake failure:", str(error)) return False class MyFuncs: def pow(self, x, y): return pow(x, y) def add(self, x, y): return x + y server = Server(address) server.register_instance(MyFuncs()) synchro.send(b'R') #sa = server.socket.getsockname() #print "Serving HTTPS on", sa[0], "port", sa[1] for i in range(6): synchro.send(b'R') server.handle_request() synchro.close() synchroSocket.close() print("Test succeeded")
def serverTestCmd(argv): address = argv[0] dir = argv[1] #Split address into hostname/port tuple address = address.split(":") address = (address[0], int(address[1])) #Connect to server lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) lsock.bind(address) lsock.listen(5) def connect(): return TLSConnection(lsock.accept()[0]) print "Test 0 - Anonymous server handshake" connection = connect() connection.handshakeServer(anon=True) testConnServer(connection) connection.close() print "Test 1 - good X.509" x509Cert = X509().parse( open(os.path.join(dir, "serverX509Cert.pem")).read()) x509Chain = X509CertChain([x509Cert]) s = open(os.path.join(dir, "serverX509Key.pem")).read() x509Key = parsePEMKey(s, private=True) connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key) assert (connection.session.serverName == address[0]) testConnServer(connection) connection.close() print "Test 1.a - good X.509, SSL v3" connection = connect() settings = HandshakeSettings() settings.minVersion = (3, 0) settings.maxVersion = (3, 0) connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, settings=settings) testConnServer(connection) connection.close() if tackpyLoaded: tack = Tack.createFromPem(open("./TACK1.pem", "rU").read()) tackUnrelated = Tack.createFromPem( open("./TACKunrelated.pem", "rU").read()) settings = HandshakeSettings() settings.useExperimentalTackExtension = True print "Test 2.a - good X.509, TACK" connection = connect() connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, tacks=[tack], activationFlags=1, settings=settings) testConnServer(connection) connection.close() print "Test 2.b - good X.509, TACK unrelated to cert chain" connection = connect() try: connection.handshakeServer(certChain=x509Chain, privateKey=x509Key, tacks=[tackUnrelated], settings=settings) assert (False) except TLSRemoteAlert, alert: if alert.description != AlertDescription.illegal_parameter: raise
if opt == "-k": s = open(arg, "rb").read() privateKey = parsePEMKey(s, private=True) elif opt == "-c": s = open(arg, "rb").read() x509 = X509() x509.parse(s) certChain = X509CertChain([x509]) elif opt == "-u": username = arg elif opt == "-p": password = arg elif opt == "-t": if tackpyLoaded: s = open(arg, "rU").read() tack = Tack.createFromPem(s) elif opt == "-b": if tackpyLoaded: s = open(arg, "rU").read() breakSigs = TackBreakSig.createFromPemList(s) elif opt == "-v": verifierDB = VerifierDB(arg) verifierDB.open() elif opt == "-d": directory = arg elif opt == "--reqcert": reqCert = True else: assert False if not argv: