Parse the output from Invoke-Mimikatz to return credential sets.

        This was directly stolen from the Empire project as well.
198430
def parse_mimikatz(self, data):
        

        # cred format:
        #   credType, domain, username, password, hostname, sid
        creds = []

        # regexes for "sekurlsa::logonpasswords" Mimikatz output
        regexes = ["(?s)(?<=msv :).*?(?=tspkg :)", "(?s)(?<=tspkg :).*?(?=wdigest :)", "(?s)(?<=wdigest :).*?(?=kerberos :)", "(?s)(?<=kerberos :).*?(?=ssp :)", "(?s)(?<=ssp :).*?(?=credman :)", "(?s)(?<=credman :).*?(?=Authentication Id :)", "(?s)(?<=credman :).*?(?=mimikatz)"]

        hostDomain = ""
        domainSid = ""
        hostName = ""

        lines = data.split("\n")
        for line in lines[0:2]:
            if line.startswith("Hostname:"):
                try:
                    domain = line.split(":")[1].strip()
                    temp = domain.split("/")[0].strip()
                    domainSid = domain.split("/")[1].strip()

                    hostName = temp.split(".")[0]
                    hostDomain = ".".join(temp.split(".")[1:])
                except:
                    pass

        for regex in regexes:

            p = re.compile(regex)

            for match in p.findall(data):

                lines2 = match.split("\n")
                username, domain, password = "", "", ""

                for line in lines2:
                    try:
                        if "Username" in line:
                            username = line.split(":",1)[1].strip()
                        elif "Domain" in line:
                            domain = line.split(":",1)[1].strip()
                        elif "NTLM" in line or "Password" in line:
                            password = line.split(":",1)[1].strip()
                    except:
                        pass

                if username != "" and password != "" and password != "(null)":

                    sid = ""

                    # substitute the FQDN in if it matches
                    if hostDomain.startswith(domain.lower()):
                        domain = hostDomain
                        sid = domainSid

                    if validate_ntlm(password):
                        credType = "hash"

                    else:
                        credType = "plaintext"

                    # ignore machine account plaintexts
                    if not (credType == "plaintext" and username.endswith("$")):
                        creds.append((credType, domain, username, password, hostName, sid))

        if len(creds) == 0:
            # check if we have lsadump output to check for krbtgt
            #   happens on domain controller hashdumps
            for x in xrange(8,13):
                if lines[x].startswith("Domain :"):

                    domain, sid, krbtgtHash = "", "", ""

                    try:
                        domainParts = lines[x].split(":")[1]
                        domain = domainParts.split("/")[0].strip()
                        sid = domainParts.split("/")[1].strip()

                        # substitute the FQDN in if it matches
                        if hostDomain.startswith(domain.lower()):
                            domain = hostDomain
                            sid = domainSid

                        for x in xrange(0, len(lines)):
                            if lines[x].startswith("User : krbtgt"):
                                krbtgtHash = lines[x+2].split(":")[1].strip()
                                break

                        if krbtgtHash != "":
                            creds.append(("hash", domain, "krbtgt", krbtgtHash, hostName, sid))
                    except Exception as e:
                        pass

        if len(creds) == 0:
            # check if we get lsadump::dcsync output
            if '** SAM ACCOUNT **' in lines:
                domain, user, userHash, dcName, sid = "", "", "", "", ""
                for line in lines:
                    try:
                        if line.strip().endswith("will be the domain"):
                            domain = line.split("'")[1]
                        elif line.strip().endswith("will be the DC server"):
                            dcName = line.split("'")[1].split(".")[0]
                        elif line.strip().startswith("SAM Username"):
                            user = line.split(":")[1].strip()
                        elif line.strip().startswith("Object Security ID"):
                            parts = line.split(":")[1].strip().split("-")
                            sid = "-".join(parts[0:-1])
                        elif line.strip().startswith("Hash NTLM:"):
                            userHash = line.split(":")[1].strip()
                    except:
                        pass

                if domain != "" and userHash != "":
                    creds.append(("hash", domain, user, userHash, dcName, sid))

        return self.uniquify_tuples(creds)
1131434
function parse() {
  var msie = /MSIE.(\d+)/i.exec(ua);
  var rv = /Trident.+rv:(\d+)/i.exec(ua);
  var version = msie || rv || undefined;
  return version ? +version[1] : version;
}
868770
function extractMDNProperties(mdnEntry) {
  if (mdnEntry.status === 'standard') {
    return {
      syntax: mdnEntry.syntax
    }
  }

  return {
    status: abbreviateStatus(mdnEntry.status),
    syntax: mdnEntry.syntax
  }
}
941887
def from_credentials(credentials, loop: asyncio.AbstractEventLoop=asyncio.get_event_loop()):
        
        return API(username=credentials.username, password=credentials.password,
                   database=credentials.database, session_id=credentials.session_id,
                   server=credentials.server, loop=loop)
