Beispiel #1
0
def create_client_proxy_context(
    *,
    min_version: Version,
    max_version: Version,
    cipher_list: Optional[Tuple[str, ...]],
    cert: certs.Cert,
    key: rsa.RSAPrivateKey,
    chain_file: Optional[Path],
    alpn_select_callback: Optional[Callable[[SSL.Connection, List[bytes]],
                                            Any]],
    request_client_cert: bool,
    extra_chain_certs: Tuple[certs.Cert, ...],
    dhparams: certs.DHParams,
) -> SSL.Context:
    context: SSL.Context = _create_ssl_context(
        method=Method.TLS_SERVER_METHOD,
        min_version=min_version,
        max_version=max_version,
        cipher_list=cipher_list,
    )

    context.use_certificate(cert.to_pyopenssl())
    context.use_privatekey(crypto.PKey.from_cryptography_key(key))
    if chain_file is not None:
        try:
            context.load_verify_locations(str(chain_file), None)
        except SSL.Error as e:
            raise RuntimeError(
                f"Cannot load certificate chain ({chain_file}).") from e

    if alpn_select_callback is not None:
        assert callable(alpn_select_callback)
        context.set_alpn_select_callback(alpn_select_callback)

    if request_client_cert:
        # The request_client_cert argument requires some explanation. We're
        # supposed to be able to do this with no negative effects - if the
        # client has no cert to present, we're notified and proceed as usual.
        # Unfortunately, Android seems to have a bug (tested on 4.2.2) - when
        # an Android client is asked to present a certificate it does not
        # have, it hangs up, which is frankly bogus. Some time down the track
        # we may be able to make the proper behaviour the default again, but
        # until then we're conservative.
        context.set_verify(Verify.VERIFY_PEER.value, accept_all)
    else:
        context.set_verify(Verify.VERIFY_NONE.value, None)

    for i in extra_chain_certs:
        context.add_extra_chain_cert(i.to_pyopenssl())

    if dhparams:
        SSL._lib.SSL_CTX_set_tmp_dh(context._context, dhparams)  # type: ignore

    return context
Beispiel #2
0
def _load_http_server_conn(o: http_pb2.ServerConnection) -> ServerConnection:
    d: dict = {}
    _move_attrs(o, d, ['id', 'tls_established', 'sni', 'alpn_proto_negotiated', 'tls_version',
                       'timestamp_start', 'timestamp_tcp_setup', 'timestamp_tls_setup', 'timestamp_end'])
    for addr in ['address', 'ip_address', 'source_address']:
        if hasattr(o, addr):
            d[addr] = (getattr(o, addr).host, getattr(o, addr).port)
    if o.cert:
        c = Cert.from_pem(o.cert)
        d['cert'] = c
    if o.HasField('via'):
        d['via'] = _load_http_server_conn(o.via)
    sc = ServerConnection(tuple())
    for k, v in d.items():
        setattr(sc, k, v)
    return sc
Beispiel #3
0
def _load_http_server_conn(o: http_pb2.ServerConnection) -> ServerConnection:
    d: dict = {}
    _move_attrs(o, d, ['id', 'tls_established', 'sni', 'alpn_proto_negotiated', 'tls_version',
                       'timestamp_start', 'timestamp_tcp_setup', 'timestamp_tls_setup', 'timestamp_end'])
    for addr in ['address', 'ip_address', 'source_address']:
        if hasattr(o, addr):
            d[addr] = (getattr(o, addr).host, getattr(o, addr).port)
    if o.cert:
        c = Cert.from_pem(o.cert)
        d['cert'] = c
    if o.HasField('via'):
        d['via'] = _load_http_server_conn(o.via)
    sc = ServerConnection(tuple())
    for k, v in d.items():
        setattr(sc, k, v)
    return sc
Beispiel #4
0
def monkey_dummy_cert(privkey, cacert, commonname, sans):
    ss = []
    for i in sans:
        try:
            ipaddress.ip_address(i.decode("ascii"))
        except ValueError:
            # Change values in Certificate's Alt Name as well.
            if ctx.options.certwrongCN:
                ss.append(b"DNS:%sm" % i)
            else:
                ss.append(b"DNS:%s" % i)
        else:
            ss.append(b"IP:%s" % i)
    ss = b", ".join(ss)

    cert = OpenSSL.crypto.X509()
    if ctx.options.certbeginon:
        # Set certificate start time somewhere in the future
        cert.gmtime_adj_notBefore(3600 * 48)
    else:
        cert.gmtime_adj_notBefore(-3600 * 48)

    if ctx.options.certexpire:
        # sets the expire date of the certificate in the past.
        cert.gmtime_adj_notAfter(-3600 * 24)
    else:
        cert.gmtime_adj_notAfter(94608000)  # = 24 * 60 * 60 * 365 * 3

    cert.set_issuer(cacert.get_subject())
    if commonname is not None and len(commonname) < 64:
        if ctx.options.certwrongCN:
            # append an extra char to make certs common name different than original one.
            # APpending a char in the end of the domain name.
            new_cn = commonname + b'm'
            cert.get_subject().CN = new_cn

        else:
            cert.get_subject().CN = commonname

    cert.set_serial_number(int(time.time() * 10000))
    if ss:
        cert.set_version(2)
        cert.add_extensions(
            [OpenSSL.crypto.X509Extension(b"subjectAltName", False, ss)])
        cert.set_pubkey(cacert.get_pubkey())
        cert.sign(privkey, "sha256")
        return Cert(cert)
Beispiel #5
0
def _load_http_client_conn(o: http_pb2.ClientConnection) -> ClientConnection:
    d: dict = {}
    _move_attrs(o, d, ['id', 'tls_established', 'sni', 'cipher_name', 'alpn_proto_negotiated', 'tls_version',
                       'timestamp_start', 'timestamp_tcp_setup', 'timestamp_tls_setup', 'timestamp_end'])
    for cert in ['clientcert', 'mitmcert']:
        if hasattr(o, cert) and getattr(o, cert):
            d[cert] = Cert.from_pem(getattr(o, cert))
    if o.tls_extensions:
        d['tls_extensions'] = []
        for extension in o.tls_extensions:
            d['tls_extensions'].append((extension.int, extension.bytes))
    if o.address:
        d['address'] = (o.address.host, o.address.port)
    cc = ClientConnection(None, tuple(), None)
    for k, v in d.items():
        setattr(cc, k, v)
    return cc
Beispiel #6
0
def _load_http_client_conn(o: http_pb2.ClientConnection) -> ClientConnection:
    d: dict = {}
    _move_attrs(o, d, ['id', 'tls_established', 'sni', 'cipher_name', 'alpn_proto_negotiated', 'tls_version',
                       'timestamp_start', 'timestamp_tcp_setup', 'timestamp_tls_setup', 'timestamp_end'])
    for cert in ['clientcert', 'mitmcert']:
        if hasattr(o, cert) and getattr(o, cert):
            d[cert] = Cert.from_pem(getattr(o, cert))
    if o.tls_extensions:
        d['tls_extensions'] = []
        for extension in o.tls_extensions:
            d['tls_extensions'].append((extension.int, extension.bytes))
    if o.address:
        d['address'] = (o.address.host, o.address.port)
    cc = ClientConnection(None, tuple(), None)
    for k, v in d.items():
        setattr(cc, k, v)
    return cc