コード例 #1
0
  def Parse(self, stat, _):
    """Parses a SystemDrive environment variable."""
    if isinstance(stat, rdf_client.StatEntry):
      value = stat.registry_data.GetValue()
    elif isinstance(stat, rdfvalue.RDFString):
      value = stat
    if not value:
      raise parser.ParseError("Invalid value for key %s" % stat.pathspec.path)

    systemdrive = value[0:2]
    if re.match(r"^[A-Za-z]:$", systemdrive):
      yield rdfvalue.RDFString(systemdrive)
    else:
      raise parser.ParseError(
          "Bad drive letter for key %s" % stat.pathspec.path)
コード例 #2
0
 def Parse(self, stat, knowledge_base):
   """Expand any variables in the value."""
   value = stat.registry_data.GetValue()
   if not value:
     raise parser.ParseError("Invalid value for key %s" % stat.pathspec.path)
   value = artifact_utils.ExpandWindowsEnvironmentVariables(
       value, knowledge_base)
   if value:
     yield rdfvalue.RDFString(value)
コード例 #3
0
  def Parse(self, stat, unused_knowledge_base):
    """Parse the key currentcontrolset output."""
    value = stat.registry_data.GetValue()

    if not str(value).isdigit() or int(value) > 999 or int(value) < 0:
      raise parser.ParseError(
          "Invalid value for CurrentControlSet key %s" % value)
    yield rdfvalue.RDFString(
        "HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet%03d" % int(value))
コード例 #4
0
ファイル: linux_cmd_parser.py プロジェクト: rainser/grr
    def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
              knowledge_base):
        """Parse the dpkg output."""
        _ = stderr, time_taken, args, knowledge_base  # Unused.
        self.CheckReturn(cmd, return_val)
        column_lengths = []
        i = 0
        for i, line in enumerate(stdout.splitlines()):
            if line.startswith("+++-"):
                # This is a special header line that determines column size.
                for col in line.split("-")[1:]:
                    if not re.match("=*", col):
                        raise parser.ParseError(
                            "Invalid header parsing for %s at line "
                            "%s" % (cmd, i))
                    column_lengths.append(len(col))
                break

        if column_lengths:
            remaining_lines = stdout.splitlines()[i + 1:]
            for i, line in enumerate(remaining_lines):
                cols = line.split(None, len(column_lengths))

                # The status column is ignored in column_lengths.
                if len(column_lengths) == 4:
                    # Installed, Name, Version, Architecture, Description
                    status, name, version, arch, desc = cols
                elif len(column_lengths) == 3:
                    # Older versions of dpkg don't print Architecture
                    status, name, version, desc = cols
                    arch = None
                else:
                    raise ValueError(
                        "Bad number of columns in dpkg --list output: %s" %
                        len(column_lengths))

                # Status is potentially 3 columns, but always at least two, desired and
                # actual state. We only care about actual state.
                if status[1] == "i":
                    status = rdf_client.SoftwarePackage.InstallState.INSTALLED
                else:
                    status = rdf_client.SoftwarePackage.InstallState.UNKNOWN
                yield rdf_client.SoftwarePackage(name=name,
                                                 description=desc,
                                                 version=version,
                                                 architecture=arch,
                                                 install_state=status)
コード例 #5
0
    def ParseLine(cls, index, line):
        fields = "username,password,uid,gid,fullname,homedir,shell".split(",")
        try:
            if not line:
                return
            dat = dict(zip(fields, line.split(":")))
            user = rdf_client.User(username=dat["username"],
                                   uid=int(dat["uid"]),
                                   homedir=dat["homedir"],
                                   shell=dat["shell"],
                                   gid=int(dat["gid"]),
                                   full_name=dat["fullname"])
            return user

        except (IndexError, KeyError):
            raise parser.ParseError("Invalid passwd file at line %d. %s" %
                                    ((index + 1), line))
コード例 #6
0
    def _ParseFile(self, file_obj, line_parser):
        """Process a file line by line.

    Args:
      file_obj: The file to parse.
      line_parser: The parser method used to process and store line content.

    Raises:
      parser.ParseError if the parser is unable to process the line.
    """
        lines = [l.strip() for l in file_obj.read().splitlines()]
        try:
            for index, line in enumerate(lines):
                if line:
                    line_parser(line)
        except (IndexError, KeyError) as e:
            raise parser.ParseError("Invalid file at line %d: %s" %
                                    (index + 1, e))
コード例 #7
0
ファイル: osx_file_parser.py プロジェクト: rainser/grr
    def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
              knowledge_base):
        """Parse the system profiler output. We get it in the form of a plist."""
        _ = stderr, time_taken, args, knowledge_base  # Unused
        self.CheckReturn(cmd, return_val)

        plist = binplist.readPlist(cStringIO.StringIO(stdout))

        if len(plist) > 1:
            raise parser.ParseError(
                "SPHardwareDataType plist has too many items.")

        hardware_list = plist[0]["_items"][0]
        serial_number = getattr(hardware_list, "serial_number", None)
        system_product_name = getattr(hardware_list, "machine_model", None)
        bios_version = getattr(hardware_list, "boot_rom_version", None)

        yield rdf_client.HardwareInfo(serial_number=serial_number,
                                      bios_version=bios_version,
                                      system_product_name=system_product_name)
コード例 #8
0
    def ParseLines(cls, lines):
        users = set()
        filter_regexes = [
            re.compile(x)
            for x in config.CONFIG["Artifacts.netgroup_filter_regexes"]
        ]
        username_regex = re.compile(cls.USERNAME_REGEX)
        blacklist = config.CONFIG["Artifacts.netgroup_user_blacklist"]
        for index, line in enumerate(lines):
            if line.startswith("#"):
                continue

            splitline = line.split(" ")
            group_name = splitline[0]

            if filter_regexes:
                filter_match = False
                for regex in filter_regexes:
                    if regex.search(group_name):
                        filter_match = True
                        break
                if not filter_match:
                    continue

            for member in splitline[1:]:
                if member.startswith("("):
                    try:
                        _, user, _ = member.split(",")
                        if user not in users and user not in blacklist:
                            if not username_regex.match(user):
                                yield rdf_anomaly.Anomaly(
                                    type="PARSER_ANOMALY",
                                    symptom="Invalid username: %s" % user)
                            else:
                                users.add(user)
                                yield rdf_client.User(
                                    username=utils.SmartUnicode(user))
                    except ValueError:
                        raise parser.ParseError(
                            "Invalid netgroup file at line %d: %s" %
                            (index + 1, line))
コード例 #9
0
 def Parse(self, stat, _):
   value = stat.registry_data.GetValue()
   if value:
     yield rdfvalue.RDFString(value)
   else:
     raise parser.ParseError("Invalid value for key %s" % stat.pathspec.path)