OpenSecurity/bin/vmmanager.pyw
author BarthaM@N3SIM1218.D03.arc.local
Mon, 19 May 2014 15:39:55 +0100
changeset 159 30947d377e7c
parent 151 d0f24f265331
child 162 c1c9ccd9d7c8
permissions -rwxr-xr-x
corrected concurent VM creation problem
mb@90
     1
'''
mb@90
     2
Created on Nov 19, 2013
mb@90
     3
mb@90
     4
@author: BarthaM
mb@90
     5
'''
mb@90
     6
import os
mb@90
     7
import os.path
mb@90
     8
from subprocess import Popen, PIPE, call, STARTUPINFO, _subprocess
mb@90
     9
import sys
mb@90
    10
import re
mb@90
    11
mb@90
    12
from cygwin import Cygwin
mb@90
    13
from environment import Environment
mb@90
    14
import threading
mb@90
    15
import time
mb@90
    16
import string
mb@90
    17
mb@90
    18
import shutil
mb@90
    19
import stat
mb@90
    20
import tempfile
mb@90
    21
from opensecurity_util import logger, setupLogger, OpenSecurityException
mb@90
    22
import ctypes
mb@90
    23
import itertools
BarthaM@143
    24
import win32api
BarthaM@143
    25
import win32con
BarthaM@143
    26
import win32security
BarthaM@151
    27
import urllib
BarthaM@151
    28
import urllib2
mb@90
    29
DEBUG = True
mb@90
    30
BarthaM@159
    31
BarthaM@159
    32
new_sdvm_lock = threading.Lock()
BarthaM@159
    33
mb@90
    34
class VMManagerException(Exception):
mb@90
    35
    def __init__(self, value):
mb@90
    36
        self.value = value
mb@90
    37
    def __str__(self):
mb@90
    38
        return repr(self.value)
mb@90
    39
mb@90
    40
class USBFilter:
mb@90
    41
    vendorid = ""
mb@90
    42
    productid = ""
mb@90
    43
    revision = ""
mb@90
    44
    
mb@90
    45
    def __init__(self, vendorid, productid, revision):
mb@90
    46
        self.vendorid = vendorid.lower()
mb@90
    47
        self.productid = productid.lower()
mb@90
    48
        self.revision = revision.lower()
mb@90
    49
        return
mb@90
    50
    
mb@90
    51
    def __eq__(self, other):
mb@90
    52
        return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
mb@90
    53
    
mb@90
    54
    def __hash__(self):
mb@90
    55
        return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
mb@90
    56
    
mb@90
    57
    def __repr__(self):
mb@90
    58
        return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
mb@90
    59
    
mb@90
    60
    #def __getitem__(self, item):
mb@90
    61
    #    return self.coords[item]
mb@90
    62
 
mb@90
    63
class VMManager(object):
mb@90
    64
    vmRootName = "SecurityDVM"
mb@90
    65
    systemProperties = None
mb@90
    66
    _instance = None
mb@90
    67
    machineFolder = ''
mb@90
    68
    rsdHandler = None
BarthaM@141
    69
    browsingManager = None
oliver@131
    70
    status_message = 'Starting up...'
oliver@131
    71
oliver@131
    72
 
oliver@131
    73
    def __init__(self):
oliver@131
    74
oliver@131
    75
        self.systemProperties = self.getSystemProperties()
oliver@133
    76
        self.machineFolder = self.systemProperties["Default machine folder"]
oliver@131
    77
oliver@131
    78
        # only proceed if we have a working background environment
oliver@131
    79
        if self.backend_ok():
oliver@131
    80
            self.cleanup()
BarthaM@159
    81
            self.browsingManager = BrowsingManager(self)
BarthaM@159
    82
            self.browsingManager.start()
oliver@131
    83
            self.rsdHandler = DeviceHandler(self)
oliver@131
    84
            self.rsdHandler.start()
oliver@131
    85
        else:
oliver@131
    86
            logger.critical(self.status_message)
mb@90
    87
    
oliver@131
    88
mb@90
    89
    @staticmethod
mb@90
    90
    def getInstance():
mb@90
    91
        if VMManager._instance == None:
mb@90
    92
            VMManager._instance = VMManager()
mb@90
    93
        return VMManager._instance
mb@90
    94
    
oliver@131
    95
oliver@131
    96
    def backend_ok(self):
oliver@131
    97
oliver@131
    98
        """check if the backend (VirtualBox) is sufficient for our task"""
oliver@131
    99
oliver@131
   100
        # ensure we have our system props
oliver@131
   101
        if self.systemProperties == None:
oliver@131
   102
            self.systemProperties = self.getSystemProperties()
oliver@131
   103
        if self.systemProperties == None:
oliver@131
   104
            self.status_message = 'Failed to get backend system properties. Is Backend (VirtualBox?) installed?'
oliver@131
   105
            return False
oliver@131
   106
oliver@131
   107
        # check for existing Extension pack
oliver@131
   108
        if not 'Remote desktop ExtPack' in self.systemProperties:
oliver@131
   109
            self.status_message = 'No remote desktop extension pack found. Please install the "Oracle VM VirtualBox Extension Pack" from https://www.virtualbox.org/wiki/Downloads.'
oliver@131
   110
            return False
oliver@131
   111
        if self.systemProperties['Remote desktop ExtPack'] == 'Oracle VM VirtualBox Extension Pack ':
oliver@131
   112
            self.status_message = 'Unsure if suitable extension pack is installed. Please install the "Oracle VM VirtualBox Extension Pack" from https://www.virtualbox.org/wiki/Downloads.'
oliver@131
   113
            return False
oliver@131
   114
oliver@131
   115
        # check if we do have our root VMs installed
oliver@131
   116
        vms = self.listVM()
oliver@131
   117
        if not self.vmRootName in vms:
oliver@131
   118
            self.status_message = 'Unable to locate root SecurityDVM. Please download and setup the initial image.'
oliver@131
   119
            return False
