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