tlslite-ng

repository·master·Indexed 42 days ago

https://github.com/tlsfuzzer/tlslite-ng

A pure-Python implementation of SSL and TLS cryptographic protocols, supporting versions from SSLv3 through TLSv1.3. It provides a standalone socket wrapper and backend for networking libraries, featuring support for X.509 and SRP authentication, modern ciphersuites, and specialized extensions for httplib, poplib, imaplib, and smtplib.

Tokens
5.7K
Snippets
7
Records
39
Agent score
54%

What's inside tlslite-ng

  1. Overview of the tlslite.integration package

    master
    The tlslite.integration package provides high-level integration modules for using tlslite-ng with various network protocols and application patterns. It includes specialized submodules for handling asynchronous state machines, client helpers, and TLS-wrapped implementations of common protocols like HTTPS, IMAP4, POP3, and SMTP. It also provides mixins for building asynchronous dispatchers and TLS socket servers, as well as support for XML-RPC over TLS.
  2. Use the tlslite.session module

    master
    The tlslite.session module provides high-level session management capabilities for the tlslite-ng library. It is designed to handle the lifecycle and state of secure sessions, abstracting the underlying cryptographic and protocol-specific details to allow developers to establish and maintain secure communications easily.
  3. Explore the tlslite package structure

    master

    The tlslite package is the core of the library, providing TLS and cryptographic primitives. It is organized into subpackages and submodules that handle specific aspects of the protocol and security operations.

    Subpackages

    • tlslite.integration: Likely contains integration logic for external systems or protocols.
    • tlslite.utils: General utility functions used across the library.

    Key Submodules

    The library is composed of several specialized modules, including:

    • Protocol & Connection: tlslite.tlsconnection, tlslite.session, tlslite.recordlayer, tlslite.messagesocket, tlslite.bufferedsocket.
    • Cryptography & Handshake: tlslite.dh (Diffie-Hellman), tlslite.keyexchange, tlslite.handshakehelpers, tlslite.handshakesettings, tlslite.handshakehashes.
    • X.509 & Certificates: tlslite.x509, tlslite.x509certchain, tlslite.verifierdb.
    • Core Logic: tlslite.api, tlslite.constants, tlslite.errors, tlslite.messages.
  4. Explore the tlslite.utils package submodules

    master

    The tlslite.utils package provides a collection of utility submodules for cryptographic operations, encoding, and mathematical functions. Depending on your needs, you can use specific submodules for different algorithms or interfaces:

    • Symmetric Ciphers: aes, aesgcm, chacha, chacha20_poly1305, rc4, tripledes, and rijndael.
    • Asymmetric/Key Management: ecc, ecdsakey, rsakey, x25519, and keyfactory.
    • External Library Wrappers: Submodules prefixed with openssl_ (e.g., openssl_aes) or pycrypto_ (e.g., pycrypto_aes) allow using external cryptographic providers.
    • Encoding and Parsing: asn1parser, codec, pem, and tackwrapper.
    • Mathematical and Low-level Utilities: cryptomath, constanttime, poly1305, and tlshashlib.
    • System/Data Utilities: datefuncs, dns_utils, lists, and compat.
  5. Configure HandshakeSettings for fine-grained control

    master

    The HandshakeSettings class allows you to customize the TLS handshake process.

    Key attributes include:

    • minKeySize: Minimum bit length for keys (e.g., 2048).
    • cipherNames: A list of allowed cipher names (e.g., ["aes256"]).
    • minVersion: The minimum TLS version as a tuple (e.g., (3, 1)).
    • useExperimentalTACKExtension: Boolean to enable/disable the experimental TACK extension.

    Example usage:

    from tlslite import HandshakeSettings
    
    settings = HandshakeSettings()
    settings.minKeySize = 2048
    settings.cipherNames = ["aes256"]
    settings.minVersion = (3, 1)
    settings.useExperimentalTACKExtension = True
  6. Implement a TLS client with tlslite-ng

    master

    To implement a TLS client, follow these steps:

    1. Create a socket: Connect to the target host.
    2. Construct a TLSConnection: Wrap the socket in a TLSConnection instance.
    3. Perform Handshake: Call a handshake function based on your authentication needs:
      • handshakeClientCert(): For standard X.509 authentication (no client cert required).
      • handshakeClientCert(certChain, privateKey): For mutual X.509 authentication.
      • handshakeClientSRP(username, password): For SRP authentication.
    4. Exchange Data: Use the connection object to send/receive data.
    5. Close: Call .close() when finished.

    Example: Standard X.509 Client

    from socket import *
    from tlslite import TLSConnection
    
    sock = socket(AF_INET, SOCK_STREAM)
    sock.connect(("www.amazon.com", 443))
    
    connection = TLSConnection(sock)
    connection.handshakeClientCert()
    # ... use connection to exchange data ...
    connection.close()

    Example: SRP Client with Custom Handshake Settings

    You can use HandshakeSettings to restrict ciphers, minimum key sizes, or TLS versions.

    from tlslite import TLSConnection, HandshakeSettings
    
    settings = HandshakeSettings()
    settings.minKeySize = 2048
    settings.cipherNames = ["aes256"]
    settings.minVersion = (3,1)
    
    connection.handshakeClientSRP("alice", "abra123cadabra", settings=settings)
    from socket import *
    from tlslite import TLSConnection
    
    sock = socket(AF_INET, SOCK_STREAM)
    sock.connect(("www.amazon.com", 443))
    
    connection = TLSConnection(sock)
    connection.handshakeClientCert()
  7. Handle TLS alerts and errors

    master

    Handshake failures or data exchange errors raise specific exceptions:

    • TLSLocalAlert: An error signaled by the local implementation. Includes a message string with details.
    • TLSRemoteAlert: An error signaled by the remote party. The exception object has a description member corresponding to RFC 2246 codes.
    • TLSAbruptCloseError: Raised if the socket is closed unexpectedly.
    • socket.error: Raised if the socket times out or is closed unexpectedly during data exchange.

    Example of handling a specific remote alert:

    try:
        # ... handshake/data exchange ...
    except TLSRemoteAlert as alert:
        if alert.description == AlertDescription.unknown_psk_identity:
            print "Unknown user."
    try:
        [...] 
    except TLSRemoteAlert as alert:
        if alert.description == AlertDescription.unknown_psk_identity:
            print "Unknown user."
    [...]
  8. Use tlslite-ng with httplib, poplib, imaplib, and smtplib

    master

    tlslite-ng provides specialized classes that extend standard Python libraries to support SSL/TLS:

    HTTP (via HTTPTLSConnection)

    Extends httplib. Supports various authentication modes:

    • No authentication: h = HTTPTLSConnection("host", port)
    • TACK authentication: h = HTTPTLSConnection("host", port, tackID="ID", hardTack=False)
    • SRP mutual authentication: h = HTTPTLSConnection("host", port, username="user", password="pass")

    POP3 and IMAP (via POP3_TLS and IMAP4_TLS)

    Extends poplib and imaplib respectively. They accept the same parameters as HTTPTLSConnection.

    # Example: Connect to POP3 and show fingerprint
    from tlslite.api import *
    p = POP3_TLS("---------.net", port=995)
    print p.sock.session.serverCertChain.getFingerprint()
    
    # Example: Connect to IMAP using a known fingerprint
    i = IMAP4_TLS("cyrus.andrew.cmu.edu", x509Fingerprint="00c14371227b3b677ddb9c4901e6f2aee18d3e45")

    SMTP (via SMTP_TLS)

    Extends smtplib. Authentication depends on how starttls() is called.

    # Example: Connect to SMTP using a known fingerprint
    from tlslite.api import *
    s = SMTP_TLS("----------.net", port=587)
    s.ehlo()
    s.starttls(x509Fingerprint="7e39be84a2e3a7ad071752e3001d931bf82c32dc")
    # To connect to a POP3 server over SSL and display its fingerprint:
    from tlslite.api import *
    p = POP3_TLS("---------.net", port=995)
    print p.sock.session.serverCertChain.getFingerprint()
    [...]
    
    # To connect to an IMAP server once you know its fingerprint:
    from tlslite.api import *
    i = IMAP4_TLS("cyrus.andrew.cmu.edu", 
              x509Fingerprint="00c14371227b3b677ddb9c4901e6f2aee18d3e45")
    
    # To connect to an SMTP server once you know its fingerprint:
    from tlslite.api import *
    s = SMTP_TLS("----------.net", port=587)
    s.ehlo()
    s.starttls(x509Fingerprint="7e39be84a2e3a7ad071752e3001d931bf82c32dc")
  9. Implement a TLS server with tlslite-ng

    master

    To implement a TLS server, follow these steps:

    1. Create a socket: Listen for and accept connections.
    2. Construct a TLSConnection: Wrap the accepted socket.
    3. Perform Handshake: Call handshakeServer() with appropriate authentication parameters:
      • SRP: Pass a VerifierDB instance.
      • X.509: Pass a certChain and privateKey. Set reqCert=True to request a certificate from the client.
    4. Exchange Data: Use the connection object.
    5. Close: Call .close().

    Example: SRP Server

    from tlslite import TLSConnection, VerifierDB
    
    # Assuming 'connection' is a TLSConnection wrapping an accepted socket
    verifierDB = VerifierDB("./test/verifierDB")
    verifierDB.open()
    connection.handshakeServer(verifierDB=verifierDB)

    Example: X.509 Server with Client Authentication

    from tlslite import TLSConnection
    
    # Assuming 'certChain' and 'privateKey' are loaded via X509/parsePEMKey
    connection.handshakeServer(certChain=certChain, privateKey=privateKey, reqCert=True)