summaryrefslogtreecommitdiffstats
path: root/chrome/test/pyautolib/chromeos/suid_actions.py
blob: d7dfe5f1b3ffeaec7ef917a5eb2bf4c6d85cd43e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Helper script to perform actions as a super-user on ChromeOS.

Needs to be run with superuser privileges, typically using the
suid_python binary.

Usage:
  sudo python suid_actions.py --action=CleanFlimflamDirs
"""

import logging
import optparse
import os
import shutil
import sys

sys.path.append('/usr/local')  # to import autotest libs.
from autotest.cros import cryptohome

# TODO(bartfab): Remove when crosbug.com/20709 is fixed.
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))
from pyauto import AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE


class SuidAction(object):
  """Helper to perform some super-user actions on ChromeOS."""

  def _ParseArgs(self):
    parser = optparse.OptionParser()
    parser.add_option(
        '-a', '--action', help='Action to perform.')
    self._options = parser.parse_args()[0]
    if not self._options.action:
      raise RuntimeError('No action specified.')

  def Run(self):
    self._ParseArgs()
    assert os.geteuid() == 0, 'Needs superuser privileges.'
    handler = getattr(self, self._options.action)
    assert handler and callable(handler), \
        'No handler for %s' % self._options.action
    handler()
    return 0

  ## Actions ##
  def CleanFlimflamDirs(self):
    """Clean the contents of all flimflam profiles.

    TODO(stanleyw): crosbug.com/29421 This method restarts flimflam. It should
    wait until flimflam is fully initialized and accessible via DBus. Otherwise,
    there is a race conditions and subsequent accesses to flimflam may fail.
    """
    flimflam_dirs = ['/home/chronos/user/flimflam',
                     '/var/cache/flimflam']
    os.system('stop flimflam')
    try:
      for flimflam_dir in flimflam_dirs:
        if not os.path.exists(flimflam_dir):
          continue
        for item in os.listdir(flimflam_dir):
          path = os.path.join(flimflam_dir, item)
          if os.path.isdir(path):
            shutil.rmtree(path)
          else:
            os.remove(path)
    finally:
      os.system('start flimflam')

  def RemoveAllCryptohomeVaults(self):
    """Remove any existing cryptohome vaults."""
    cryptohome.remove_all_vaults()

  def TryToDisableLocalStateAutoClearing(self):
    """Try to disable clearing of the local state on session manager startup.

    This will fail if rootfs verification is on.
    TODO(bartfab): Remove this method when crosbug.com/20709 is fixed.
    """
    os.system('mount -o remount,rw /')
    os.remove(AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE)
    os.system('mount -o remount,ro /')
    if os.path.exists(AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE):
      logging.debug('Failed to remove %s. Session manager will clear local '
                    'state on startup.' % AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE)
    else:
      logging.debug('Removed %s. Session manager will not clear local state on '
                    'startup.' % AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE)

  def TryToEnableLocalStateAutoClearing(self):
    """Try to enable clearing of the local state on session manager startup.

    This will fail if rootfs verification is on.
    TODO(bartfab): Remove this method when crosbug.com/20709 is fixed.
    """
    os.system('mount -o remount,rw /')
    open(AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE, 'w').close()
    os.system('mount -o remount,ro /')
    if os.path.exists(AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE):
      logging.debug('Created %s. Session manager will clear local state on '
                    'startup.' % AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE)
    else:
      logging.debug('Failed to create %s. Session manager will not clear local '
                    'state on startup.' % AUTO_CLEAR_LOCAL_STATE_MAGIC_FILE)


if __name__ == '__main__':
  sys.exit(SuidAction().Run())