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