Parse CPE_NAME data from the os-release

    Info: https://csrc.nist.gov/projects/security-content-automation-protocol/scap-specifications/cpe

    :param cpe:
    :return:
6372
def _parse_cpe_name(cpe):
    '''
    
    '''
    part = {
        'o': 'operating system',
        'h': 'hardware',
        'a': 'application',
    }
    ret = {}
    cpe = (cpe or '').split(':')
    if len(cpe) > 4 and cpe[0] == 'cpe':
        if cpe[1].startswith('/'):  # WFN to URI
            ret['vendor'], ret['product'], ret['version'] = cpe[2:5]
            ret['phase'] = cpe[5] if len(cpe) > 5 else None
            ret['part'] = part.get(cpe[1][1:])
        elif len(cpe) == 13 and cpe[1] == '2.3':  # WFN to a string
            ret['vendor'], ret['product'], ret['version'], ret['phase'] = [x if x != '*' else None for x in cpe[3:7]]
            ret['part'] = part.get(cpe[2])

    return ret
447719
def _parse(self):
        

        # CPE Name must not have whitespaces
        if (self._str.find(" ") != -1):
            msg = "Bad-formed CPE Name: it must not have whitespaces"
            raise ValueError(msg)

        # Partitioning of CPE Name
        parts_match = CPE2_3_URI._parts_rxc.match(self._str)

        # Validation of CPE Name parts
        if (parts_match is None):
            msg = "Bad-formed CPE Name: validation of parts failed"
            raise ValueError(msg)

        components = dict()
        edition_parts = dict()

        for ck in CPEComponent.CPE_COMP_KEYS:
            value = parts_match.group(ck)

            try:
                if (ck == CPEComponent.ATT_EDITION and value is not None):
                    if value[0] == CPEComponent2_3_URI.SEPARATOR_PACKED_EDITION:
                        # Unpack the edition part
                        edition_parts = CPE2_3_URI._unpack_edition(value)
                    else:
                        comp = CPE2_3_URI._create_component(ck, value)
                else:
                    comp = CPE2_3_URI._create_component(ck, value)
            except ValueError:
                errmsg = "Bad-formed CPE Name: not correct value '{0}'".format(
                    value)
                raise ValueError(errmsg)
            else:
                components[ck] = comp

        components = dict(components, **edition_parts)

        # Adds the components of version 2.3 of CPE not defined in version 2.2
        for ck2 in CPEComponent.CPE_COMP_KEYS_EXTENDED:
            if ck2 not in components.keys():
                components[ck2] = CPEComponentUndefined()

        # Exchange the undefined values in middle attributes of CPE Name for
        # logical value ANY
        check_change = True

        # Start in the last attribute specififed in CPE Name
        for ck in CPEComponent.CPE_COMP_KEYS[::-1]:
            if ck in components:
                comp = components[ck]
                if check_change:
                    check_change = ((ck != CPEComponent.ATT_EDITION) and
                                   (comp == CPEComponentUndefined()) or
                                   (ck == CPEComponent.ATT_EDITION and
                                   (len(edition_parts) == 0)))
                elif comp == CPEComponentUndefined():
                    comp = CPEComponentAnyValue()

                components[ck] = comp

        #  Storage of CPE Name
        part_comp = components[CPEComponent.ATT_PART]
        if isinstance(part_comp, CPEComponentLogical):
            elements = []
            elements.append(components)
            self[CPE.KEY_UNDEFINED] = elements
        else:
            # Create internal structure of CPE Name in parts:
            # one of them is filled with identified components,
            # the rest are empty
            system = parts_match.group(CPEComponent.ATT_PART)
            if system in CPEComponent.SYSTEM_VALUES:
                self._create_cpe_parts(system, components)
            else:
                self._create_cpe_parts(CPEComponent.VALUE_PART_UNDEFINED,
                                       components)

        # Fills the empty parts of internal structure of CPE Name
        for pk in CPE.CPE_PART_KEYS:
            if pk not in self.keys():
                # Empty part
                self[pk] = []
926300
def as_fs(self):
        

        fs = []
        fs.append("cpe:2.3:")

        for i in range(0, len(CPEComponent.ordered_comp_parts)):
            ck = CPEComponent.ordered_comp_parts[i]
            lc = self._get_attribute_components(ck)

            if len(lc) > 1:
                # Incompatible version 1.1, there are two or more elements
                # in CPE Name
                errmsg = "Incompatible version {0} with formatted string".format(
                    self.VERSION)
                raise TypeError(errmsg)

            else:
                comp = lc[0]

                if (isinstance(comp, CPEComponentUndefined) or
                   isinstance(comp, CPEComponentEmpty) or
                   isinstance(comp, CPEComponentAnyValue)):

                    # Logical value any
                    v = CPEComponent2_3_FS.VALUE_ANY

                elif isinstance(comp, CPEComponentNotApplicable):

                    # Logical value not applicable
                    v = CPEComponent2_3_FS.VALUE_NA
                else:
                    # Get the value of component encoded in formatted string
                    v = comp.as_fs()

            # Append v to the formatted string then add a separator.
            fs.append(v)
            fs.append(CPEComponent2_3_FS.SEPARATOR_COMP)

        # Return the formatted string
        return CPE._trim("".join(fs[:-1]))
