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