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