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