コード例 #1
0
def GenerateCSRFToken(user_id, time):
    """Generates a CSRF token based on a secret key, id and time."""
    precondition.AssertType(user_id, Text)
    precondition.AssertOptionalType(time, int)

    time = time or rdfvalue.RDFDatetime.Now().AsMicrosecondsSinceEpoch()

    secret = config.CONFIG.Get("AdminUI.csrf_secret_key", None)
    if secret is None:
        raise ValueError("CSRF secret not available.")
    digester = hmac.new(secret.encode("ascii"), digestmod=hashlib.sha256)
    digester.update(user_id.encode("ascii"))
    digester.update(CSRF_DELIMITER)
    digester.update(str(time).encode("ascii"))
    digest = digester.digest()

    token = base64.urlsafe_b64encode(b"%s%s%d" %
                                     (digest, CSRF_DELIMITER, time))
    return token.rstrip(b"=")
コード例 #2
0
ファイル: ip_resolver.py プロジェクト: lordlee0702/grr
  def RetrieveIPInfo(self, ip):
    precondition.AssertOptionalType(
        ip, (ipaddress.IPv4Address, ipaddress.IPv6Address))

    if ip is None:
      return (IPInfo.UNKNOWN, "No ip information.")

    ip_str = utils.SmartStr(ip)
    try:
      return self.cache.Get(ip_str)
    except KeyError:
      pass

    if ip.version == 6:
      res = self.RetrieveIP6Info(ip)
    else:
      res = self.RetrieveIP4Info(ip)

    self.cache.Put(ip_str, res)
    return res
コード例 #3
0
    def AsIPAddr(self) -> Optional[IPAddress]:
        """Returns the IP as an `IPAddress` object (if packed bytes are defined)."""
        precondition.AssertOptionalType(self.packed_bytes, bytes)

        if self.packed_bytes is None:
            return None

        try:
            if self.address_type == NetworkAddress.Family.INET:
                return ipaddress.IPv4Address(self.packed_bytes)
            if self.address_type == NetworkAddress.Family.INET6:
                return ipaddress.IPv6Address(self.packed_bytes)
        except ipaddress.AddressValueError:
            hex_packed_bytes = text.Hexify(self.packed_bytes)
            logging.error("AddressValueError for %s (%s)", hex_packed_bytes,
                          self.address_type)
            raise

        message = "IP address has invalid type: {}".format(self.address_type)
        raise ValueError(message)
コード例 #4
0
ファイル: wsgiapp.py プロジェクト: thetraker/grr
def GenerateCSRFToken(user_id, time):
    """Generates a CSRF token based on a secret key, id and time."""
    precondition.AssertType(user_id, unicode)
    precondition.AssertOptionalType(time, int)

    time = time or rdfvalue.RDFDatetime.Now().AsMicrosecondsSinceEpoch()

    secret = config.CONFIG.Get("AdminUI.csrf_secret_key", None)
    # TODO(amoser): Django is deprecated. Remove this at some point.
    if not secret:
        secret = config.CONFIG["AdminUI.django_secret_key"]
    digester = hmac.new(secret.encode("ascii"), digestmod=hashlib.sha256)
    digester.update(user_id.encode("ascii"))
    digester.update(CSRF_DELIMITER)
    digester.update(unicode(time).encode("ascii"))
    digest = digester.digest()

    token = base64.urlsafe_b64encode(b"%s%s%d" %
                                     (digest, CSRF_DELIMITER, time))
    return token.rstrip(b"=")
コード例 #5
0
def TempFilePath(
        suffix: Text = "",
        prefix: Text = "tmp",
        dir: Text = None) -> Text:  # pylint: disable=redefined-builtin
    """Creates a temporary file based on the environment configuration.

  If no directory is specified the file will be placed in folder as specified by
  the `TEST_TMPDIR` environment variable if available or fallback to
  `FLAGS.test_tmpdir` if provided or just use Python's default.

  If directory is specified it must be part of the default test temporary
  directory.

  Args:
    suffix: A suffix to end the file name with.
    prefix: A prefix to begin the file name with.
    dir: A directory to place the file in.

  Returns:
    An absolute path to the created file.

  Raises:
    ValueError: If the specified directory is not part of the default test
        temporary directory.
  """
    precondition.AssertType(suffix, Text)
    precondition.AssertType(prefix, Text)
    precondition.AssertOptionalType(dir, Text)

    root = _TestTempRootPath()
    if not dir:
        dir = root
    elif root and not os.path.commonprefix([dir, root]):
        raise ValueError("path '%s' must start with '%s'" % (dir, root))

    # `mkstemp` returns an open descriptor for the file. We don't care about it as
    # we are only concerned with the path, but we need to close it first or else
    # the file will remain open until the garbage collectors steps in.
    desc, path = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)
    os.close(desc)
    return path
