OpenSecurity/bin/vmmanager.pyw
author mb
Thu, 27 Feb 2014 11:39:37 +0100
changeset 81 84663db906d7
parent 79 617009c32da0
child 87 d5b04809faca
permissions -rwxr-xr-x
corrected forgotten notification remove call
mb@63
     1
'''
mb@63
     2
Created on Nov 19, 2013
mb@63
     3
mb@63
     4
@author: BarthaM
mb@63
     5
'''
mb@63
     6
import os
mb@63
     7
import os.path
mb@63
     8
from subprocess import Popen, PIPE, call, STARTUPINFO, _subprocess
mb@63
     9
import sys
mb@63
    10
import re
mb@63
    11
mb@63
    12
from cygwin import Cygwin
mb@63
    13
from environment import Environment
mb@63
    14
import threading
mb@63
    15
import time
mb@63
    16
import string
mb@63
    17
mb@63
    18
import shutil
mb@63
    19
import stat
mb@63
    20
import tempfile
mb@63
    21
from opensecurity_util import logger, setupLogger, OpenSecurityException
mb@79
    22
import ctypes
mb@79
    23
import itertools
mb@63
    24
DEBUG = True
mb@63
    25
mb@63
    26
class VMManagerException(Exception):
mb@63
    27
    def __init__(self, value):
mb@63
    28
        self.value = value
mb@63
    29
    def __str__(self):
mb@63
    30
        return repr(self.value)
mb@63
    31
mb@63
    32
class USBFilter:
mb@63
    33
    vendorid = ""
mb@63
    34
    productid = ""
mb@63
    35
    revision = ""
mb@63
    36
    
mb@63
    37
    def __init__(self, vendorid, productid, revision):
mb@63
    38
        self.vendorid = vendorid.lower()
mb@63
    39
        self.productid = productid.lower()
mb@63
    40
        self.revision = revision.lower()
mb@63
    41
        return
mb@63
    42
    
mb@63
    43
    def __eq__(self, other):
mb@63
    44
        return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
mb@63
    45
    
mb@63
    46
    def __hash__(self):
mb@63
    47
        return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
mb@63
    48
    
mb@63
    49
    def __repr__(self):
mb@63
    50
        return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
mb@63
    51
 
mb@63
    52
class VMManager(object):
mb@63
    53
    vmRootName = "SecurityDVM"
mb@63
    54
    systemProperties = None
mb@63
    55
    _instance = None
mb@63
    56
    machineFolder = ''
mb@79
    57
    rsdHandler = None
mb@63
    58
    
mb@63
    59
    def __init__(self):
mb@63
    60
        self.systemProperties = self.getSystemProperties()
mb@63
    61
        self.machineFolder = self.systemProperties["Default machine folder"]
mb@63
    62
        self.cleanup()
mb@79
    63
        self.rsdHandler = DeviceHandler(self)
mb@79
    64
        self.rsdHandler.start()
mb@63
    65
        return
mb@63
    66
    
mb@63
    67
    @staticmethod
mb@63
    68
    def getInstance():
mb@63
    69
        if VMManager._instance == None:
mb@63
    70
            VMManager._instance = VMManager()
mb@63
    71
        return VMManager._instance
mb@63
    72
    
mb@63
    73
    def cleanup(self):
mb@79
    74
        if self.rsdHandler != None:
mb@79
    75
            self.rsdHandler.stop()
mb@79
    76
            self.rsdHandler.join()
mb@79
    77
        drives = self.getNetworkDrives()
mb@79
    78
        for drive in drives.keys():
mb@79
    79
            self.unmapNetworkDrive(drive)
mb@63
    80
        for vm in self.listSDVM():
mb@63
    81
            self.poweroffVM(vm)
mb@63
    82
            self.removeVM(vm)
mb@63
    83
        
mb@63
    84
    # return hosty system properties
mb@63
    85
    def getSystemProperties(self):
mb@63
    86
        result = Cygwin.vboxExecute('list systemproperties')
mb@63
    87
        if result[1]=='':
mb@63
    88
            return None
mb@63
    89
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
mb@78
    90
        #logger.debug(props)
mb@63
    91
        return props
mb@63
    92
    
mb@63
    93
    # return the folder containing the guest VMs     
