当前位置: 首页>>代码示例>>Python>>正文


Python ssl.get_server_certificate方法代码示例

本文整理汇总了Python中ssl.get_server_certificate方法的典型用法代码示例。如果您正苦于以下问题:Python ssl.get_server_certificate方法的具体用法?Python ssl.get_server_certificate怎么用?Python ssl.get_server_certificate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ssl的用法示例。


在下文中一共展示了ssl.get_server_certificate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: process_host

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import get_server_certificate [as 别名]
def process_host(self, host_spec, name, line_idx=0):
        """
        One host spec processing
        :param host_spec:
        :param name:
        :param line_idx:
        :return:
        """
        try:
            parts = host_spec.split(':', 1)
            host = parts[0].strip()
            port = parts[1] if len(parts) > 1 else 443
            pem_cert = self.get_server_certificate(host, port)
            if pem_cert:
                sub = self.roca.process_pem_cert(pem_cert, name, line_idx)
                return sub

        except Exception as e:
            logger.error('Error in file processing %s (%s) : %s' % (host_spec, name, e))
            self.roca.trace_logger.log(e) 
开发者ID:crocs-muni,项目名称:roca,代码行数:22,代码来源:detect_tls.py

示例2: ssl_grabber

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import get_server_certificate [as 别名]
def ssl_grabber(resolved_ip, port):
    try:
        cert = ssl.get_server_certificate((resolved_ip.address, port))
        x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
        cert_hostname = x509.get_subject().CN

        # Add New HostNames to List
        for host in cert_hostname.split('\n'):
            # print(host)
            if (host == "") or (host in resolved_ip.hostname):
                pass
            else:
                try:
                    resolved_ip.hostname.append(host)
                except:
                    pass
    except (urllib3.exceptions.ReadTimeoutError, requests.ConnectionError, urllib3.connection.ConnectionError,
            urllib3.exceptions.MaxRetryError, urllib3.exceptions.ConnectTimeoutError, urllib3.exceptions.TimeoutError,
            socket.error, socket.timeout) as e:
        pass


# r_dns Function 
开发者ID:superhedgy,项目名称:AttackSurfaceMapper,代码行数:25,代码来源:hosthunter.py

示例3: _certificate_required

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import get_server_certificate [as 别名]
def _certificate_required(cls, hostname, port=XCLI_DEFAULT_PORT,
                              ca_certs=None, validate=None):
        '''
        returns true if connection should verify certificate
        '''
        if not ca_certs:
            return False

        xlog.debug("CONNECT SSL %s:%s, cert_file=%s",
                   hostname, port, ca_certs)
        certificate = ssl.get_server_certificate((hostname, port),
                                                 ca_certs=None)
        # handle XIV pre-defined certifications
        # if a validation function was given - we let the user check
        # the certificate himself, with the user's own validate function.
        # if the validate returned True - the user checked the cert
        # and we don't need check it, so we return false.
        if validate:
            return not validate(certificate)
        return True 
开发者ID:IBM,项目名称:pyxcli,代码行数:22,代码来源:transports.py

示例4: sslGrabber

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import get_server_certificate [as 别名]
def sslGrabber(hostx,port):
    try:
        cert=ssl.get_server_certificate((hostx.address, port))
        x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
        cert_hostname=x509.get_subject().CN
        # Add New HostNames to List
        if cert_hostname is not None:
            for host in cert_hostname.split('\n'):
                if (host=="") or (host in hostx.hname):
                    pass
                else:
                    hostx.hname.append(host)
    except (urllib3.exceptions.ReadTimeoutError,requests.ConnectionError,urllib3.connection.ConnectionError,urllib3.exceptions.MaxRetryError,urllib3.exceptions.ConnectTimeoutError,urllib3.exceptions.TimeoutError,socket.error,socket.timeout) as e:
        pass

# queryAPI Function 
开发者ID:SpiderLabs,项目名称:HostHunter,代码行数:18,代码来源:hosthunter.py

示例5: get_ssl_certificate

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import get_server_certificate [as 别名]
def get_ssl_certificate(self, ssl_version=None):
        """
        Get an OpenSSL cryptographic PEM certificate from the endpoint using the specified SSL version.
        :param ssl_version: The SSL version to connect with. If None, then let OpenSSL negotiate which
        protocol to use.
        :return: A tuple containing (1) the certificate string and (2) an OpenSSL cryptographic PEM
        certificate from the endpoint.
        """

        try:
            if ssl_version is not None:
                cert = ssl.get_server_certificate((self.address, self.port), ssl_version=getattr(ssl, ssl_version))
            else:
                cert = ssl.get_server_certificate((self.address, self.port))
            return cert, OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
        except ssl.SSLError as e:
            raise SslCertificateRetrievalFailedError(
                message="SSL error thrown when retrieving SSL certificate: %s." % (e,)
            )

    # Protected Methods

    # Private Methods 
