Example #1
0
  def Parse(self, stat, _):
    """Parse the key currentcontrolset output."""
    value = stat.registry_data.GetValue()
    if not value:
      raise parsers.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 parsers.ParseError(
          "Bad drive letter for key %s" % stat.pathspec.path)
  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 parsers.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 parsers.ParseError(
          "Bad drive letter for key %s" % stat.pathspec.path)
Example #3
0
  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 parsers.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))
        # Installed, Name, Version, Architecture, Description
        status, name, version, arch, desc = cols
        # 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)
Example #4
0
 def Parse(self, stat, _):
     value = stat.registry_data.GetValue()
     if value:
         yield rdfvalue.RDFString(value)
     else:
         raise parsers.ParseError("Invalid value for key %s" %
                                  stat.pathspec.path)
Example #5
0
  def Parse(self, stat, _):
    """Parse the key currentcontrolset output."""
    # SystemDriveEnvironmentVariable produces a statentry,
    # WindowsEnvironmentVariableSystemDrive produces a string
    if isinstance(stat, rdf_client.StatEntry):
      value = stat.registry_data.GetValue()
    elif isinstance(stat, rdfvalue.RDFString):
      value = stat
    if not value:
      raise parsers.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 parsers.ParseError("Bad drive letter for key %s" %
                               stat.pathspec.path)
 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 parsers.ParseError(
             "Invalid value for CurrentControlSet key %s" % value)
     yield rdfvalue.RDFString("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet%03d" %
                              int(value))
Example #7
0
 def Parse(self, stat, knowledge_base):
   """Expand any variables in the value."""
   value = stat.registry_data.GetValue()
   if not value:
     raise parsers.ParseError("Invalid value for key %s" % stat.pathspec.path)
   value = artifact_utils.ExpandWindowsEnvironmentVariables(value,
                                                            knowledge_base)
   if value:
     yield rdfvalue.RDFString(value)
 def Parse(self, stat, knowledge_base):
     """Convert the timezone to Olson format."""
     _ = knowledge_base
     value = stat.registry_data.GetValue()
     result = ZONE_LIST.get(value.strip())
     if not result:
         raise parsers.ParseError(
             "Unknown value for TimeZoneKeyName key %s" % value)
     yield rdfvalue.RDFString(result)
Example #9
0
 def Parse(self, stat, knowledge_base):
     """Parse the key currentcontrolset output."""
     value = stat.registry_data.GetValue()
     if not value:
         raise parsers.ParseError("Invalid value for key %s" %
                                  stat.pathspec.path)
     value = artifact_lib.ExpandWindowsEnvironmentVariables(
         value, knowledge_base)
     if value:
         yield rdfvalue.RDFString(value)
Example #10
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 parsers.ParseError(
          "Invalid passwd file at line %d. %s" % ((index + 1), line))
Example #11
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(100000).splitlines()]
    try:
      for index, line in enumerate(lines):
        if line:
          line_parser(line)
    except (IndexError, KeyError) as e:
      raise parsers.ParseError("Invalid file at line %d: %s" % (index + 1, e))
Example #12
0
  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)

    serial_number = []
    hardware_list = []
    plist = binplist.readPlist(cStringIO.StringIO(stdout))

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

    hardware_list = plist[0]["_items"][0]
    serial_number = hardware_list["serial_number"]

    yield rdfvalue.HardwareInfo(serial_number=serial_number)
Example #13
0
  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 parsers.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)
Example #14
0
    def ParseLines(cls, lines):
        users = set()
        filter_regexes = [
            re.compile(x)
            for x in config_lib.CONFIG["Artifacts.netgroup_filter_regexes"]
        ]
        username_regex = re.compile(cls.USERNAME_REGEX)
        blacklist = config_lib.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 anomaly.Anomaly(
                                    type="PARSER_ANOMALY",
                                    symptom="Invalid username: %s" % user)
                            else:
                                users.add(user)
                                yield client.KnowledgeBaseUser(
                                    username=utils.SmartUnicode(user))
                    except ValueError:
                        raise parsers.ParseError(
                            "Invalid netgroup file at line %d: %s" %
                            (index + 1, line))