Given an PyOpenSSL certificate, provides all the subject alternative names.
499747
def get_subj_alt_name(peer_cert):
    
    # Pass the cert to cryptography, which has much better APIs for this.
    if hasattr(peer_cert, "to_cryptography"):
        cert = peer_cert.to_cryptography()
    else:
        # This is technically using private APIs, but should work across all
        # relevant versions before PyOpenSSL got a proper API for this.
        cert = _Certificate(openssl_backend, peer_cert._x509)

    # We want to find the SAN extension. Ask Cryptography to locate it (it's
    # faster than looping in Python)
    try:
        ext = cert.extensions.get_extension_for_class(
            x509.SubjectAlternativeName
        ).value
    except x509.ExtensionNotFound:
        # No such extension, return the empty list.
        return []
    except (x509.DuplicateExtension, UnsupportedExtension,
            x509.UnsupportedGeneralNameType, UnicodeError) as e:
        # A problem has been found with the quality of the certificate. Assume
        # no SAN field is present.
        log.warning(
            "A problem was encountered with the certificate that prevented "
            "urllib3 from finding the SubjectAlternativeName field. This can "
            "affect certificate validation. The error was %s",
            e,
        )
        return []

    # We want to return dNSName and iPAddress fields. We need to cast the IPs
    # back to strings because the match_hostname function wants them as
    # strings.
    # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8
    # decoded. This is pretty frustrating, but that's what the standard library
    # does with certificates, and so we need to attempt to do the same.
    # We also want to skip over names which cannot be idna encoded.
    names = [
        ('DNS', name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName))
        if name is not None
    ]
    names.extend(
        ('IP Address', str(name))
        for name in ext.get_values_for_type(x509.IPAddress)
    )

    return names
1098329
def possible_target_profiles(nickname, server, all_profiles_dict,
                             org_vm, autonomous=True, output='path'):
    
    assert output in ['path', 'name']
    profiles_in_svr = get_profiles_in_svr(nickname, server,
                                          all_profiles_dict,
                                          org_vm)
    # list of possible autonomous profiles for testing
    possible_profiles = []

    for profile_inst in profiles_in_svr:
        profile_org_name = profile_name(org_vm, profile_inst, short=True)
        if autonomous:
            if all_profiles_dict[profile_org_name].type == 'autonomous':
                possible_profiles.append(profile_inst)
        else:
            if not all_profiles_dict[profile_org_name].type == 'component':
                possible_profiles.append(profile_inst)

    if output == 'path':
        possible_profiles = [inst.path for inst in possible_profiles]
    elif output == 'name':
        possible_profiles = [profile_name(org_vm, inst)
                             for inst in possible_profiles]

    return possible_profiles
506620
def _get_csr_extensions(csr):
    '''
    
    '''
    ret = OrderedDict()

    csrtempfile = tempfile.NamedTemporaryFile()
    csrtempfile.write(csr.as_pem())
    csrtempfile.flush()
    csryaml = _parse_openssl_req(csrtempfile.name)
    csrtempfile.close()
    if csryaml and 'Requested Extensions' in csryaml['Certificate Request']['Data']:
        csrexts = csryaml['Certificate Request']['Data']['Requested Extensions']

        if not csrexts:
            return ret

        for short_name, long_name in six.iteritems(EXT_NAME_MAPPINGS):
            if long_name in csrexts:
                csrexts[short_name] = csrexts[long_name]
                del csrexts[long_name]
        ret = csrexts
    return ret
54987
def _identify(self, subject):
        
        ourPrivateCert = self.service.certificateStorage.getPrivateCertificate(
            str(subject)
        )
        ourCA = Certificate(ourPrivateCert.original)
        return dict(certificate=ourCA)
1120378
def validate_host(cert, name):
    
    cn = None
    for t, v in cert.get_subject().get_components():
        if t == b'CN':
            cn = v
            break

    if cn == name:
        return True

    # checking SAN
    s_name = name.decode('ascii')
    for i in range(cert.get_extension_count()):
        ext = cert.get_extension(i)
        if ext.get_short_name() == b'subjectAltName':
            s = str(ext)
            # SANs are usually have form like: DNS:hostname
            if s.startswith('DNS:') and s[4:] == s_name:
                return True

    # TODO handle wildcards
    return False