コード例 #6
0
ファイル: sleuthkit.py プロジェクト: mmaj5524/grr
    def MakeStatResponse(self, tsk_file, tsk_attribute=None, append_name=None):
        """Given a TSK info object make a StatEntry.

    Note that tsk uses two things to uniquely identify a data stream - the inode
    object given in tsk_file and the attribute object which may correspond to an
    ADS of this file for filesystems which support ADS. We store both of these
    in the stat response.

    Args:
      tsk_file: A TSK File object for the specified inode.
      tsk_attribute: A TSK Attribute object for the ADS. If None we use the main
        stream.
      append_name: If specified we append this name to the last element of the
        pathspec.

    Returns:
      A StatEntry which can be used to re-open this exact VFS node.
    """
        precondition.AssertOptionalType(append_name, Text)

        info = tsk_file.info
        response = rdf_client_fs.StatEntry()
        meta = info.meta
        if meta:
            response.st_ino = meta.addr
            for attribute in [
                    "mode",
                    "nlink",
                    "uid",
                    "gid",
                    "size",
                    "atime",
                    "mtime",
                    "ctime",
            ]:
                try:
                    value = int(getattr(meta, attribute))
                    if value < 0:
                        value &= 0xFFFFFFFF

                    setattr(response, "st_%s" % attribute, value)
                except AttributeError:
                    pass

            if hasattr(meta, "crtime"):
                value = meta.crtime
                if value < 0:
                    value &= 0xFFFFFFFF
                response.st_btime = value

        name = info.name
        child_pathspec = self.pathspec.Copy()

        if append_name is not None:
            # Append the name to the most inner pathspec
            child_pathspec.last.path = utils.JoinPath(child_pathspec.last.path,
                                                      append_name)

        child_pathspec.last.inode = meta.addr
        if tsk_attribute is not None:
            child_pathspec.last.ntfs_type = int(tsk_attribute.info.type)
            child_pathspec.last.ntfs_id = int(tsk_attribute.info.id)
            child_pathspec.last.stream_name = tsk_attribute.info.name

            # Update the size with the attribute size.
            response.st_size = tsk_attribute.info.size

            default = rdf_paths.PathSpec.tsk_fs_attr_type.TSK_FS_ATTR_TYPE_DEFAULT
            last = child_pathspec.last
            if last.ntfs_type != default or last.ntfs_id:
                # This is an ads and should be treated as a file.
                # Clear all file type bits.
                response.st_mode &= ~self.stat_type_mask
                response.st_mode |= stat.S_IFREG

        else:
            child_pathspec.last.ntfs_type = None
            child_pathspec.last.ntfs_id = None
            child_pathspec.last.stream_name = None

        if name:
            # Encode the type onto the st_mode response
            response.st_mode |= self.FILE_TYPE_LOOKUP.get(int(name.type), 0)

        if meta:
            # What if the types are different? What to do here?
            response.st_mode |= self.META_TYPE_LOOKUP.get(int(meta.type), 0)

        # Write the pathspec on the response.
        response.pathspec = child_pathspec
        return response
コード例 #7
0
ファイル: precondition_test.py プロジェクト: ehossam/grr
 def testBytesIncorrect(self):
     with self.assertRaises(TypeError):
         precondition.AssertOptionalType("quux", bytes)
コード例 #8
0
ファイル: precondition_test.py プロジェクト: ehossam/grr
 def testBytesCorrect(self):
     del self  # Unused.
     precondition.AssertOptionalType(b"quux", bytes)
     precondition.AssertOptionalType(None, bytes)
コード例 #9
0
ファイル: precondition_test.py プロジェクト: ehossam/grr
 def testStringIncorrect(self):
     with self.assertRaises(TypeError):
         precondition.AssertOptionalType(b"foo", str)
コード例 #10
0
ファイル: precondition_test.py プロジェクト: ehossam/grr
 def testStringCorrect(self):
     del self  # Unused.
     precondition.AssertOptionalType("foo", str)
     precondition.AssertOptionalType(None, str)
コード例 #11
0
ファイル: precondition_test.py プロジェクト: ehossam/grr
 def testIntIncorrect(self):
     with self.assertRaises(TypeError):
         precondition.AssertOptionalType(13.37, int)
コード例 #12
0
ファイル: precondition_test.py プロジェクト: ehossam/grr
 def testIntCorrect(self):
     del self  # Unused.
     precondition.AssertOptionalType(1337, int)
     precondition.AssertOptionalType(None, int)