OpenSecurity/bin/cygwin.py
author Oliver Maurhart <oliver.maurhart@ait.ac.at>
Wed, 29 Oct 2014 15:18:22 +0100
changeset 240 d7ef04254e9c
parent 219 9480e5ba1a82
child 252 824ae4324f57
permissions -rwxr-xr-x
lizenz fixed in all files
     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 2013-2014 X-Net and AIT Austrian Institute of Technology
    13 # 
    14 # 
    15 #     X-Net Services GmbH
    16 #     Elisabethstrasse 1
    17 #     4020 Linz
    18 #     AUSTRIA
    19 #     https://www.x-net.at
    20 # 
    21 #     AIT Austrian Institute of Technology
    22 #     Donau City Strasse 1
    23 #     1220 Wien
    24 #     AUSTRIA
    25 #     http://www.ait.ac.at
    26 # 
    27 # 
    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
    31 # 
    32 #    http://www.apache.org/licenses/LICENSE-2.0
    33 # 
    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 # ------------------------------------------------------------
    40 
    41 
    42 # ------------------------------------------------------------
    43 # imports
    44 
    45 import os
    46 import subprocess
    47 import sys
    48 import _winreg
    49 from subprocess import Popen, PIPE, STARTUPINFO, _subprocess
    50 import threading
    51 
    52 # local
    53 from environment import Environment
    54 from opensecurity_util import logger, setupLogger, OpenSecurityException
    55 import time
    56 
    57 
    58 # ------------------------------------------------------------
    59 # code
    60 
    61 def once(theClass):
    62     """get the path to our local cygwin installment"""
    63     home_drive = os.path.expandvars("%HOMEDRIVE%") + os.sep
    64     e = Environment('OpenSecurity')
    65     path_hint = [ 
    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'))
    70     ]
    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 
    85     return theClass
    86 
    87             
    88 @once
    89 class Cygwin(object):
    90     cygwin_root = ''
    91     cygwin_bin = ''
    92     cygwin_bash = ''
    93     cygwin_ssh = ''
    94     cygwin_x11 = ''
    95     cygwin_scp = ''
    96     vbox_root = ''
    97     vbox_man = ''
    98     win_cmd = ''
    99     user_home = ''
   100     allow_exec = True 
   101     """Some nifty methods working with Cygwin"""
   102     
   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)
   106 
   107     @staticmethod
   108     def getRegEntry(key, value):
   109         try:
   110             k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key)
   111             value = _winreg.QueryValueEx(k, value)
   112             _winreg.CloseKey(k)
   113             return value
   114         except:
   115             pass
   116     
   117             
   118     @staticmethod
   119     def root():
   120         return Cygwin.cygwin_root
   121 
   122     @staticmethod
   123     def bin():
   124         return Cygwin.cygwin_bin
   125     
   126     @staticmethod
   127     def bash():
   128         return Cygwin.cygwin_bash
   129     
   130     @staticmethod    
   131     def ssh():
   132         return Cygwin.cygwin_ssh
   133     
   134     @staticmethod    
   135     def scp():
   136         return Cygwin.cygwin_scp
   137 
   138     @staticmethod    
   139     def x11():
   140         return Cygwin.cygwin_x11
   141     
   142     @staticmethod
   143     def vboxman():
   144         return Cygwin.vbox_man
   145     
   146     @staticmethod
   147     def cmd():
   148         return Cygwin.win_cmd
   149     
   150     @staticmethod
   151     def home():
   152         return Cygwin.user_home
   153     
   154     @staticmethod
   155     def allowExec():
   156         Cygwin.allow_exec = True
   157     
   158     @staticmethod
   159     def denyExec():
   160         Cygwin.allow_exec = False
   161     
   162     executeLock = threading.Lock()
   163     #executes command on host system
   164     @staticmethod
   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).')
   169             
   170         _startupinfo = STARTUPINFO()
   171         if not window:
   172             _startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
   173             _startupinfo.wShowWindow = _subprocess.SW_HIDE
   174             #logger.debug('trying to launch: ' + program + ' ' + ''.join(arguments))
   175         
   176         result, res_stdout, res_stderr = None, None, None
   177         try:
   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)
   186             if not wait_return:
   187                 return [0, 'working in background', '']
   188             
   189             res_stdout, res_stderr = process.communicate()
   190             result = process.returncode
   191             logger.debug('Finished: ' + program + ' ' + ''.join(arguments))
   192 
   193         except Exception as ex:
   194             res_stderr = ''.join(str(ex.args))
   195             result = 1 
   196     
   197         if result != 0:
   198             logger.error('Command failed:' + ''.join(res_stderr))
   199             raise OpenSecurityException('Command failed:' + ''.join(res_stderr))
   200         
   201         return result, res_stdout, res_stderr
   202     
   203     @staticmethod
   204     def vboxExecute(command, wait_return=True, window = False, bash_opts='', try_count = 3):
   205         retry = 0
   206         result = None
   207         while retry < try_count:
   208             if Cygwin.executeLock.acquire(True):
   209                 try:
   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:
   214                         raise ex
   215                 else:
   216                     Cygwin.executeLock.release()
   217                     return result
   218             retry+=1
   219         raise OpenSecurityException('Command max retry reached: ' + ''.join(command))
   220 
   221 
   222     @staticmethod
   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 
   226         # directly
   227         command = bash_opts + ' -l -c "'  + command + '"'
   228         return Cygwin.execute(Cygwin.cygwin_bash, command, wait_return, window, stdin = stdin, stdout = stdout, stderr = stderr)
   229     
   230     @staticmethod
   231     def cmdExecute(command, wait_return=True, window = False):
   232         command = ' /c ' + command 
   233         return Cygwin.execute(Cygwin.win_cmd, command, wait_return, window)
   234 
   235     # executes command over ssh on guest vm
   236     @staticmethod
   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)
   242 
   243     # executes command over ssh on guest vm
   244     @staticmethod
   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)
   248     
   249     #machineFolder + '/' + vm_name + '/dvm_key
   250     #address = self.getHostOnlyIP(vm_name)
   251     #machineFolder = self.getDefaultMachineFolder()
   252     #machineFolder = Cygwin.cygwinPath(machineFolder)
   253     
   254     # executes command over ssh on guest vm with X forwarding
   255     @staticmethod
   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 + '')
   258 
   259     @staticmethod
   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) 
   263         return p[0] == 0
   264         
   265     @staticmethod
   266     def start_X11():
   267         """start X11 in the background (if not already running) on DISPLAY=:0
   268         
   269         If there is already a X11 running then exit silently, calling this
   270         method as often as needed.
   271         """
   272         Popen('"' + Cygwin.cygwin_x11 + '" :0 -multiwindow -resize -silent-dup-error')
   273         return (0, None, None)
   274     
   275     @staticmethod    
   276     def cygPath(path):
   277         cmd = 'cygpath -u \'' + path + '\''
   278         return Cygwin.bashExecute(cmd)[1].rstrip('\n')
   279     
   280 # start
   281 import os
   282 import win32api
   283 import win32con
   284 import win32security
   285 
   286 if __name__ == "__main__":
   287     logger = setupLogger('Cygwin')
   288     c = Cygwin()
   289     logger.info(c.root())
   290     logger.info(c.bin())
   291     logger.info(c.bash())
   292     logger.info(c.ssh())
   293     logger.info(c.x11())
   294     logger.info(c.home())   
   295     
   296     #PSEXEC -i -s -d CMD
   297     #tasklist /v /fo list /fi "IMAGENAME eq explorer.exe"
   298     
   299     #runner = XRunner()
   300     #runner.start()
   301     
   302     #Cygwin.start_X11()
   303             
   304     #time.sleep(500)
   305     
   306     #Cygwin.start_X11()
   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()
   312     #new_ip = '+'
   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'))
   316             
   317     #print(Cygwin.bashExecute('echo $PATH')[1])
   318     #print(Cygwin.cygPath('C:'))
   319     #print('C:\\Program Files\\OpenSecurity: ' + c.cygPath('C:\\Program Files\\OpenSecurity'))
   320     
   321     sys.exit(0)
   322