1# Copyright 2013 The Chromium Authors. All rights reserved. 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4 5import distutils.spawn 6import logging 7import os 8import re 9import stat 10import subprocess 11import sys 12 13from telemetry.internal.platform import desktop_platform_backend 14from telemetry.internal.util import ps_util 15 16 17def _BinaryExistsInSudoersFiles(path, sudoers_file_contents): 18 """Returns True if the binary in |path| features in the sudoers file. 19 """ 20 for line in sudoers_file_contents.splitlines(): 21 if re.match(r'\s*\(.+\) NOPASSWD: %s(\s\S+)*$' % re.escape(path), line): 22 return True 23 return False 24 25 26def _CanRunElevatedWithSudo(path): 27 """Returns True if the binary at |path| appears in the sudoers file. 28 If this function returns true then the binary at |path| can be run via sudo 29 without prompting for a password. 30 """ 31 sudoers = subprocess.check_output(['/usr/bin/sudo', '-l']) 32 return _BinaryExistsInSudoersFiles(path, sudoers) 33 34 35class PosixPlatformBackend(desktop_platform_backend.DesktopPlatformBackend): 36 37 # This is an abstract class. It is OK to have abstract methods. 38 # pylint: disable=abstract-method 39 40 def HasRootAccess(self): 41 return os.getuid() == 0 42 43 def RunCommand(self, args): 44 return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0] 45 46 def GetFileContents(self, path): 47 with open(path, 'r') as f: 48 return f.read() 49 50 def GetPsOutput(self, columns, pid=None): 51 """Returns output of the 'ps' command as a list of lines. 52 Subclass should override this function. 53 54 Args: 55 columns: A list of require columns, e.g., ['pid', 'pss']. 56 pid: If not None, returns only the information of the process 57 with the pid. 58 """ 59 return ps_util.GetPsOutputWithPlatformBackend(self, columns, pid) 60 61 def _GetTopOutput(self, pid, columns): 62 """Returns output of the 'top' command as a list of lines. 63 64 Args: 65 pid: pid of process to examine. 66 columns: A list of require columns, e.g., ['idlew', 'vsize']. 67 """ 68 args = ['top'] 69 args.extend(['-pid', str(pid), '-l', '1', '-s', '0', '-stats', 70 ','.join(columns)]) 71 return self.RunCommand(args).splitlines() 72 73 def GetChildPids(self, pid): 74 """Returns a list of child pids of |pid|.""" 75 ps_output = self.GetPsOutput(['pid', 'ppid', 'state']) 76 ps_line_re = re.compile( 77 r'\s*(?P<pid>\d+)\s*(?P<ppid>\d+)\s*(?P<state>\S*)\s*') 78 processes = [] 79 for pid_ppid_state in ps_output: 80 m = ps_line_re.match(pid_ppid_state) 81 assert m, 'Did not understand ps output: %s' % pid_ppid_state 82 processes.append((m.group('pid'), m.group('ppid'), m.group('state'))) 83 return ps_util.GetChildPids(processes, pid) 84 85 def GetCommandLine(self, pid): 86 command = self.GetPsOutput(['command'], pid) 87 return command[0] if command else None 88 89 def CanLaunchApplication(self, application): 90 return bool(distutils.spawn.find_executable(application)) 91 92 def IsApplicationRunning(self, application): 93 ps_output = self.GetPsOutput(['command']) 94 application_re = re.compile( 95 r'(.*%s|^)%s(\s|$)' % (os.path.sep, application)) 96 return any(application_re.match(cmd) for cmd in ps_output) 97 98 def LaunchApplication( 99 self, application, parameters=None, elevate_privilege=False): 100 assert application, 'Must specify application to launch' 101 102 if os.path.sep not in application: 103 application = distutils.spawn.find_executable(application) 104 assert application, 'Failed to find application in path' 105 106 args = [application] 107 108 if parameters: 109 assert isinstance(parameters, list), 'parameters must be a list' 110 args += parameters 111 112 def IsElevated(): 113 """ Returns True if the current process is elevated via sudo i.e. running 114 sudo will not prompt for a password. Returns False if not authenticated 115 via sudo or if telemetry is run on a non-interactive TTY.""" 116 # `sudo -v` will always fail if run from a non-interactive TTY. 117 p = subprocess.Popen( 118 ['/usr/bin/sudo', '-nv'], stdin=subprocess.PIPE, 119 stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 120 stdout = p.communicate()[0] 121 # Some versions of sudo set the returncode based on whether sudo requires 122 # a password currently. Other versions return output when password is 123 # required and no output when the user is already authenticated. 124 return not p.returncode and not stdout 125 126 def IsSetUID(path): 127 """Returns True if the binary at |path| has the setuid bit set.""" 128 return (os.stat(path).st_mode & stat.S_ISUID) == stat.S_ISUID 129 130 if elevate_privilege and not IsSetUID(application): 131 args = ['/usr/bin/sudo'] + args 132 if not _CanRunElevatedWithSudo(application) and not IsElevated(): 133 if not sys.stdout.isatty(): 134 # Without an interactive terminal (or a configured 'askpass', but 135 # that is rarely relevant), there's no way to prompt the user for 136 # sudo. Fail with a helpful error message. For more information, see: 137 # https://code.google.com/p/chromium/issues/detail?id=426720 138 text = ('Telemetry needs to run %s with elevated privileges, but the ' 139 'setuid bit is not set and there is no interactive terminal ' 140 'for a prompt. Please ask an administrator to set the setuid ' 141 'bit on this executable and ensure that it is owned by a user ' 142 'with the necessary privileges. Aborting.' % application) 143 print text 144 raise Exception(text) 145 # Else, there is a tty that can be used for a useful interactive prompt. 146 print ('Telemetry needs to run %s under sudo. Please authenticate.' % 147 application) 148 # Synchronously authenticate. 149 subprocess.check_call(['/usr/bin/sudo', '-v']) 150 151 stderror_destination = subprocess.PIPE 152 if logging.getLogger().isEnabledFor(logging.DEBUG): 153 stderror_destination = None 154 155 return subprocess.Popen( 156 args, stdout=subprocess.PIPE, stderr=stderror_destination) 157