oliver@131
   120
oliver@131
   121
        # basically all seems nice and ready to rumble
oliver@131
   122
        self.status_message = 'All is ok.'
oliver@131
   123
oliver@131
   124
        return True
oliver@131
   125
oliver@131
   126
mb@90
   127
    def cleanup(self):
mb@90
   128
        if self.rsdHandler != None:
mb@90
   129
            self.rsdHandler.stop()
mb@90
   130
            self.rsdHandler.join()
mb@90
   131
        drives = self.getNetworkDrives()
mb@90
   132
        for drive in drives.keys():
BarthaM@151
   133
            result = urllib2.urlopen('http://127.0.0.1:8090/netumount?'+'drive_letter='+drive).readline()
BarthaM@151
   134
            
mb@90
   135
        for vm in self.listSDVM():
mb@90
   136
            self.poweroffVM(vm)
mb@90
   137
            self.removeVM(vm)
mb@90
   138
        
mb@90
   139
    # return hosty system properties
mb@90
   140
    def getSystemProperties(self):
BarthaM@151
   141
        result = Cygwin.checkResult(Cygwin.vboxExecute('list systemproperties'))
mb@90
   142
        if result[1]=='':
mb@90
   143
            return None
mb@90
   144
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
mb@90
   145
        return props
mb@90
   146
    
mb@90
   147
    # return the folder containing the guest VMs     
mb@90
   148
    def getMachineFolder(self):
mb@90
   149
        return self.machineFolder
mb@90
   150
mb@90
   151
    # list all existing VMs registered with VBox
mb@90
   152
    def listVM(self):
BarthaM@151
   153
        result = Cygwin.checkResult(Cygwin.vboxExecute('list vms'))[1]
mb@90
   154
        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
mb@90
   155
        return vms
mb@90
   156
    
mb@90
   157
    # list running VMs
mb@90
   158
    def listRunningVMS(self):
BarthaM@151
   159
        result = Cygwin.checkResult(Cygwin.vboxExecute('list runningvms'))[1]
mb@90
   160
        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
mb@90
   161
        return vms
mb@90
   162
    
mb@90
   163
    # list existing SDVMs
mb@90
   164
    def listSDVM(self):
mb@90
   165
        vms = self.listVM()
mb@90
   166
        svdms = []
mb@90
   167
        for vm in vms:
mb@90
   168
            if vm.startswith(self.vmRootName) and vm != self.vmRootName:
mb@90
   169
                svdms.append(vm)
mb@90
   170
        return svdms
mb@90
   171
    
mb@90
   172
    # generate valid (not already existing SDVM name). necessary for creating a new VM
BarthaM@159
   173
    def genSDVMName(self):
mb@90
   174
        vms = self.listVM()
mb@90
   175
        for i in range(0,999):
mb@90
   176
            if(not self.vmRootName+str(i) in vms):
mb@90
   177
                return self.vmRootName+str(i)
mb@90
   178
        return ''
mb@90
   179
    
mb@90
   180
    # check if the device is mass storage type
mb@90
   181
    @staticmethod
mb@90
   182
    def isMassStorageDevice(device):
mb@90
   183
        keyname = 'SYSTEM\CurrentControlSet\Enum\USB' + '\VID_' + device.vendorid+'&'+'PID_'+ device.productid
BarthaM@143
   184
        key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyname)
mb@90
   185
        #subkeys = _winreg.QueryInfoKey(key)[0]
mb@90
   186
        #for i in range(0, subkeys):
mb@90
   187
        #    print _winreg.EnumKey(key, i)     
BarthaM@143
   188
        devinfokeyname = win32api.RegEnumKey(key, 0)
BarthaM@143
   189
        win32api.RegCloseKey(key)
mb@90
   190
BarthaM@143
   191
        devinfokey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyname+'\\'+devinfokeyname)
BarthaM@143
   192
        value = win32api.RegQueryValueEx(devinfokey, 'SERVICE')[0]
BarthaM@143
   193
        win32api.RegCloseKey(devinfokey)
mb@90
   194
        
mb@90
   195
        return 'USBSTOR' in value
mb@90
   196
    
mb@90
   197
    # return the RSDs connected to the host
mb@90
   198
    @staticmethod
mb@90
   199
    def getConnectedRSDS():
BarthaM@151
   200
        results = Cygwin.checkResult(Cygwin.vboxExecute('list usbhost'))[1]
mb@90
   201
        results = results.split('Host USB Devices:')[1].strip()
mb@90
   202
        
mb@90
   203
        items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
mb@90
   204
        rsds = dict()   
mb@90
   205
        for item in items:
mb@90
   206
            props = dict()
mb@90
   207
            for line in item.splitlines():
mb@90
   208
                if line != "":         
mb@90
   209
                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
mb@90
   210
                    props[k] = v
mb@90
   211
            
mb@90
   212
            #if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
mb@90
   213
            
mb@90
   214
            usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], 
mb@90
   215
                                    re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
mb@90
   216
                                    re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
mb@90
   217
            if VMManager.isMassStorageDevice(usb_filter):
mb@90
   218
                rsds[props['UUID']] = usb_filter;
mb@90
   219
                logger.debug(usb_filter)
mb@90
   220
        return rsds
mb@90
   221
    
mb@90
   222
    # return the RSDs attached to all existing SDVMs
mb@90
   223
    def getAttachedRSDs(self):
mb@90
   224
        vms = self.listSDVM()
mb@90
   225
        attached_devices = dict()
mb@90
   226
        for vm in vms:
mb@90
   227
            rsd_filter = self.getUSBFilter(vm)
mb@90
   228
            if rsd_filter != None:
mb@90
   229
                attached_devices[vm] = rsd_filter
mb@90
   230
        return attached_devices
mb@90
   231
    
mb@90
   232
    # configures hostonly networking and DHCP server. requires admin rights
mb@90
   233
    def configureHostNetworking(self):
mb@90
   234
        #cmd = 'vboxmanage list hostonlyifs'
