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