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 2013-2014 X-Net and AIT Austrian Institute of Technology
19 # https://www.x-net.at
21 # AIT Austrian Institute of Technology
22 # Donau City Strasse 1
25 # http://www.ait.ac.at
28 # Licensed under the Apache License, Version 2.0 (the "License");
29 # you may not use this file except in compliance with the License.
30 # You may obtain a copy of the License at
32 # http://www.apache.org/licenses/LICENSE-2.0
34 # Unless required by applicable law or agreed to in writing, software
35 # distributed under the License is distributed on an "AS IS" BASIS,
36 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
37 # See the License for the specific language governing permissions and
38 # limitations under the License.
39 # ------------------------------------------------------------
42 # ------------------------------------------------------------
49 from subprocess import Popen, PIPE, STARTUPINFO, _subprocess
53 from environment import Environment
54 from opensecurity_util import logger, setupLogger, OpenSecurityException
58 # ------------------------------------------------------------
62 """get the path to our local cygwin installment"""
63 home_drive = os.path.expandvars("%HOMEDRIVE%") + os.sep
64 e = Environment('OpenSecurity')
66 os.path.abspath(os.path.join(e.prefix_path, 'cygwin')),
67 os.path.abspath(os.path.join(e.prefix_path, 'cygwin64')),
68 os.path.abspath(os.path.join(home_drive, 'cygwin')),
69 os.path.abspath(os.path.join(home_drive, 'cygwin64'))
71 path_valid = [ p for p in path_hint if os.path.exists(p) ]
72 theClass.cygwin_root = path_valid[0]
73 theClass.cygwin_bin = os.path.join(theClass.cygwin_root, 'bin') + os.path.sep
74 theClass.cygwin_bash = os.path.join(theClass.cygwin_bin, 'bash.exe')
75 theClass.cygwin_ssh = os.path.join(theClass.cygwin_bin, 'ssh.exe')
76 theClass.cygwin_scp = os.path.join(theClass.cygwin_bin, 'scp.exe')
77 theClass.cygwin_x11 = os.path.join(theClass.cygwin_bin, 'XWin.exe')
78 theClass.win_cmd = os.environ.get("COMSPEC", "cmd.exe")
79 """get the path to the VirtualBox installation on this system"""
80 theClass.vbox_root = theClass.getRegEntry('SOFTWARE\Oracle\VirtualBox', 'InstallDir')[0]
81 theClass.vbox_man = os.path.join(theClass.vbox_root, 'VBoxManage.exe')
82 #theClass.user_home = os.path.expanduser("~")
83 theClass.user_home = os.environ['APPDATA']#os.path.expandvars("%APPDATA%")
84 theClass.allow_exec = True
101 """Some nifty methods working with Cygwin"""
103 def __call__(self, command, arguments, wait_return=True, window = False):
104 """make an instance of this object act as a function"""
105 return self.execute(command, arguments, wait_return, window)
108 def getRegEntry(key, value):
110 k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key)
111 value = _winreg.QueryValueEx(k, value)
120 return Cygwin.cygwin_root
124 return Cygwin.cygwin_bin
128 return Cygwin.cygwin_bash
132 return Cygwin.cygwin_ssh
136 return Cygwin.cygwin_scp
140 return Cygwin.cygwin_x11
144 return Cygwin.vbox_man
148 return Cygwin.win_cmd
152 return Cygwin.user_home
156 Cygwin.allow_exec = True
160 Cygwin.allow_exec = False
162 executeLock = threading.Lock()
163 #executes command on host system
165 def execute(program, arguments, wait_return=True, window = False, stdin = PIPE, stdout = PIPE, stderr = PIPE):
166 if not Cygwin.allow_exec:
167 logger.error('Execution cancelled by system (shutting down).')
168 raise OpenSecurityException('Execution cancelled by system (shutting down).')
170 _startupinfo = STARTUPINFO()
172 _startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
173 _startupinfo.wShowWindow = _subprocess.SW_HIDE
174 #logger.debug('trying to launch: ' + program + ' ' + ''.join(arguments))
176 result, res_stdout, res_stderr = None, None, None
178 # quote the executable otherwise we run into troubles
179 # when the path contains spaces and additional arguments
180 # are presented as well.
181 # special: invoking bash as login shell here with
182 # an unquoted command does not execute /etc/profile
183 args = '"' + program + '" ' + arguments
184 logger.debug('Launching: ' + program + ' ' + ''.join(arguments))
185 process = Popen(args, startupinfo = _startupinfo, stdin = stdin, stdout = stdout, stderr = stderr, shell = False)
187 return [0, 'working in background', '']
189 res_stdout, res_stderr = process.communicate()
190 result = process.returncode
191 logger.debug('Finished: ' + program + ' ' + ''.join(arguments))
193 except Exception as ex:
194 res_stderr = ''.join(str(ex.args))
198 logger.error('Command failed:' + ''.join(res_stderr))
199 raise OpenSecurityException('Command failed:' + ''.join(res_stderr))
201 return result, res_stdout, res_stderr
204 def vboxExecute(command, wait_return=True, window = False, bash_opts='', try_count = 3):
207 while retry < try_count:
208 if Cygwin.executeLock.acquire(True):
210 result = Cygwin.execute(Cygwin.vbox_man, command, wait_return, window)
211 except Exception as ex:
212 Cygwin.executeLock.release()
213 if (retry+1) == try_count:
216 Cygwin.executeLock.release()
219 raise OpenSecurityException('Command max retry reached: ' + ''.join(command))
223 def bashExecute(command, wait_return=True, window = False, bash_opts='', stdin = PIPE, stdout = PIPE, stderr = PIPE):
224 # for some reason, the '-l' is ignored when started via python
225 # so the same behavior is triggered by calling /etc/profile
227 command = bash_opts + ' -l -c "' + command + '"'
228 return Cygwin.execute(Cygwin.cygwin_bash, command, wait_return, window, stdin = stdin, stdout = stdout, stderr = stderr)
231 def cmdExecute(command, wait_return=True, window = False):
232 command = ' /c ' + command
233 return Cygwin.execute(Cygwin.win_cmd, command, wait_return, window)
235 # executes command over ssh on guest vm
237 def sshExecute(command, address, user_name, certificate, wait_return=True, window = False):
238 if command == None or address == None or user_name == None or certificate == None:
239 raise OpenSecurityException('Invalid parameter value')
240 command = ' -v -o StrictHostKeyChecking=no -i "' + certificate + '" ' + user_name + '@' + address + ' ' + command
241 return Cygwin.execute(Cygwin.cygwin_ssh, command, wait_return, window)
243 # executes command over ssh on guest vm
245 def sshBackgroundExecute(command, address, user_name, certificate, wait_return=True, window = False):
246 command = ' -f -v -o StrictHostKeyChecking=no -i "' + certificate + '" ' + user_name + '@' + address + ' ' + command
247 return Cygwin.execute(Cygwin.cygwin_ssh, command, wait_return, window)
249 #machineFolder + '/' + vm_name + '/dvm_key
250 #address = self.getHostOnlyIP(vm_name)
251 #machineFolder = self.getDefaultMachineFolder()
252 #machineFolder = Cygwin.cygwinPath(machineFolder)
254 # executes command over ssh on guest vm with X forwarding
256 def sshExecuteX11(command, address, user_name, certificate, wait_return=True):
257 return Cygwin.bashExecute('DISPLAY=:0.0 ssh -Y -o StrictHostKeyChecking=no -i \\\"' + certificate +'\\\" ' + user_name + '@' + address + ' ' + command + '')
260 def is_X11_running():
261 """check if we can connect to a X11 running instance"""
262 p = Cygwin.bashExecute('xset -display :0 q', wait_return = True, window = False)
267 """start X11 in the background (if not already running) on DISPLAY=:0
269 If there is already a X11 running then exit silently, calling this
270 method as often as needed.
272 Popen('"' + Cygwin.cygwin_x11 + '" :0 -multiwindow -resize -silent-dup-error')
273 return (0, None, None)
277 cmd = 'cygpath -u \'' + path + '\''
278 return Cygwin.bashExecute(cmd)[1].rstrip('\n')
286 if __name__ == "__main__":
287 logger = setupLogger('Cygwin')
289 logger.info(c.root())
291 logger.info(c.bash())
294 logger.info(c.home())
297 #tasklist /v /fo list /fi "IMAGENAME eq explorer.exe"
307 #print (Cygwin.is_X11_running())
308 #print (Cygwin.is_X11_running())
309 #new_sdvm = 'SecurityDVM0'
310 #new_ip = Cygwin.vboxExecute('guestproperty get ' + new_sdvm + ' /VirtualBox/GuestInfo/Net/0/V4/IP')[1]
311 #new_ip = new_ip[new_ip.index(':')+1:].strip()
313 #result = Cygwin.bashExecute('DISPLAY=:0.0 xhost '+new_ip)
314 #browser = '/usr/bin/midori '
315 #print(Cygwin.sshExecuteX11(browser, new_ip, 'osecuser', '/cygdrive/c/Users/BarthaM/VirtualBox VMs' + '/' + new_sdvm + '/dvm_key'))
317 #print(Cygwin.bashExecute('echo $PATH')[1])
318 #print(Cygwin.cygPath('C:'))
319 #print('C:\\Program Files\\OpenSecurity: ' + c.cygPath('C:\\Program Files\\OpenSecurity'))