OpenSecurity/bin/cygwin.py
author Oliver Maurhart <oliver.maurhart@ait.ac.at>
Thu, 22 May 2014 11:00:33 +0200
changeset 167 1e1811fa44bc
parent 165 a1b7a5a48a1e
child 169 a133c8d03ef8
permissions -rwxr-xr-x
eXtreme Programming session - changes by Mihai
     1 #!/bin/env python
     2 # -*- coding: utf-8 -*-
     3 
     4 # ------------------------------------------------------------
     5 # cygwin command
     6 # 
     7 # executes a cygwin command inside the opensecurity project
     8 #
     9 # Autor: Mihai Bartha, <mihai.bartha@ait.ac.at>
    10 #        Oliver Maurhart, <oliver.maurhart@ait.ac.at>
    11 #
    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
    16 #
    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.
    20 # 
    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.
    25 # 
    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 # ------------------------------------------------------------
    31 
    32 
    33 # ------------------------------------------------------------
    34 # imports
    35 
    36 import os
    37 import subprocess
    38 import sys
    39 import _winreg
    40 from subprocess import Popen, PIPE, STARTUPINFO, _subprocess
    41 import threading
    42 
    43 # local
    44 from environment import Environment
    45 from opensecurity_util import logger, setupLogger, OpenSecurityException
    46 import time
    47 
    48 
    49 # ------------------------------------------------------------
    50 # code
    51 
    52 def once(theClass):
    53     """get the path to our local cygwin installment"""
    54     home_drive = os.path.expandvars("%HOMEDRIVE%") + os.sep
    55     path_hint = [ 
    56         os.path.abspath(os.path.join(Environment('OpenSecurity').prefix_path, 'cygwin')), 
    57         os.path.abspath(os.path.join(Environment('OpenSecurity').prefix_path, 'cygwin64')), 
    58         os.path.abspath(os.path.join(home_drive, 'cygwin')),
    59         os.path.abspath(os.path.join(home_drive, 'cygwin64'))
    60     ]
    61     path_valid = [ p for p in path_hint if os.path.exists(p) ]
    62         
    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%")
    75     return theClass
    76 
    77             
    78 @once
    79 class Cygwin(object):
    80     cygwin_root = ''
    81     cygwin_bin = ''
    82     cygwin_bash = ''
    83     cygwin_ssh = ''
    84     cygwin_x11 = ''
    85     cygwin_scp = ''
    86     vbox_root = ''
    87     vbox_man = ''
    88     win_cmd = ''
    89     user_home = ''
    90     """Some nifty methods working with Cygwin"""
    91     
    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)
    95 
    96     @staticmethod
    97     def getRegEntry(key, value):
    98         try:
    99             k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key)
   100             value = _winreg.QueryValueEx(k, value)
   101             _winreg.CloseKey(k)
   102             return value
   103         except:
   104             pass
   105     
   106             
   107     @staticmethod
   108     def root():
   109         return Cygwin.cygwin_root
   110 
   111     @staticmethod
   112     def bin():
   113         return Cygwin.cygwin_bin
   114     
   115     @staticmethod
   116     def bash():
   117         return Cygwin.cygwin_bash
   118     
   119     @staticmethod    
   120     def ssh():
   121         return Cygwin.cygwin_ssh
   122     
   123     @staticmethod    
   124     def scp():
   125         return Cygwin.cygwin_scp
   126 
   127     @staticmethod    
   128     def x11():
   129         return Cygwin.cygwin_x11
   130     
   131     @staticmethod
   132     def vboxman():
   133         return Cygwin.vbox_man
   134     
   135     @staticmethod
   136     def cmd():
   137         return Cygwin.win_cmd
   138     
   139     @staticmethod
   140     def home():
   141         return Cygwin.user_home
   142     
   143     executeLock = threading.Lock()
   144     #executes command on host system
   145     @staticmethod
   146     def execute(program, arguments, wait_return=True, window = False, stdin = PIPE, stdout = PIPE, stderr = PIPE):
   147         _startupinfo = STARTUPINFO()
   148         if not window:
   149             _startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
   150             _startupinfo.wShowWindow = _subprocess.SW_HIDE
   151             #logger.debug('trying to launch: ' + program + ' ' + ''.join(arguments))
   152         
   153 	    result, res_stdout, res_stderr = None, None, None
   154 		
   155         try:
   156             # quote the executable otherwise we run into troubles
   157             # when the path contains spaces and additonal arguments
   158             # are presented as well.
   159             # special: invoking bash as login shell here with
   160             # an unquoted command does not execute /etc/profile
   161             args = '"' + program + '" ' + arguments
   162             process = Popen(args, startupinfo = _startupinfo, stdin = stdin, stdout = stdout, stderr = stderr, shell = False)
   163             logger.debug('Launched: ' + program + ' ' + ''.join(arguments))
   164             if not wait_return:
   165                 return [0, 'working in background', '']
   166 				
   167             res_stdout, res_stderr = process.communicate()
   168             result = process.returncode
   169 			
   170 			#result = process.wait()
   171             #res_stdout = process.stdout.read();
   172             #res_stderr = process.stderr.read();
   173 
   174         except Exception as ex:
   175             res_stderr = ''.join(str(ex.args))
   176             result = 1 
   177             
   178         return result, res_stdout, res_stderr
   179     
   180     @staticmethod
   181     def vboxExecute(command, wait_return=True, window = False, bash_opts=''):
   182         retry = 0
   183         result = None
   184         while retry < 3:
   185             if Cygwin.executeLock.acquire(True):
   186                 result = Cygwin.execute(Cygwin.vbox_man, command, wait_return, window)
   187                 Cygwin.executeLock.release()
   188                 if result[0] == 0:
   189                     return result
   190                 retry+=1
   191         return result
   192 
   193 
   194     @staticmethod
   195     def bashExecute(command, wait_return=True, window = False, bash_opts='', stdin = PIPE, stdout = PIPE, stderr = PIPE):
   196         # for some reason, the '-l' is ignored when started via python
   197         # so the same behavior is triggered by calling /etc/profile 
   198         # directly
   199         command = bash_opts + ' -l -c "'  + command + '"'
   200         return Cygwin.execute(Cygwin.cygwin_bash, command, wait_return, window, stdin = stdin, stdout = stdout, stderr = stderr)
   201     
   202     @staticmethod
   203     def cmdExecute(command, wait_return=True, window = False):
   204         command = ' /c ' + command 
   205         return Cygwin.execute(Cygwin.win_cmd, command, wait_return, window)
   206 
   207     # executes command over ssh on guest vm
   208     @staticmethod
   209     def sshExecute(command, address, user_name, certificate, wait_return=True, window = False):
   210         command = ' -v -o StrictHostKeyChecking=no -i "' + certificate + '" ' + user_name + '@' + address + ' ' + command        
   211         return Cygwin.execute(Cygwin.cygwin_ssh, command, wait_return, window)
   212 	
   213 	# executes command over ssh on guest vm
   214     @staticmethod
   215     def sshBackgroundExecute(command, address, user_name, certificate, wait_return=True, window = False):
   216         command = ' -f -v -o StrictHostKeyChecking=no -i "' + certificate + '" ' + user_name + '@' + address + ' ' + command        
   217         return Cygwin.execute(Cygwin.cygwin_ssh, command, wait_return, window)
   218     
   219     #machineFolder + '/' + vm_name + '/dvm_key
   220     #address = self.getHostOnlyIP(vm_name)
   221     #machineFolder = self.getDefaultMachineFolder()
   222     #machineFolder = Cygwin.cygwinPath(machineFolder)
   223     
   224     # executes command over ssh on guest vm with X forwarding
   225     @staticmethod
   226     def sshExecuteX11(command, address, user_name, certificate, wait_return=True):
   227         return Cygwin.bashExecute('DISPLAY=:0.0 ssh -Y -o StrictHostKeyChecking=no -i \\\"' + certificate +'\\\" ' + user_name + '@' + address + ' ' + command + '')
   228 
   229     @staticmethod
   230     def is_X11_running():
   231         """check if we can connect to a X11 running instance"""
   232         p = Cygwin.bashExecute('xset -display :0 q', wait_return = True, window = False) 
   233         return p[0] == 0
   234         
   235     @staticmethod
   236     def start_X11():
   237         """start X11 in the background (if not already running) on DISPLAY=:0
   238         
   239         If there is already a X11 running then exit silently, calling this
   240         method as often as needed.
   241         """
   242         Popen('"' + Cygwin.cygwin_x11 + '" :0 -multiwindow -resize -silent-dup-error')
   243         return (0, None, None)
   244     
   245     @staticmethod    
   246     def cygPath(path):
   247         cmd = 'cygpath -u \'' + path + '\''
   248         return Cygwin.bashExecute(cmd)[1].rstrip('\n')
   249     
   250     @staticmethod
   251     def checkResult(result):
   252         if result[0] != 0:
   253             logger.error('Command failed:' + ''.join(result[2]))
   254             raise OpenSecurityException('Command failed:' + ''.join(result[2]))
   255         return result
   256                 
   257 # start
   258 import os
   259 import win32api
   260 import win32con
   261 import win32security
   262 
   263 if __name__ == "__main__":
   264     logger = setupLogger('Cygwin')
   265     c = Cygwin()
   266     #logger.info(c.root())
   267     #logger.info(c.bin())
   268     #logger.info(c.bash())
   269     #logger.info(c.ssh())
   270     #logger.info(c.x11())
   271     #logger.info(c.home())   
   272     
   273     #PSEXEC -i -s -d CMD
   274     #tasklist /v /fo list /fi "IMAGENAME eq explorer.exe"
   275     
   276     #runner = XRunner()
   277     #runner.start()
   278     
   279     #Cygwin.start_X11()
   280     
   281     
   282             
   283     #time.sleep(500)
   284     
   285     #Cygwin.start_X11()
   286     #print (Cygwin.is_X11_running())
   287     #print (Cygwin.is_X11_running())
   288     #new_sdvm = 'SecurityDVM0'
   289     #new_ip = Cygwin.vboxExecute('guestproperty get ' + new_sdvm + ' /VirtualBox/GuestInfo/Net/0/V4/IP')[1]
   290     #new_ip = new_ip[new_ip.index(':')+1:].strip()
   291     #new_ip = '+'
   292     #result = Cygwin.bashExecute('DISPLAY=:0.0 xhost '+new_ip)
   293     #browser = '/usr/bin/midori '
   294     #print(Cygwin.sshExecuteX11(browser, new_ip, 'osecuser', '/cygdrive/c/Users/BarthaM/VirtualBox VMs' + '/' + new_sdvm + '/dvm_key'))
   295             
   296     #print(Cygwin.bashExecute('echo $PATH')[1])
   297     #print(Cygwin.cygPath('C:'))
   298     #print('C:\\Program Files\\OpenSecurity: ' + c.cygPath('C:\\Program Files\\OpenSecurity'))
   299     
   300     sys.exit(0)
   301