OpenSecurity/bin/vmmanager.py
author dyle@opensecurity.d03.arc.local
Wed, 29 Jan 2014 09:23:52 +0000
changeset 53 01839f13cef3
parent 52 1238895dc6b6
child 55 42238cd74afe
permissions -rw-r--r--
SSH cert and ISO creation with shadowrun.exe
mb@7
     1
'''
mb@7
     2
Created on Nov 19, 2013
mb@7
     3
mb@7
     4
@author: BarthaM
mb@7
     5
'''
mb@7
     6
import os
mb@7
     7
import os.path
mb@7
     8
from subprocess import Popen, PIPE, call
mb@7
     9
import subprocess
mb@7
    10
import sys
mb@7
    11
import re
om@19
    12
import _winreg
om@18
    13
from cygwin import Cygwin
dyle@53
    14
from environment import Environment
mb@36
    15
import threading
mb@40
    16
import time
mb@40
    17
import string
mb@7
    18
dyle@53
    19
import shutil
dyle@53
    20
import stat
dyle@53
    21
import tempfile
dyle@52
    22
om@19
    23
om@42
    24
DEBUG = True
mb@46
    25
class VMManagerException(Exception):
mb@46
    26
    def __init__(self, value):
mb@46
    27
        self.value = value
mb@46
    28
    def __str__(self):
mb@46
    29
        return repr(self.value)
mb@7
    30
mb@7
    31
class USBFilter:
mb@7
    32
    vendorid = ""
mb@7
    33
    productid = ""
mb@7
    34
    revision = ""
mb@7
    35
    
mb@7
    36
    def __init__(self, vendorid, productid, revision):
mb@7
    37
        self.vendorid = vendorid.lower()
mb@7
    38
        self.productid = productid.lower()
mb@7
    39
        self.revision = revision.lower()
mb@7
    40
        return
mb@7
    41
    
mb@7
    42
    def __eq__(self, other):
mb@7
    43
        return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
mb@7
    44
    
mb@7
    45
    def __hash__(self):
mb@7
    46
        return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
mb@7
    47
    
mb@7
    48
    def __repr__(self):
mb@7
    49
        return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
mb@7
    50
        
mb@7
    51
mb@7
    52
class VMManager(object):
mb@7
    53
    vmRootName = "SecurityDVM"
mb@7
    54
    systemProperties = None
mb@7
    55
    cygwin_path = 'c:\\cygwin64\\bin\\'
om@19
    56
    vboxManage = 'VBoxManage'
mb@34
    57
    startNotifications = list()
mb@34
    58
    
mb@34
    59
    _instance = None
mb@34
    60
    #def __new__(cls, *args, **kwargs):
mb@34
    61
    #    if not cls._instance:
mb@34
    62
    #        cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
mb@34
    63
    #    return cls._instance
mb@7
    64
    
mb@33
    65
    _instance = None
mb@33
    66
    #def __new__(cls, *args, **kwargs):
mb@33
    67
    #    if not cls._instance:
mb@33
    68
    #        cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
mb@33
    69
    #    return cls._instance
mb@33
    70
    
mb@7
    71
    def __init__(self):
om@31
    72
        self.cygwin_path = os.path.join(Cygwin.root(), 'bin') + os.path.sep
om@22
    73
        self.vboxManage = os.path.join(self.getVBoxManagePath(), 'VBoxManage')
mb@7
    74
        self.systemProperties = self.getSystemProperties()
mb@7
    75
        return
mb@33
    76
    
mb@33
    77
    @staticmethod
mb@33
    78
    def getInstance():
mb@33
    79
        if VMManager._instance == None:
mb@33
    80
            VMManager._instance = VMManager()
mb@33
    81
        return VMManager._instance
mb@34
    82
    
mb@34
    83
    def putStartNotification(self, ip):
mb@34
    84
        self.startNotifications.append(ip)
mb@34
    85
    