mb@63
    94
    def getMachineFolder(self):
mb@63
    95
        return self.machineFolder
mb@63
    96
mb@63
    97
    # list all existing VMs registered with VBox
mb@63
    98
    def listVM(self):
mb@63
    99
        result = Cygwin.vboxExecute('list vms')[1]
mb@63
   100
        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
mb@63
   101
        return vms
mb@63
   102
    
mb@63
   103
    # list running VMs
mb@63
   104
    def listRunningVMS(self):
mb@63
   105
        result = Cygwin.vboxExecute('list runningvms')[1]
mb@63
   106
        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
mb@63
   107
        return vms
mb@63
   108
    
mb@63
   109
    # list existing SDVMs
mb@63
   110
    def listSDVM(self):
mb@63
   111
        vms = self.listVM()
mb@63
   112
        svdms = []
mb@63
   113
        for vm in vms:
mb@63
   114
            if vm.startswith(self.vmRootName) and vm != self.vmRootName:
mb@63
   115
                svdms.append(vm)
mb@63
   116
        return svdms
mb@63
   117
    
mb@63
   118
    # generate valid (not already existing SDVM name). necessary for creating a new VM
mb@63
   119
    def generateSDVMName(self):
mb@63
   120
        vms = self.listVM()
mb@63
   121
        for i in range(0,999):
mb@63
   122
            if(not self.vmRootName+str(i) in vms):
mb@63
   123
                return self.vmRootName+str(i)
mb@63
   124
        return ''
mb@63
   125
    
mb@78
   126
    # return the RSDs connected to the host
mb@78
   127
    def getConnectedRSDS(self):
mb@78
   128
        results = Cygwin.vboxExecute('list usbhost')[1]
mb@78
   129
        results = results.split('Host USB Devices:')[1].strip()
mb@78
   130
        
mb@78
   131
        items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
mb@78
   132
        rsds = dict()   
mb@78
   133
        for item in items:
mb@78
   134
            props = dict()
mb@78
   135
            for line in item.splitlines():
mb@78
   136
                if line != "":         
mb@78
   137
                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
mb@78
   138
                    props[k] = v
mb@78
   139
            
mb@78
   140
            if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
mb@78
   141
                usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], 
mb@78
   142
                                        re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
mb@78
   143
                                        re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
mb@78
   144
                rsds[props['UUID']] = usb_filter;
mb@78
   145
                logger.debug(usb_filter)
mb@78
   146
        return rsds
mb@78
   147
    
mb@63
   148
    # return the RSDs attached to all existing SDVMs
mb@63
   149
    def getAttachedRSDs(self):
mb@63
   150
        vms = self.listSDVM()
mb@63
   151
        attached_devices = dict()
mb@63
   152
        for vm in vms:
mb@63
   153
            rsd_filter = self.getUSBFilter(vm)
mb@63
   154
            if rsd_filter != None:
mb@63
   155
                attached_devices[vm] = rsd_filter
mb@63
   156
        return attached_devices
mb@63
   157
    
mb@63
   158
    # configures hostonly networking and DHCP server. requires admin rights
mb@63
   159
    def configureHostNetworking(self):
mb@63
   160
        #cmd = 'vboxmanage list hostonlyifs'
mb@63
   161
        #Cygwin.vboxExecute(cmd)
mb@63
   162
        #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
mb@63
   163
        #Cygwin.vboxExecute(cmd)
mb@63
   164
        #cmd = 'vboxmanage hostonlyif create'
mb@63
   165
        #Cygwin.vboxExecute(cmd)
mb@63
   166
        Cygwin.vboxExecute('hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0')
mb@63
   167
        #cmd = 'vboxmanage dhcpserver add'
mb@63
   168
        #Cygwin.vboxExecute(cmd)
mb@63
   169
        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@63
   170
    
mb@63
   171
    #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
mb@63
   172
    def createVM(self, vm_name):
mb@63
   173
        hostonly_if = self.getHostOnlyIFs()
mb@63
   174
        Cygwin.vboxExecute('createvm --name ' + vm_name + ' --ostype Debian --register')
mb@63
   175
        Cygwin.vboxExecute('modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat')