1091292
def SSLCertificates(self):
        
        url = self._url + "/SSLCertificate"
        params = {"f" : "json"}
        return self._post(url=url,
                          param_dict=params,
                          proxy_url=self._proxy_url,
                          proxy_port=self._proxy_port)
1034051
def get_sea_names():
    '''
    
    '''
    global _SEA_NAMES
    if _SEA_NAMES is None:
        buf = {}
        with open(resource_filename('compliance_checker', 'data/seanames.csv'), 'r') as f:
            reader = csv.reader(f)
            for code, sea_name in reader:
                buf[sea_name] = code
        _SEA_NAMES = buf
    return _SEA_NAMES
84152
def parse_csr():
    
    LOGGER.info("Parsing CSR...")
    cmd = [
        'openssl', 'req',
        '-in', os.path.join(gettempdir(), 'domain.csr'),
        '-noout',
        '-text'
    ]
    devnull = open(os.devnull, 'wb')
    out = subprocess.check_output(cmd, stderr=devnull)
    domains = set([])
    common_name = re.search(r"Subject:.*? CN\s?=\s?([^\s,;/]+)", out.decode('utf8'))
    if common_name is not None:
        domains.add(common_name.group(1))
    subject_alt_names = re.search(r"X509v3 Subject Alternative Name: \n +([^\n]+)\n", out.decode('utf8'), re.MULTILINE | re.DOTALL)
    if subject_alt_names is not None:
        for san in subject_alt_names.group(1).split(", "):
            if san.startswith("DNS:"):
                domains.add(san[4:])

    return domains
160084
def protocols():
    
    if not hasattr(protocols, 'protlist'):
        plist = []
        try:
            data = requests.get('http://www.iana.org/assignments/service-names'
                                '-port-numbers/service-names-port-numbers.csv')
        except requests.exceptions.RequestException:
            return []

        for line in data.iter_lines():
            if line:
                line = line.decode("utf-8")
                if line.count(',') > 0:
                    vals = line.split(',')
                    if vals[0]:
                        plist.append(vals[0])
                    if len(vals) > 2 and vals[2] and vals[2] not in plist:
                        plist.append(vals[2])

        plist.append('ipv4')
        plist.append('ipv6')
        plist.append('ssl')
        plist.append('tls')
        plist.append('dns')
        protocols.protlist = plist
    return protocols.protlist
103045
def get_certificates_der_v3(self):
        

        if self._v3_signing_data == None:
            self.parse_v3_signing_block()

        certs = []
        for signed_data in [signer.signed_data for signer in self._v3_signing_data]:
            for cert in signed_data.certificates:
                certs.append(cert)

        return certs
157993
private void verifyCert(X500Name subject,
        CertificateExtensions extensions)
        throws CertificateParsingException, IOException {

        // if SubjectName is empty, check for SubjectAlternativeNameExtension
        if (subject.isEmpty()) {
            if (extensions == null) {
                throw new CertificateParsingException("X.509 Certificate is " +
                        "incomplete: subject field is empty, and certificate " +
                        "has no extensions");
            }
            SubjectAlternativeNameExtension subjectAltNameExt = null;
            SubjectAlternativeNameExtension extValue = null;
            GeneralNames names = null;
            try {
                subjectAltNameExt = (SubjectAlternativeNameExtension)
                        extensions.get(SubjectAlternativeNameExtension.NAME);
                names = subjectAltNameExt.get(
                        SubjectAlternativeNameExtension.SUBJECT_NAME);
            } catch (IOException e) {
                throw new CertificateParsingException("X.509 Certificate is " +
                        "incomplete: subject field is empty, and " +
                        "SubjectAlternativeName extension is absent");
            }

            // SubjectAlternativeName extension is empty or not marked critical
            if (names == null || names.isEmpty()) {
                throw new CertificateParsingException("X.509 Certificate is " +
                        "incomplete: subject field is empty, and " +
                        "SubjectAlternativeName extension is empty");
            } else if (subjectAltNameExt.isCritical() == false) {
                throw new CertificateParsingException("X.509 Certificate is " +
                        "incomplete: SubjectAlternativeName extension MUST " +
                        "be marked critical when subject field is empty");
            }
        }
    }
