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