mb@63
   176
        Cygwin.vboxExecute('storagectl ' + vm_name + ' --name SATA --add sata --portcount 2')
mb@63
   177
        return
mb@63
   178
    
mb@63
   179
    # attach storage image to controller
mb@63
   180
    def storageAttach(self, vm_name):
mb@63
   181
        if self.isStorageAttached(vm_name):
mb@63
   182
            self.storageDetach(vm_name)
mb@63
   183
        Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium \"'+ self.machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"')
mb@63
   184
        return
mb@63
   185
    
mb@63
   186
    # return true if storage is attached 
mb@63
   187
    def isStorageAttached(self, vm_name):
mb@63
   188
        info = self.getVMInfo(vm_name)
mb@63
   189
        return (info['SATA-0-0']!='none')
mb@63
   190
    
mb@63
   191
    # detach storage from controller
mb@63
   192
    def storageDetach(self, vm_name):
mb@63
   193
        if self.isStorageAttached(vm_name):
mb@63
   194
            Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium none')
mb@63
   195
        return
mb@63
   196
    
mb@63
   197
    def changeStorageType(self, filename, storage_type):
mb@63
   198
        Cygwin.vboxExecute('modifyhd \"' + filename + '\" --type ' + storage_type)
mb@63
   199
        return
mb@63
   200
    
mb@63
   201
    # list storage snaphots for VM
mb@63
   202
    def updateTemplate(self):
mb@78
   203
        self.cleanup()
mb@63
   204
        self.poweroffVM('SecurityDVM')
mb@63
   205
        self.waitShutdown('SecurityDVM')
mb@63
   206
        
mb@63
   207
        # check for updates
mb@63
   208
        self.genCertificateISO('SecurityDVM')
mb@63
   209
        self.attachCertificateISO('SecurityDVM')
mb@63
   210
        
mb@63
   211
        self.storageDetach('SecurityDVM')
mb@63
   212
        results = Cygwin.vboxExecute('list hdds')[1]
mb@63
   213
        results = results.replace('Parent UUID', 'Parent')
mb@63
   214
        items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
mb@63
   215
        
mb@63
   216
        snaps = dict()   
mb@63
   217
        for item in items:
mb@63
   218
            props = dict()
mb@63
   219
            for line in item.splitlines():
mb@63
   220
                if line != "":         
mb@63
   221
                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
mb@63
   222
                    props[k] = v;
mb@63
   223
            snaps[props['UUID']] = props
mb@63
   224
        
mb@63
   225
        
mb@63
   226
        template_storage = self.machineFolder + '\SecurityDVM\SecurityDVM.vmdk'
mb@63
   227
        
mb@63
   228
        # find template uuid
mb@63
   229
        template_uuid = ''
mb@63
   230
        for hdd in snaps.values():
mb@63
   231
            if hdd['Location'] == template_storage:
mb@63
   232
                template_uuid = hdd['UUID']
mb@63
   233
        logger.debug('found parent uuid ' + template_uuid)
mb@63
   234
        
mb@63
   235
        # remove snapshots 
mb@63
   236
        for hdd in snaps.values():
mb@63
   237
            if hdd['Parent'] == template_uuid:
mb@63
   238
                #template_uuid = hdd['UUID']
mb@63
   239
                logger.debug('removing snapshot ' + hdd['UUID'])
mb@63
   240
                results = Cygwin.vboxExecute('closemedium disk {' + hdd['UUID'] + '} --delete')[1]
mb@63
   241
                # parse result 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
mb@63
   242
        
mb@63
   243
        self.changeStorageType(template_storage,'normal')
mb@63
   244
        self.storageAttach('SecurityDVM')
mb@63
   245
        self.startVM('SecurityDVM')
mb@63
   246
        self.waitStartup('SecurityDVM')
mb@78
   247
        Cygwin.sshExecute('"sudo apt-get -y update"', VMManager.getHostOnlyIP('SecurityDVM'), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + 'SecurityDVM' + '/dvm_key'  )
mb@78
   248
        Cygwin.sshExecute('"sudo apt-get -y upgrade"', VMManager.getHostOnlyIP('SecurityDVM'), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + 'SecurityDVM' + '/dvm_key'  )
mb@79
   249
        #self.stopVM('SecurityDVM')