711918
def name_match(self, elt):
        '''
        '''
        return self.pname == elt.localName and \
                    self.nspname in [None, '', elt.namespaceURI]
1005629
def get_active_subject_set(self, request):
        """"""
        # Handle complete certificate in vendor specific extension.
        if django.conf.settings.DEBUG_GMN:
            if 'HTTP_VENDOR_INCLUDE_CERTIFICATE' in request.META:
                request.META[
                    'SSL_CLIENT_CERT'
                ] = self.pem_in_http_header_to_pem_in_string(
                    request.META['HTTP_VENDOR_INCLUDE_CERTIFICATE']
                )

        # Add subjects from any provided certificate and JWT and store them in
        # the Django request obj.
        cert_primary_str, cert_equivalent_set = d1_gmn.app.middleware.session_cert.get_subjects(
            request
        )
        jwt_subject_list = d1_gmn.app.middleware.session_jwt.validate_jwt_and_get_subject_list(
            request
        )
        primary_subject_str = cert_primary_str
        all_subjects_set = (
            cert_equivalent_set | {cert_primary_str} | set(jwt_subject_list)
        )
        if len(jwt_subject_list) == 1:
            jwt_primary_str = jwt_subject_list[0]
            if jwt_primary_str != cert_primary_str:
                if cert_primary_str == d1_common.const.SUBJECT_PUBLIC:
                    primary_subject_str = jwt_primary_str
                else:
                    logging.warning(
                        'Both a certificate and a JWT were provided and the primary '
                        'subjects differ. Using the certificate for primary subject and'
                        'the JWT as equivalent.'
                    )

        logging.info('Primary active subject: {}'.format(primary_subject_str))
        logging.info(
            'All active subjects: {}'.format(', '.join(sorted(all_subjects_set)))
        )

        # Handle list of subjects in vendor specific extension:
        if django.conf.settings.DEBUG_GMN:
            # This is added to any subjects obtained from cert and/or JWT.
            if 'HTTP_VENDOR_INCLUDE_SUBJECTS' in request.META:
                request.all_subjects_set.update(
                    request.META['HTTP_VENDOR_INCLUDE_SUBJECTS'].split('\t')
                )

        return primary_subject_str, all_subjects_set
643715
public List<String> getRoleNames(final Optional<Subject> subjectOption)
    {
        final List<String> roleNames = new ArrayList<String>();
        subjectOption.ifPresent(subject -> {
            final List<? extends Role> roles = subject.getRoles();
            if (roles != null)
            {
                for (Role role : roles)
                {
                    if (role != null)
                    {
                        roleNames.add(role.getName());
                    }
                }
            }
        });

        return roleNames;
    }
229834
def GetValidHostsForCert(cert):
  
  if 'subjectAltName' in cert:
    return [x[1] for x in cert['subjectAltName'] if x[0].lower() == 'dns']
  else:
    return [x[0][1] for x in cert['subject']
            if x[0][0].lower() == 'commonname']
557536
def _get_client_side_certificate_subject():
    
    subject = django.core.cache.cache.get('client_side_certificate_subject')
    if subject is not None:
        return subject
    cert_pem = _get_client_side_certificate_pem()
    if cert_pem is None:
        return None
    subject = _extract_subject_from_pem(cert_pem)
    django.core.cache.cache.set('client_side_certificate_subject', subject)
    return subject
851857
def canonical_names(self):
        
        cns = []
        for r_id in relation_ids('identity-service'):
            for unit in related_units(r_id):
                rdata = relation_get(rid=r_id, unit=unit)
                for k in rdata:
                    if k.startswith('ssl_key_'):
                        cns.append(k.lstrip('ssl_key_'))

        return sorted(list(set(cns)))