mb@34
    86
    def isSDVMStarted(self, ip):
mb@34
    87
        return self.startNotifications.contains(ip)
mb@33
    88
             
mb@46
    89
    def execute(self, cmd, wait_return=True ):
mb@7
    90
        if DEBUG:
mb@7
    91
            print('trying to launch: ' + cmd)
mb@40
    92
        process = Popen(cmd, stdout=PIPE, stderr=PIPE) #shell = True
mb@7
    93
        if DEBUG:
mb@7
    94
            print('launched: ' + cmd)
mb@46
    95
        if not wait_return:
mb@46
    96
            return [0, 'working in background', '']
mb@7
    97
        result = process.wait()
mb@7
    98
        res_stdout = process.stdout.read();
mb@7
    99
        res_stderr = process.stderr.read();
mb@7
   100
        if DEBUG:
mb@7
   101
            if res_stdout != "":
mb@7
   102
                print res_stdout
mb@7
   103
            if res_stderr != "":
mb@7
   104
                print res_stderr
mb@46
   105
        if result !=0:
mb@46
   106
            raise VMManagerException(res_stderr)
mb@7
   107
        return result, res_stdout, res_stderr
mb@7
   108
    
om@19
   109
    def getVBoxManagePath(self):
om@19
   110
        """get the path to the VirtualBox installation on this system"""
om@19
   111
        p = None
om@19
   112
        try:
om@19
   113
            k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
om@19
   114
            p = _winreg.QueryValueEx(k, 'InstallDir')[0]
om@19
   115
            _winreg.CloseKey(k)
om@19
   116
        except:
om@19
   117
            pass
om@19
   118
        return p
om@19
   119
    
BarthaM@8
   120
    # return hosty system properties
mb@7
   121
    def getSystemProperties(self):
om@22
   122
        cmd = self.vboxManage + ' list systemproperties'
mb@7
   123
        result = self.execute(cmd)
mb@7
   124
        if result[1]=='':
mb@7
   125
            return None
mb@7
   126
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
mb@7
   127
        return props
BarthaM@8
   128
    
BarthaM@8
   129
    # return the folder containing the guest VMs     
mb@7
   130
    def getDefaultMachineFolder(self):
mb@7
   131
        return self.systemProperties["Default machine folder"]
mb@7
   132
    
BarthaM@8
   133
    #list the hostonly IFs exposed by the VBox host
mb@7
   134
    def getHostOnlyIFs(self):
mb@11
   135
        cmd = 'VBoxManage list hostonlyifs'
mb@11
   136
        result = self.execute(cmd)[1]
mb@7
   137
        if result=='':
mb@7
   138
            return None
mb@7
   139
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
mb@7
   140
        return props
mb@7
   141
        
mb@7
   142
    def listRSDS(self):
mb@7
   143
        cmd = 'VBoxManage list usbhost'
mb@12
   144
        results = self.execute(cmd)[1]
mb@7
   145
        results = results.split('Host USB Devices:')[1].strip()
mb@7
   146
        
mb@7
   147
        items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
mb@7
   148
        rsds = dict()   
mb@7
   149
        for item in items:
mb@7
   150
            props = dict()
mb@7
   151
            for line in item.splitlines():
mb@7
   152
                if line != "":         
mb@7
   153
                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
mb@7
   154
                    props[k] = v;
mb@7
   155
            
mb@7
   156
            if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
mb@7
   157
                usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], 
mb@7
   158
                                        re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
mb@7
   159
                                        re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
mb@7
   160
                rsds[props['UUID']] = usb_filter;
mb@7
   161
                if DEBUG:
mb@33
   162
                    print usb_filter
mb@7
   163
        return rsds
mb@7
   164
BarthaM@8
   165
    # list all existing VMs registered with VBox
mb@7
   166
    def listVM(self):
mb@7
   167
        cmd = 'VBoxManage list vms'
mb@11
   168
        result = self.execute(cmd)[1]