mb@90
   235
        #Cygwin.vboxExecute(cmd)
mb@90
   236
        #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
mb@90
   237
        #Cygwin.vboxExecute(cmd)
mb@90
   238
        #cmd = 'vboxmanage hostonlyif create'
mb@90
   239
        #Cygwin.vboxExecute(cmd)
BarthaM@151
   240
        Cygwin.checkResult(Cygwin.vboxExecute('hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'))
mb@90
   241
        #cmd = 'vboxmanage dhcpserver add'
mb@90
   242
        #Cygwin.vboxExecute(cmd)
BarthaM@151
   243
        Cygwin.checkResult(Cygwin.vboxExecute('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'))
mb@90
   244
    
BarthaM@125
   245
    def isSDVMExisting(self, vm_name):
BarthaM@125
   246
        sdvms = self.listSDVM()
BarthaM@125
   247
        return vm_name in sdvms
BarthaM@125
   248
        
mb@90
   249
    #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
mb@90
   250
    def createVM(self, vm_name):
BarthaM@125
   251
        if self.isSDVMExisting(vm_name):
BarthaM@125
   252
            return
BarthaM@125
   253
        #remove eventually existing SDVM folder
BarthaM@125
   254
        machineFolder = Cygwin.cygPath(self.machineFolder)
BarthaM@151
   255
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '\\\"'))
mb@90
   256
        hostonly_if = self.getHostOnlyIFs()
BarthaM@151
   257
        Cygwin.checkResult(Cygwin.vboxExecute('createvm --name ' + vm_name + ' --ostype Debian --register'))
BarthaM@151
   258
        Cygwin.checkResult(Cygwin.vboxExecute('modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat'))
BarthaM@151
   259
        Cygwin.checkResult(Cygwin.vboxExecute('storagectl ' + vm_name + ' --name SATA --add sata --portcount 2'))
BarthaM@159
   260
BarthaM@159
   261
    #create new SecurityDVM with automatically generated name from template (thread safe)        
BarthaM@159
   262
    def newSDVM(self):
BarthaM@159
   263
        with new_sdvm_lock:
BarthaM@159
   264
            vm_name = self.genSDVMName()
BarthaM@159
   265
            self.createVM(vm_name)
BarthaM@159
   266
        return vm_name
mb@90
   267
    
mb@90
   268
    # attach storage image to controller
mb@90
   269
    def storageAttach(self, vm_name):
mb@90
   270
        if self.isStorageAttached(vm_name):
mb@90
   271
            self.storageDetach(vm_name)
BarthaM@151
   272
        Cygwin.checkResult(Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium \"'+ self.machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'))
mb@90
   273
    
mb@90
   274
    # return true if storage is attached 
mb@90
   275
    def isStorageAttached(self, vm_name):
mb@90
   276
        info = self.getVMInfo(vm_name)
mb@90
   277
        return (info['SATA-0-0']!='none')
mb@90
   278
    
mb@90
   279
    # detach storage from controller
mb@90
   280
    def storageDetach(self, vm_name):
mb@90
   281
        if self.isStorageAttached(vm_name):
BarthaM@151
   282
            Cygwin.checkResult(Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium none'))
mb@90
   283
    
mb@90
   284
    def changeStorageType(self, filename, storage_type):
BarthaM@151
   285
        Cygwin.checkResult(Cygwin.vboxExecute('modifyhd \"' + filename + '\" --type ' + storage_type))
mb@90
   286
    
mb@90
   287
    # list storage snaphots for VM
mb@90
   288
    def updateTemplate(self):
mb@95
   289
mb@90
   290
        self.cleanup()
mb@90
   291
        self.poweroffVM('SecurityDVM')
mb@90
   292
        self.waitShutdown('SecurityDVM')
mb@90
   293
        
mb@90
   294
        # check for updates
mb@90
   295
        self.genCertificateISO('SecurityDVM')
mb@90
   296
        self.attachCertificateISO('SecurityDVM')
mb@90
   297
        
mb@90
   298
        self.storageDetach('SecurityDVM')
BarthaM@151
   299
        results = Cygwin.checkResult(Cygwin.vboxExecute('list hdds'))[1]
mb@90
   300
        results = results.replace('Parent UUID', 'Parent')
mb@90
   301
        items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
mb@90
   302
        
mb@90
   303
        snaps = dict()   
mb@90
   304
        for item in items:
mb@90
   305
            props = dict()
mb@90
   306
            for line in item.splitlines():
mb@90
   307
                if line != "":         
mb@90
   308
                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
mb@90
   309
                    props[k] = v;
mb@90
   310
            snaps[props['UUID']] = props
mb@90
   311
        
mb@90
   312
        
mb@90
   313
        template_storage = self.machineFolder + '\SecurityDVM\SecurityDVM.vmdk'
mb@90
   314
        
mb@90
   315
        # find template uuid
mb@90
   316
        template_uuid = ''
mb@90
   317
        for hdd in snaps.values():
mb@90
   318
            if hdd['Location'] == template_storage:
mb@90
   319
                template_uuid = hdd['UUID']
mb@90
   320
        logger.debug('found parent uuid ' + template_uuid)
mb@90
   321
        
mb@90
   322
        # remove snapshots 
mb@90
   323
        for hdd in snaps.values():
mb@90
   324
            if hdd['Parent'] == template_uuid:
mb@90
   325
                #template_uuid = hdd['UUID']
mb@90
   326
                logger.debug('removing snapshot ' + hdd['UUID'])
BarthaM@151
   327
                Cygwin.checkResult(Cygwin.vboxExecute('closemedium disk {' + hdd['UUID'] + '} --delete'))#[1]
mb@90
   328
                # parse result 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
mb@90
   329
        
mb@90
   330
        self.changeStorageType(template_storage,'normal')
mb@90
   331
        self.storageAttach('SecurityDVM')
mb@90
   332
        self.startVM('SecurityDVM')
mb@90
   333
        self.waitStartup('SecurityDVM')
BarthaM@151
   334
        Cygwin.checkResult(Cygwin.sshExecute('"sudo apt-get -y update"', VMManager.getHostOnlyIP('SecurityDVM'), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + 'SecurityDVM' + '/dvm_key'))
BarthaM@151
   335
        Cygwin.checkResult(Cygwin.sshExecute('"sudo apt-get -y upgrade"', VMManager.getHostOnlyIP('SecurityDVM'), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + 'SecurityDVM' + '/dvm_key'))
mb@90
   336
        #self.stopVM('SecurityDVM')
mb@90
   337
        self.hibernateVM('SecurityDVM')
mb@90
   338
        self.waitShutdown('SecurityDVM')
mb@90
   339
        self.storageDetach('SecurityDVM')
mb@90
   340
        self.changeStorageType(template_storage,'immutable')
mb@90
   341
        self.storageAttach('SecurityDVM')
mb@90
   342
        self.rsdHandler = DeviceHandler(self)
mb@90
   343
        self.rsdHandler.start()
mb@90
   344
    
mb@90
   345
    #remove VM from the system. should be used on VMs returned by listSDVMs    
mb@90
   346
    def removeVM(self, vm_name):
mb@90
   347
        logger.info('Removing ' + vm_name)
BarthaM@151
   348
        Cygwin.checkResult(Cygwin.vboxExecute('unregistervm ' + vm_name + ' --delete'))
mb@90
   349
        machineFolder = Cygwin.cygPath(self.machineFolder)
BarthaM@151
   350
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '\\\"'))
mb@90
   351
    
