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