mb@79
   250
        self.hibernateVM('SecurityDVM')
mb@63
   251
        self.waitShutdown('SecurityDVM')
mb@63
   252
        self.storageDetach('SecurityDVM')
mb@63
   253
        self.changeStorageType(template_storage,'immutable')
mb@63
   254
        self.storageAttach('SecurityDVM')
mb@79
   255
        self.rsdHandler = DeviceHandler(self)
mb@79
   256
        self.rsdHandler.start()
mb@63
   257
    
mb@63
   258
    #remove VM from the system. should be used on VMs returned by listSDVMs    
mb@63
   259
    def removeVM(self, vm_name):
mb@63
   260
        logger.info('Removing ' + vm_name)
mb@63
   261
        Cygwin.vboxExecute('unregistervm ' + vm_name + ' --delete')
mb@63
   262
        machineFolder = Cygwin.cygPath(self.machineFolder)
mb@63
   263
        Cygwin.bashExecute('"/usr/bin/rm -rf ' + machineFolder + '/' + vm_name + '"')
mb@63
   264
    
mb@63
   265
    # start VM
mb@63
   266
    def startVM(self, vm_name):
mb@63
   267
        logger.info('Starting ' +  vm_name)
mb@66
   268
        result = Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless' )
mb@63
   269
        while not string.find(str(result), 'successfully started',):
mb@63
   270
            logger.error("Failed to start SDVM: " + vm_name + " retrying")
mb@63
   271
            time.sleep(1)
mb@63
   272
            result = Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless')
mb@63
   273
        return result[0]
mb@63
   274
    
mb@63
   275
    # return wether VM is running or not
mb@63
   276
    def isVMRunning(self, vm_name):
mb@63
   277
        return vm_name in self.listRunningVMS()    
mb@63
   278
    
mb@63
   279
    # stop VM
mb@63
   280
    def stopVM(self, vm_name):
mb@63
   281
        logger.info('Sending shutdown signal to ' + vm_name)
mb@78
   282
        Cygwin.sshExecute( '"sudo shutdown -h now"', VMManager.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + vm_name + '/dvm_key' )
mb@78
   283
    
mb@78
   284
    # stop VM
mb@78
   285
    def hibernateVM(self, vm_name):
mb@78
   286
        logger.info('Sending shutdown signal to ' + vm_name)
mb@79
   287
        Cygwin.sshExecute( '"sudo hibernate-disk&"', VMManager.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + vm_name + '/dvm_key', wait_return=False )
mb@63
   288
            
mb@63
   289
    # poweroff VM
mb@63
   290
    def poweroffVM(self, vm_name):
mb@63
   291
        if not self.isVMRunning(vm_name):
mb@63
   292
            return
mb@63
   293
        logger.info('Powering off ' + vm_name)
mb@63
   294
        return Cygwin.vboxExecute('controlvm ' + vm_name + ' poweroff')
mb@63
   295
    
mb@79
   296
    #list the hostonly IFs exposed by the VBox host
mb@79
   297
    @staticmethod    
mb@79
   298
    def getHostOnlyIFs():
mb@79
   299
        result = Cygwin.vboxExecute('list hostonlyifs')[1]
mb@79
   300
        if result=='':
mb@79
   301
            return None
mb@79
   302
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
mb@79
   303
        return props
mb@79
   304
    
mb@79
   305
    # return the hostOnly IP for a running guest or the host
mb@63
   306
    @staticmethod    
mb@63
   307
    def getHostOnlyIP(vm_name):
mb@79
   308
        if vm_name == None:
mb@79
   309
            logger.info('Gettting hostOnly IP address for Host')
mb@79
   310
            return VMManager.getHostOnlyIFs()['IPAddress']
mb@79
   311
        else:
mb@79
   312
            logger.info('Gettting hostOnly IP address ' + vm_name)
mb@79
   313
            result = Cygwin.vboxExecute('guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP')
mb@79
   314
            if result=='':
mb@79
   315
                return None
mb@79
   316
            result = result[1]
mb@79
   317
            if result.startswith('No value set!'):
mb@79
   318
                return None
mb@79
   319
            return result[result.index(':')+1:].strip()
mb@79
   320
            
mb@63
   321
    # attach removable storage device to VM by provision of filter