开发者ID:lavalamp-,项目名称:ws-backend-community,代码行数:25,代码来源:network.py

示例6: tls

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import get_server_certificate [as 别名]
def tls(ctx, domain_name):
    """Get the TLS certificate for a domain.

    Example:

        $ lokey fetch tls gliderlabs.com
    """
    try:
        cert = stdlib_ssl.get_server_certificate((domain_name, 443))
        click.echo(cert)
    except:
        msg =("Unable to fetch key from {}, "
              "is that domain configured for TLS?").format(domain_name)
        raise click.ClickException(msg) 
开发者ID:jpf,项目名称:lokey,代码行数:16,代码来源:__init__.py

示例7: in_abuse_list

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import get_server_certificate [as 别名]
def in_abuse_list(self, url_domain: str) -> Tuple:
        """
        Validate if a domain or URL's SSL cert the abuse.ch SSL Abuse List.

        Parameters
        ----------
        url_domain : str
            The url or domain to validate.

        Returns
        -------
        result:
            True if valid in the list, False if not.

        """
        try:
            cert = ssl.get_server_certificate((url_domain, 443))
            backend = crypto.hazmat.backends.default_backend()  # type: ignore
            x509 = crypto.x509.load_pem_x509_certificate(  # type: ignore
                cert.encode("ascii"), backend
            )
            cert_sha1 = x509.fingerprint(
                crypto.hazmat.primitives.hashes.SHA1()  # type: ignore # nosec
            )
            result = bool(
                self.ssl_abuse_list["SHA1"]
                .str.contains(cert_sha1.hex())
                .any()  # type: ignore
            )
        except Exception:  # pylint: disable=broad-except
            result = False
            x509 = None

        return result, x509 
开发者ID:microsoft,项目名称:msticpy,代码行数:36,代码来源:domain_utils.py

示例8: _check_ssl_cert

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import get_server_certificate [as 别名]
def _check_ssl_cert(self):
        """Preflight the SSL certificate presented by the backend.

        This isn't 100% bulletproof, in that we're not actually validating the
        transport used to communicate with Shippo, merely that the first
        attempt to does not use a revoked certificate.

        Unfortunately the interface to OpenSSL doesn't make it easy to check
        the certificate before sending potentially sensitive data on the wire.
        This approach raises the bar for an attacker significantly."""

        from shippo.config import verify_ssl_certs

        if verify_ssl_certs and not self._CERTIFICATE_VERIFIED:
            uri = urllib.parse.urlparse(shippo.config.api_base)
            try:
                certificate = ssl.get_server_certificate(
                    (uri.hostname, uri.port or 443))
                der_cert = ssl.PEM_cert_to_DER_cert(certificate)
            except socket.error as e:
                raise error.APIConnectionError(e)
            except TypeError:
                # The Google App Engine development server blocks the C socket
                # module which causes a type error when using the SSL library
                if ('APPENGINE_RUNTIME' in os.environ and
                        'Dev' in os.environ.get('SERVER_SOFTWARE', '')):
                    self._CERTIFICATE_VERIFIED = True
                    warnings.warn(
                        'We were unable to verify Shippo\'s SSL certificate '
                        'due to a bug in the Google App Engine development '
                        'server. Please alert us immediately at '
                        'suppgoshippo.compo.com if this message appears in your '
                        'production logs.')
                    return
                else:
                    raise

            self._CERTIFICATE_VERIFIED = certificate_blacklist.verify(
                uri.hostname, der_cert) 
开发者ID:goshippo,项目名称:shippo-python-client,代码行数:41,代码来源:api_requestor.py

示例9: get_server_certificate

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import get_server_certificate [as 别名]
def get_server_certificate(self, host, port):
        """
        Gets the remote x.509 certificate
        :param host:
        :param port:
        :return:
        """
        logger.info("Fetching server certificate from %s:%s" % (host,port))
        try:
            return get_server_certificate((host, int(port)))
        except Exception as e:
            logger.error('Error getting server certificate from %s:%s: %s' %
                         (host, port, e))
            return False 
开发者ID:crocs-muni,项目名称:roca,代码行数:16,代码来源:detect_tls.py

示例10: get_socket

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import get_server_certificate [as 别名]
def get_socket(self):
        if self.use_ssl:
            cert_path = os.path.join( self.config.path, 'certs', self.host)
            if not os.path.exists(cert_path):
                is_new = True
                s = self.get_simple_socket()
                if s is None:
                    return
                # try with CA first
                try:
                    s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23, cert_reqs=ssl.CERT_REQUIRED, ca_certs=ca_path, do_handshake_on_connect=True)
                except ssl.SSLError, e:
                    s = None
                if s and self.check_host_name(s.getpeercert(), self.host):
                    print_error("SSL certificate signed by CA:", self.host)
                    return s

                # get server certificate.
                # Do not use ssl.get_server_certificate because it does not work with proxy
                s = self.get_simple_socket()
                try:
                    s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23, cert_reqs=ssl.CERT_NONE, ca_certs=None)
                except ssl.SSLError, e:
                    print_error("SSL error retrieving SSL certificate:", self.host, e)
                    return

                dercert = s.getpeercert(True)
                s.close()
                cert = ssl.DER_cert_to_PEM_cert(dercert)
                # workaround android bug
                cert = re.sub("([^\n])-----END CERTIFICATE-----","\\1\n-----END CERTIFICATE-----",cert)
                temporary_path = cert_path + '.temp'
                with open(temporary_path,"w") as f:
                    f.write(cert) 