mb@7
   169
        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
mb@7
   170
        return vms
mb@7
   171
    
BarthaM@8
   172
    # list existing SDVMs
mb@7
   173
    def listSDVM(self):
mb@7
   174
        vms = self.listVM()
mb@7
   175
        svdms = []
mb@7
   176
        for vm in vms:
mb@7
   177
            if vm.startswith(self.vmRootName) and vm != self.vmRootName:
mb@7
   178
                svdms.append(vm)
mb@7
   179
        return svdms
mb@7
   180
    
BarthaM@8
   181
    # generate valid (not already existing SDVM name). necessary for creating a new VM
mb@7
   182
    def generateSDVMName(self):
mb@7
   183
        vms = self.listVM()
mb@7
   184
        for i in range(0,999):
mb@7
   185
            if(not self.vmRootName+str(i) in vms):
mb@7
   186
                return self.vmRootName+str(i)
mb@7
   187
        return ''
mb@7
   188
    
BarthaM@8
   189
    # return the RSDs attached to all existing SDVMs
BarthaM@8
   190
    def getAttachedRSDs(self):
BarthaM@8
   191
        vms = self.listSDVM()
BarthaM@8
   192
        attached_devices = dict()
BarthaM@8
   193
        for vm in vms:
BarthaM@8
   194
            rsd_filter = self.getUSBFilter(vm)
mb@12
   195
            if rsd_filter != None:
BarthaM@8
   196
                attached_devices[vm] = rsd_filter
BarthaM@8
   197
        return attached_devices
BarthaM@8
   198
    
BarthaM@8
   199
    # configures hostonly networking and DHCP server. requires admin rights
BarthaM@8
   200
    def configureHostNetworking(self):
BarthaM@8
   201
        #cmd = 'vboxmanage list hostonlyifs'
BarthaM@8
   202
        #self.execute(cmd)
BarthaM@8
   203
        #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
BarthaM@8
   204
        #self.execute(cmd)
BarthaM@8
   205
        #cmd = 'vboxmanage hostonlyif create'
BarthaM@8
   206
        #self.execute(cmd)
mb@33
   207
        cmd = 'VBoxManage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
BarthaM@8
   208
        self.execute(cmd)
BarthaM@8
   209
        #cmd = 'vboxmanage dhcpserver add'
BarthaM@8
   210
        #self.execute(cmd)
mb@33
   211
        cmd = 'VBoxManage dhcpserver modify --ifname \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.100 --netmask 255.255.255.0 --lowerip 192.168.56.101 --upperip 192.168.56.200'
BarthaM@8
   212
        self.execute(cmd)
BarthaM@8
   213
    
mb@11
   214
    #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
BarthaM@8
   215
    def createVM(self, vm_name):
BarthaM@8
   216
        hostonly_if = self.getHostOnlyIFs()
BarthaM@8
   217
        machineFolder = self.getDefaultMachineFolder()
mb@11
   218
        cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
BarthaM@8
   219
        self.execute(cmd)
mb@11
   220
        cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat' 
BarthaM@8
   221
        self.execute(cmd)
mb@11
   222
        cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
BarthaM@8
   223
        self.execute(cmd)
mb@46
   224
        cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"' #--mtype immutable
BarthaM@8
   225
        self.execute(cmd)
BarthaM@8
   226
        return
BarthaM@8
   227
    
BarthaM@8
   228
    #remove VM from the system. should be used on VMs returned by listSDVMs    
BarthaM@8
   229
    def removeVM(self, vm_name):
BarthaM@8
   230
        print('removing ' + vm_name)
mb@36
   231
        cmd = 'VBoxManage unregistervm ' + vm_name + ' --delete'
BarthaM@8
   232
        print self.execute(cmd)
BarthaM@8
   233
        machineFolder = self.getDefaultMachineFolder()
mb@36
   234
        cmd = self.cygwin_path + 'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
