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