2 import subprocess, sys, argparse, time, re
3 from collections import OrderedDict, namedtuple
6 # progress bar and other console output fun
10 import fcntl, termios, struct
12 result = fcntl.ioctl(1, termios.TIOCGWINSZ, struct.pack('HHHH', 0, 0, 0, 0))
14 # this is not a terminal
16 h, w, hp, wp = struct.unpack('HHHH', result)
17 assert w > 0 and h > 0, "Empty terminal...??"
20 def compute_frac(fracs):
23 for complete, total in fracs:
24 frac += (complete*last_frac/total)
28 def print_progress(state, fracs):
29 w, h = terminal_size()
30 if w < STATE_WIDTH+10: return # not a (wide enough) terminal
31 bar_width = w-STATE_WIDTH-3
32 hashes = int(bar_width*compute_frac(fracs))
33 sys.stdout.write('\r{0} [{1}{2}]'.format(state[:STATE_WIDTH].ljust(STATE_WIDTH), '#'*hashes, ' '*(bar_width-hashes)))
35 def finish_progress():
36 w, h = terminal_size()
37 sys.stdout.write('\r'+(' '*w)+'\r')
41 BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
43 COLOR_SEQ = "\033[1;3%dm"
47 def color(text, color):
48 return (ConsoleFormat.COLOR_SEQ % color) + text + ConsoleFormat.RESET_SEQ
52 def list_ciphers(spec="ALL:COMPLEMENTOFALL"):
53 ciphers = subprocess.check_output(["openssl", "ciphers", spec]).decode('UTF-8').strip()
54 return ciphers.split(':')
56 def test_cipher(host, port, protocol, cipher = None, options=[]):
58 if cipher is not None:
59 options = ["-cipher", cipher]+options
60 subprocess.check_call(["openssl", "s_client", "-"+protocol, "-connect", host+":"+str(port)]+options,
61 stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
62 except subprocess.CalledProcessError:
67 def test_protocol(host, port, protocol, ciphers, base_frac, wait_time=0, options=[]):
68 if test_cipher(host, port, protocol, options=options):
69 # the protocol is supported
70 results = OrderedDict()
71 for i in range(len(ciphers)):
73 print_progress(protocol+" "+cipher, base_frac+[(i, len(ciphers))])
74 results[cipher] = test_cipher(host, port, protocol, cipher, options)
76 time.sleep(wait_time/1000)
82 def test_host(host, port, wait_time=0, options=[]):
83 ciphers = list_ciphers()
84 results = OrderedDict()
85 protocols = ('ssl2', 'ssl3', 'tls1', 'tls1_1', 'tls1_2')
86 for i in range(len(protocols)):
87 protocol = protocols[i]
88 print_progress(protocol, [(i, len(protocols))])
89 results[protocol] = test_protocol(host, port, protocol, ciphers, [(i, len(protocols))], wait_time, options)
93 # cipher classification
94 class CipherStrength(Enum):
102 if self == CipherStrength.unknown:
104 elif self.value == CipherStrength.high.value:
105 return ConsoleFormat.color(self.name, ConsoleFormat.GREEN)
106 elif self.value == CipherStrength.medium.value:
107 return ConsoleFormat.color(self.name, ConsoleFormat.YELLOW)
109 return ConsoleFormat.color(self.name, ConsoleFormat.RED)
111 CipherProps = namedtuple('CipherProps', 'bits, strength, isPfs')
113 class CipherPropsProvider:
115 self.exp = set(list_ciphers("EXP"))
116 self.low = set(list_ciphers("LOW"))
117 self.medium = set(list_ciphers("MEDIUM"))
118 self.high = set(list_ciphers("HIGH"))
121 def __getProps(self, cipher):
122 # as OpenSSL about this cipher
123 cipherInfo = subprocess.check_output(["openssl", "ciphers", "-v", cipher]).decode('UTF-8').strip()
124 assert '\n' not in cipherInfo
125 cipherInfoFields = cipherInfo.split()
127 bitMatch = re.match(r'^Enc=[0-9A-Za-z]+\(([0-9]+)\)$', cipherInfoFields[4])
129 raise Exception("Unexpected OpenSSL output: Cannot determine encryption strength from {1}\nComplete output: {0}".format(cipherInfo, cipherInfoFields[4]))
130 bits = int(bitMatch.group(1))
131 # figure out whether the cipher is pfs
132 kxMatch = re.match(r'^Kx=([0-9A-Z/()]+)$', cipherInfoFields[2])
134 raise Exception("Unexpected OpenSSL output: Cannot determine key-exchange method from {1}\nComplete output: {0}".format(cipherInfo, cipherInfoFields[2]))
135 kx = kxMatch.group(1)
136 isPfs = kx in ('DH', 'DH(512)', 'ECDH')
137 # determine security level
138 isExp = cipher in self.exp
139 isLow = cipher in self.low
140 isMedium = cipher in self.medium
141 isHigh = cipher in self.high
142 assert isExp+isLow+isMedium+isHigh <= 1, "Cipher is more than one from EXP, LOW, MEDIUM, HIGH"
144 strength = CipherStrength.exp
146 strength = CipherStrength.low
148 strength = CipherStrength.medium
150 strength = CipherStrength.high
152 strength = CipherStrength.unknown
154 return CipherProps(bits=bits, strength=strength, isPfs=isPfs)
156 def getProps(self, cipher):
157 if cipher in self.props:
158 return self.props[cipher]
159 props = self.__getProps(cipher)
160 self.props[cipher] = props
164 if __name__ == "__main__":
165 parser = argparse.ArgumentParser(description='Check TLS ciphers supported by a host')
166 parser.add_argument("--starttls", dest="starttls",
167 help="Use a STARTTLS variant to establish the TLS connection. Possible values include smpt, imap, xmpp.")
168 parser.add_argument("--wait-time", "-t", dest="wait_time", default="10",
169 help="Time (in ms) to wait between two connections to the server. Default is 10ms.")
170 parser.add_argument("host", metavar='HOST[:PORT]',
171 help="The host to check")
172 args = parser.parse_args()
176 host, port = args.host.split(':')
181 # get options and other stuff
182 wait_time = float(args.wait_time)
184 if args.starttls is not None:
185 options += ['-starttls', args.starttls]
188 results = test_host(host, port, wait_time, options)
191 propsProvider = CipherPropsProvider()
192 for protocol, ciphers in results.items():
195 print(" Is not supported by client or server")
197 for cipher, supported in ciphers.items():
199 cipherProps = propsProvider.getProps(cipher)
200 fsText = ConsoleFormat.color("FS", ConsoleFormat.GREEN) if cipherProps.isPfs else ConsoleFormat.color("no FS", ConsoleFormat.RED)
201 bitColor = ConsoleFormat.GREEN if cipherProps.bits > 128 else (ConsoleFormat.YELLOW if cipherProps.bits >= 100 else ConsoleFormat.RED)
202 print(" {0} ({1}, {2}, {3})".format(cipher.ljust(STATE_WIDTH), cipherProps.strength.colorName(), ConsoleFormat.color(str(cipherProps.bits)+" bits", bitColor), fsText))