BarthaM@8
   235
        print self.execute(cmd)
BarthaM@8
   236
    
BarthaM@8
   237
    # start VM
BarthaM@8
   238
    def startVM(self, vm_name):
BarthaM@8
   239
        print('starting ' +  vm_name)
mb@40
   240
        cmd = 'VBoxManage startvm ' + vm_name + ' --type headless' 
mb@46
   241
        result = self.execute(cmd)
mb@46
   242
        while not string.find(str(result), 'successfully started',):
mb@46
   243
            print "Failed to start SDVM: ", vm_name, " retrying"
mb@46
   244
            time.sleep(1)
mb@46
   245
            result = self.execute(cmd)
mb@46
   246
        return result[0]
BarthaM@8
   247
        
BarthaM@8
   248
    # stop VM    
BarthaM@8
   249
    def stopVM(self, vm_name):
BarthaM@8
   250
        print('stopping ' + vm_name)
BarthaM@8
   251
        cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
mb@46
   252
        self.execute(cmd)
BarthaM@8
   253
    
BarthaM@8
   254
    # return the hostOnly IP for a running guest    
BarthaM@8
   255
    def getHostOnlyIP(self, vm_name):
BarthaM@8
   256
        print('gettting hostOnly IP address ' + vm_name)
BarthaM@8
   257
        cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
BarthaM@8
   258
        result = self.execute(cmd)
BarthaM@8
   259
        if result=='':
BarthaM@8
   260
            return None
BarthaM@8
   261
        result = result[1]
mb@40
   262
        if result.startswith('No value set!'):
mb@40
   263
            return None
BarthaM@8
   264
        return result[result.index(':')+1:].strip()
BarthaM@8
   265
    
BarthaM@8
   266
    # attach removable storage device to VM by provision of filter
BarthaM@8
   267
    def attachRSD(self, vm_name, rsd_filter):
BarthaM@8
   268
        cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
BarthaM@8
   269
        print self.execute(cmd)
BarthaM@8
   270
        
BarthaM@8
   271
    
BarthaM@8
   272
    # return the description set for an existing VM
mb@7
   273
    def getVMInfo(self, vm_name):
mb@7
   274
        cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
mb@12
   275
        results = self.execute(cmd)[1]
mb@7
   276
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
mb@7
   277
        return props
mb@7
   278
    
BarthaM@8
   279
    # return the configured USB filter for an existing VM 
mb@7
   280
    def getUSBFilter(self, vm_name):
mb@7
   281
        props = self.getVMInfo(vm_name)
mb@7
   282
        keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
mb@7
   283
        keyset = set(props.keys())
mb@7
   284
        usb_filter = None
mb@7
   285
        if keyset.issuperset(keys):
mb@7
   286
            usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
mb@7
   287
        return usb_filter
mb@7
   288
    
mb@7
   289
    #generates ISO containing authorized_keys for use with guest VM
mb@7
   290
    def genCertificateISO(self, vm_name):
dyle@53
   291
dyle@53
   292
        # create a SSH key pair in a machine subfolder
dyle@53
   293
        #
dyle@53
   294
        # to avoid any DOS window popping up we use
dyle@53
   295
        # the cygwin's class which relies on the
dyle@53
   296
        # shadowrun.exe.
dyle@53
   297
        #
dyle@53
   298
        # shadowrun.exe is derived from a run.exe of
dyle@53
   299
        # the cygwin utilities but with a fix to
dyle@53
   300
        # avoid Console Windows to pop up.
dyle@53
   301
        # 
dyle@53
   302
        # However, run.exe suffers from bad
dyle@53
   303
        # argument handling, when there are spaces
dyle@53
   304
        # within and so does shadowrun.exe
dyle@53
   305
        #
dyle@53
   306
        # In order to avoid any complex mechanics
dyle@53
   307
        # we start a bash script, which creates the
dyle@53
   308
        # SSH certificate in the local folder.