1359744
def _parse_info(self, data):
		

		match = GNTP_INFO_LINE.match(data)

		if not match:
			raise errors.ParseError('ERROR_PARSING_INFO_LINE')

		info = match.groupdict()
		if info['encryptionAlgorithmID'] == 'NONE':
			info['encryptionAlgorithmID'] = None

		return info
257161
def get_nameid_data(self):
        
        nameid = None
        nameid_data = {}

        encrypted_id_data_nodes = self.__query_assertion('/saml:Subject/saml:EncryptedID/xenc:EncryptedData')
        if encrypted_id_data_nodes:
            encrypted_data = encrypted_id_data_nodes[0]
            key = self.__settings.get_sp_key()
            nameid = OneLogin_Saml2_Utils.decrypt_element(encrypted_data, key)
        else:
            nameid_nodes = self.__query_assertion('/saml:Subject/saml:NameID')
            if nameid_nodes:
                nameid = nameid_nodes[0]

        is_strict = self.__settings.is_strict()
        want_nameid = self.__settings.get_security_data().get('wantNameId', True)
        if nameid is None:
            if is_strict and want_nameid:
                raise OneLogin_Saml2_ValidationError(
                    'NameID not found in the assertion of the Response',
                    OneLogin_Saml2_ValidationError.NO_NAMEID
                )
        else:
            if is_strict and want_nameid and not OneLogin_Saml2_Utils.element_text(nameid):
                raise OneLogin_Saml2_ValidationError(
                    'An empty NameID value found',
                    OneLogin_Saml2_ValidationError.EMPTY_NAMEID
                )

            nameid_data = {'Value': OneLogin_Saml2_Utils.element_text(nameid)}
            for attr in ['Format', 'SPNameQualifier', 'NameQualifier']:
                value = nameid.get(attr, None)
                if value:
                    if is_strict and attr == 'SPNameQualifier':
                        sp_data = self.__settings.get_sp_data()
                        sp_entity_id = sp_data.get('entityId', '')
                        if sp_entity_id != value:
                            raise OneLogin_Saml2_ValidationError(
                                'The SPNameQualifier value mistmatch the SP entityID value.',
                                OneLogin_Saml2_ValidationError.SP_NAME_QUALIFIER_NAME_MISMATCH
                            )

                    nameid_data[attr] = value
        return nameid_data
955457
def get_crt_common_name(certificate_path=OLD_CERTIFICATE_PATH):
    '''
        
    '''
    try:
        certificate_file = open(certificate_path)
        crt = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
                                              certificate_file.read())
        return crt.get_subject().commonName
    except IOError:
        return None
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
223119
def parse(self):
        

        keys = {
            'fn': self._parse_name,
            'kind': self._parse_kind,
            'adr': self._parse_address,
            'tel': self._parse_phone,
            'email': self._parse_email,
            'role': self._parse_role,
            'title': self._parse_title
        }

        for val in self.vcard:

            try:

                parser = keys.get(val[0])
                parser(val)

            except (KeyError, ValueError, TypeError):

                pass
1196481
def _parse_name(name):
    
    required = False

    if name[-1] == '*':
        name = name[0:-1]
        required = True

    return name, required
975752
def parse( bin_payload ):
   
  
   if len(bin_payload) == 0:
       log.error("empty namespace")
       return None 

   if bin_payload[0] != '.':
       log.error("Missing namespace delimiter '.'")
       return None 

   namespace_id = bin_payload[ 1: ]
   
   # sanity check
   if not is_b40( namespace_id ) or "+" in namespace_id or namespace_id.count(".") > 0:
       log.error("Invalid namespace ID '%s'" % namespace_id)
       return None

   if len(namespace_id) <= 0 or len(namespace_id) > LENGTHS['blockchain_id_namespace_id']:
       log.error("Invalid namespace of length %s" % len(namespace_id))
       return None 

   return {
      'opcode': 'NAMESPACE_READY',
      'namespace_id': namespace_id
   }