658307
private String authenticate(Credentials credentials) throws AuthenticationException {
        if (!(credentials instanceof EsApiKeyCredentials)) {
            throw new AuthenticationException("Incorrect credentials type provided. Expected [" + EsApiKeyCredentials.class.getName()
                    + "] but got [" + credentials.getClass().getName() + "]");
        }

        EsApiKeyCredentials esApiKeyCredentials = ((EsApiKeyCredentials) credentials);
        String authString = null;

        if (esApiKeyCredentials.getToken() != null && StringUtils.hasText(esApiKeyCredentials.getToken().getName())) {
            EsToken token = esApiKeyCredentials.getToken();
            String keyComponents = token.getId() + ":" + token.getApiKey();
            byte[] base64Encoded = Base64.encodeBase64(keyComponents.getBytes(StringUtils.UTF_8));
            String tokenText = new String(base64Encoded, StringUtils.UTF_8);
            authString = EsHadoopAuthPolicies.APIKEY + " " + tokenText;
        }

        return authString;
    }
90391
def _parse_openssh_output(lines, fingerprint_hash_type=None):
    '''
    
    '''
    for line in lines:
        # We don't need any whitespace-only containing lines or arbitrary doubled newlines
        line = line.strip()
        if line == '':
            continue
        line += '\n'

        if line.startswith('#'):
            continue
        try:
            hostname, enc, key = line.split()
        except ValueError:  # incorrect format
            continue
        fingerprint = _fingerprint(key,
                                   fingerprint_hash_type=fingerprint_hash_type)
        if not fingerprint:
            continue
        yield {'hostname': hostname, 'key': key, 'enc': enc,
               'fingerprint': fingerprint}
1229542
def _parse_to_recoverable_signature(sig):
    
    # Buffer for getting values of signature object
    assert isinstance(sig, bytes)
    assert len(sig) == 65

    # Make a recoverable signature of 65 bytes
    rec_sig = ffi.new("secp256k1_ecdsa_recoverable_signature *")
    # Retrieving the recid from the last byte of the signed key
    recid = ord(sig[64:65])

    # Parse a revoverable signature
    parsable_sig = lib.secp256k1_ecdsa_recoverable_signature_parse_compact(
        ctx,
        rec_sig,
        sig,
        recid
    )
    # Verify that the signature is parsable
    if not parsable_sig:
        raise InvalidSignatureError()

    return rec_sig
1142010
def from_credentials(credentials):
        
        return API(username=credentials.username, password=credentials.password,
                   database=credentials.database, session_id=credentials.session_id,
                   server=credentials.server)
725848
public static Credential decode(Object encoded, Resource rolesDir) throws PageException {
	String dec;
	try {
	    dec = Base64Coder.decodeToString(Caster.toString(encoded), "UTF-8");
	}
	catch (Exception e) {
	    throw Caster.toPageException(e);
	}

	Array arr = ListUtil.listToArray(dec, "" + ONE);
	int len = arr.size();
	if (len == 3) {
	    String str = Caster.toString(arr.get(3, ""));
	    if (str.startsWith("md5:")) {
		if (!rolesDir.exists()) rolesDir.mkdirs();
		str = str.substring(4);
		Resource md5 = rolesDir.getRealResource(str);
		try {
		    str = IOUtil.toString(md5, "utf-8");
		}
		catch (IOException e) {
		    str = "";
		}
	    }

	    return new CredentialImpl(Caster.toString(arr.get(1, "")), Caster.toString(arr.get(2, "")), str, rolesDir);
	}
	if (len == 2) return new CredentialImpl(Caster.toString(arr.get(1, "")), Caster.toString(arr.get(2, "")), rolesDir);
	if (len == 1) return new CredentialImpl(Caster.toString(arr.get(1, "")), rolesDir);

	return null;
    }
1357404
def retrieve_and_parse_profile(handle):
    
    hcard = retrieve_diaspora_hcard(handle)
    if not hcard:
        return None
    profile = parse_profile_from_hcard(hcard, handle)
    try:
        profile.validate()
    except ValueError as ex:
        logger.warning("retrieve_and_parse_profile - found profile %s but it didn't validate: %s",
                       profile, ex)
        return None
    return profile
1228534
def parse(cls, detail_string):
        """"""
        split = detail_string.split(':')
        if len(split) != 4:
            raise Exception('invalid credentials')  # TODO: other exception

        ltpk = binascii.unhexlify(split[0])
        ltsk = binascii.unhexlify(split[1])
        atv_id = binascii.unhexlify(split[2])
        client_id = binascii.unhexlify(split[3])
        return Credentials(ltpk, ltsk, atv_id, client_id)