dyle@53
   309
        #
dyle@53
   310
        # Even more: to get rid of any potential
dyle@53
   311
        # space ' ' hazard in path names, we copy
dyle@53
   312
        # the script to the creation side as well.
dyle@53
   313
        #
dyle@53
   314
        # ... and yes: shadowrun.exe terminates
dyle@53
   315
        # with a ACCESS_VIOLATION and creates another
dyle@53
   316
        # stack-trace-dump file in the folder.
dyle@53
   317
        #
dyle@53
   318
        # But so does the original cygwin's run.exe
dyle@53
   319
        # too.
dyle@53
   320
        #           -.-
dyle@53
   321
        #
dyle@53
   322
        # (On the good side: the access violation happens
dyle@53
   323
        # *after* the wrapped process has been launched)
dyle@53
   324
        #
mb@7
   325
        machineFolder = self.getDefaultMachineFolder()
dyle@53
   326
        vm_folder = os.path.join(machineFolder, vm_name)
dyle@53
   327
        old_dir = os.getcwd()
dyle@53
   328
        os.chdir(vm_folder)
dyle@53
   329
        print(os.path.join(sys.path[0], 'create-cert-and-iso.sh'))
dyle@53
   330
        shutil.copy(os.path.join(sys.path[0], 'create-cert-and-iso.sh'), vm_folder)
dyle@53
   331
        p = Cygwin()(['/bin/bash', '-c', './create-cert-and-iso.sh'])
dyle@53
   332
        p.communicate()
dyle@53
   333
        os.chdir(old_dir)
dyle@52
   334
mb@7
   335
    
mb@7
   336
    # attaches generated ssh public cert to guest vm
mb@7
   337
    def attachCertificateISO(self, vm_name):
mb@7
   338
        machineFolder = self.getDefaultMachineFolder()
mb@7
   339
        cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
mb@7
   340
        result = self.execute(cmd)
mb@7
   341
        return result
mb@7
   342
    
mb@36
   343
    handleDeviceChangeLock = threading.Lock()
mb@36
   344
    
mb@7
   345
    # handles device change events
mb@7
   346
    def handleDeviceChange(self):
mb@36
   347
        if VMManager.handleDeviceChangeLock.acquire(True):
mb@36
   348
            #destroy unused vms
mb@40
   349
            new_ip = None
mb@36
   350
            attached_devices = self.getAttachedRSDs()
mb@36
   351
            connected_devices = self.listRSDS()
mb@36
   352
            for vm_name in attached_devices.keys():
mb@36
   353
                if attached_devices[vm_name] not in connected_devices.values():
mb@40
   354
                    self.unmapNetworkDrive('h:')
mb@36
   355
                    self.stopVM(vm_name)
mb@36
   356
                    self.removeVM(vm_name)
mb@36
   357
            #create new vm for attached device if any
mb@36
   358
            attached_devices = self.getAttachedRSDs()
mb@36
   359
            for connected_device in connected_devices.values():
mb@36
   360
                if (attached_devices and False) or (connected_device not in attached_devices.values()):
mb@36
   361
                    new_sdvm = self.generateSDVMName()
mb@36
   362
                    self.createVM(new_sdvm)
mb@36
   363
                    self.attachRSD(new_sdvm, connected_device)
mb@46
   364
mb@46
   365
mb@36
   366
                    self.startVM(new_sdvm)
mb@46
   367
                    # wait for machine to come up
mb@40
   368
                    while new_ip == None:
mb@40
   369
                        time.sleep(1)
mb@40
   370
                        new_ip = self.getHostOnlyIP(new_sdvm)
mb@40
   371
                    while new_ip not in self.startNotifications:
mb@40
   372
                        time.sleep(1)
mb@46
   373
                    if new_ip != None:
mb@46
   374
                        self.mapNetworkDrive('h:', '\\\\' + new_ip + '\\USB', None, None)