715298
def _parse(self):
        

        # CPE Name must not have whitespaces
        if (self.cpe_str.find(" ") != -1):
            errmsg = "Bad-formed CPE Name: it must not have whitespaces"
            raise ValueError(errmsg)

        # Partitioning of CPE Name in parts
        parts_match = CPE1_1._parts_rxc.match(self.cpe_str)

        # ################################
        #  Validation of CPE Name parts  #
        # ################################

        if (parts_match is None):
            errmsg = "Bad-formed CPE Name: not correct definition of CPE Name parts"
            raise ValueError(errmsg)

        CPE_PART_KEYS = (CPE.KEY_HW, CPE.KEY_OS, CPE.KEY_APP)

        for pk in CPE_PART_KEYS:
            # Get part content
            part = parts_match.group(pk)
            elements = []

            if (part is not None):
                # Part of CPE Name defined

                # ###############################
                #  Validation of part elements  #
                # ###############################

                # semicolon (;) is used to separate the part elements
                for part_elem in part.split(CPE1_1.ELEMENT_SEPARATOR):
                    j = 1

                    # ####################################
                    #  Validation of element components  #
                    # ####################################

                    components = dict()

                    # colon (:) is used to separate the element components
                    for elem_comp in part_elem.split(CPEComponent1_1.SEPARATOR_COMP):
                        comp_att = CPEComponent.ordered_comp_parts[j]

                        if elem_comp == CPEComponent1_1.VALUE_EMPTY:
                            comp = CPEComponentEmpty()
                        else:
                            try:
                                comp = CPEComponent1_1(elem_comp, comp_att)
                            except ValueError:
                                errmsg = "Bad-formed CPE Name: not correct value: {0}".format(
                                    elem_comp)
                                raise ValueError(errmsg)

                        # Identification of component name
                        components[comp_att] = comp

                        j += 1

                    # Adds the components of version 2.3 of CPE not defined
                    # in version 1.1
                    for idx in range(j, len(CPEComponent.ordered_comp_parts)):
                        comp_att = CPEComponent.ordered_comp_parts[idx]
                        components[comp_att] = CPEComponentUndefined()

                    # Get the type of system associated with CPE Name and
                    # store it in element as component
                    if (pk == CPE.KEY_HW):
                        components[CPEComponent.ATT_PART] = CPEComponent1_1(
                            CPEComponent.VALUE_PART_HW, CPEComponent.ATT_PART)
                    elif (pk == CPE.KEY_OS):
                        components[CPEComponent.ATT_PART] = CPEComponent1_1(
                            CPEComponent.VALUE_PART_OS, CPEComponent.ATT_PART)
                    elif (pk == CPE.KEY_APP):
                        components[CPEComponent.ATT_PART] = CPEComponent1_1(
                            CPEComponent.VALUE_PART_APP, CPEComponent.ATT_PART)

                    # Store the element identified
                    elements.append(components)

            # Store the part identified
            self[pk] = elements

        self[CPE.KEY_UNDEFINED] = []
1294411
def get_name_as_short_text(cls, name_field: cryptography.x509.Name) -> str:
        
        # Name_field is supposed to be a Subject or an Issuer; print the CN if there is one
        common_names = cls.get_common_names(name_field)
        if common_names:
            # We don't support certs with multiple CNs
            return common_names[0]
        else:
            # Otherwise show the whole field
            return cls.get_name_as_text(name_field)
478057
def _parse_openssl_crl(crl_filename):
    '''
    
    '''
    if not salt.utils.path.which('openssl'):
        raise salt.exceptions.SaltInvocationError(
            'openssl binary not found in path'
        )
    cmd = ('openssl crl -text -noout -in {0}'.format(crl_filename))

    output = __salt__['cmd.run_stdout'](cmd)

    crl = {}
    for line in output.split('\n'):
        line = line.strip()
        if line.startswith('Version '):
            crl['Version'] = line.replace('Version ', '')
        if line.startswith('Signature Algorithm: '):
            crl['Signature Algorithm'] = line.replace(
                'Signature Algorithm: ', '')
        if line.startswith('Issuer: '):
            line = line.replace('Issuer: ', '')
            subject = {}
            for sub_entry in line.split('/'):
                if '=' in sub_entry:
                    sub_entry = sub_entry.split('=')
                    subject[sub_entry[0]] = sub_entry[1]
            crl['Issuer'] = subject
        if line.startswith('Last Update: '):
            crl['Last Update'] = line.replace('Last Update: ', '')
            last_update = datetime.datetime.strptime(
                crl['Last Update'], "%b %d %H:%M:%S %Y %Z")
            crl['Last Update'] = last_update.strftime("%Y-%m-%d %H:%M:%S")
        if line.startswith('Next Update: '):
            crl['Next Update'] = line.replace('Next Update: ', '')
            next_update = datetime.datetime.strptime(
                crl['Next Update'], "%b %d %H:%M:%S %Y %Z")
            crl['Next Update'] = next_update.strftime("%Y-%m-%d %H:%M:%S")
        if line.startswith('Revoked Certificates:'):
            break

    if 'No Revoked Certificates.' in output:
        crl['Revoked Certificates'] = []
        return crl

    output = output.split('Revoked Certificates:')[1]
    output = output.split('Signature Algorithm:')[0]

    rev = []
    for revoked in output.split('Serial Number: '):
        if not revoked.strip():
            continue

        rev_sn = revoked.split('\n')[0].strip()
        revoked = rev_sn + ':\n' + '\n'.join(revoked.split('\n')[1:])
        rev_yaml = salt.utils.data.decode(salt.utils.yaml.safe_load(revoked))
        # pylint: disable=unused-variable
        for rev_item, rev_values in six.iteritems(rev_yaml):
            # pylint: enable=unused-variable
            if 'Revocation Date' in rev_values:
                rev_date = datetime.datetime.strptime(
                    rev_values['Revocation Date'], "%b %d %H:%M:%S %Y %Z")
                rev_values['Revocation Date'] = rev_date.strftime(
                    "%Y-%m-%d %H:%M:%S")

        rev.append(rev_yaml)

    crl['Revoked Certificates'] = rev

    return crl