mb@63
   322
    def attachRSD(self, vm_name, rsd_filter):
mb@63
   323
        return Cygwin.vboxExecute('usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision)
mb@63
   324
    
mb@63
   325
    # detach removable storage from VM by 
mb@63
   326
    def detachRSD(self, vm_name):
mb@63
   327
        return Cygwin.vboxExecute('usbfilter remove 0 --target ' + vm_name )
mb@63
   328
        
mb@63
   329
    
mb@63
   330
    # return the description set for an existing VM
mb@63
   331
    def getVMInfo(self, vm_name):
mb@63
   332
        results = Cygwin.vboxExecute('showvminfo ' + vm_name + ' --machinereadable')[1]
mb@63
   333
        props = dict((k.strip().strip('"'),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
mb@78
   334
        #logger.debug(props)
mb@63
   335
        return props
mb@63
   336
    
mb@63
   337
    # return the configured USB filter for an existing VM 
mb@63
   338
    def getUSBFilter(self, vm_name):
mb@63
   339
        props = self.getVMInfo(vm_name)
mb@63
   340
        keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
mb@63
   341
        keyset = set(props.keys())
mb@63
   342
        usb_filter = None
mb@63
   343
        if keyset.issuperset(keys):
mb@63
   344
            usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
mb@63
   345
        return usb_filter
mb@63
   346
    
mb@63
   347
    #generates ISO containing authorized_keys for use with guest VM
mb@63
   348
    def genCertificateISO(self, vm_name):
mb@63
   349
        machineFolder = Cygwin.cygPath(self.machineFolder)
mb@63
   350
        # remove .ssh folder if exists
mb@63
   351
        cmd = '\"/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"'
mb@63
   352
        Cygwin.bashExecute(cmd)
mb@63
   353
        # remove .ssh folder if exists
mb@63
   354
        Cygwin.bashExecute('\"/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"\"')
mb@63
   355
        # create .ssh folder in vm_name
mb@63
   356
        Cygwin.bashExecute('\"/usr/bin/mkdir -p \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"')
mb@63
   357
        # generate dvm_key pair in vm_name / .ssh     
mb@63
   358
        Cygwin.bashExecute('\"/usr/bin/ssh-keygen -q -t rsa -N \\"\\" -C \\\"' + vm_name + '\\\" -f \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\"\"')
mb@63
   359
        # move out private key
mb@63
   360
        Cygwin.bashExecute('\"/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\" \\\"' + machineFolder + '/' + vm_name + '\\\"')
mb@63
   361
        # set permissions for private key
mb@63
   362
        Cygwin.bashExecute('\"/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"\"')
mb@63
   363
        # rename public key to authorized_keys
mb@63
   364
        Cygwin.bashExecute('\"/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key.pub\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"')
mb@63
   365
        # set permissions for authorized_keys
mb@63
   366
        Cygwin.bashExecute('\"/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"\"')
mb@63
   367
        # generate iso image with .ssh/authorized keys
mb@63
   368
        Cygwin.bashExecute('\"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '/' + vm_name + '/'+ vm_name + '.iso\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"')
mb@63
   369
    
mb@63
   370
    # attaches generated ssh public cert to guest vm
mb@63
   371
    def attachCertificateISO(self, vm_name):
mb@63
   372
        result = Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + self.machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"')
mb@63
   373
        return result
mb@63
   374
    
mb@63
   375
    # wait for machine to come up
mb@79
   376
    def waitStartup(self, vm_name, timeout_ms = 30000):
mb@79
   377
        result = Cygwin.vboxExecute('guestproperty wait ' + vm_name + ' SDVMStarted --timeout ' + str(timeout_ms) + ' --fail-on-timeout')
mb@79
   378
        return VMManager.getHostOnlyIP(vm_name)
mb@63
   379
    
mb@63
   380
    # wait for machine to shutdown
mb@63
   381
    def waitShutdown(self, vm_name):
mb@63
   382
        while vm_name in self.listRunningVMS():
mb@63
   383
            time.sleep(1)
mb@63
   384
        return
mb@63
   385
        
mb@63
   386
    # handles browsing request    
mb@63
   387
    def handleBrowsingRequest(self):
mb@63
   388
        if VMManager.handleDeviceChangeLock.acquire(True):
mb@63
   389
            new_sdvm = self.generateSDVMName()
mb@63
   390
            self.createVM(new_sdvm)
mb@63
   391
            self.storageAttach(new_sdvm)
mb@63
   392
            self.genCertificateISO(new_sdvm)
mb@63
   393
            self.attachCertificateISO(new_sdvm)
mb@63
   394
            self.startVM(new_sdvm)
mb@63
   395
            new_ip = self.waitStartup(new_sdvm)
mb@63
   396
            if new_ip != None:
mb@63
   397
                self.mapNetworkDrive('g:', '\\\\' + new_ip + '\\Download', None, None)
mb@63
   398
            #TODO: cleanup notifications somwhere else (eg. machine shutdown)
mb@63
   399
            VMManager.handleDeviceChangeLock.release()
mb@63
   400
        return new_sdvm
mb@63
   401
    
mb@63
   402
    #Small function to check the availability of network resource.
mb@78
   403
    #def isAvailable(self, path):
mb@78
   404
        #return os.path.exists(path)
mb@78
   405
        #result = Cygwin.cmdExecute('IF EXIST "' + path + '" echo YES')
mb@78
   406
        #return string.find(result[1], 'YES',)
mb@63
   407
    
mb@63
   408
    #Small function to check if the mention location is a directory
mb@63
   409
    def isDirectory(self, path):
mb@63
   410
        result = Cygwin.cmdExecute('dir ' + path + ' | FIND ".."')
mb@63
   411
        return string.find(result[1], 'DIR',)
mb@63
   412
mb@63
   413
    def mapNetworkDrive(self, drive, networkPath, user, password):
mb@63
   414
        self.unmapNetworkDrive(drive)
mb@63
   415
        #Check for drive availability
mb@78
   416
        if os.path.exists(drive):
mb@63
   417
            logger.error("Drive letter is already in use: " + drive)
mb@63
   418
            return -1
mb@63
   419
        #Check for network resource availability
mb@78
   420
        while not os.path.exists(networkPath):
mb@63
   421
            time.sleep(1)
mb@63
   422
            logger.info("Path not accessible: " + networkPath + " retrying")
mb@63
   423
            #return -1
mb@63
   424
    
mb@79
   425
        command = 'USE ' + drive + ' ' + networkPath + ' /PERSISTENT:NO'
mb@63
   426
        if user != None:
mb@63
   427
            command += ' ' + password + ' /User' + user
mb@63
   428
    
mb@63
   429
        #TODO: Execute 'NET USE' command with authentication
mb@63
   430
        result = Cygwin.execute('C:\\Windows\\system32\\net.exe', command)
mb@63
   431
        if string.find(result[1], 'successfully',) == -1:
mb@63
   432
            logger.error("Failed: NET " + command)
mb@63
   433
            return -1
mb@63
   434
        return 1
mb@63
   435
    
mb@63
   436
    def unmapNetworkDrive(self, drive):
mb@79
   437
        drives = self.getNetworkDrives()
mb@79
   438
        if drive not in drives.keys():
mb@79
   439
            return 1 
mb@63
   440
        result = Cygwin.execute('C:\\Windows\\system32\\net.exe', 'USE ' + drive + ' /DELETE /YES')
mb@79
   441
        if string.find(str(result[1]), 'successfully',) == -1:
mb@78
   442
            logger.error(result[2])
mb@63
   443
            return -1
mb@63
   444
        return 1
mb@79
   445
    
mb@79
   446
    def getNetworkDrives(self):
mb@79
   447
        ip = VMManager.getHostOnlyIP(None)
mb@79
   448
        ip = ip[:ip.rindex('.')]
mb@79
   449
        drives = dict()    
mb@79
   450
        result = Cygwin.execute('C:\\Windows\\system32\\net.exe', 'USE')
mb@79
   451
        for line in result[1].splitlines():
mb@79
   452
            if ip in line:
mb@79
   453
                parts = line.split()
mb@79
   454
                drives[parts[1]] = parts[2]
mb@79
   455
        return drives
mb@79
   456
            
mb@79
   457
    def genNetworkDrive(self):
mb@79
   458
        network_drives = self.getNetworkDrives()
mb@79
   459
        logical_drives = self.getLogicalDrives()
mb@79
   460
        drives = list(map(chr, range(68, 91)))  
mb@79
   461
        for drive in drives:
mb@79
   462
            if drive+':' not in network_drives and drive not in logical_drives:
mb@79
   463
                return drive+':'
mb@63
   464
mb@79
   465
    def getNetworkDrive(self, vm_name):
mb@79
   466
        ip = self.getHostOnlyIP(vm_name)
mb@79
   467
        result = Cygwin.execute('C:\\Windows\\system32\\net.exe', 'USE')
mb@79
   468
        for line in result[1].splitlines():
mb@79
   469
            if ip in line:
mb@79
   470
                parts = line.split()
mb@79
   471
                return parts[0]
mb@79
   472
    
mb@79
   473
    def getLogicalDrives(self):
mb@79
   474
        drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
mb@79
   475
        return list(itertools.compress(string.ascii_uppercase,  map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
mb@79
   476
                    
mb@79
   477
        #vms = self.listSDVM()
mb@79
   478
        #for vm in vms:
mb@79
   479
        #    ip = self.getHostOnlyIP(vm)
mb@79
   480
        
mb@78
   481
class DeviceHandler(threading.Thread): 
mb@78
   482
    vmm = None
mb@79
   483
    #handleDeviceChangeLock = threading.Lock()
mb@79
   484
    attachedRSDs = None  
mb@79
   485
    connectedRSDs = None
mb@79
   486
    running = True
mb@79
   487
    def __init__(self, vmmanger): 
mb@79
   488
        threading.Thread.__init__(self)
mb@79
   489
        self.vmm = vmmanger
mb@78
   490
 
mb@79
   491
    def stop(self):
mb@79
   492
        self.running = False
mb@79
   493
        
mb@78
   494
    def run(self):
mb@79
   495
        self.connectedRSDs = dict()#self.vmm.getConnectedRSDS()
mb@79
   496
        self.attachedRSDs = self.vmm.getAttachedRSDs()
mb@79
   497
        while self.running:
mb@79
   498
            tmp_rsds = self.vmm.getConnectedRSDS()
mb@79
   499
            if tmp_rsds.keys() == self.connectedRSDs.keys():
mb@79
   500
                logger.debug("Nothing's changed. sleep(3)")
mb@79
   501
                time.sleep(3)
mb@79
   502
                continue
mb@79
   503
            
mb@79
   504
            logger.info("Something's changed")          
mb@79
   505
            
mb@79
   506
            self.connectedRSDs = tmp_rsds
mb@79
   507
            self.attachedRSDs = self.vmm.getAttachedRSDs()
mb@79
   508
            
mb@79
   509
            
mb@79
   510
            for vm_name in self.attachedRSDs.keys():
mb@79
   511
                if self.attachedRSDs[vm_name] not in self.connectedRSDs.values():
mb@79
   512
                    drive = self.vmm.getNetworkDrive(vm_name)
mb@79
   513
                    self.vmm.unmapNetworkDrive(drive)
mb@79
   514
                    #self.stopVM(vm_name)
mb@79
   515
                    self.vmm.detachRSD(vm_name)
mb@79
   516
                    self.vmm.poweroffVM(vm_name)
mb@79
   517
                    self.vmm.removeVM(vm_name)
mb@79
   518
            #create new vm for attached device if any
mb@79
   519
            self.attachedRSDs = self.vmm.getAttachedRSDs()
mb@79
   520
            self.connectedRSDs = self.vmm.getConnectedRSDS()
mb@79
   521
            
mb@79
   522
            new_ip = None
mb@79
   523
            for connected_device in self.connectedRSDs.values():
mb@79
   524
                if (self.attachedRSDs and False) or (connected_device not in self.attachedRSDs.values()):
mb@79
   525
                    new_sdvm = self.vmm.generateSDVMName()
mb@79
   526
                    self.vmm.createVM(new_sdvm)
mb@79
   527
                    self.vmm.storageAttach(new_sdvm)
mb@79
   528
                    self.vmm.attachRSD(new_sdvm, connected_device)
mb@79
   529
                    self.vmm.startVM(new_sdvm)
mb@79
   530
                    new_ip = self.vmm.waitStartup(new_sdvm)
mb@79
   531
                    drive = self.vmm.genNetworkDrive()
mb@79
   532
                    if new_ip != None:
mb@79
   533
                        self.vmm.mapNetworkDrive(drive, '\\\\' + new_ip + '\\USB', None, None)
mb@79
   534
                    #TODO: cleanup notifications somwhere else (eg. machine shutdown)
mb@79
   535
            #self.handleDeviceChangeLock.release()
mb@78
   536
                
mb@63
   537
mb@63
   538
if __name__ == '__main__':
mb@79
   539
    #man = VMManager.getInstance()
mb@63
   540
    #man.listVM()
mb@79
   541
    #print man.getConnectedRSDs()
mb@79
   542
    #print man.getNetworkDrives()
mb@79
   543
    #man.genNetworkDrive()
mb@79
   544
    drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
mb@79
   545
    print list(itertools.compress(string.ascii_uppercase,  map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
mb@79
   546
    #print list(map(chr, range(68, 91))) 
mb@63
   547
    
mb@79
   548
    #time.sleep(-1)
mb@63
   549
    #man.listVM()
mb@63
   550
    #man.listVM()
mb@63
   551
    #man.listVM()
mb@63
   552
    #man.listVM()
mb@63
   553
    #man.genCertificateISO('SecurityDVM0')
mb@63
   554
    #man.guestExecute('SecurityDVM0', '/bin/ls -la')
mb@63
   555
    #logger = setupLogger('VMManager')
mb@79
   556
    #c = Cygwin()
mb@63
   557
    
mb@63
   558
    #man.sshExecute('/bin/ls -la', 'SecurityDVM0')
mb@63
   559
    #man.sshExecuteX11('/usr/bin/iceweasel', 'SecurityDVM0')
mb@63
   560
    #man.removeVM('SecurityDVM0')
mb@63
   561
    #man.netUse('192.168.56.134', 'USB\\')
mb@63
   562
    #ip = '192.168.56.139'
mb@63
   563
    
mb@63
   564
    #man.cygwin_path = 'c:\\cygwin64\\bin\\'
mb@63
   565
    #man.handleDeviceChange()
mb@63
   566
    #print man.listSDVM()
mb@63
   567
    #man.configureHostNetworking()
mb@63
   568
    #new_vm = man.generateSDVMName()
mb@63
   569
    #man.createVM(new_vm)
mb@63
   570
    
mb@63
   571
    #print Cygwin.cmd()
mb@63
   572
    #man.isAvailable('c:')
mb@63
   573
    #ip = man.getHostOnlyIP('SecurityDVM0')
mb@63
   574
    #man.mapNetworkDrive('h:', '\\\\' + ip + '\Download', None, None)
mb@63
   575
    
mb@63
   576
    #man.genCertificateISO(new_vm)
mb@63
   577
    #man.attachCertificateISO(new_vm)
mb@63
   578
    
mb@63
   579
    #man.attachCertificateISO(vm_name)
mb@63
   580
    #man.guestExecute(vm_name, "ls")
mb@63
   581
    #man.sshGuestX11Execute('SecurityDVM1', '/usr/bin/iceweasel')
mb@63
   582
    #time.sleep(60)
mb@63
   583
    #print man.cygwinPath("C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\.ssh\*")
mb@63
   584
    #man.genCertificateISO('SecurityDVM')
mb@63
   585
    #man.attachCertificateISO('SecurityDVM')
mb@63
   586
    #man.isStorageAttached('SecurityDVM')
mb@63
   587
    #man.guestExecute('SecurityDVM', 'sudo apt-get -y update')
mb@63
   588
    #man.guestExecute('SecurityDVM', 'sudo apt-get -y upgrade' )
mb@63
   589
    
mb@63
   590
    #man.stopVM('SecurityDVM')
mb@63
   591
    #man.storageDetach('SecurityDVM')
mb@63
   592
    #man.changeStorageType('C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\SecurityDVM.vmdk','immutable')
mb@63
   593
    #man.storageAttach('SecurityDVM')
mb@63
   594
    
mb@63
   595
    
mb@63
   596
    #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
mb@63
   597
    #man.execute(cmd)
mb@63
   598