mb@40
   375
                    #TODO: cleanup notifications somwhere else (eg. machine shutdown)
mb@40
   376
                    self.startNotifications.remove(new_ip)
mb@36
   377
            VMManager.handleDeviceChangeLock.release()
mb@40
   378
            return new_ip
mb@12
   379
    
mb@12
   380
    def handleBrowsingRequest(self):
mb@46
   381
        if VMManager.handleDeviceChangeLock.acquire(True):
mb@46
   382
            new_ip = None
mb@46
   383
            new_sdvm = self.generateSDVMName()
mb@46
   384
            self.createVM(new_sdvm)
mb@46
   385
            self.genCertificateISO(new_sdvm)
mb@46
   386
            self.attachCertificateISO(new_sdvm)
mb@46
   387
            self.startVM(new_sdvm)
mb@46
   388
            # wait for machine to come up
mb@46
   389
            while new_ip == None:
mb@46
   390
                time.sleep(1)
mb@46
   391
                new_ip = self.getHostOnlyIP(new_sdvm)
mb@46
   392
            while new_ip not in self.startNotifications:
mb@46
   393
                time.sleep(1)
mb@46
   394
            if new_ip != None:
mb@46
   395
                self.mapNetworkDrive('g:', '\\\\' + new_ip + '\\Download', None, None)
mb@46
   396
            #TODO: cleanup notifications somwhere else (eg. machine shutdown)
mb@46
   397
            self.startNotifications.remove(new_ip)
mb@46
   398
            VMManager.handleDeviceChangeLock.release()
om@31
   399
        return new_sdvm
mb@7
   400
    
mb@7
   401
    # executes command over ssh on guest vm
mb@46
   402
    def sshGuestExecute(self, vm_name, prog, user_name='osecuser'):
mb@7
   403
        # get vm ip
mb@7
   404
        address = self.getHostOnlyIP(vm_name)
mb@7
   405
        machineFolder = self.getDefaultMachineFolder()
mb@7
   406
        # run command
dyle@53
   407
        cmd = self.cygwin_path+'bash.exe --login -c \"ssh -o StrictHostKeyChecking=no -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  ' + user_name + '@' + address + ' ' + prog + '\"'
mb@7
   408
        return self.execute(cmd)
mb@7
   409
    
mb@7
   410
    # executes command over ssh on guest vm with X forwarding
mb@46
   411
    def sshGuestX11Execute(self, vm_name, prog, user_name='osecuser'):
mb@7
   412
        #TODO: verify if X server is running on user account 
mb@7
   413
        #TODO: set DISPLAY accordingly
mb@7
   414
        address = self.getHostOnlyIP(vm_name)
mb@7
   415
        machineFolder = self.getDefaultMachineFolder()
mb@7
   416
        # run command
mb@46
   417
        #--login
mb@46
   418
        #cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -v -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  '  + user_name + '@' + address + ' ' + prog + '\"'
dyle@53
   419
        cmd = self.cygwin_path+'mintty.exe -e /bin/env DISPLAY=:0 /usr/bin/ssh -o StrictHostKeyChecking=no -v -Y -i \"' + machineFolder + '\\' + vm_name + '\\dvm_key\"  '  + user_name + '@' + address + ' ' + prog + ''
mb@46
   420
        #cmd = self.cygwin_path+'mintty.exe -e /bin/bash --login -c \"DISPLAY=:0 /usr/bin/ssh -v -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  '  + user_name + '@' + address + ' ' + prog + '\"'
mb@46
   421
        if DEBUG:
mb@46
   422
            print('trying to launch: ' + cmd)
mb@46
   423
        process = Popen(cmd)
mb@46
   424
        if DEBUG:
mb@46
   425
            print('launched: ' + cmd)
mb@46
   426
        return     
mb@7
   427
    
mb@40
   428
    #Small function to check the availability of network resource.
mb@40
   429
    def isAvailable(self, path):
