diff --git a/scripts/tls.py b/scripts/tls.py index e0653ca2..5628afbc 100755 --- a/scripts/tls.py +++ b/scripts/tls.py @@ -43,12 +43,12 @@ def printUsage(s=None): if s: - print("ERROR: %s" % s) + print("ERROR: {0!s}".format(s)) print("") - print("Version: %s" % __version__) + print("Version: {0!s}".format(__version__)) print("") - print("RNG: %s" % prngName) + print("RNG: {0!s}".format(prngName)) print("") print("Modules:") if tackpyLoaded: @@ -88,7 +88,7 @@ def printUsage(s=None): def printError(s): """Print error message and exit""" - sys.stderr.write("ERROR: %s\n" % s) + sys.stderr.write("ERROR: {0!s}\n".format(s)) sys.exit(-1) @@ -192,22 +192,22 @@ def handleArgs(argv, argString, flagsList=[]): def printGoodConnection(connection, seconds): - print(" Handshake time: %.3f seconds" % seconds) - print(" Version: %s" % connection.getVersionName()) - print(" Cipher: %s %s" % (connection.getCipherName(), + print(" Handshake time: {0:.3f} seconds".format(seconds)) + print(" Version: {0!s}".format(connection.getVersionName())) + print(" Cipher: {0!s} {1!s}".format(connection.getCipherName(), connection.getCipherImplementation())) print(" Ciphersuite: {0}".\ format(CipherSuite.ietfNames[connection.session.cipherSuite])) if connection.session.srpUsername: - print(" Client SRP username: %s" % connection.session.srpUsername) + print(" Client SRP username: {0!s}".format(connection.session.srpUsername)) if connection.session.clientCertChain: - print(" Client X.509 SHA1 fingerprint: %s" % - connection.session.clientCertChain.getFingerprint()) + print(" Client X.509 SHA1 fingerprint: {0!s}".format( + connection.session.clientCertChain.getFingerprint())) else: print(" No client certificate provided by peer") if connection.session.serverCertChain: - print(" Server X.509 SHA1 fingerprint: %s" % - connection.session.serverCertChain.getFingerprint()) + print(" Server X.509 SHA1 fingerprint: {0!s}".format( + connection.session.serverCertChain.getFingerprint())) if connection.version >= (3, 3) and connection.serverSigAlg is not None: print(" Key exchange signature: {1}+{0}".format(\ HashAlgorithm.toStr(connection.serverSigAlg[0]), @@ -218,18 +218,18 @@ def printGoodConnection(connection, seconds): if connection.dhGroupSize is not None: print(" DH group size: {0} bits".format(connection.dhGroupSize)) if connection.session.serverName: - print(" SNI: %s" % connection.session.serverName) + print(" SNI: {0!s}".format(connection.session.serverName)) if connection.session.tackExt: if connection.session.tackInHelloExt: emptyStr = "\n (via TLS Extension)" else: emptyStr = "\n (via TACK Certificate)" - print(" TACK: %s" % emptyStr) + print(" TACK: {0!s}".format(emptyStr)) print(str(connection.session.tackExt)) if connection.session.appProto: print(" Application Layer Protocol negotiated: {0}".format( connection.session.appProto.decode('utf-8'))) - print(" Next-Protocol Negotiated: %s" % connection.next_proto) + print(" Next-Protocol Negotiated: {0!s}".format(connection.next_proto)) print(" Encrypt-then-MAC: {0}".format(connection.encryptThenMAC)) print(" Extended Master Secret: {0}".format( connection.extendedMasterSecret)) @@ -314,11 +314,10 @@ def serverCmd(argv): if tacks and not certChain: raise SyntaxError("Must specify CERT with Tacks") - print("I am an HTTPS test server, I will listen on %s:%d" % - (address[0], address[1])) + print("I am an HTTPS test server, I will listen on {0!s}:{1:d}".format(address[0], address[1])) if directory: os.chdir(directory) - print("Serving files from %s" % os.getcwd()) + print("Serving files from {0!s}".format(os.getcwd())) if certChain and privateKey: print("Using certificate and private key...") @@ -402,5 +401,5 @@ def handshake(self, connection): elif sys.argv[1] == "server"[:len(sys.argv[1])]: serverCmd(sys.argv[2:]) else: - printUsage("Unknown command: %s" % sys.argv[1]) + printUsage("Unknown command: {0!s}".format(sys.argv[1])) diff --git a/scripts/tlsdb.py b/scripts/tlsdb.py index 476d6189..967b02e1 100755 --- a/scripts/tlsdb.py +++ b/scripts/tlsdb.py @@ -21,9 +21,9 @@ if len(sys.argv) == 1 or (len(sys.argv)==2 and sys.argv[1].lower().endswith("help")): print("") - print("Version: %s" % __version__) + print("Version: {0!s}".format(__version__)) print("") - print("RNG: %s" % prngName) + print("RNG: {0!s}".format(prngName)) print("") print("Modules:") if m2cryptoLoaded: @@ -78,7 +78,7 @@ def reformatDocString(s): if command == "valid": print("") else: - print("Bad command: '%s'" % command) + print("Bad command: '{0!s}'".format(command)) elif cmd == "createsrp": dbName = args.get(2) @@ -145,6 +145,6 @@ def numBits(n): N, g, s, v = db[username] print(numBits(N), username) else: - print("Bad command: '%s'" % cmd) + print("Bad command: '{0!s}'".format(cmd)) except: raise diff --git a/tests/tlstest.py b/tests/tlstest.py index e4f225d1..f64b1d64 100755 --- a/tests/tlstest.py +++ b/tests/tlstest.py @@ -53,14 +53,14 @@ def printUsage(s=None): else: crypto = "Python crypto" if s: - print("ERROR: %s" % s) - print("""\ntls.py version %s (using %s) + print("ERROR: {0!s}".format(s)) + print("""\ntls.py version {0!s} (using {1!s}) Commands: server HOST:PORT DIRECTORY client HOST:PORT DIRECTORY -""" % (__version__, crypto)) +""".format(__version__, crypto)) sys.exit(-1) @@ -220,9 +220,9 @@ def connect(): connection.fault = fault try: connection.handshakeClientSRP("test", "password") - print(" Good Fault %s" % (Fault.faultNames[fault])) + print(" Good Fault {0!s}".format((Fault.faultNames[fault]))) except TLSFaultError as e: - print(" BAD FAULT %s: %s" % (Fault.faultNames[fault], str(e))) + print(" BAD FAULT {0!s}: {1!s}".format(Fault.faultNames[fault], str(e))) badFault = True test_no += 1 @@ -247,9 +247,9 @@ def connect(): connection.fault = fault try: connection.handshakeClientSRP("test", "password") - print(" Good Fault %s" % (Fault.faultNames[fault])) + print(" Good Fault {0!s}".format((Fault.faultNames[fault]))) except TLSFaultError as e: - print(" BAD FAULT %s: %s" % (Fault.faultNames[fault], str(e))) + print(" BAD FAULT {0!s}: {1!s}".format(Fault.faultNames[fault], str(e))) badFault = True test_no += 1 @@ -261,9 +261,9 @@ def connect(): connection.fault = fault try: connection.handshakeClientCert() - print(" Good Fault %s" % (Fault.faultNames[fault])) + print(" Good Fault {0!s}".format((Fault.faultNames[fault]))) except TLSFaultError as e: - print(" BAD FAULT %s: %s" % (Fault.faultNames[fault], str(e))) + print(" BAD FAULT {0!s}: {1!s}".format(Fault.faultNames[fault], str(e))) badFault = True test_no += 1 @@ -316,9 +316,9 @@ def connect(): connection.fault = fault try: connection.handshakeClientCert(x509Chain, x509Key) - print(" Good Fault %s" % (Fault.faultNames[fault])) + print(" Good Fault {0!s}".format((Fault.faultNames[fault]))) except TLSFaultError as e: - print(" BAD FAULT %s: %s" % (Fault.faultNames[fault], str(e))) + print(" BAD FAULT {0!s}: {1!s}".format(Fault.faultNames[fault], str(e))) badFault = True test_no += 1 @@ -416,7 +416,7 @@ def connect(): settings.maxVersion = (3,1) connection.handshakeClientCert(settings=settings) testConnClient(connection) - print("%s %s" % (connection.getCipherName(), connection.getCipherImplementation())) + print("{0!s} {1!s}".format(connection.getCipherName(), connection.getCipherImplementation())) connection.close() test_no += 1 @@ -448,14 +448,14 @@ def connect(): settings.cipherNames = [cipher] settings.cipherImplementations = [implementation, "python"] connection.handshakeClientCert(settings=settings) - print("%s %s:" % (connection.getCipherName(), connection.getCipherImplementation()), end=' ') + print("{0!s} {1!s}:".format(connection.getCipherName(), connection.getCipherImplementation()), end=' ') startTime = time.clock() connection.write(b"hello"*10000) h = connection.read(min=50000, max=50000) stopTime = time.clock() if stopTime-startTime: - print("100K exchanged at rate of %d bytes/sec" % int(100000/(stopTime-startTime))) + print("100K exchanged at rate of {0:d} bytes/sec".format(int(100000/(stopTime-startTime)))) else: print("100K exchanged very fast") @@ -657,9 +657,9 @@ def connect(): # python 3.4.2 doesn't have it though context = ssl.create_default_context(\ cafile=os.path.join(dir, "serverX509Cert.pem")) - server = xmlrpclib.Server('https://%s:%s' % address, context=context) + server = xmlrpclib.Server('https://{0!s}:{1!s}'.format(*address), context=context) except (TypeError, AttributeError): - server = xmlrpclib.Server('https://%s:%s' % address) + server = xmlrpclib.Server('https://{0!s}:{1!s}'.format(*address)) synchro.recv(1) assert server.add(1,2) == 3 @@ -670,7 +670,7 @@ def connect(): print('Test {0} - good tlslite XMLRPC client'.format(test_no)) transport = XMLRPCTransport(ignoreAbruptClose=True) - server = xmlrpclib.Server('https://%s:%s' % address, transport) + server = xmlrpclib.Server('https://{0!s}:{1!s}'.format(*address), transport) synchro.recv(1) assert server.add(1,2) == 3 synchro.recv(1) @@ -679,7 +679,7 @@ def connect(): test_no += 1 print('Test {0} - good XMLRPC ignored protocol'.format(test_no)) - server = xmlrpclib.Server('http://%s:%s' % address, transport) + server = xmlrpclib.Server('http://{0!s}:{1!s}'.format(*address), transport) synchro.recv(1) assert server.add(1,2) == 3 synchro.recv(1) @@ -1311,4 +1311,4 @@ def add(self, x, y): return x + y elif sys.argv[1] == "server"[:len(sys.argv[1])]: serverTestCmd(sys.argv[2:]) else: - printUsage("Unknown command: %s" % sys.argv[1]) + printUsage("Unknown command: {0!s}".format(sys.argv[1])) diff --git a/tlslite/basedb.py b/tlslite/basedb.py index 7ec45672..ce6e7ed7 100644 --- a/tlslite/basedb.py +++ b/tlslite/basedb.py @@ -46,7 +46,7 @@ def open(self): self.db = anydbm.open(self.filename, "w") #raises anydbm.error try: if self.db["--Reserved--type"] != self.type: - raise ValueError("Not a %s database" % self.type) + raise ValueError("Not a {0!s} database".format(self.type)) except KeyError: raise ValueError("Not a recognized database") diff --git a/tlslite/checker.py b/tlslite/checker.py index 4f2ee820..9ed3e6ad 100644 --- a/tlslite/checker.py +++ b/tlslite/checker.py @@ -69,8 +69,7 @@ def __call__(self, connection): if self.x509Fingerprint: if chain.getFingerprint() != self.x509Fingerprint: raise TLSFingerprintError(\ - "X.509 fingerprint mismatch: %s, %s" % \ - (chain.getFingerprint(), self.x509Fingerprint)) + "X.509 fingerprint mismatch: {0!s}, {1!s}".format(chain.getFingerprint(), self.x509Fingerprint)) elif chain: raise TLSAuthenticationTypeError() else: diff --git a/tlslite/handshakesettings.py b/tlslite/handshakesettings.py index a1d61562..c5f98be5 100644 --- a/tlslite/handshakesettings.py +++ b/tlslite/handshakesettings.py @@ -178,28 +178,28 @@ def _sanityCheckPrimitivesNames(other): unknownCiphers = [val for val in other.cipherNames \ if val not in ALL_CIPHER_NAMES] if unknownCiphers: - raise ValueError("Unknown cipher name: %s" % unknownCiphers) + raise ValueError("Unknown cipher name: {0!s}".format(unknownCiphers)) unknownMacs = [val for val in other.macNames \ if val not in ALL_MAC_NAMES] if unknownMacs: - raise ValueError("Unknown MAC name: %s" % unknownMacs) + raise ValueError("Unknown MAC name: {0!s}".format(unknownMacs)) unknownKex = [val for val in other.keyExchangeNames \ if val not in KEY_EXCHANGE_NAMES] if unknownKex: - raise ValueError("Unknown key exchange name: %s" % unknownKex) + raise ValueError("Unknown key exchange name: {0!s}".format(unknownKex)) unknownImpl = [val for val in other.cipherImplementations \ if val not in CIPHER_IMPLEMENTATIONS] if unknownImpl: - raise ValueError("Unknown cipher implementation: %s" % \ - unknownImpl) + raise ValueError("Unknown cipher implementation: {0!s}".format( \ + unknownImpl)) unknownType = [val for val in other.certificateTypes \ if val not in CERTIFICATE_TYPES] if unknownType: - raise ValueError("Unknown certificate type: %s" % unknownType) + raise ValueError("Unknown certificate type: {0!s}".format(unknownType)) unknownCurve = [val for val in other.eccCurves \ if val not in ALL_CURVE_NAMES] diff --git a/tlslite/tlsconnection.py b/tlslite/tlsconnection.py index 9ca33617..998bdf5b 100644 --- a/tlslite/tlsconnection.py +++ b/tlslite/tlsconnection.py @@ -698,12 +698,12 @@ def _clientGetServerHello(self, settings, clientHello): if serverHello.server_version < settings.minVersion: for result in self._sendError(\ AlertDescription.protocol_version, - "Too old version: %s" % str(serverHello.server_version)): + "Too old version: {0!s}".format(str(serverHello.server_version))): yield result if serverHello.server_version > settings.maxVersion: for result in self._sendError(\ AlertDescription.protocol_version, - "Too new version: %s" % str(serverHello.server_version)): + "Too new version: {0!s}".format(str(serverHello.server_version))): yield result serverVer = serverHello.server_version cipherSuites = CipherSuite.filterForVersion(clientHello.cipher_suites, @@ -1035,11 +1035,11 @@ def _clientGetKeyFromChain(self, certificate, settings, tackExt=None): publicKey = certChain.getEndEntityPublicKey() if len(publicKey) < settings.minKeySize: for result in self._sendError(AlertDescription.handshake_failure, - "Other party's public key too small: %d" % len(publicKey)): + "Other party's public key too small: {0:d}".format(len(publicKey))): yield result if len(publicKey) > settings.maxKeySize: for result in self._sendError(AlertDescription.handshake_failure, - "Other party's public key too large: %d" % len(publicKey)): + "Other party's public key too large: {0:d}".format(len(publicKey))): yield result # If there's no TLS Extension, look for a TACK cert @@ -1449,7 +1449,7 @@ def _serverGetClientHello(self, settings, certChain, verifierDB, self.version = settings.minVersion for result in self._sendError(\ AlertDescription.protocol_version, - "Too old version: %s" % str(clientHello.client_version)): + "Too old version: {0!s}".format(str(clientHello.client_version))): yield result # Sanity check the ALPN extension @@ -1834,13 +1834,13 @@ def _serverCertKeyExchange(self, clientHello, serverHello, if len(publicKey) < settings.minKeySize: for result in self._sendError(\ AlertDescription.handshake_failure, - "Client's public key too small: %d" % len(publicKey)): + "Client's public key too small: {0:d}".format(len(publicKey))): yield result if len(publicKey) > settings.maxKeySize: for result in self._sendError(\ AlertDescription.handshake_failure, - "Client's public key too large: %d" % len(publicKey)): + "Client's public key too large: {0:d}".format(len(publicKey))): yield result if not publicKey.verify(certificateVerify.signature, verifyBytes): diff --git a/tlslite/tlsrecordlayer.py b/tlslite/tlsrecordlayer.py index 828e3058..185133d6 100644 --- a/tlslite/tlsrecordlayer.py +++ b/tlslite/tlsrecordlayer.py @@ -725,7 +725,7 @@ def _getMsg(self, expectedType, secondaryType=None, constructorType=None): #alert nor renegotiation for result in self._sendError(\ AlertDescription.unexpected_message, - "received type=%d" % recordHeader.type): + "received type={0:d}".format(recordHeader.type)): yield result break @@ -760,7 +760,7 @@ def _getMsg(self, expectedType, secondaryType=None, constructorType=None): if subType not in secondaryType: for result in self._sendError(\ AlertDescription.unexpected_message, - "Expecting %s, got %s" % (str(secondaryType), subType)): + "Expecting {0!s}, got {1!s}".format(str(secondaryType), subType)): yield result #Update handshake hashes diff --git a/tlslite/utils/compat.py b/tlslite/utils/compat.py index c971eff8..a8ddbda4 100644 --- a/tlslite/utils/compat.py +++ b/tlslite/utils/compat.py @@ -31,7 +31,7 @@ def a2b_hex(s): try: b = bytearray(binascii.a2b_hex(bytearray(s, "ascii"))) except Exception as e: - raise SyntaxError("base16 error: %s" % e) + raise SyntaxError("base16 error: {0!s}".format(e)) return b def a2b_base64(s): @@ -40,7 +40,7 @@ def a2b_base64(s): s = bytearray(s, "ascii") b = bytearray(binascii.a2b_base64(s)) except Exception as e: - raise SyntaxError("base64 error: %s" % e) + raise SyntaxError("base64 error: {0!s}".format(e)) return b def b2a_hex(b): @@ -76,14 +76,14 @@ def a2b_hex(s): try: b = bytearray(binascii.a2b_hex(s)) except Exception as e: - raise SyntaxError("base16 error: %s" % e) + raise SyntaxError("base16 error: {0!s}".format(e)) return b def a2b_base64(s): try: b = bytearray(binascii.a2b_base64(s)) except Exception as e: - raise SyntaxError("base64 error: %s" % e) + raise SyntaxError("base64 error: {0!s}".format(e)) return b def b2a_hex(b): diff --git a/tlslite/utils/datefuncs.py b/tlslite/utils/datefuncs.py index d8f0d240..02788f55 100644 --- a/tlslite/utils/datefuncs.py +++ b/tlslite/utils/datefuncs.py @@ -54,8 +54,7 @@ def createDateClass(year, month, day, hour, minute, second): return c def printDateClass(d): - return "%04d-%02d-%02dT%02d:%02d:%02dZ" % \ - (d.get(d.YEAR), d.get(d.MONTH)+1, d.get(d.DATE), \ + return "{0:04d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}Z".format(d.get(d.YEAR), d.get(d.MONTH)+1, d.get(d.DATE), \ d.get(d.HOUR_OF_DAY), d.get(d.MINUTE), d.get(d.SECOND)) def getNow(): diff --git a/tlslite/utils/pem.py b/tlslite/utils/pem.py index 548bc34d..ff5237d3 100644 --- a/tlslite/utils/pem.py +++ b/tlslite/utils/pem.py @@ -22,15 +22,15 @@ def dePem(s, name): The first such PEM block in the input will be found, and its payload will be base64 decoded and returned. """ - prefix = "-----BEGIN %s-----" % name - postfix = "-----END %s-----" % name + prefix = "-----BEGIN {0!s}-----".format(name) + postfix = "-----END {0!s}-----".format(name) start = s.find(prefix) if start == -1: raise SyntaxError("Missing PEM prefix") end = s.find(postfix, start+len(prefix)) if end == -1: raise SyntaxError("Missing PEM postfix") - s = s[start+len("-----BEGIN %s-----" % name) : end] + s = s[start+len("-----BEGIN {0!s}-----".format(name)) : end] retBytes = a2b_base64(s) # May raise SyntaxError return retBytes @@ -59,8 +59,8 @@ def dePemList(s, name): of bytearrays, which may have zero elements if not PEM blocks are found. """ bList = [] - prefix = "-----BEGIN %s-----" % name - postfix = "-----END %s-----" % name + prefix = "-----BEGIN {0!s}-----".format(name) + postfix = "-----END {0!s}-----".format(name) while 1: start = s.find(prefix) if start == -1: @@ -90,10 +90,10 @@ def pem(b, name): while s1: s2 += s1[:64] + "\n" s1 = s1[64:] - s = ("-----BEGIN %s-----\n" % name) + s2 + \ - ("-----END %s-----\n" % name) + s = ("-----BEGIN {0!s}-----\n".format(name)) + s2 + \ + ("-----END {0!s}-----\n".format(name)) return s def pemSniff(inStr, name): - searchStr = "-----BEGIN %s-----" % name + searchStr = "-----BEGIN {0!s}-----".format(name) return searchStr in inStr