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