966949
def __parse_scanned_version_info(self):
        """"""
        string = self.sys_version_info_formatted
        try:
            major, minor, micro, release_level, serial = string.split(",")
            if (release_level in ("alfa", "beta", "candidate", "final") and
                    (release_level != "final" or serial == "0") and
                    major.isdigit() and  # --- --- --- --- --- --- --- --- ---
                    minor.isdigit() and  # Explicit isdigit() checks to detect
                    micro.isdigit() and  # leading/trailing whitespace.
                    serial.isdigit()):   # --- --- --- --- --- --- --- --- ---
                self.sys_version_info = (int(major), int(minor), int(micro),
                    release_level, int(serial))
                self.__construct_python_version()
                return
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            pass
        raise BadEnvironment("Unsupported Python version (%s)" % (string,))
1228952
def parse_packet(self, data):
        
        packet = Packet(data=data)
        packet.header = data[0:const.IKE_HEADER.size]
        (packet.iSPI, packet.rSPI, next_payload, packet.version, exchange_type, packet.flags,
         packet.message_id, packet.length) = const.IKE_HEADER.unpack(packet.header)
        packet.exchange_type = const.ExchangeType(exchange_type)
        if self.iSPI != packet.iSPI:
            raise IkeError("Initiator SPI mismatch, packet to an unknown IKE SA")
        elif not self.rSPI:
            logger.debug("Setting responder SPI: {0:x}".format(packet.rSPI))
            self.rSPI = packet.rSPI
        elif self.rSPI != packet.rSPI:
            raise IkeError("Responder SPI mismatch, packet to an unknown IKE SA")
        if packet.message_id - int(self.state) != 1:
            logger.debug("message ID {} at state {!r}".format(packet.message_id, self.state))
        logger.debug("next payload: {!r}".format(next_payload))
        if next_payload == 46:
            self.verify_hmac(data)
            next_payload, data = self.decrypt(data[const.IKE_HEADER.size:])
        else:
            data = data[const.IKE_HEADER.size:]
        while next_payload:
            logger.debug('Next payload: {0!r}'.format(next_payload))
            logger.debug('{0} bytes remaining'.format(len(data)))
            try:
                payload = payloads.get_by_type(next_payload)(data=data)
            except KeyError as e:
                logger.error("Unidentified payload {}".format(e))
                payload = payloads._IkePayload(data=data)
            packet.payloads.append(payload)
            logger.debug('Payloads: {0!r}'.format(packet.payloads))
            next_payload = payload.next_payload
            data = data[payload.length:]
        logger.debug("Packed parsed successfully")
        self.packets.append(packet)
        return packet
598278
def get_release_info(self, name, version):  # type: (str, str) -> dict
        
        if self._disable_cache:
            return self._get_release_info(name, version)

        cached = self._cache.remember_forever(
            "{}:{}".format(name, version), lambda: self._get_release_info(name, version)
        )

        cache_version = cached.get("_cache_version", "0.0.0")
        if parse_constraint(cache_version) != self.CACHE_VERSION:
            # The cache must be updated
            self._log(
                "The cache for {} {} is outdated. Refreshing.".format(name, version),
                level="debug",
            )
            cached = self._get_release_info(name, version)

            self._cache.forever("{}:{}".format(name, version), cached)

        return cached
1088584
def _parseKeyName(self, name):
        
        if name.endswith(Store.theInfoExtension):
            return {'type': 'info'}

        match = self.keyPattern.match(name)
        if not match:
            return None

        match = match.groupdict()
        match.update(type='diff')

        return match