2 # -*- coding: utf-8 -*-
4 # ------------------------------------------------------------
7 # executes a cygwin command inside the opensecurity project
9 # Autor: Mihai Bartha, <mihai.bartha@ait.ac.at>
10 # Oliver Maurhart, <oliver.maurhart@ait.ac.at>
12 # Copyright (C) 2013 AIT Austrian Institute of Technology
13 # AIT Austrian Institute of Technology GmbH
14 # Donau-City-Strasse 1 | 1220 Vienna | Austria
15 # http://www.ait.ac.at
17 # This program is free software; you can redistribute it and/or
18 # modify it under the terms of the GNU General Public License
19 # as published by the Free Software Foundation version 2.
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 51 Franklin Street, Fifth Floor,
29 # Boston, MA 02110-1301, USA.
30 # ------------------------------------------------------------
33 # ------------------------------------------------------------
40 from subprocess import Popen, PIPE, STARTUPINFO, _subprocess
44 from environment import Environment
45 from opensecurity_util import logger, setupLogger, OpenSecurityException
49 # ------------------------------------------------------------
53 """get the path to our local cygwin installment"""
54 home_drive = os.path.expandvars("%HOMEDRIVE%") + os.sep
55 e = Environment('OpenSecurity')
57 os.path.abspath(os.path.join(e.prefix_path, 'cygwin')),
58 os.path.abspath(os.path.join(e.prefix_path, 'cygwin64')),
59 os.path.abspath(os.path.join(home_drive, 'cygwin')),
60 os.path.abspath(os.path.join(home_drive, 'cygwin64'))
62 path_valid = [ p for p in path_hint if os.path.exists(p) ]
63 theClass.cygwin_root = path_valid[0]
64 theClass.cygwin_bin = os.path.join(theClass.cygwin_root, 'bin') + os.path.sep
65 theClass.cygwin_bash = os.path.join(theClass.cygwin_bin, 'bash.exe')
66 theClass.cygwin_ssh = os.path.join(theClass.cygwin_bin, 'ssh.exe')
67 theClass.cygwin_scp = os.path.join(theClass.cygwin_bin, 'scp.exe')
68 theClass.cygwin_x11 = os.path.join(theClass.cygwin_bin, 'XWin.exe')
69 theClass.win_cmd = os.environ.get("COMSPEC", "cmd.exe")
70 """get the path to the VirtualBox installation on this system"""
71 theClass.vbox_root = theClass.getRegEntry('SOFTWARE\Oracle\VirtualBox', 'InstallDir')[0]
72 theClass.vbox_man = os.path.join(theClass.vbox_root, 'VBoxManage.exe')
73 #theClass.user_home = os.path.expanduser("~")
74 theClass.user_home = os.environ['APPDATA']#os.path.expandvars("%APPDATA%")
90 """Some nifty methods working with Cygwin"""
92 def __call__(self, command, arguments, wait_return=True, window = False):
93 """make an instance of this object act as a function"""
94 return self.execute(command, arguments, wait_return, window)
97 def getRegEntry(key, value):
99 k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key)
100 value = _winreg.QueryValueEx(k, value)
109 return Cygwin.cygwin_root
113 return Cygwin.cygwin_bin
117 return Cygwin.cygwin_bash
121 return Cygwin.cygwin_ssh
125 return Cygwin.cygwin_scp
129 return Cygwin.cygwin_x11
133 return Cygwin.vbox_man
137 return Cygwin.win_cmd
141 return Cygwin.user_home
143 executeLock = threading.Lock()
144 #executes command on host system
146 def execute(program, arguments, wait_return=True, window = False, stdin = PIPE, stdout = PIPE, stderr = PIPE):
147 _startupinfo = STARTUPINFO()
149 _startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
150 _startupinfo.wShowWindow = _subprocess.SW_HIDE
151 #logger.debug('trying to launch: ' + program + ' ' + ''.join(arguments))
153 result, res_stdout, res_stderr = None, None, None
155 # quote the executable otherwise we run into troubles
156 # when the path contains spaces and additonal arguments
157 # are presented as well.
158 # special: invoking bash as login shell here with
159 # an unquoted command does not execute /etc/profile
160 args = '"' + program + '" ' + arguments
161 logger.debug('Launching: ' + program + ' ' + ''.join(arguments))
162 process = Popen(args, startupinfo = _startupinfo, stdin = stdin, stdout = stdout, stderr = stderr, shell = False)
164 return [0, 'working in background', '']
166 res_stdout, res_stderr = process.communicate()
167 result = process.returncode
168 logger.debug('Finished: ' + program + ' ' + ''.join(arguments))
169 #result = process.wait()
170 #res_stdout = process.stdout.read();
171 #res_stderr = process.stderr.read();
173 except Exception as ex:
174 res_stderr = ''.join(str(ex.args))
177 return result, res_stdout, res_stderr
180 def vboxExecute(command, wait_return=True, window = False, bash_opts='', try_count = 3):
183 while retry < try_count:
184 if Cygwin.executeLock.acquire(True):
185 result = Cygwin.execute(Cygwin.vbox_man, command, wait_return, window)
186 Cygwin.executeLock.release()
194 def bashExecute(command, wait_return=True, window = False, bash_opts='', stdin = PIPE, stdout = PIPE, stderr = PIPE):
195 # for some reason, the '-l' is ignored when started via python
196 # so the same behavior is triggered by calling /etc/profile
198 command = bash_opts + ' -l -c "' + command + '"'
199 return Cygwin.execute(Cygwin.cygwin_bash, command, wait_return, window, stdin = stdin, stdout = stdout, stderr = stderr)
202 def cmdExecute(command, wait_return=True, window = False):
203 command = ' /c ' + command
204 return Cygwin.execute(Cygwin.win_cmd, command, wait_return, window)
206 # executes command over ssh on guest vm
208 def sshExecute(command, address, user_name, certificate, wait_return=True, window = False):
209 command = ' -v -o StrictHostKeyChecking=no -i "' + certificate + '" ' + user_name + '@' + address + ' ' + command
210 return Cygwin.execute(Cygwin.cygwin_ssh, command, wait_return, window)
212 # executes command over ssh on guest vm
214 def sshBackgroundExecute(command, address, user_name, certificate, wait_return=True, window = False):
215 command = ' -f -v -o StrictHostKeyChecking=no -i "' + certificate + '" ' + user_name + '@' + address + ' ' + command
216 return Cygwin.execute(Cygwin.cygwin_ssh, command, wait_return, window)
218 #machineFolder + '/' + vm_name + '/dvm_key
219 #address = self.getHostOnlyIP(vm_name)
220 #machineFolder = self.getDefaultMachineFolder()
221 #machineFolder = Cygwin.cygwinPath(machineFolder)
223 # executes command over ssh on guest vm with X forwarding
225 def sshExecuteX11(command, address, user_name, certificate, wait_return=True):
226 return Cygwin.bashExecute('DISPLAY=:0.0 ssh -Y -o StrictHostKeyChecking=no -i \\\"' + certificate +'\\\" ' + user_name + '@' + address + ' ' + command + '')
229 def is_X11_running():
230 """check if we can connect to a X11 running instance"""
231 p = Cygwin.bashExecute('xset -display :0 q', wait_return = True, window = False)
236 """start X11 in the background (if not already running) on DISPLAY=:0
238 If there is already a X11 running then exit silently, calling this
239 method as often as needed.
241 Popen('"' + Cygwin.cygwin_x11 + '" :0 -multiwindow -resize -silent-dup-error')
242 return (0, None, None)
246 cmd = 'cygpath -u \'' + path + '\''
247 return Cygwin.bashExecute(cmd)[1].rstrip('\n')
250 def checkResult(result):
252 logger.error('Command failed:' + ''.join(result[2]))
253 raise OpenSecurityException('Command failed:' + ''.join(result[2]))
262 if __name__ == "__main__":
263 logger = setupLogger('Cygwin')
265 logger.info(c.root())
267 logger.info(c.bash())
270 logger.info(c.home())
273 #tasklist /v /fo list /fi "IMAGENAME eq explorer.exe"
283 #print (Cygwin.is_X11_running())
284 #print (Cygwin.is_X11_running())
285 #new_sdvm = 'SecurityDVM0'
286 #new_ip = Cygwin.vboxExecute('guestproperty get ' + new_sdvm + ' /VirtualBox/GuestInfo/Net/0/V4/IP')[1]
287 #new_ip = new_ip[new_ip.index(':')+1:].strip()
289 #result = Cygwin.bashExecute('DISPLAY=:0.0 xhost '+new_ip)
290 #browser = '/usr/bin/midori '
291 #print(Cygwin.sshExecuteX11(browser, new_ip, 'osecuser', '/cygdrive/c/Users/BarthaM/VirtualBox VMs' + '/' + new_sdvm + '/dvm_key'))
293 #print(Cygwin.bashExecute('echo $PATH')[1])
294 #print(Cygwin.cygPath('C:'))
295 #print('C:\\Program Files\\OpenSecurity: ' + c.cygPath('C:\\Program Files\\OpenSecurity'))