开发者ID:mazaclub,项目名称:encompass,代码行数:36,代码来源:interface.py

示例11: fetch

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import get_server_certificate [as 别名]
def fetch(self):
        self.certinfo = ssl.get_server_certificate((self.ip, self.port)) 
开发者ID:corelan,项目名称:certmon,代码行数:4,代码来源:cert.py

示例12: org_finder

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import get_server_certificate [as 别名]
def org_finder(hostx):
    target = hostx.primary_domain

    try:
        cert = ssl.get_server_certificate((target, 443))
        x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
        orgName = x509.get_subject().organizationName
        unit = x509.get_subject().organizationalUnitName
        hostx.orgName = str(orgName)
    except:
        pass


#  dnsloopkup Function 
开发者ID:superhedgy,项目名称:AttackSurfaceMapper,代码行数:16,代码来源:hosthunter.py

示例13: process

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import get_server_certificate [as 别名]
def process(self, profile, state, vertex):
        if 'type' not in vertex:
            return { 'error' : "No vertex type defined!" }

        properties = dict()

        if vertex['type'] == "domain":
            try:
                begin = time.time()
                properties['content'] = ssl.get_server_certificate((vertex['id'], self.ssl_port))
                properties['time'] = time.time() - begin
            except Exception as e:
                properties['error'] = str(e)
 
        return { "properties": properties, "neighbors" : [] } 
开发者ID:opendns,项目名称:og-miner,代码行数:17,代码来源:ssl.py

示例14: module_run

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import get_server_certificate [as 别名]
def module_run(self, hosts):
        cn_regex_pat = r'.*CN=(.+?)(,|$)'
        dn_regex_pat = r'^(?!:\/\/)([a-zA-Z0-9-_]+\.)*[a-zA-Z0-9][a-zA-Z0-9-_]+\.[a-zA-Z]{2,11}?$'
        for host in hosts:
            setdefaulttimeout(10)
            ip, port = host.split(':')
            try:
                cert = ssl.get_server_certificate((ip, port), ssl_version=ssl.PROTOCOL_TLS)
            except (ssl.SSLError, ConnectionResetError, ConnectionRefusedError, ssl.SSLEOFError, OSError):
                self.alert(f"This is not a proper HTTPS service: {ip}:{port}")
                continue
            except timeout:
                self.alert(f"Timed out connecting to host {ip}:{port}")
                continue

            x509 = M2Crypto.X509.load_cert_string(cert)
            regex = re.compile(cn_regex_pat)
            commonname = regex.search(x509.get_subject().as_text()).group(1).lower()

            if re.match(dn_regex_pat, commonname):
                self.output(f"Updating ports table for {ip} to include host {commonname}")
                self.query('UPDATE ports SET ip_address=?, host=?, port=?, protocol=? WHERE ip_address=?',
                           (ip, commonname, port, 'tcp', ip))
            else:
                self.alert(f"Not a valid Common Name: {commonname}")

            try:
                subaltname = x509.get_ext('subjectAltName').get_value().split(',')
            except LookupError:
                continue

            for san in subaltname:
                san = san.split(':')[1].lower()
                if re.match(dn_regex_pat, san):
                    self.insert_hosts(host=san) 
开发者ID:lanmaster53,项目名称:recon-ng-marketplace,代码行数:37,代码来源:ssl_scan.py

示例15: getcert

# 需要导入模块: import ssl [as 别名]
# 或者: from ssl import get_server_certificate [as 别名]
def getcert(a):
    """Get SSL Cert CN"""
    refPorts = open('config/ports.txt', 'r').readlines()
    for port in refPorts:
        # Make sure we don't have any extra characters like \n or \r
        port = port.rstrip()
        try:
            # time to connect!
            cert = ssl.get_server_certificate((a, port))
        except Exception, e:
            # If it can't connect go to the next iteration so we don't waste time
            continue
        try:
            # use openssl to pull cert information
            c = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
            subj = c.get_subject()
            comp = subj.get_components()
            for data in comp:
                if 'CN' in data:
                    out[a] = a,data[1]
                elif 'CN' not in data:
                    continue
                else:
                    continue
        except Exception,e:
            # if openssl fails to get information, return nothing
            continue 
开发者ID:krintoxi,项目名称:NoobSec-Toolkit,代码行数:29,代码来源:sslscan.py


注:本文中的ssl.get_server_certificate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。