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