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