mb@90
   352
    # start VM
mb@90
   353
    def startVM(self, vm_name):
mb@90
   354
        logger.info('Starting ' +  vm_name)
BarthaM@151
   355
        result = Cygwin.checkResult(Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless' ))
mb@90
   356
        while 'successfully started' not in result[1]:
mb@90
   357
            logger.error("Failed to start SDVM: " + vm_name + " retrying")
oliver@129
   358
            logger.error("Command returned:\n" + result[2])
mb@90
   359
            time.sleep(1)
BarthaM@151
   360
            result = Cygwin.checkResult(Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless'))
mb@90
   361
        return result[0]
mb@90
   362
    
mb@90
   363
    # return wether VM is running or not
mb@90
   364
    def isVMRunning(self, vm_name):
mb@90
   365
        return vm_name in self.listRunningVMS()    
mb@90
   366
    
mb@90
   367
    # stop VM
mb@90
   368
    def stopVM(self, vm_name):
mb@90
   369
        logger.info('Sending shutdown signal to ' + vm_name)
BarthaM@151
   370
        Cygwin.checkResult(Cygwin.sshExecute( '"sudo shutdown -h now"', VMManager.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + vm_name + '/dvm_key' ))
mb@90
   371
    
mb@90
   372
    # stop VM
mb@90
   373
    def hibernateVM(self, vm_name):
mb@95
   374
        logger.info('Sending hibernate-disk signal to ' + vm_name)
BarthaM@151
   375
        Cygwin.checkResult(Cygwin.sshExecute( '"sudo hibernate-disk&"', VMManager.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + vm_name + '/dvm_key', wait_return=False))
mb@90
   376
            
mb@90
   377
    # poweroff VM
mb@90
   378
    def poweroffVM(self, vm_name):
mb@90
   379
        if not self.isVMRunning(vm_name):
mb@90
   380
            return
mb@90
   381
        logger.info('Powering off ' + vm_name)
BarthaM@151
   382
        return Cygwin.checkResult(Cygwin.vboxExecute('controlvm ' + vm_name + ' poweroff'))
mb@90
   383
    
mb@90
   384
    #list the hostonly IFs exposed by the VBox host
mb@90
   385
    @staticmethod    
mb@90
   386
    def getHostOnlyIFs():
mb@90
   387
        result = Cygwin.vboxExecute('list hostonlyifs')[1]
mb@90
   388
        if result=='':
mb@90
   389
            return None
mb@90
   390
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
mb@90
   391
        return props
mb@90
   392
    
mb@90
   393
    # return the hostOnly IP for a running guest or the host
mb@90
   394
    @staticmethod    
mb@90
   395
    def getHostOnlyIP(vm_name):
mb@90
   396
        if vm_name == None:
oliver@129
   397
            logger.info('Getting hostOnly IP address for Host')
mb@90
   398
            return VMManager.getHostOnlyIFs()['IPAddress']
mb@90
   399
        else:
oliver@129
   400
            logger.info('Getting hostOnly IP address ' + vm_name)
BarthaM@151
   401
            result = Cygwin.checkResult(Cygwin.vboxExecute('guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'))
mb@90
   402
            if result=='':
mb@90
   403
                return None
mb@90
   404
            result = result[1]
mb@90
   405
            if result.startswith('No value set!'):
mb@90
   406
                return None
mb@90
   407
            return result[result.index(':')+1:].strip()
mb@90
   408
            
mb@90
   409
    # attach removable storage device to VM by provision of filter
mb@90
   410
    def attachRSD(self, vm_name, rsd_filter):
BarthaM@151
   411
        return Cygwin.checkResult(Cygwin.vboxExecute('usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision))
mb@90
   412
    
mb@90
   413
    # detach removable storage from VM by 
mb@90
   414
    def detachRSD(self, vm_name):
BarthaM@151
   415
        return Cygwin.checkResult(Cygwin.vboxExecute('usbfilter remove 0 --target ' + vm_name))
mb@90
   416
        
mb@90
   417
    # return the description set for an existing VM
mb@90
   418
    def getVMInfo(self, vm_name):
BarthaM@151
   419
        results = Cygwin.checkResult(Cygwin.vboxExecute('showvminfo ' + vm_name + ' --machinereadable'))[1]
mb@90
   420
        props = dict((k.strip().strip('"'),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
mb@90
   421
        return props
mb@90
   422
    
mb@90
   423
    # return the configured USB filter for an existing VM 
mb@90
   424
    def getUSBFilter(self, vm_name):
mb@90
   425
        props = self.getVMInfo(vm_name)
mb@90
   426
        keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
mb@90
   427
        keyset = set(props.keys())
mb@90
   428
        usb_filter = None
mb@90
   429
        if keyset.issuperset(keys):
mb@90
   430
            usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
mb@90
   431
        return usb_filter
mb@90
   432
    
mb@90
   433
    #generates ISO containing authorized_keys for use with guest VM
mb@90
   434
    def genCertificateISO(self, vm_name):
mb@90
   435
        machineFolder = Cygwin.cygPath(self.machineFolder)
mb@90
   436
        # remove .ssh folder if exists
BarthaM@151
   437
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"'))
mb@90
   438
        # remove .ssh folder if exists
BarthaM@151
   439
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"'))
mb@90
   440
        # create .ssh folder in vm_name
BarthaM@151
   441
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/mkdir -p \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"'))
mb@90
   442
        # generate dvm_key pair in vm_name / .ssh     
BarthaM@151
   443
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/ssh-keygen -q -t rsa -N \\\"\\\" -C \\\"' + vm_name + '\\\" -f \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\"'))
mb@90
   444
        # move out private key
BarthaM@151
   445
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\" \\\"' + machineFolder + '/' + vm_name + '\\\"'))
mb@90
   446
        # set permissions for private key
BarthaM@151
   447
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"'))
mb@90
   448
        # rename public key to authorized_keys
BarthaM@151
   449
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key.pub\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"'))
mb@90
   450
        # set permissions for authorized_keys
BarthaM@151
   451
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"'))
mb@90
   452
        # generate iso image with .ssh/authorized keys
BarthaM@151
   453
        Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '/' + vm_name + '/'+ vm_name + '.iso\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"'))
mb@90
   454
    
mb@90
   455
    # attaches generated ssh public cert to guest vm
mb@90
   456
    def attachCertificateISO(self, vm_name):
BarthaM@151
   457
        result = Cygwin.checkResult(Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + self.machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'))
mb@90
   458
        return result
mb@90
   459
    
mb@90
   460
    # wait for machine to come up
mb@90
   461
    def waitStartup(self, vm_name, timeout_ms = 30000):
BarthaM@151
   462
        Cygwin.checkResult(Cygwin.vboxExecute('guestproperty wait ' + vm_name + ' SDVMStarted --timeout ' + str(timeout_ms) + ' --fail-on-timeout'))
mb@90
   463
        return VMManager.getHostOnlyIP(vm_name)
mb@90
   464
    
mb@90
   465
    # wait for machine to shutdown
mb@90
   466
    def waitShutdown(self, vm_name):
mb@90
   467
        while vm_name in self.listRunningVMS():
mb@90
   468
            time.sleep(1)
mb@90
   469
        return
mb@90
   470
    
BarthaM@135
   471
    #Small function to check if the mentioned location is a directory
mb@90
   472
    def isDirectory(self, path):
BarthaM@151
   473
        result = Cygwin.checkResult(Cygwin.cmdExecute('dir ' + path + ' | FIND ".."'))
mb@90
   474
        return string.find(result[1], 'DIR',)
mb@90
   475
    
mb@90
   476
    def getNetworkDrives(self):
mb@90
   477
        ip = VMManager.getHostOnlyIP(None)
mb@90
   478
        ip = ip[:ip.rindex('.')]
mb@90
   479
        drives = dict()    
BarthaM@151
   480
        result = Cygwin.checkResult(Cygwin.execute('C:\\Windows\\system32\\net.exe', 'USE'))
mb@90
   481
        for line in result[1].splitlines():
mb@90
   482
            if ip in line:
mb@90
   483
                parts = line.split()
mb@90
   484
                drives[parts[1]] = parts[2]
mb@90
   485
        return drives
mb@90
   486
            
mb@90
   487
    def genNetworkDrive(self):
mb@90
   488
        network_drives = self.getNetworkDrives()
mb@90
   489
        logical_drives = VMManager.getLogicalDrives()
mb@90
   490
        drives = list(map(chr, range(68, 91)))  
mb@90
   491
        for drive in drives:
mb@90
   492
            if drive+':' not in network_drives and drive not in logical_drives:
mb@90
   493
                return drive+':'
mb@90
   494
mb@90
   495
    def getNetworkDrive(self, vm_name):
mb@90
   496
        ip = self.getHostOnlyIP(vm_name)
BarthaM@151
   497
        result = Cygwin.checkResult(Cygwin.execute('C:\\Windows\\system32\\net.exe', 'USE'))
mb@90
   498
        for line in result[1].splitlines():
mb@90
   499
            if line != None and ip in line:
mb@90
   500
                parts = line.split()
BarthaM@135
   501
                return parts[1]
BarthaM@151
   502
            
mb@90
   503
    @staticmethod
mb@90
   504
    def getLogicalDrives():
mb@90
   505
        drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
mb@90
   506
        return list(itertools.compress(string.ascii_uppercase,  map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
mb@90
   507
    
mb@90
   508
    @staticmethod
mb@90
   509
    def getDriveType(drive):
mb@90
   510
        return ctypes.cdll.kernel32.GetDriveTypeW(u"%s:\\"%drive)
mb@90
   511
    
mb@90
   512
    @staticmethod
mb@90
   513
    def getVolumeInfo(drive):
mb@90
   514
        volumeNameBuffer = ctypes.create_unicode_buffer(1024)
mb@90
   515
        fileSystemNameBuffer = ctypes.create_unicode_buffer(1024)
mb@90
   516
        serial_number = None
mb@90
   517
        max_component_length = None
mb@90
   518
        file_system_flags = None
mb@90
   519
        
mb@90
   520
        rc = ctypes.cdll.kernel32.GetVolumeInformationW(
mb@90
   521
            #ctypes.c_wchar_p("F:\\"),
mb@90
   522
            u"%s:\\"%drive,
mb@90
   523
            volumeNameBuffer,
mb@90
   524
            ctypes.sizeof(volumeNameBuffer),
mb@90
   525
            serial_number,
mb@90
   526
            max_component_length,
mb@90
   527
            file_system_flags,
mb@90
   528
            fileSystemNameBuffer,
mb@90
   529
            ctypes.sizeof(fileSystemNameBuffer)
mb@90
   530
        )
mb@90
   531
        
mb@90
   532
        return volumeNameBuffer.value, fileSystemNameBuffer.value
BarthaM@141
   533
    
BarthaM@141
   534
    # handles browsing request    
BarthaM@141
   535
    def handleBrowsingRequest(self):
BarthaM@141
   536
        handler = BrowsingHandler(self)
BarthaM@141
   537
        handler.start()
BarthaM@141
   538
        return 'ok'
BarthaM@143
   539
    
BarthaM@143
   540
    def getActiveUserName(self):
BarthaM@143
   541
        key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI')
BarthaM@143
   542
        v = str(win32api.RegQueryValueEx(key, 'LastLoggedOnUser')[0])
BarthaM@143
   543
        win32api.RegCloseKey(key)
BarthaM@143
   544
        user_name = win32api.ExpandEnvironmentStrings(v)
BarthaM@143
   545
        return user_name
BarthaM@143
   546
        
BarthaM@143
   547
    def getUserSID(self, user_name):
BarthaM@143
   548
        account_name = win32security.LookupAccountName(None, user_name)
BarthaM@143
   549
        sid = win32security.ConvertSidToStringSid(account_name[0])
BarthaM@143
   550
        return sid
BarthaM@143
   551
        
BarthaM@143
   552
    def getAppDataDir(self, sid):    
BarthaM@143
   553
        key = win32api.RegOpenKey(win32con.HKEY_USERS, sid + '\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
BarthaM@143
   554
        value, type = win32api.RegQueryValueEx(key, "AppData")
BarthaM@143
   555
        win32api.RegCloseKey(key)
BarthaM@143
   556
        return value
BarthaM@143
   557
        
BarthaM@143
   558
        #key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' + '\\' + sid)
BarthaM@143
   559
        #value, type = win32api.RegQueryValueEx(key, "ProfileImagePath")
BarthaM@143
   560
        #print value
BarthaM@143
   561
    
BarthaM@143
   562
    def backupFile(self, src, dest):
BarthaM@143
   563
        certificate = Cygwin.cygPath(self.getMachineFolder()) + '/' + self.browsingManager.vm_name + '/dvm_key'
BarthaM@143
   564
        command = '-r -o StrictHostKeyChecking=no -i "' + certificate + '" "osecuser@' + self.browsingManager.ip_addr + ':' + src + '" "' + dest + '"'
BarthaM@143
   565
        return Cygwin.execute(Cygwin.cygwin_scp, command, wait_return=True, window=False)
BarthaM@143
   566
    
BarthaM@143
   567
    def restoreFile(self, src, dest):
BarthaM@143
   568
        certificate = Cygwin.cygPath(self.getMachineFolder()) + '/' + self.browsingManager.vm_name + '/dvm_key'
BarthaM@143
   569
        #command = '-r -v -o StrictHostKeyChecking=no -i \"' + certificate + '\" \"' + src + '\" \"osecuser@' + self.browsingManager.ip_addr + ':' + dest + '\"'
BarthaM@143
   570
        command = '-r -o StrictHostKeyChecking=no -i "' + certificate + '" "' + src + '" "osecuser@' + self.browsingManager.ip_addr + ':' + dest + '"'
BarthaM@143
   571
        return Cygwin.execute(Cygwin.cygwin_scp, command, wait_return=True, window=False)    
mb@90
   572
BarthaM@141
   573
BarthaM@141
   574
#handles browsing session creation 
BarthaM@141
   575
class BrowsingHandler(threading.Thread):
mb@90
   576
    vmm = None
BarthaM@141
   577
    def __init__(self, vmmanager):
BarthaM@141
   578
         threading.Thread.__init__(self)
BarthaM@141
   579
         self.vmm = vmmanager
BarthaM@141
   580
        
BarthaM@141
   581
    def run(self):
BarthaM@141
   582
        browser = '\\\"/usr/bin/chromium; pidof dbus-launch | xargs kill\\\"'
BarthaM@141
   583
        if Cygwin.is_X11_running()==False:
BarthaM@141
   584
            Cygwin.start_X11()
BarthaM@141
   585
        try:
BarthaM@143
   586
            self.vmm.browsingManager.started.wait() 
BarthaM@151
   587
            result = Cygwin.checkResult(Cygwin.sshExecuteX11(browser, self.vmm.browsingManager.ip_addr, 'osecuser', Cygwin.cygPath(self.vmm.getMachineFolder()) + '/' + self.vmm.browsingManager.vm_name + '/dvm_key'))
BarthaM@143
   588
            #backup settings on vm
BarthaM@141
   589
        except:
BarthaM@141
   590
            logger.error("BrowsingHandler closing. Cleaning up")    
BarthaM@143
   591
        self.vmm.backupFile('/home/osecuser/.config/chromium', self.vmm.browsingManager.appDataDir + '/OpenSecurity/')
BarthaM@141
   592
        self.vmm.browsingManager.restart.set()
BarthaM@141
   593
        
BarthaM@141
   594
            
BarthaM@141
   595
# handles browsing Vm creation and destruction                    
BarthaM@141
   596
class BrowsingManager(threading.Thread):   
BarthaM@141
   597
    vmm = None
BarthaM@141
   598
    running = True
BarthaM@141
   599
    restart = None
BarthaM@141
   600
    ip_addr = None
BarthaM@141
   601
    vm_name = None
BarthaM@141
   602
    drive = None
BarthaM@143
   603
    appDataDir = None
BarthaM@141
   604
    
mb@90
   605
    def __init__(self, vmmanager):
mb@90
   606
        threading.Thread.__init__(self)
mb@90
   607
        self.vmm = vmmanager
BarthaM@141
   608
        self.restart = threading.Event()
BarthaM@141
   609
        self.started = threading.Event()
BarthaM@141
   610
        
mb@90
   611
     
mb@90
   612
    def run(self):
BarthaM@141
   613
        while self.running:
BarthaM@141
   614
            self.restart.clear()
BarthaM@141
   615
            self.started.clear()
BarthaM@141
   616
            if self.drive != None:     
BarthaM@151
   617
                browsing_vm = urllib2.urlopen('http://127.0.0.1:8090/netumount?'+'drive_letter='+self.drive).readline()
BarthaM@141
   618
                self.drive = None
BarthaM@135
   619
            
BarthaM@141
   620
            self.ip_addr = None
BarthaM@141
   621
            
BarthaM@141
   622
            if self.vm_name != None:
BarthaM@141
   623
                self.vmm.poweroffVM(self.vm_name)
BarthaM@141
   624
                self.vmm.removeVM(self.vm_name)
BarthaM@141
   625
            
BarthaM@141
   626
            try:
BarthaM@159
   627
                self.vm_name = self.vmm.newSDVM()
BarthaM@141
   628
                self.vmm.storageAttach(self.vm_name)
BarthaM@141
   629
                self.vmm.genCertificateISO(self.vm_name)
BarthaM@141
   630
                self.vmm.attachCertificateISO(self.vm_name)
BarthaM@141
   631
                self.vmm.startVM(self.vm_name)
BarthaM@141
   632
                self.ip_addr = self.vmm.waitStartup(self.vm_name)
BarthaM@141
   633
                if self.ip_addr == None:
BarthaM@141
   634
                    continue
BarthaM@141
   635
                self.drive = self.vmm.genNetworkDrive()
BarthaM@141
   636
                if self.drive == None:
BarthaM@141
   637
                    continue
BarthaM@151
   638
                
BarthaM@151
   639
                net_resource = '\\\\' + self.ip_addr + '\\Download'
BarthaM@151
   640
                result = urllib2.urlopen('http://127.0.0.1:8090/netmount?'+'drive_letter='+self.drive+'&net_resource='+net_resource).readline()
BarthaM@151
   641
                
BarthaM@141
   642
                self.started.set()
BarthaM@143
   643
                
BarthaM@143
   644
                user = self.vmm.getActiveUserName()
BarthaM@143
   645
                sid = self.vmm.getUserSID(user)
BarthaM@143
   646
                path = self.vmm.getAppDataDir(sid)
BarthaM@143
   647
                self.appDataDir = Cygwin.cygPath(path)
BarthaM@149
   648
                # create OpenSecurity settings dir on local machine user home /AppData/Roaming 
BarthaM@151
   649
                Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/mkdir -p \\\"' + self.appDataDir + '/OpenSecurity\\\"'))
BarthaM@143
   650
                # create chromium settings dir on local machine if not existing
BarthaM@151
   651
                Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/mkdir -p \\\"' + self.appDataDir + '/OpenSecurity/chromium\\\"'))
BarthaM@143
   652
                # create chromium settings dir on remote machine if not existing
BarthaM@151
   653
                Cygwin.checkResult(Cygwin.sshExecute('"mkdir -p \\\"/home/osecuser/.config\\\""', self.ip_addr, 'osecuser', Cygwin.cygPath(self.vmm.getMachineFolder()) + '/' + self.vm_name + '/dvm_key'))
BarthaM@143
   654
                #restore settings on vm
BarthaM@143
   655
                self.vmm.restoreFile(self.appDataDir + '/OpenSecurity/chromium', '/home/osecuser/.config/')
BarthaM@141
   656
                self.restart.wait()
BarthaM@141
   657
            except:
BarthaM@141
   658
                logger.error("BrowsingHandler failed. Cleaning up")
mb@90
   659
                
mb@90
   660
class DeviceHandler(threading.Thread): 
mb@90
   661
    vmm = None
mb@90
   662
    attachedRSDs = None  
mb@90
   663
    connectedRSDs = None
mb@90
   664
    running = True
mb@90
   665
    def __init__(self, vmmanger): 
mb@90
   666
        threading.Thread.__init__(self)
mb@90
   667
        self.vmm = vmmanger
mb@90
   668
 
mb@90
   669
    def stop(self):
mb@90
   670
        self.running = False
mb@90
   671
        
mb@90
   672
    def run(self):
mb@90
   673
        self.connectedRSDs = dict()
BarthaM@135
   674
        
mb@90
   675
        while self.running:
mb@90
   676
            tmp_rsds = self.vmm.getConnectedRSDS()
mb@95
   677
            
mb@95
   678
            self.attachedRSDs = self.vmm.getAttachedRSDs()
mb@95
   679
            for vm_name in self.attachedRSDs.keys():
mb@95
   680
                if self.attachedRSDs[vm_name] not in tmp_rsds.values():
mb@95
   681
                    drive = self.vmm.getNetworkDrive(vm_name)
mb@95
   682
                    #self.stopVM(vm_name)
mb@95
   683
                    self.vmm.detachRSD(vm_name)
mb@95
   684
                    self.vmm.poweroffVM(vm_name)
mb@95
   685
                    self.vmm.removeVM(vm_name)
BarthaM@135
   686
                    if drive != None:
BarthaM@151
   687
                        result = urllib2.urlopen('http://127.0.0.1:8090/netumount?'+'drive_letter='+drive).readline()
mb@95
   688
                    break
mb@95
   689
                    
mb@95
   690
                    
mb@90
   691
            if tmp_rsds.keys() == self.connectedRSDs.keys():
mb@90
   692
                logger.debug("Nothing's changed. sleep(3)")
mb@90
   693
                time.sleep(3)
mb@90
   694
                continue
mb@90
   695
            
mb@90
   696
            logger.info("Something's changed")          
mb@90
   697
            self.connectedRSDs = tmp_rsds
BarthaM@135
   698
           
mb@90
   699
            #create new vm for attached device if any
mb@90
   700
            self.attachedRSDs = self.vmm.getAttachedRSDs()
mb@90
   701
            self.connectedRSDs = self.vmm.getConnectedRSDS()
mb@90
   702
            
mb@90
   703
            new_ip = None
mb@90
   704
            for connected_device in self.connectedRSDs.values():
mb@90
   705
                if (self.attachedRSDs and False) or (connected_device not in self.attachedRSDs.values()):
BarthaM@159
   706
                    new_sdvm = self.vmm.newSDVM()
mb@90
   707
                    self.vmm.storageAttach(new_sdvm)
mb@90
   708
                    self.vmm.attachRSD(new_sdvm, connected_device)
mb@90
   709
                    self.vmm.startVM(new_sdvm)
mb@90
   710
                    new_ip = self.vmm.waitStartup(new_sdvm)
mb@90
   711
                    drive = self.vmm.genNetworkDrive()
mb@90
   712
                    if new_ip != None:
BarthaM@151
   713
                        net_resource = '\\\\' + new_ip + '\\USB'
BarthaM@151
   714
                        result = urllib2.urlopen('http://127.0.0.1:8090/netmount?'+'drive_letter='+drive+'&net_resource='+net_resource).readline()
BarthaM@151
   715
                        
mb@90
   716
mb@90
   717
if __name__ == '__main__':
mb@90
   718
    #man = VMManager.getInstance()
mb@90
   719
    #man.listVM()
mb@90
   720
    #print man.getConnectedRSDs()
mb@90
   721
    #print man.getNetworkDrives()
mb@90
   722
    #man.genNetworkDrive()
mb@90
   723
    #drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
mb@90
   724
    #print list(itertools.compress(string.ascii_uppercase,  map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
mb@90
   725
    #print list(map(chr, range(68, 91))) 
mb@90
   726
    #print Cygwin.getRegEntry('SYSTEM\CurrentControlSet\Enum\USB', 'VID_1058&PID_0704')[0]
mb@90
   727
    #devices = VMManager.getConnectedRSDS()
mb@90
   728
    #print devices
mb@90
   729
    
mb@90
   730
    drives = VMManager.getLogicalDrives()
mb@90
   731
    print drives
mb@90
   732
    print VMManager.getDriveType("E")
mb@90
   733
    print VMManager.getVolumeInfo("E")
BarthaM@143
   734
    
BarthaM@143
   735
    #vmm.backupFile()
mb@90
   736
    #for device in devices.values():
mb@90
   737
    #    #print device
mb@90
   738
    #    if VMManager.isMassStorageDevice(device):
mb@90
   739
    #        print device
mb@90
   740
        
mb@90
   741
    
mb@90
   742
    
mb@90
   743
    #time.sleep(-1)
mb@90
   744
    #man.listVM()
mb@90
   745
    #man.listVM()
mb@90
   746
    #man.listVM()
mb@90
   747
    #man.listVM()
mb@90
   748
    #man.genCertificateISO('SecurityDVM0')
mb@90
   749
    #man.guestExecute('SecurityDVM0', '/bin/ls -la')
mb@90
   750
    #logger = setupLogger('VMManager')
mb@90
   751
    #c = Cygwin()
mb@90
   752
    
mb@90
   753
    #man.sshExecute('/bin/ls -la', 'SecurityDVM0')
mb@90
   754
    #man.sshExecuteX11('/usr/bin/iceweasel', 'SecurityDVM0')
mb@90
   755
    #man.removeVM('SecurityDVM0')
mb@90
   756
    #man.netUse('192.168.56.134', 'USB\\')
mb@90
   757
    #ip = '192.168.56.139'
mb@90
   758
    
mb@90
   759
    #man.cygwin_path = 'c:\\cygwin64\\bin\\'
mb@90
   760
    #man.handleDeviceChange()
mb@90
   761
    #print man.listSDVM()
mb@90
   762
    #man.configureHostNetworking()
mb@90
   763
    #new_vm = man.generateSDVMName()
mb@90
   764
    #man.createVM(new_vm)
mb@90
   765
    
mb@90
   766
    #print Cygwin.cmd()
mb@90
   767
    #man.isAvailable('c:')
mb@90
   768
    #ip = man.getHostOnlyIP('SecurityDVM0')
mb@90
   769
    #man.mapNetworkDrive('h:', '\\\\' + ip + '\Download', None, None)
mb@90
   770
    
mb@90
   771
    #man.genCertificateISO(new_vm)
mb@90
   772
    #man.attachCertificateISO(new_vm)
mb@90
   773
    
mb@90
   774
    #man.attachCertificateISO(vm_name)
mb@90
   775
    #man.guestExecute(vm_name, "ls")
mb@90
   776
    #man.sshGuestX11Execute('SecurityDVM1', '/usr/bin/iceweasel')
mb@90
   777
    #time.sleep(60)
mb@90
   778
    #print man.cygwinPath("C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\.ssh\*")
mb@90
   779
    #man.genCertificateISO('SecurityDVM')
mb@90
   780
    #man.attachCertificateISO('SecurityDVM')
mb@90
   781
    #man.isStorageAttached('SecurityDVM')
mb@90
   782
    #man.guestExecute('SecurityDVM', 'sudo apt-get -y update')
mb@90
   783
    #man.guestExecute('SecurityDVM', 'sudo apt-get -y upgrade' )
mb@90
   784
    
mb@90
   785
    #man.stopVM('SecurityDVM')
mb@90
   786
    #man.storageDetach('SecurityDVM')
mb@90
   787
    #man.changeStorageType('C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\SecurityDVM.vmdk','immutable')
mb@90
   788
    #man.storageAttach('SecurityDVM')
mb@90
   789
    
mb@90
   790
    
mb@90
   791
    #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
mb@90
   792
    #man.execute(cmd)