2 tlslite version 0.4.8 Nov 12 2014
3 Trevor Perrin <tlslite at trevp.net>
4 http://trevp.net/tlslite/
5 ============================================================================
11 2 License/Acknowledgements
13 4 Getting Started with the Command-Line Tools
14 5 Getting Started with the Library
15 6 Using TLS Lite with httplib
16 7 Using TLS Lite with poplib or imaplib
17 8 Using TLS Lite with smtplib
18 9 Using TLS Lite with SocketServer
19 10 Using TLS Lite with asyncore
20 11 SECURITY CONSIDERATIONS
26 TLS Lite is an open source python library that implements SSL and TLS. TLS
27 Lite supports RSA and SRP ciphersuites. TLS Lite is pure python, however it
28 can use other libraries for faster crypto operations. TLS Lite integrates with
29 several stdlib neworking libraries.
31 API documentation is available in the 'docs' directory.
33 If you have questions or feedback, feel free to contact me. For discussing
34 improvements to tlslite, also see 'tlslite-dev@googlegroups.com'.
37 2 Licenses/Acknowledgements
38 ============================
39 TLS Lite is written (mostly) by Trevor Perrin. It includes code from Bram
40 Cohen, Google, Kees Bos, Sam Rushing, Dimitris Moraitis, Marcelo Fernandez,
41 Martin von Loewis, Dave Baggett, and Yngve N. Pettersen (ported by Paul
44 All code in TLS Lite has either been dedicated to the public domain by its
45 authors, or placed under a BSD-style license. See the LICENSE file for
48 Thanks to Edward Loper for Epydoc, which generated the API docs.
53 Python 2.6 or higher is required. Python 3 is supported.
56 - If you have the M2Crypto interface to OpenSSL, this will be used for fast
57 RSA operations and fast ciphers.
59 - If you have pycrypto this will be used for fast RSA operations and fast
62 - If you have the GMPY interface to GMP, this will be used for fast RSA and
65 - These modules don't need to be present at installation - you can install
68 Run 'python setup.py install'
70 Test the Installation:
71 - From the distribution's ./tests subdirectory, run:
72 ./tlstest.py server localhost:4443 .
73 - While the test server is waiting, run:
74 ./tlstest.py client localhost:4443 .
76 If both say "Test succeeded" at the end, you're ready to go.
79 4 Getting Started with the Command-Line Tools
80 ==============================================
81 tlslite installs two command-line scripts: 'tlsdb.py' and 'tls.py'.
83 'tls.py' lets you run test clients and servers. It can be used for testing
84 other TLS implementations, or as example code. Note that 'tls.py server' runs
85 an HTTPS server which will serve files rooted at the current directory by
86 default, so be careful.
88 'tlsdb.py' lets you manage SRP verifier databases. These databases are used by
89 a TLS server when authenticating clients with SRP.
93 To run an X.509 server, go to the ./tests directory and do:
95 tls.py server -k serverX509Key.pem -c serverX509Cert.pem localhost:4443
97 Try connecting to the server with a web browser, or with:
99 tls.py client localhost:4443
103 To run an X.509 server using a TACK, install TACKpy, then run the same server
104 command as above with added arguments:
106 ... -t TACK1.pem localhost:4443
110 To run an SRP server, try something like:
112 tlsdb.py createsrp verifierDB
113 tlsdb.py add verifierDB alice abra123cadabra 1024
114 tlsdb.py add verifierDB bob swordfish 2048
116 tls.py server -v verifierDB localhost:4443
118 Then try connecting to the server with:
120 tls.py client localhost:4443 alice abra123cadabra
124 To run an HTTPS server with less typing, run ./tests/httpsserver.sh.
126 To run an HTTPS client, run ./tests/httpsclient.py.
129 5 Getting Started with the Library
130 ===================================
131 Whether you're writing a client or server, there are six steps:
133 1) Create a socket and connect it to the other party.
134 2) Construct a TLSConnection instance with the socket.
135 3) Call a handshake function on TLSConnection to perform the TLS handshake.
136 4) Check the results to make sure you're talking to the right party.
137 5) Use the TLSConnection to exchange data.
138 6) Call close() on the TLSConnection when you're done.
140 TLS Lite also integrates with several stdlib python libraries. See the
141 sections following this one for details.
143 5 Step 1 - create a socket
144 ---------------------------
145 Below demonstrates a socket connection to Amazon's secure site.
148 sock = socket(AF_INET, SOCK_STREAM)
149 sock.connect( ("www.amazon.com", 443) )
151 5 Step 2 - construct a TLSConnection
152 -------------------------------------
153 You can import tlslite objects individually, such as:
154 from tlslite import TLSConnection
156 Or import the most useful objects through:
157 from tlslite.api import *
160 connection = TLSConnection(sock)
162 5 Step 3 - call a handshake function (client)
163 ----------------------------------------------
164 If you're a client, there's two different handshake functions you can call,
165 depending on how you want to authenticate:
167 connection.handshakeClientCert()
168 connection.handshakeClientCert(certChain, privateKey)
170 connection.handshakeClientSRP("alice", "abra123cadabra")
172 The ClientCert function without arguments is used when connecting to a site
173 like Amazon, which doesn't require client authentication, but which will
174 authenticate itself using an X.509 certificate chain.
176 The ClientCert function can also be used to do client authentication with an
177 X.509 certificate chain and corresponding private key. To use X.509 chains,
178 you'll need some way of creating these, such as OpenSSL (see
179 http://www.openssl.org/docs/HOWTO/ for details).
181 Below is an example of loading an X.509 chain and private key:
183 from tlslite import X509, X509CertChain, parsePEMKey
184 s = open("./test/clientX509Cert.pem").read()
187 certChain = X509CertChain([x509])
188 s = open("./test/clientX509Key.pem").read()
189 privateKey = parsePEMKey(s, private=True)
191 The SRP function does mutual authentication with a username and password - see
192 RFC 5054 for details.
194 If you want more control over the handshake, you can pass in a
195 HandshakeSettings instance. For example, if you're performing SRP, but you
196 only want to use SRP parameters of at least 2048 bits, and you only want to
197 use the AES-256 cipher, and you only want to allow TLS (version 3.1), not SSL
198 (version 3.0), you can do:
200 settings = HandshakeSettings()
201 settings.minKeySize = 2048
202 settings.cipherNames = ["aes256"]
203 settings.minVersion = (3,1)
204 settings.useExperimentalTACKExtension = True # Needed for TACK support
206 connection.handshakeClientSRP("alice", "abra123cadabra", settings=settings)
208 If you want to check the server's certificate using TACK, you should set the
209 "useExperiementalTACKExtension" value in HandshakeSettings. (Eventually, TACK
210 support will be enabled by default, but for now it is an experimental feature
211 which relies on a temporary TLS Extension number, and should not be used for
212 production software.) This will cause the client to request the server to send
213 you a TACK (and/or any TACK Break Signatures):
215 Finally, every TLSConnection has a session object. You can try to resume a
216 previous session by passing in the session object from the old session. If the
217 server remembers this old session and supports resumption, the handshake will
218 finish more quickly. Otherwise, the full handshake will be done. For example:
220 connection.handshakeClientSRP("alice", "abra123cadabra")
223 oldSession = connection.session
224 connection2.handshakeClientSRP("alice", "abra123cadabra", session=
227 5 Step 3 - call a handshake function (server)
228 ----------------------------------------------
229 If you're a server, there's only one handshake function, but you can pass it
230 several different parameters, depending on which types of authentication
231 you're willing to perform.
233 To perform SRP authentication, you have to pass in a database of password
234 verifiers. The VerifierDB class manages an in-memory or on-disk verifier
237 verifierDB = VerifierDB("./test/verifierDB")
239 connection.handshakeServer(verifierDB=verifierDB)
241 To perform authentication with a certificate and private key, the server must
242 load these as described in the previous section, then pass them in. If the
243 server sets the reqCert boolean to True, a certificate chain will be requested
246 connection.handshakeServer(certChain=certChain, privateKey=privateKey,
249 You can pass in a verifier database and/or a certificate chain+private key.
250 The client will use one or both to authenticate the server.
252 You can also pass in a HandshakeSettings object, as described in the last
253 section, for finer control over handshaking details.
255 If you are passing in a certificate chain+private key, you may additionally
256 provide a TACK to assist the client in authenticating your certificate chain.
257 This requires the TACKpy library. Load a TACKpy.TACK object, then do:
259 settings = HandshakeSettings()
260 settings.useExperimentalTACKExtension = True # Needed for TACK support
262 connection.handshakeServer(certChain=certChain, privateKey=privateKey,
263 tack=tack, settings=settings)
265 Finally, the server can maintain a SessionCache, which will allow clients to
266 use session resumption:
268 sessionCache = SessionCache()
269 connection.handshakeServer(verifierDB=verifierDB, sessionCache=sessionCache)
271 It should be noted that the session cache, and the verifier databases, are all
274 5 Step 4 - check the results
275 -----------------------------
276 If the handshake completes without raising an exception, authentication
277 results will be stored in the connection's session object. The following
278 variables will be populated if applicable, or else set to None:
280 connection.session.srpUsername # string
281 connection.session.clientCertChain # X509CertChain
282 connection.session.serverCertChain # X509CertChain
283 connection.session.tackExt # TACKpy.TACK_Extension
285 X.509 chain objects return the end-entity fingerprint via getFingerprint(),
286 and ignore the other certificates.
288 TACK objects return the (validated) TACK ID via getTACKID().
290 To save yourself the trouble of inspecting certificates after the handshake,
291 you can pass a Checker object into the handshake function. The checker will be
292 called if the handshake completes successfully. If the other party isn't
293 approved by the checker, a subclass of TLSAuthenticationError will be raised.
295 If the handshake fails for any reason, including a Checker error, an exception
296 will be raised and the socket will be closed. If the socket timed out or was
297 unexpectedly closed, a socket.error or TLSAbruptCloseError will be raised.
299 Otherwise, either a TLSLocalAlert or TLSRemoteAlert will be raised, depending
300 on whether the local or remote implementation signalled the error. The
301 exception object has a 'description' member which identifies the error based
302 on the codes in RFC 2246. A TLSLocalAlert also has a 'message' string that may
305 Example of handling a remote alert:
309 except TLSRemoteAlert as alert:
310 if alert.description == AlertDescription.unknown_psk_identity:
311 print "Unknown user."
314 Below are some common alerts and their probable causes, and whether they are
315 signalled by the client or server.
317 Client handshake_failure:
318 - SRP parameters are not recognized by client
319 - Server's TACK was unrelated to its certificate chain
321 Client insufficient_security:
322 - SRP parameters are too small
324 Client protocol_version:
325 - Client doesn't support the server's protocol version
327 Server protocol_version:
328 - Server doesn't support the client's protocol version
330 Server bad_record_mac:
331 - bad SRP username or password
333 Server unknown_psk_identity
334 - bad SRP username (bad_record_mac could be used for the same thing)
336 Server handshake_failure:
337 - no matching cipher suites
339 5 Step 5 - exchange data
340 -------------------------
341 Now that you have a connection, you can call read() and write() as if it were
342 a socket.SSL object. You can also call send(), sendall(), recv(), and
343 makefile() as if it were a socket. These calls may raise TLSLocalAlert,
344 TLSRemoteAlert, socket.error, or TLSAbruptCloseError, just like the handshake
347 Once the TLS connection is closed by the other side, calls to read() or recv()
348 will return an empty string. If the socket is closed by the other side without
349 first closing the TLS connection, calls to read() or recv() will return a
350 TLSAbruptCloseError, and calls to write() or send() will return a
353 5 Step 6 - close the connection
354 --------------------------------
355 When you're finished sending data, you should call close() to close the
356 connection and socket. When the connection is closed properly, the session
357 object can be used for session resumption.
359 If an exception is raised the connection will be automatically closed; you
360 don't need to call close(). Furthermore, you will probably not be able to
361 re-use the socket, the connection object, or the session object, and you
364 By default, calling close() will close the underlying socket. If you set the
365 connection's closeSocket flag to False, the socket will remain open after
366 close. (NOTE: some TLS implementations will not respond properly to the
367 close_notify alert that close() generates, so the connection will hang if
368 closeSocket is set to True.)
371 6 Using TLS Lite with httplib
372 ==============================
373 TLS Lite comes with an HTTPTLSConnection class that extends httplib to work
374 over SSL/TLS connections. Depending on how you construct it, it will do
375 different types of authentication.
377 #No authentication whatsoever
378 h = HTTPTLSConnection("www.amazon.com", 443)
383 #Authenticate server based on its TACK ID
384 h = HTTPTLSConnection("localhost", 4443,
385 tackID="B3ARS.EQ61B.F34EL.9KKLN.3WEW5", hardTack=False)
388 #Mutually authenticate with SRP
389 h = HTTPTLSConnection("localhost", 443,
390 username="alice", password="abra123cadabra")
394 7 Using TLS Lite with poplib or imaplib
395 ========================================
396 TLS Lite comes with POP3_TLS and IMAP4_TLS classes that extend poplib and
397 imaplib to work over SSL/TLS connections. These classes can be constructed
398 with the same parameters as HTTPTLSConnection (see previous section), and
401 #To connect to a POP3 server over SSL and display its fingerprint:
402 from tlslite.api import *
403 p = POP3_TLS("---------.net", port=995)
404 print p.sock.session.serverCertChain.getFingerprint()
407 #To connect to an IMAP server once you know its fingerprint:
408 from tlslite.api import *
409 i = IMAP4_TLS("cyrus.andrew.cmu.edu",
410 x509Fingerprint="00c14371227b3b677ddb9c4901e6f2aee18d3e45")
414 8 Using TLS Lite with smtplib
415 ==============================
416 TLS Lite comes with an SMTP_TLS class that extends smtplib to work
417 over SSL/TLS connections. This class accepts the same parameters as
418 HTTPTLSConnection (see previous section), and behaves similarly. Depending
419 on how you call starttls(), it will do different types of authentication.
421 #To connect to an SMTP server once you know its fingerprint:
422 from tlslite.api import *
423 s = SMTP_TLS("----------.net", port=587)
425 s.starttls(x509Fingerprint="7e39be84a2e3a7ad071752e3001d931bf82c32dc")
429 9 Using TLS Lite with SocketServer
430 ====================================
431 You can use TLS Lite to implement servers using Python's SocketServer
432 framework. TLS Lite comes with a TLSSocketServerMixIn class. You can combine
433 this with a TCPServer such as HTTPServer. To combine them, define a new class
434 that inherits from both of them (with the mix-in first). Then implement the
435 handshake() method, doing some sort of server handshake on the connection
436 argument. If the handshake method returns True, the RequestHandler will be
437 triggered. See the tests/httpsserver.py example.
440 10 Using TLS Lite with asyncore
441 ================================
442 TLS Lite can be used with subclasses of asyncore.dispatcher. See the comments
443 in TLSAsyncDispatcherMixIn.py for details. This is still experimental, and
444 may not work with all asyncore.dispatcher subclasses.
447 11 Security Considerations
448 ===========================
449 TLS Lite is beta-quality code. It hasn't received much security analysis. Use
452 TLS Lite does NOT verify certificates by default.
454 TLS Lite's pure-python ciphers are probably vulnerable to timing attacks.
456 TLS Lite is probably vulnerable to the "Lucky 13" timing attack if AES or 3DES
457 are used, or the weak cipher RC4 otherwise. This unhappy situation will remain
458 until TLS Lite implements authenticated-encryption ciphersuites (like GCM), or
465 - Added more acknowledgements and security considerations
467 - Added TLS 1.2 support (Yngve Pettersen and Paul Sokolovsky)
468 - Don't offer SSLv3 by default (e.g. POODLE)
469 - Fixed bug with PyCrypto_RSA integration
470 - Fixed harmless bug that added non-prime into sieves list
471 - Added "make test" and "make test-dev" targets (Hubert Kario)
473 - **API CHANGE**: TLSClosedConnectionError instead of ValueError when writing
474 to a closed connection. This inherits from socket.error, so should
475 interact better with SocketServer (see http://bugs.python.org/issue14574)
476 and other things expecting a socket.error in this situation.
477 - Added support for RC4-MD5 ciphersuite (if enabled in settings)
478 - This is allegedly necessary to connect to some Internet servers.
479 - Added TLSConnection.unread() function
480 - Switched to New-style classes (inherit from 'object')
483 - Added Python 3 support (Martin von Loewis)
484 - Added NPN client support (Marcelo Fernandez)
485 - Switched to RC4 as preferred cipher
486 - faster in Python, avoids "Lucky 13" timing attacks
487 - Fixed bug when specifying ciphers for anon ciphersuites
488 - Made RSA hashAndVerify() tolerant of sigs w/o encoded NULL AlgorithmParam
489 - (this function is not used for TLS currently, and this tolerance may
490 not even be necessary)
492 - Minor bugfix (0.4.2 doesn't load tackpy)
494 - Updated TACK (compatible with tackpy 0.9.9)
496 - Fixed RSA padding bugs (w/help from John Randolph)
497 - Updated TACK (compatible with tackpy 0.9.7)
499 - Added NPN server support (Sam Rushing/Google)
500 - Added AnonDH (Dimitris Moraitis)
501 - Added X509CertChain.parsePemList
502 - Improved XML-RPC (Kees Bos)
505 - Fixed pycrypto support
506 - Fixed python 2.6 problems
510 Much code cleanup, in particular decomposing the handshake functions so they
511 are readable. The main new feature is support for TACK, an experimental
512 authentication method that provides a new way to pin server certificates (See
513 https://github.com/moxie0/Convergence/wiki/TACK ).
518 - Sends SCSV ciphersuite as per RFC 5746, to signal non-renegotiated
519 Client Hello. Does not support renegotiation (never has).
520 - Change from e=3 to e=65537 for generated RSA keys, not strictly
521 necessary but mitigates risk of sloppy verifier.
522 - 1/(n-1) countermeasure for BEAST.
525 - Split cmdline into tls.py and tlstest.py, improved options.
526 - Formalized LICENSE.
527 - Defaults to closing socket after sending close_notify, fixes hanging.
528 problem that would occur sometime when waiting for other party's
530 - Update SRP to RFC 5054 compliance.
531 - Removed client handshake "callbacks", no longer support the SRP
532 re-handshake idiom within a single handshake function.
535 - Added hashlib support, removes Deprecation Warning due to sha and md5.
536 - Handled GeneratorExit exceptions that are a new Python feature, and
537 interfere with the async code if not handled.
540 - Shared keys (it was based on an ancient I-D, not TLS-PSK).
541 - cryptlib support, it wasn't used much, we have enough other options.
542 - cryptoIDs (TACK is better).
543 - win32prng extension module, as os.urandom is now available.
544 - Twisted integration (unused?, slowed down loading).
545 - Jython code (ancient, didn't work).
546 - Compat support for python versions < 2.7.
549 - Support for TACK via TACKpy.
550 - Support for CertificateRequest.certificate_authorities ("reqCAs")
551 - Added TLSConnection.shutdown() to better mimic socket.
552 - Enabled Session resumption for XMLRPCTransport.
555 - Added support for poplib, imaplib, and smtplib
556 - Added python 2.4 windows installer
557 - Fixed occassional timing problems with test suite
559 - Added support for Python 2.2
560 - Cleaned up compatibility code, and docs, a bit
562 - Fixed script installation on UNIX
563 - Give better error message on old Python versions
566 - os.urandom() support
567 - Fixed win32prng on some systems
569 - Updated for TLS/SRP draft 8
570 - Bugfix: was setting _versioncheck on SRP 1st hello, causing problems
571 with GnuTLS (which was offering TLS 1.1)
572 - Removed _versioncheck checking, since it could cause interop problems
573 - Minor bugfix: when cryptlib_py and and cryptoIDlib present, cryptlib
574 was complaining about being initialized twice
576 - Updated for TLS/SRP draft 7
577 - Updated test cryptoID cert chains for cryptoIDlib 0.3.1
579 - fixed bug when handling multiple handshake messages per record (e.g. IIS)
581 - added xmlrpclib integration
582 - fixed hanging bug in Twisted integration
583 - fixed win32prng to work on a wider range of win32 sytems
584 - fixed import problem with cryptoIDlib
585 - fixed port allocation problem when test scripts are run on some UNIXes
586 - made tolerant of buggy IE sending wrong version in premaster secret
588 - added API docs thanks to epydoc
589 - added X.509 path validation via cryptlib
590 - much cleaning/tweaking/re-factoring/minor fixes
592 - changed Twisted error handling to use connectionLost()
593 - added ignoreAbruptClose
595 - added Twisted errorHandler
596 - added TLSAbruptCloseError
597 - added 'integration' subdirectory
599 - improved asynchronous support a bit
600 - added first-draft of Twisted support
602 - cleaned up asyncore support
603 - added proof-of-concept for Twisted
605 - added pycrypto RSA support
606 - added asyncore support
609 - added pycrypto support
610 - added support for PEM-encoded private keys, in pure python
612 - improved PRNG use (cryptlib, or /dev/random, or CryptoAPI)
613 - added RSA blinding, to avoid timing attacks
614 - don't install local copy of M2Crypto, too problematic
616 - changed VerifierDB to take per-user parameters
617 - renamed tls_lite -> tlslite
619 - added post-handshake 'Checker'
620 - made compatible with Python 2.2
621 - made more forgiving of abrupt closure, since everyone does it:
622 if the socket is closed while sending/recv'ing close_notify,
625 - TLSConnections now emulate sockets, including makefile()
626 - HTTPTLSConnection and TLSMixIn simplified as a result
628 - fixed httplib.HTTPTLSConnection with multiple requests
629 - fixed SocketServer to handle close_notify
630 - changed handshakeClientNoAuth() to ignore CertificateRequests
631 - changed handshakeClient() to ignore non-resumable session arguments
633 - fixed httplib support
635 - added support for httplib and SocketServer
636 - added support for SSLv3
637 - added support for 3DES
638 - cleaned up read()/write() behavior
639 - improved HMAC speed
641 - fixed dumb bug in tls.py
643 - change read() to only return requested number of bytes
644 - added support for shared-key and in-memory databases
645 - added support for PEM-encoded X.509 certificates
646 - added support for SSLv2 ClientHello
647 - fixed shutdown/re-handshaking behavior
648 - cleaned up handling of missing_srp_username
649 - renamed readString()/writeString() -> read()/write()
650 - added documentation
652 - added clienttest/servertest functions
653 - improved OpenSSL cipher wrappers speed
654 - fixed server when it has a key, but client selects plain SRP
655 - fixed server to postpone errors until it has read client's messages
656 - fixed ServerHello to only include extension data if necessary
658 - fixed close_notify behavior
659 - fixed handling of empty application data packets
660 - fixed socket reads to not consume extra bytes
661 - added testing functions to tls.py