1363176
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
            knowledge_base):
    """"""
    _ = stderr, time_taken, args, knowledge_base  # Unused.
    self.CheckReturn(cmd, return_val)
    output = iter(stdout.decode("utf-8").splitlines())

    # Compile all regexes in advance.
    sys_info_re = re.compile(r"\s*System Information")
    sys_regexes = {
        "system_manufacturer": self._re_compile("Manufacturer"),
        "serial_number": self._re_compile("Serial Number"),
        "system_product_name": self._re_compile("Product Name"),
        "system_uuid": self._re_compile("UUID"),
        "system_sku_number": self._re_compile("SKU Number"),
        "system_family": self._re_compile("Family"),
        "system_assettag": self._re_compile("Asset Tag")
    }

    bios_info_re = re.compile(r"\s*BIOS Information")
    bios_regexes = {
        "bios_vendor": self._re_compile("Vendor"),
        "bios_version": self._re_compile("Version"),
        "bios_release_date": self._re_compile("Release Date"),
        "bios_rom_size": self._re_compile("ROM Size"),
        "bios_revision": self._re_compile("BIOS Revision")
    }

    # Initialize RDF.
    dmi_info = rdf_client.HardwareInfo()

    for line in output:
      if sys_info_re.match(line):
        # Collect all System Information until we hit a blank line.
        while line:
          for attr, regex in iteritems(sys_regexes):
            match = regex.match(line)
            if match:
              setattr(dmi_info, attr, match.group(1).strip())
              break
          line = next(output)

      elif bios_info_re.match(line):
        # Collect all BIOS Information until we hit a blank line.
        while line:
          for attr, regex in iteritems(bios_regexes):
            match = regex.match(line)
            if match:
              setattr(dmi_info, attr, match.group(1).strip())
              break
          line = next(output)

    yield dmi_info
32015
def parse_space_delimited_cert(raw_cert)
      cert_contents = raw_cert.split(' ')
      # "-----BEGIN CERTIFICATE------" fix
      cert_contents[0] += " #{cert_contents.delete_at(1)}"
      # "-----END CERTIFICATE------" fix
      cert_contents[-1] = "#{cert_contents[-2]} #{cert_contents.delete_at(-1)}"

      cert_contents.map { |el| "\\t#{el}" } # Hack it to match expected syntax
    end
807386
def parse_imethodresponse(self, tup_tree):
        

        self.check_node(tup_tree, 'IMETHODRESPONSE', ('NAME',))

        return (name(tup_tree), attrs(tup_tree),
                self.list_of_various(tup_tree,
                                     ('ERROR', 'IRETURNVALUE', 'PARAMVALUE')))
1358724
def get_profile_from_tokens(token_records, public_key_or_address,
                            hierarchical_keys=False):
    
    if hierarchical_keys:
        raise NotImplementedError("Hierarchical key support not implemented")

    profile = {}

    for token_record in token_records:
        # print token_record
        try:
            decoded_token = verify_token_record(token_record, public_key_or_address)
        except ValueError:
            # traceback.print_exc()
            continue
        else:
            if "payload" in decoded_token:
                if "claim" in decoded_token["payload"]:
                    claim = decoded_token["payload"]["claim"]
                    profile.update(claim)

    return profile
348628
def read_creds_from_ec2_instance_metadata():
    
    creds = init_creds()
    try:
        has_role = requests.get('http://169.254.169.254/latest/meta-data/iam/security-credentials', timeout = 1)
        if has_role.status_code == 200:
            iam_role = has_role.text
            credentials = requests.get('http://169.254.169.254/latest/meta-data/iam/security-credentials/%s/' %
                                       iam_role.strip()).json()
            for c in ['AccessKeyId', 'SecretAccessKey']:
                creds[c] = credentials[c]
            creds['SessionToken'] = credentials['Token']
        return creds
    except Exception as e:
        return False
794090
def _ParseCredentialOptions(self, options):
    
    credentials = getattr(options, 'credentials', [])
    if not isinstance(credentials, list):
      raise errors.BadConfigOption('Unsupported credentials value.')

    for credential_string in credentials:
      credential_type, _, credential_data = credential_string.partition(':')
      if not credential_type or not credential_data:
        raise errors.BadConfigOption(
            'Badly formatted credential: {0:s}.'.format(credential_string))

      if credential_type not in self._SUPPORTED_CREDENTIAL_TYPES:
        raise errors.BadConfigOption(
            'Unsupported credential type for: {0:s}.'.format(
                credential_string))

      if credential_type in self._BINARY_DATA_CREDENTIAL_TYPES:
        try:
          credential_data = credential_data.decode('hex')
        except TypeError:
          raise errors.BadConfigOption(
              'Unsupported credential data for: {0:s}.'.format(
                  credential_string))

      self._credentials.append((credential_type, credential_data))