Esempio n. 1
0
def EnsureTempDirIsSane(directory):
  """Checks that the directory exists and has the correct permissions set."""

  if not os.path.isabs(directory):
    raise ErrorBadPath("Directory %s is not absolute" % directory)

  if os.path.isdir(directory):
    # The temp dir already exists, we probably created it already but
    # let's check to make sure.
    if not client_utils.VerifyFileOwner(directory):
      # Just delete it, it's only temp dirs and we don't own it. If
      # this goes wrong we just raise.
      shutil.rmtree(directory)

  if not os.path.isdir(directory):
    os.makedirs(directory)

    # Make directory 700 before we write the file
    if sys.platform == "win32":
      from grr_response_client import client_utils_windows  # pylint: disable=g-import-not-at-top
      client_utils_windows.WinChmod(directory,
                                    ["FILE_GENERIC_READ", "FILE_GENERIC_WRITE"])
    else:
      os.chmod(directory, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR)
Esempio n. 2
0
def CreateGRRTempFile(filename=None, lifetime=0, mode="w+b", suffix=""):
  """Open file with GRR prefix in directory to allow easy deletion.

  Missing parent dirs will be created. If an existing directory is specified
  its permissions won't be modified to avoid breaking system functionality.
  Permissions on the destination file will be set to root/SYSTEM rw.

  On windows the file is created, then permissions are set.  So there is
  potentially a race condition where the file is readable by other users.  If
  the caller doesn't specify a directory on windows we use the directory we are
  executing from as a safe default.

  If lifetime is specified a housekeeping thread is created to delete the file
  after lifetime seconds.  Files won't be deleted by default.

  Args:
    filename: The name of the file to use. Note that setting both filename and
       directory name is not allowed.

    lifetime: time in seconds before we should delete this tempfile.

    mode: The mode to open the file.

    suffix: optional suffix to use for the temp file

  Returns:
    Python file object

  Raises:
    OSError: on permission denied
    ErrorBadPath: if path is not absolute
    ValueError: if Client.tempfile_prefix is undefined in the config.
  """
  directory = GetDefaultGRRTempDirectory()

  EnsureTempDirIsSane(directory)

  prefix = config.CONFIG.Get("Client.tempfile_prefix")
  if filename is None:
    outfile = tempfile.NamedTemporaryFile(
        prefix=prefix, suffix=suffix, dir=directory, delete=False)
  else:
    if filename.startswith("/") or filename.startswith("\\"):
      raise ValueError("Filename must be relative")

    if suffix:
      filename = "%s.%s" % (filename, suffix)

    outfile = open(os.path.join(directory, filename), mode)

  if lifetime > 0:
    cleanup = threading.Timer(lifetime, DeleteGRRTempFile, (outfile.name,))
    cleanup.start()

  # Fix perms on the file, since this code is used for writing executable blobs
  # we apply RWX.
  if sys.platform == "win32":
    from grr_response_client import client_utils_windows  # pylint: disable=g-import-not-at-top
    client_utils_windows.WinChmod(outfile.name, ["FILE_ALL_ACCESS"])
  else:
    os.chmod(outfile.name, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR)

  return outfile