mb@40
   430
        cmd = 'IF EXIST ' + path + ' echo YES'
mb@40
   431
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
mb@40
   432
        return string.find(str(result), 'YES',)
mb@40
   433
    
mb@40
   434
    #Small function to check if the mention location is a directory
mb@40
   435
    def isDirectory(self, path):
mb@40
   436
        cmd = 'dir ' + path + ' | FIND ".."'
mb@40
   437
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
mb@40
   438
        return string.find(str(result), 'DIR',)
mb@40
   439
mb@40
   440
    def mapNetworkDrive(self, drive, networkPath, user, password):
mb@40
   441
        self.unmapNetworkDrive('h:')
mb@40
   442
        #Check for drive availability
mb@40
   443
        if self.isAvailable(drive) > -1:
mb@40
   444
            print "Drive letter is already in use: ", drive
mb@40
   445
            return -1
mb@40
   446
        #Check for network resource availability
mb@40
   447
        while self.isAvailable(networkPath) == -1:
mb@40
   448
            time.sleep(1)
mb@40
   449
            print "Path not accessible: ", networkPath, " retrying"
mb@40
   450
            #return -1
mb@40
   451
    
mb@40
   452
        #Prepare 'NET USE' commands
mb@40
   453
        cmd = 'NET USE ' + drive + ' ' + networkPath
mb@40
   454
        if user != None:
mb@40
   455
            cmd = cmd + ' ' + password + ' /User' + user
mb@40
   456
    
mb@40
   457
        print "cmd = ", cmd
mb@40
   458
        #Execute 'NET USE' command with authentication
mb@40
   459
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
mb@40
   460
        print "Executed: ", cmd
mb@40
   461
        if string.find(str(result), 'successfully',) == -1:
mb@40
   462
            print cmd, " FAILED"
mb@40
   463
            return -1
mb@40
   464
        #Mapped with first try
mb@40
   465
        return 1
mb@40
   466
    
mb@40
   467
    def unmapNetworkDrive(self, drive):
mb@40
   468
        #Check if the drive is in use
mb@40
   469
        if self.isAvailable(drive) == -1:
mb@40
   470
            #Drive is not in use
mb@40
   471
            return -1
mb@40
   472
        #Prepare 'NET USE' command
mb@40
   473
        cmd = 'net use ' + drive + ' /DELETE'
mb@40
   474
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
mb@40
   475
        if string.find(str(result), 'successfully',) == -1:
mb@40
   476
            return -1
mb@40
   477
        return 1
mb@40
   478
mb@40
   479
if __name__ == '__main__':
mb@40
   480
    man = VMManager.getInstance()
mb@40
   481
    #man.removeVM('SecurityDVM0')
mb@40
   482
    #man.netUse('192.168.56.134', 'USB\\')
mb@46
   483
    #ip = '192.168.56.139'
mb@46
   484
    #man.mapNetworkDrive('h:', '\\\\' + ip + '\USB', None, None)
mb@33
   485
    #man.cygwin_path = 'c:\\cygwin64\\bin\\'
mb@7
   486
    #man.handleDeviceChange()
mb@7
   487
    #print man.listSDVM()
mb@11
   488
    #man.configureHostNetworking()
mb@33
   489
    #new_vm = man.generateSDVMName()
mb@33
   490
    #man.createVM(new_vm)
mb@33
   491
    #man.genCertificateISO(new_vm)
mb@33
   492
    #man.attachCertificateISO(new_vm)
mb@11
   493
    
mb@7
   494
    #man.attachCertificateISO(vm_name)
mb@7
   495
    #man.sshGuestExecute(vm_name, "ls")
mb@46
   496
    man.sshGuestX11Execute('SecurityDVM1', '/usr/bin/iceweasel')
mb@46
   497
    time.sleep(60)
mb@7
   498
    #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
mb@7
   499
    #man.execute(cmd)
dyle@52
   500