OpenSecurity/bin/cygwin.py
author BarthaM@N3SIM1218.D03.arc.local
Tue, 29 Apr 2014 15:40:48 +0100
changeset 135 c9499f5166c7
parent 110 490a78181935
child 143 36948a118f71
permissions -rwxr-xr-x
unmount thread, stricthostkeychecking disable
     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, call, STARTUPINFO, _subprocess
    41 import threading
    42 # local
    43 from environment import Environment
    44 from opensecurity_util import logger, setupLogger, OpenSecurityException
    45 import time
    46 #import wmi
    47 # ------------------------------------------------------------
    48 # code
    49 
    50 def once(theClass):
    51     """get the path to our local cygwin installment"""
    52     home_drive = os.path.expandvars("%HOMEDRIVE%") + os.sep
    53     path_hint = [ 
    54         os.path.abspath(os.path.join(Environment('OpenSecurity').prefix_path, 'cygwin')), 
    55         os.path.abspath(os.path.join(Environment('OpenSecurity').prefix_path, 'cygwin64')), 
    56         os.path.abspath(os.path.join(home_drive, 'cygwin')),
    57         os.path.abspath(os.path.join(home_drive, 'cygwin64'))
    58     ]
    59     path_valid = [ p for p in path_hint if os.path.exists(p) ]
    60         
    61     theClass.cygwin_root = path_valid[0]
    62     theClass.cygwin_bin = os.path.join(theClass.cygwin_root, 'bin') + os.path.sep
    63     theClass.cygwin_bash = os.path.join(theClass.cygwin_bin, 'bash.exe')
    64     theClass.cygwin_ssh = os.path.join(theClass.cygwin_bin, 'ssh.exe')
    65     theClass.cygwin_x11 = os.path.join(theClass.cygwin_bin, 'XWin.exe')
    66     theClass.win_cmd = os.environ.get("COMSPEC", "cmd.exe") 
    67     """get the path to the VirtualBox installation on this system"""
    68     theClass.vbox_root = theClass.getRegEntry('SOFTWARE\Oracle\VirtualBox', 'InstallDir')[0]  
    69     theClass.vbox_man = os.path.join(theClass.vbox_root, 'VBoxManage.exe')
    70     
    71     return theClass
    72 
    73 class XRunner(threading.Thread): 
    74     #running = True
    75     def __init__(self): 
    76         threading.Thread.__init__(self)
    77  
    78     def stop(self):
    79         self.running = False
    80         
    81     def run(self):
    82         #while self.running:
    83         logger.info('X starting')
    84         if not Cygwin.is_X11_running():
    85             #os.system('"'+Cygwin.cygwin_x11+'" :0 -multiwindow -resize')
    86             sts = call('"'+Cygwin.cygwin_x11+'" :0 -multiwindow -resize', shell=True)
    87         else:
    88             logger.info('X already started')
    89                 
    90             
    91             
    92 @once
    93 class Cygwin(object):
    94     cygwin_root = ''
    95     cygwin_bin = ''
    96     cygwin_bash = ''
    97     cygwin_ssh = ''
    98     cygwin_x11 = ''
    99     vbox_root = ''
   100     vbox_man = ''
   101     win_cmd = ''
   102     """Some nifty methods working with Cygwin"""
   103     
   104     def __call__(self, command, arguments, wait_return=True, window = False):
   105         """make an instance of this object act as a function"""
   106         return self.execute(command, arguments, wait_return, window)
   107 
   108     @staticmethod
   109     def getRegEntry(key, value):
   110         try:
   111             k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key)
   112             value = _winreg.QueryValueEx(k, value)
   113             _winreg.CloseKey(k)
   114             return value
   115         except:
   116             pass
   117     
   118             
   119     @staticmethod
   120     def root():
   121         return Cygwin.cygwin_root
   122 
   123     @staticmethod
   124     def bin():
   125         return Cygwin.cygwin_bin
   126     
   127     @staticmethod
   128     def bash():
   129         return Cygwin.cygwin_bash
   130     
   131     @staticmethod    
   132     def ssh():
   133         return Cygwin.cygwin_ssh
   134 
   135     @staticmethod    
   136     def x11():
   137         return Cygwin.cygwin_x11
   138     
   139     @staticmethod
   140     def vboxman():
   141         return Cygwin.vbox_man
   142     
   143     @staticmethod
   144     def cmd():
   145         return Cygwin.win_cmd
   146     
   147     executeLock = threading.Lock()
   148     #executes command on host system
   149     @staticmethod
   150     def execute(program, arguments, wait_return=True, window = False, stdin = PIPE, stdout = PIPE, stderr = PIPE):
   151         _startupinfo = STARTUPINFO()
   152         if not window:
   153             _startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
   154             _startupinfo.wShowWindow = _subprocess.SW_HIDE
   155 
   156             #logger.debug('trying to launch: ' + program + ' ' + ''.join(arguments))
   157         res_stderr = None
   158         try:
   159             # quote the executable otherwise we run into troubles
   160             # when the path contains spaces and additonal arguments
   161             # are presented as well.
   162             # special: invoking bash as login shell here with
   163             # an unquoted command does not execute /etc/profile
   164             args = '"' + program + '" ' + arguments
   165             process = Popen(args, startupinfo = _startupinfo, stdin = stdin, stdout = stdout, stderr = stderr, shell = False)
   166             logger.debug('Launched: ' + program + ' ' + ''.join(arguments))
   167             if not wait_return:
   168                 return [0, 'working in background', '']
   169             result = process.wait()
   170             res_stdout = process.stdout.read();
   171             res_stderr = process.stderr.read();
   172 
   173         except Exception as ex:
   174             res_stderr = ''.join(str(ex.args))
   175             result = 1 
   176             
   177         return result, res_stdout, res_stderr
   178     
   179     @staticmethod
   180     def vboxExecute(command, wait_return=True, window = False, bash_opts=''):
   181         retry = 0
   182         result = None
   183         while retry < 3:
   184             if Cygwin.executeLock.acquire(True):
   185                 result = Cygwin.execute(Cygwin.vbox_man, command, wait_return, window)
   186                 Cygwin.executeLock.release()
   187                 if result[0] == 0:
   188                     return result
   189                 retry+=1
   190         return result
   191 
   192 
   193     @staticmethod
   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 
   197         # directly
   198         command = bash_opts + ' -l -c "'  + command + '"'
   199         return Cygwin.execute(Cygwin.cygwin_bash, command, wait_return, window, stdin = stdin, stdout = stdout, stderr = stderr)
   200     
   201     @staticmethod
   202     def cmdExecute(command, wait_return=True, window = False):
   203         command = ' /c ' + command 
   204         return Cygwin.execute(Cygwin.win_cmd, command, wait_return, window)
   205 
   206     # executes command over ssh on guest vm
   207     @staticmethod
   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)     
   211     
   212     #machineFolder + '/' + vm_name + '/dvm_key
   213     #address = self.getHostOnlyIP(vm_name)
   214     #machineFolder = self.getDefaultMachineFolder()
   215     #machineFolder = Cygwin.cygwinPath(machineFolder)
   216     
   217     # executes command over ssh on guest vm with X forwarding
   218     @staticmethod
   219     def sshExecuteX11(command, address, user_name, certificate, wait_return=True):
   220         #return call('"'+ Cygwin.cygwin_bash +'" -l -c "' + 'DISPLAY=:0.0 ssh -Y -i \\\"' + certificate +'\\\" ' + user_name + '@' + address + ' ' + command + '"', shell=True)
   221         return Cygwin.bashExecute('DISPLAY=:0.0 ssh -Y -o StrictHostKeyChecking=no -i \\\"' + certificate +'\\\" ' + user_name + '@' + address + ' ' + command + '')
   222 
   223     @staticmethod
   224     def is_X11_running():
   225         """check if we can connect to a X11 running instance"""
   226         p = Cygwin.bashExecute('xset -display :0.0 q', wait_return = True, window = False) 
   227         return p[0] == 0
   228         
   229     @staticmethod
   230     def start_X11():
   231         """start X11 in the background (if not already running) on DISPLAY=:0"""
   232         runner = XRunner()
   233         runner.start()
   234         return (0, None, None)
   235 
   236         # launch X11
   237         #return Cygwin.execute(Cygwin.cygwin_x11, ':0 -multiwindow', wait_return = True, window = False)
   238         #return Cygwin.bashExecute('XWin :0 -multiwindow', wait_return = True, window = False)
   239         #return Cygwin.bashExecute('DISPLAY=:0.0 xhost +', wait_return = True, window = False)
   240         #return os.system('"'+Cygwin.cygwin_x11+'" :0 -multiwindow -resize')
   241     
   242     @staticmethod    
   243     def cygPath(path):
   244         cmd = 'cygpath -u \'' + path + '\''
   245         return Cygwin.bashExecute(cmd)[1].rstrip('\n')
   246                 
   247 # start
   248 if __name__ == "__main__":
   249     logger = setupLogger('Cygwin')
   250     c = Cygwin()
   251     logger.info(c.root())
   252     logger.info(c.bin())
   253     logger.info(c.bash())
   254     logger.info(c.ssh())
   255     logger.info(c.x11())
   256     
   257     runner = XRunner()
   258     runner.start()
   259     
   260     Cygwin.start_X11()
   261     
   262     
   263             
   264     #time.sleep(500)
   265     
   266     #Cygwin.start_X11()
   267     #print (Cygwin.is_X11_running())
   268     #print (Cygwin.is_X11_running())
   269     #new_sdvm = 'SecurityDVM0'
   270     #new_ip = Cygwin.vboxExecute('guestproperty get ' + new_sdvm + ' /VirtualBox/GuestInfo/Net/0/V4/IP')[1]
   271     #new_ip = new_ip[new_ip.index(':')+1:].strip()
   272     #new_ip = '+'
   273     #result = Cygwin.bashExecute('DISPLAY=:0.0 xhost '+new_ip)
   274     #browser = '/usr/bin/midori '
   275     #print(Cygwin.sshExecuteX11(browser, new_ip, 'osecuser', '/cygdrive/c/Users/BarthaM/VirtualBox VMs' + '/' + new_sdvm + '/dvm_key'))
   276             
   277     #print(Cygwin.bashExecute('echo $PATH')[1])
   278     #print(Cygwin.cygPath('C:'))
   279     #print('C:\\Program Files\\OpenSecurity: ' + c.cygPath('C:\\Program Files\\OpenSecurity'))
   280     
   281     sys.exit(0)
   282