1.1 --- a/OpenSecurity/bin/cygwin.py Tue Mar 18 16:31:47 2014 +0100
1.2 +++ b/OpenSecurity/bin/cygwin.py Tue Mar 18 18:00:12 2014 +0100
1.3 @@ -197,12 +197,12 @@
1.4 # executes command over ssh on guest vm with X forwarding
1.5 @staticmethod
1.6 def sshExecuteX11(command, address, user_name, certificate, wait_return=True):
1.7 - return Cygwin.bashExecute('"DISPLAY=:0.0 /usr/bin/ssh -v -Y -i \\"' + certificate +'\\" ' + user_name + '@' + address + ' ' + command + '\"')
1.8 + return Cygwin.bashExecute('DISPLAY=:0.0 /usr/bin/ssh -v -Y -i \\\"' + certificate +'\\\" ' + user_name + '@' + address + ' ' + command + '')
1.9
1.10 @staticmethod
1.11 def is_X11_running():
1.12 """check if we can connect to a X11 running instance"""
1.13 - p = Cygwin.bashExecute('DISPLAY=:0 /usr/bin/xset -q')
1.14 + p = Cygwin.bashExecute('DISPLAY=:0 xset -q') #/usr/bin/
1.15 return p[0] == 0
1.16
1.17
2.1 --- a/OpenSecurity/bin/vmmanager.pyw Tue Mar 18 16:31:47 2014 +0100
2.2 +++ b/OpenSecurity/bin/vmmanager.pyw Tue Mar 18 18:00:12 2014 +0100
2.3 @@ -1,4 +1,3 @@
2.4 -<<<<<<< local
2.5 '''
2.6 Created on Nov 19, 2013
2.7
2.8 @@ -282,7 +281,7 @@
2.9 logger.info('Removing ' + vm_name)
2.10 checkResult(Cygwin.vboxExecute('unregistervm ' + vm_name + ' --delete'))
2.11 machineFolder = Cygwin.cygPath(self.machineFolder)
2.12 - checkResult(Cygwin.bashExecute('"/usr/bin/rm -rf ' + machineFolder + '/' + vm_name + '"'))
2.13 + checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '\\\"'))
2.14
2.15 # start VM
2.16 def startVM(self, vm_name):
2.17 @@ -368,23 +367,23 @@
2.18 def genCertificateISO(self, vm_name):
2.19 machineFolder = Cygwin.cygPath(self.machineFolder)
2.20 # remove .ssh folder if exists
2.21 - checkResult(Cygwin.bashExecute('\"/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"'))
2.22 + checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"'))
2.23 # remove .ssh folder if exists
2.24 - checkResult(Cygwin.bashExecute('\"/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"\"'))
2.25 + checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"'))
2.26 # create .ssh folder in vm_name
2.27 - checkResult(Cygwin.bashExecute('\"/usr/bin/mkdir -p \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"'))
2.28 + checkResult(Cygwin.bashExecute('/usr/bin/mkdir -p \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"'))
2.29 # generate dvm_key pair in vm_name / .ssh
2.30 - checkResult(Cygwin.bashExecute('\"/usr/bin/ssh-keygen -q -t rsa -N \\"\\" -C \\\"' + vm_name + '\\\" -f \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\"\"'))
2.31 + checkResult(Cygwin.bashExecute('/usr/bin/ssh-keygen -q -t rsa -N \\\"\\\" -C \\\"' + vm_name + '\\\" -f \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\"'))
2.32 # move out private key
2.33 - checkResult(Cygwin.bashExecute('\"/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\" \\\"' + machineFolder + '/' + vm_name + '\\\"'))
2.34 + checkResult(Cygwin.bashExecute('/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\" \\\"' + machineFolder + '/' + vm_name + '\\\"'))
2.35 # set permissions for private key
2.36 - checkResult(Cygwin.bashExecute('\"/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"\"'))
2.37 + checkResult(Cygwin.bashExecute('/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"'))
2.38 # rename public key to authorized_keys
2.39 - checkResult(Cygwin.bashExecute('\"/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key.pub\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"'))
2.40 + checkResult(Cygwin.bashExecute('/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key.pub\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"'))
2.41 # set permissions for authorized_keys
2.42 - checkResult(Cygwin.bashExecute('\"/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"\"'))
2.43 + checkResult(Cygwin.bashExecute('/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"'))
2.44 # generate iso image with .ssh/authorized keys
2.45 - checkResult(Cygwin.bashExecute('\"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '/' + vm_name + '/'+ vm_name + '.iso\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"'))
2.46 + checkResult(Cygwin.bashExecute('/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '/' + vm_name + '/'+ vm_name + '.iso\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"'))
2.47
2.48 # attaches generated ssh public cert to guest vm
2.49 def attachCertificateISO(self, vm_name):
2.50 @@ -527,6 +526,7 @@
2.51 self.vmm = vmmanager
2.52
2.53 def run(self):
2.54 + drive = None
2.55 try:
2.56 Cygwin.start_X11()
2.57 new_sdvm = self.vmm.generateSDVMName()
2.58 @@ -545,8 +545,8 @@
2.59 result = checkResult(Cygwin.sshExecuteX11(browser, new_ip, 'osecuser', Cygwin.cygPath(self.vmm.getMachineFolder()) + '/' + new_sdvm + '/dvm_key'))
2.60 except:
2.61 logger.error("BrowsingHandler failed. Cleaning up")
2.62 -
2.63 - self.vmm.unmapNetworkDrive(drive)
2.64 + if drive != None:
2.65 + self.vmm.unmapNetworkDrive(drive)
2.66 self.vmm.poweroffVM(new_sdvm)
2.67 self.vmm.removeVM(new_sdvm)
2.68
2.69 @@ -680,686 +680,3 @@
2.70
2.71 #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
2.72 #man.execute(cmd)
2.73 -=======
2.74 -'''
2.75 -Created on Nov 19, 2013
2.76 -
2.77 -@author: BarthaM
2.78 -'''
2.79 -import os
2.80 -import os.path
2.81 -from subprocess import Popen, PIPE, call, STARTUPINFO, _subprocess
2.82 -import sys
2.83 -import re
2.84 -
2.85 -from cygwin import Cygwin
2.86 -from environment import Environment
2.87 -import threading
2.88 -import time
2.89 -import string
2.90 -
2.91 -import shutil
2.92 -import stat
2.93 -import tempfile
2.94 -from opensecurity_util import logger, setupLogger, OpenSecurityException
2.95 -import ctypes
2.96 -import itertools
2.97 -import _winreg
2.98 -DEBUG = True
2.99 -
2.100 -class VMManagerException(Exception):
2.101 - def __init__(self, value):
2.102 - self.value = value
2.103 - def __str__(self):
2.104 - return repr(self.value)
2.105 -
2.106 -class USBFilter:
2.107 - vendorid = ""
2.108 - productid = ""
2.109 - revision = ""
2.110 -
2.111 - def __init__(self, vendorid, productid, revision):
2.112 - self.vendorid = vendorid.lower()
2.113 - self.productid = productid.lower()
2.114 - self.revision = revision.lower()
2.115 - return
2.116 -
2.117 - def __eq__(self, other):
2.118 - return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
2.119 -
2.120 - def __hash__(self):
2.121 - return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
2.122 -
2.123 - def __repr__(self):
2.124 - return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
2.125 -
2.126 - #def __getitem__(self, item):
2.127 - # return self.coords[item]
2.128 -
2.129 -class VMManager(object):
2.130 - vmRootName = "SecurityDVM"
2.131 - systemProperties = None
2.132 - _instance = None
2.133 - machineFolder = ''
2.134 - rsdHandler = None
2.135 - _running = True
2.136 -
2.137 - def __init__(self):
2.138 - self._running = True
2.139 - self.systemProperties = self.getSystemProperties()
2.140 - self.machineFolder = self.systemProperties["Default machine folder"]
2.141 - self.cleanup()
2.142 - self.rsdHandler = DeviceHandler(self)
2.143 - self.rsdHandler.start()
2.144 - return
2.145 -
2.146 - @staticmethod
2.147 - def getInstance():
2.148 - if VMManager._instance == None:
2.149 - VMManager._instance = VMManager()
2.150 - return VMManager._instance
2.151 -
2.152 - def cleanup(self):
2.153 - if self.rsdHandler != None:
2.154 - self.rsdHandler.stop()
2.155 - self.rsdHandler.join()
2.156 - drives = self.getNetworkDrives()
2.157 - for drive in drives.keys():
2.158 - self.unmapNetworkDrive(drive)
2.159 - for vm in self.listSDVM():
2.160 - self.poweroffVM(vm)
2.161 - self.removeVM(vm)
2.162 -
2.163 - # return hosty system properties
2.164 - def getSystemProperties(self):
2.165 - result = checkResult(Cygwin.vboxExecute('list systemproperties'))
2.166 - if result[1]=='':
2.167 - return None
2.168 - props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
2.169 - return props
2.170 -
2.171 - # return the folder containing the guest VMs
2.172 - def getMachineFolder(self):
2.173 - return self.machineFolder
2.174 -
2.175 - # list all existing VMs registered with VBox
2.176 - def listVM(self):
2.177 - result = checkResult(Cygwin.vboxExecute('list vms'))[1]
2.178 - vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
2.179 - return vms
2.180 -
2.181 - # list running VMs
2.182 - def listRunningVMS(self):
2.183 - result = checkResult(Cygwin.vboxExecute('list runningvms'))[1]
2.184 - vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
2.185 - return vms
2.186 -
2.187 - # list existing SDVMs
2.188 - def listSDVM(self):
2.189 - vms = self.listVM()
2.190 - svdms = []
2.191 - for vm in vms:
2.192 - if vm.startswith(self.vmRootName) and vm != self.vmRootName:
2.193 - svdms.append(vm)
2.194 - return svdms
2.195 -
2.196 - # generate valid (not already existing SDVM name). necessary for creating a new VM
2.197 - def generateSDVMName(self):
2.198 - vms = self.listVM()
2.199 - for i in range(0,999):
2.200 - if(not self.vmRootName+str(i) in vms):
2.201 - return self.vmRootName+str(i)
2.202 - return ''
2.203 -
2.204 - # check if the device is mass storage type
2.205 - @staticmethod
2.206 - def isMassStorageDevice(device):
2.207 - keyname = 'SYSTEM\CurrentControlSet\Enum\USB' + '\VID_' + device.vendorid+'&'+'PID_'+ device.productid
2.208 - key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keyname)
2.209 - #subkeys = _winreg.QueryInfoKey(key)[0]
2.210 - #for i in range(0, subkeys):
2.211 - # print _winreg.EnumKey(key, i)
2.212 - devinfokeyname = _winreg.EnumKey(key, 0)
2.213 - _winreg.CloseKey(key)
2.214 -
2.215 - devinfokey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keyname+'\\'+devinfokeyname)
2.216 - value = _winreg.QueryValueEx(devinfokey, 'SERVICE')[0]
2.217 - _winreg.CloseKey(devinfokey)
2.218 -
2.219 - return 'USBSTOR' in value
2.220 -
2.221 - # return the RSDs connected to the host
2.222 - @staticmethod
2.223 - def getConnectedRSDS():
2.224 - results = checkResult(Cygwin.vboxExecute('list usbhost'))[1]
2.225 - results = results.split('Host USB Devices:')[1].strip()
2.226 -
2.227 - items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
2.228 - rsds = dict()
2.229 - for item in items:
2.230 - props = dict()
2.231 - for line in item.splitlines():
2.232 - if line != "":
2.233 - k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
2.234 - props[k] = v
2.235 -
2.236 - #if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
2.237 -
2.238 - usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'],
2.239 - re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
2.240 - re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
2.241 - if VMManager.isMassStorageDevice(usb_filter):
2.242 - rsds[props['UUID']] = usb_filter;
2.243 - logger.debug(usb_filter)
2.244 - return rsds
2.245 -
2.246 - # return the RSDs attached to all existing SDVMs
2.247 - def getAttachedRSDs(self):
2.248 - vms = self.listSDVM()
2.249 - attached_devices = dict()
2.250 - for vm in vms:
2.251 - rsd_filter = self.getUSBFilter(vm)
2.252 - if rsd_filter != None:
2.253 - attached_devices[vm] = rsd_filter
2.254 - return attached_devices
2.255 -
2.256 - # configures hostonly networking and DHCP server. requires admin rights
2.257 - def configureHostNetworking(self):
2.258 - #cmd = 'vboxmanage list hostonlyifs'
2.259 - #Cygwin.vboxExecute(cmd)
2.260 - #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
2.261 - #Cygwin.vboxExecute(cmd)
2.262 - #cmd = 'vboxmanage hostonlyif create'
2.263 - #Cygwin.vboxExecute(cmd)
2.264 - checkResult(Cygwin.vboxExecute('hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'))
2.265 - #cmd = 'vboxmanage dhcpserver add'
2.266 - #Cygwin.vboxExecute(cmd)
2.267 - 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'))
2.268 -
2.269 - #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
2.270 - def createVM(self, vm_name):
2.271 - hostonly_if = self.getHostOnlyIFs()
2.272 - checkResult(Cygwin.vboxExecute('createvm --name ' + vm_name + ' --ostype Debian --register'))
2.273 - checkResult(Cygwin.vboxExecute('modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat'))
2.274 - checkResult(Cygwin.vboxExecute('storagectl ' + vm_name + ' --name SATA --add sata --portcount 2'))
2.275 - return
2.276 -
2.277 - # attach storage image to controller
2.278 - def storageAttach(self, vm_name):
2.279 - if self.isStorageAttached(vm_name):
2.280 - self.storageDetach(vm_name)
2.281 - checkResult(Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium \"'+ self.machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'))
2.282 -
2.283 - # return true if storage is attached
2.284 - def isStorageAttached(self, vm_name):
2.285 - info = self.getVMInfo(vm_name)
2.286 - return (info['SATA-0-0']!='none')
2.287 -
2.288 - # detach storage from controller
2.289 - def storageDetach(self, vm_name):
2.290 - if self.isStorageAttached(vm_name):
2.291 - checkResult(Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium none'))
2.292 -
2.293 - def changeStorageType(self, filename, storage_type):
2.294 - checkResult(Cygwin.vboxExecute('modifyhd \"' + filename + '\" --type ' + storage_type))
2.295 -
2.296 - # list storage snaphots for VM
2.297 - def updateTemplate(self):
2.298 - self.cleanup()
2.299 - self.poweroffVM('SecurityDVM')
2.300 - self.waitShutdown('SecurityDVM')
2.301 -
2.302 - # check for updates
2.303 - self.genCertificateISO('SecurityDVM')
2.304 - self.attachCertificateISO('SecurityDVM')
2.305 -
2.306 - self.storageDetach('SecurityDVM')
2.307 - results = checkResult(Cygwin.vboxExecute('list hdds'))[1]
2.308 - results = results.replace('Parent UUID', 'Parent')
2.309 - items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
2.310 -
2.311 - snaps = dict()
2.312 - for item in items:
2.313 - props = dict()
2.314 - for line in item.splitlines():
2.315 - if line != "":
2.316 - k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
2.317 - props[k] = v;
2.318 - snaps[props['UUID']] = props
2.319 -
2.320 -
2.321 - template_storage = self.machineFolder + '\SecurityDVM\SecurityDVM.vmdk'
2.322 -
2.323 - # find template uuid
2.324 - template_uuid = ''
2.325 - for hdd in snaps.values():
2.326 - if hdd['Location'] == template_storage:
2.327 - template_uuid = hdd['UUID']
2.328 - logger.debug('found parent uuid ' + template_uuid)
2.329 -
2.330 - # remove snapshots
2.331 - for hdd in snaps.values():
2.332 - if hdd['Parent'] == template_uuid:
2.333 - #template_uuid = hdd['UUID']
2.334 - logger.debug('removing snapshot ' + hdd['UUID'])
2.335 - checkResult(Cygwin.vboxExecute('closemedium disk {' + hdd['UUID'] + '} --delete'))#[1]
2.336 - # parse result 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
2.337 -
2.338 - self.changeStorageType(template_storage,'normal')
2.339 - self.storageAttach('SecurityDVM')
2.340 - self.startVM('SecurityDVM')
2.341 - self.waitStartup('SecurityDVM')
2.342 - checkResult(Cygwin.sshExecute('"sudo apt-get -y update"', VMManager.getHostOnlyIP('SecurityDVM'), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + 'SecurityDVM' + '/dvm_key'))
2.343 - checkResult(Cygwin.sshExecute('"sudo apt-get -y upgrade"', VMManager.getHostOnlyIP('SecurityDVM'), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + 'SecurityDVM' + '/dvm_key'))
2.344 - #self.stopVM('SecurityDVM')
2.345 - self.hibernateVM('SecurityDVM')
2.346 - self.waitShutdown('SecurityDVM')
2.347 - self.storageDetach('SecurityDVM')
2.348 - self.changeStorageType(template_storage,'immutable')
2.349 - self.storageAttach('SecurityDVM')
2.350 - self.rsdHandler = DeviceHandler(self)
2.351 - self.rsdHandler.start()
2.352 -
2.353 - #remove VM from the system. should be used on VMs returned by listSDVMs
2.354 - def removeVM(self, vm_name):
2.355 - logger.info('Removing ' + vm_name)
2.356 - checkResult(Cygwin.vboxExecute('unregistervm ' + vm_name + ' --delete'))
2.357 - vm_file = Cygwin.cygPath(self.machineFolder + '\\' + vm_name)
2.358 - checkResult(Cygwin.bashExecute('rm -rf \'' + vm_file + '\''))
2.359 -
2.360 - # start VM
2.361 - def startVM(self, vm_name):
2.362 - logger.info('Starting ' + vm_name)
2.363 - result = checkResult(Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless' ))
2.364 - while 'successfully started' not in result[1] and _running:
2.365 - logger.error("Failed to start SDVM: " + vm_name + " retrying")
2.366 - time.sleep(1)
2.367 - result = checkResult(Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless'))
2.368 - return result[0]
2.369 -
2.370 - # return wether VM is running or not
2.371 - def isVMRunning(self, vm_name):
2.372 - return vm_name in self.listRunningVMS()
2.373 -
2.374 - # stop VM
2.375 - def stopVM(self, vm_name):
2.376 - logger.info('Sending shutdown signal to ' + vm_name)
2.377 - checkResult(Cygwin.sshExecute( '"sudo shutdown -h now"', VMManager.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + vm_name + '/dvm_key' ))
2.378 -
2.379 - # stop VM
2.380 - def hibernateVM(self, vm_name):
2.381 - logger.info('Sending shutdown signal to ' + vm_name)
2.382 - checkResult(Cygwin.sshExecute( '"sudo hibernate-disk&"', VMManager.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + vm_name + '/dvm_key', wait_return=False))
2.383 -
2.384 - # poweroff VM
2.385 - def poweroffVM(self, vm_name):
2.386 - if not self.isVMRunning(vm_name):
2.387 - return
2.388 - logger.info('Powering off ' + vm_name)
2.389 - return checkResult(Cygwin.vboxExecute('controlvm ' + vm_name + ' poweroff'))
2.390 -
2.391 - #list the hostonly IFs exposed by the VBox host
2.392 - @staticmethod
2.393 - def getHostOnlyIFs():
2.394 - result = Cygwin.vboxExecute('list hostonlyifs')[1]
2.395 - if result=='':
2.396 - return None
2.397 - props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
2.398 - return props
2.399 -
2.400 - # return the hostOnly IP for a running guest or the host
2.401 - @staticmethod
2.402 - def getHostOnlyIP(vm_name):
2.403 - if vm_name == None:
2.404 - logger.info('Gettting hostOnly IP address for Host')
2.405 - return VMManager.getHostOnlyIFs()['IPAddress']
2.406 - else:
2.407 - logger.info('Gettting hostOnly IP address ' + vm_name)
2.408 - result = checkResult(Cygwin.vboxExecute('guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'))
2.409 - if result=='':
2.410 - return None
2.411 - result = result[1]
2.412 - if result.startswith('No value set!'):
2.413 - return None
2.414 - return result[result.index(':')+1:].strip()
2.415 -
2.416 - # attach removable storage device to VM by provision of filter
2.417 - def attachRSD(self, vm_name, rsd_filter):
2.418 - return checkResult(Cygwin.vboxExecute('usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision))
2.419 -
2.420 - # detach removable storage from VM by
2.421 - def detachRSD(self, vm_name):
2.422 - return checkResult(Cygwin.vboxExecute('usbfilter remove 0 --target ' + vm_name))
2.423 -
2.424 - # return the description set for an existing VM
2.425 - def getVMInfo(self, vm_name):
2.426 - results = checkResult(Cygwin.vboxExecute('showvminfo ' + vm_name + ' --machinereadable'))[1]
2.427 - props = dict((k.strip().strip('"'),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
2.428 - return props
2.429 -
2.430 - # return the configured USB filter for an existing VM
2.431 - def getUSBFilter(self, vm_name):
2.432 - props = self.getVMInfo(vm_name)
2.433 - keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
2.434 - keyset = set(props.keys())
2.435 - usb_filter = None
2.436 - if keyset.issuperset(keys):
2.437 - usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
2.438 - return usb_filter
2.439 -
2.440 - #generates ISO containing authorized_keys for use with guest VM
2.441 - def genCertificateISO(self, vm_name):
2.442 - machineFolder = Cygwin.cygPath(self.machineFolder)
2.443 - # remove .ssh folder if exists
2.444 - checkResult(Cygwin.bashExecute('\"/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"'))
2.445 - # remove .ssh folder if exists
2.446 - checkResult(Cygwin.bashExecute('\"/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"\"'))
2.447 - # create .ssh folder in vm_name
2.448 - checkResult(Cygwin.bashExecute('\"/usr/bin/mkdir -p \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"'))
2.449 - # generate dvm_key pair in vm_name / .ssh
2.450 - checkResult(Cygwin.bashExecute('\"/usr/bin/ssh-keygen -q -t rsa -N \\"\\" -C \\\"' + vm_name + '\\\" -f \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\"\"'))
2.451 - # move out private key
2.452 - checkResult(Cygwin.bashExecute('\"/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\" \\\"' + machineFolder + '/' + vm_name + '\\\"'))
2.453 - # set permissions for private key
2.454 - checkResult(Cygwin.bashExecute('\"/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"\"'))
2.455 - # rename public key to authorized_keys
2.456 - checkResult(Cygwin.bashExecute('\"/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key.pub\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"'))
2.457 - # set permissions for authorized_keys
2.458 - checkResult(Cygwin.bashExecute('\"/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"\"'))
2.459 - # generate iso image with .ssh/authorized keys
2.460 - checkResult(Cygwin.bashExecute('\"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '/' + vm_name + '/'+ vm_name + '.iso\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"'))
2.461 -
2.462 - # attaches generated ssh public cert to guest vm
2.463 - def attachCertificateISO(self, vm_name):
2.464 - result = checkResult(Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + self.machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'))
2.465 - return result
2.466 -
2.467 - # wait for machine to come up
2.468 - def waitStartup(self, vm_name, timeout_ms = 30000):
2.469 - checkResult(Cygwin.vboxExecute('guestproperty wait ' + vm_name + ' SDVMStarted --timeout ' + str(timeout_ms) + ' --fail-on-timeout'))
2.470 - return VMManager.getHostOnlyIP(vm_name)
2.471 -
2.472 - # wait for machine to shutdown
2.473 - def waitShutdown(self, vm_name):
2.474 - while vm_name in self.listRunningVMS() and _running:
2.475 - time.sleep(1)
2.476 - return
2.477 -
2.478 - # handles browsing request
2.479 - def handleBrowsingRequest(self):
2.480 - handler = BrowsingHandler(self)
2.481 - handler.start()
2.482 - return 'ok'
2.483 -
2.484 - #Small function to check the availability of network resource.
2.485 - #def isAvailable(self, path):
2.486 - #return os.path.exists(path)
2.487 - #result = Cygwin.cmdExecute('IF EXIST "' + path + '" echo YES')
2.488 - #return string.find(result[1], 'YES',)
2.489 -
2.490 - #Small function to check if the mention location is a directory
2.491 - def isDirectory(self, path):
2.492 - result = checkResult(Cygwin.cmdExecute('dir ' + path + ' | FIND ".."'))
2.493 - return string.find(result[1], 'DIR',)
2.494 -
2.495 - def mapNetworkDrive(self, drive, networkPath, user, password):
2.496 - self.unmapNetworkDrive(drive)
2.497 - #Check for drive availability
2.498 - if os.path.exists(drive):
2.499 - logger.error("Drive letter is already in use: " + drive)
2.500 - return -1
2.501 - #Check for network resource availability
2.502 - retry = 5
2.503 - while not os.path.exists(networkPath):
2.504 - time.sleep(1)
2.505 - if retry == 0:
2.506 - return -1
2.507 - logger.info("Path not accessible: " + networkPath + " retrying")
2.508 - retry-=1
2.509 - #return -1
2.510 -
2.511 - command = 'USE ' + drive + ' ' + networkPath + ' /PERSISTENT:NO'
2.512 - if user != None:
2.513 - command += ' ' + password + ' /User' + user
2.514 -
2.515 - #TODO: Execute 'NET USE' command with authentication
2.516 - result = checkResult(Cygwin.execute('C:\\Windows\\system32\\net.exe', command))
2.517 - if string.find(result[1], 'successfully',) == -1:
2.518 - logger.error("Failed: NET " + command)
2.519 - return -1
2.520 - return 1
2.521 -
2.522 - def unmapNetworkDrive(self, drive):
2.523 - drives = self.getNetworkDrives()
2.524 - if drive not in drives.keys():
2.525 - return 1
2.526 - result = checkResult(Cygwin.execute('C:\\Windows\\system32\\net.exe', 'USE ' + drive + ' /DELETE /YES'))
2.527 - if string.find(str(result[1]), 'successfully',) == -1:
2.528 - logger.error(result[2])
2.529 - return -1
2.530 - return 1
2.531 -
2.532 - def getNetworkDrives(self):
2.533 - ip = VMManager.getHostOnlyIP(None)
2.534 - ip = ip[:ip.rindex('.')]
2.535 - drives = dict()
2.536 - result = checkResult(Cygwin.execute('C:\\Windows\\system32\\net.exe', 'USE'))
2.537 - for line in result[1].splitlines():
2.538 - if ip in line:
2.539 - parts = line.split()
2.540 - drives[parts[1]] = parts[2]
2.541 - return drives
2.542 -
2.543 - def genNetworkDrive(self):
2.544 - network_drives = self.getNetworkDrives()
2.545 - logical_drives = VMManager.getLogicalDrives()
2.546 - drives = list(map(chr, range(68, 91)))
2.547 - for drive in drives:
2.548 - if drive+':' not in network_drives and drive not in logical_drives:
2.549 - return drive+':'
2.550 -
2.551 - def getNetworkDrive(self, vm_name):
2.552 - ip = self.getHostOnlyIP(vm_name)
2.553 - result = checkResult(Cygwin.execute('C:\\Windows\\system32\\net.exe', 'USE'))
2.554 - for line in result[1].splitlines():
2.555 - if line != None and ip in line:
2.556 - parts = line.split()
2.557 - return parts[0]
2.558 - @staticmethod
2.559 - def getLogicalDrives():
2.560 - drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
2.561 - return list(itertools.compress(string.ascii_uppercase, map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
2.562 -
2.563 - @staticmethod
2.564 - def getDriveType(drive):
2.565 - return ctypes.cdll.kernel32.GetDriveTypeW(u"%s:\\"%drive)
2.566 -
2.567 - @staticmethod
2.568 - def getVolumeInfo(drive):
2.569 - volumeNameBuffer = ctypes.create_unicode_buffer(1024)
2.570 - fileSystemNameBuffer = ctypes.create_unicode_buffer(1024)
2.571 - serial_number = None
2.572 - max_component_length = None
2.573 - file_system_flags = None
2.574 -
2.575 - rc = ctypes.cdll.kernel32.GetVolumeInformationW(
2.576 - #ctypes.c_wchar_p("F:\\"),
2.577 - u"%s:\\"%drive,
2.578 - volumeNameBuffer,
2.579 - ctypes.sizeof(volumeNameBuffer),
2.580 - serial_number,
2.581 - max_component_length,
2.582 - file_system_flags,
2.583 - fileSystemNameBuffer,
2.584 - ctypes.sizeof(fileSystemNameBuffer)
2.585 - )
2.586 -
2.587 - return volumeNameBuffer.value, fileSystemNameBuffer.value
2.588 -
2.589 - @staticmethod
2.590 - def stop():
2.591 - """stop all running infinite loops now --> needed for gracefull shutdown"""
2.592 - _running = False
2.593 -
2.594 -
2.595 -
2.596 -def checkResult(result):
2.597 - if result[0] != 0:
2.598 - logger.error('Command failed:' + ''.join(result[2]))
2.599 - raise OpenSecurityException('Command failed:' + ''.join(result[2]))
2.600 - return result
2.601 -
2.602 -# handles browsing request
2.603 -class BrowsingHandler(threading.Thread):
2.604 - vmm = None
2.605 - def __init__(self, vmmanager):
2.606 - threading.Thread.__init__(self)
2.607 - self.vmm = vmmanager
2.608 -
2.609 - def run(self):
2.610 - try:
2.611 - new_sdvm = self.vmm.generateSDVMName()
2.612 - self.vmm.createVM(new_sdvm)
2.613 - self.vmm.storageAttach(new_sdvm)
2.614 - self.vmm.genCertificateISO(new_sdvm)
2.615 - self.vmm.attachCertificateISO(new_sdvm)
2.616 - self.vmm.startVM(new_sdvm)
2.617 - new_ip = self.vmm.waitStartup(new_sdvm)
2.618 - drive = self.vmm.genNetworkDrive()
2.619 - if new_ip != None:
2.620 - self.vmm.mapNetworkDrive(drive, '\\\\' + new_ip + '\\Download', None, None)
2.621 - result = checkResult(Cygwin.sshExecuteX11('/usr/bin/iceweasel', new_ip, 'osecuser', Cygwin.cygPath(self.vmm.getMachineFolder()) + '/' + new_sdvm + '/dvm_key'))
2.622 - except:
2.623 - logger.error("BrowsingHandler failed. Cleaning up")
2.624 -
2.625 - self.vmm.unmapNetworkDrive(drive)
2.626 - self.vmm.poweroffVM(new_sdvm)
2.627 - self.vmm.removeVM(new_sdvm)
2.628 -
2.629 -class DeviceHandler(threading.Thread):
2.630 - vmm = None
2.631 - #handleDeviceChangeLock = threading.Lock()
2.632 - attachedRSDs = None
2.633 - connectedRSDs = None
2.634 - running = True
2.635 - def __init__(self, vmmanger):
2.636 - threading.Thread.__init__(self)
2.637 - self.vmm = vmmanger
2.638 -
2.639 - def stop(self):
2.640 - self.running = False
2.641 -
2.642 - def run(self):
2.643 - self.connectedRSDs = dict()
2.644 - self.attachedRSDs = self.vmm.getAttachedRSDs()
2.645 - while self.running:
2.646 - tmp_rsds = self.vmm.getConnectedRSDS()
2.647 - if tmp_rsds.keys() == self.connectedRSDs.keys():
2.648 - logger.debug("Nothing's changed. sleep(3)")
2.649 - time.sleep(3)
2.650 - continue
2.651 -
2.652 - logger.info("Something's changed")
2.653 - self.connectedRSDs = tmp_rsds
2.654 - self.attachedRSDs = self.vmm.getAttachedRSDs()
2.655 -
2.656 - for vm_name in self.attachedRSDs.keys():
2.657 - if self.attachedRSDs[vm_name] not in self.connectedRSDs.values():
2.658 - drive = self.vmm.getNetworkDrive(vm_name)
2.659 - self.vmm.unmapNetworkDrive(drive)
2.660 - #self.stopVM(vm_name)
2.661 - self.vmm.detachRSD(vm_name)
2.662 - self.vmm.poweroffVM(vm_name)
2.663 - self.vmm.removeVM(vm_name)
2.664 - #create new vm for attached device if any
2.665 - self.attachedRSDs = self.vmm.getAttachedRSDs()
2.666 - self.connectedRSDs = self.vmm.getConnectedRSDS()
2.667 -
2.668 - new_ip = None
2.669 - for connected_device in self.connectedRSDs.values():
2.670 - if (self.attachedRSDs and False) or (connected_device not in self.attachedRSDs.values()):
2.671 - new_sdvm = self.vmm.generateSDVMName()
2.672 - self.vmm.createVM(new_sdvm)
2.673 - self.vmm.storageAttach(new_sdvm)
2.674 - self.vmm.attachRSD(new_sdvm, connected_device)
2.675 - self.vmm.startVM(new_sdvm)
2.676 - new_ip = self.vmm.waitStartup(new_sdvm)
2.677 - drive = self.vmm.genNetworkDrive()
2.678 - if new_ip != None:
2.679 - self.vmm.mapNetworkDrive(drive, '\\\\' + new_ip + '\\USB', None, None)
2.680 -
2.681 -if __name__ == '__main__':
2.682 - #man = VMManager.getInstance()
2.683 - #man.listVM()
2.684 - #print man.getConnectedRSDs()
2.685 - #print man.getNetworkDrives()
2.686 - #man.genNetworkDrive()
2.687 - #drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
2.688 - #print list(itertools.compress(string.ascii_uppercase, map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
2.689 - #print list(map(chr, range(68, 91)))
2.690 - #print Cygwin.getRegEntry('SYSTEM\CurrentControlSet\Enum\USB', 'VID_1058&PID_0704')[0]
2.691 - #devices = VMManager.getConnectedRSDS()
2.692 - #print devices
2.693 -
2.694 - drives = VMManager.getLogicalDrives()
2.695 - print drives
2.696 - print VMManager.getDriveType("E")
2.697 - print VMManager.getVolumeInfo("E")
2.698 - #for device in devices.values():
2.699 - # #print device
2.700 - # if VMManager.isMassStorageDevice(device):
2.701 - # print device
2.702 -
2.703 -
2.704 -
2.705 - #time.sleep(-1)
2.706 - #man.listVM()
2.707 - #man.listVM()
2.708 - #man.listVM()
2.709 - #man.listVM()
2.710 - #man.genCertificateISO('SecurityDVM0')
2.711 - #man.guestExecute('SecurityDVM0', '/bin/ls -la')
2.712 - #logger = setupLogger('VMManager')
2.713 - #c = Cygwin()
2.714 -
2.715 - #man.sshExecute('/bin/ls -la', 'SecurityDVM0')
2.716 - #man.sshExecuteX11('/usr/bin/iceweasel', 'SecurityDVM0')
2.717 - #man.removeVM('SecurityDVM0')
2.718 - #man.netUse('192.168.56.134', 'USB\\')
2.719 - #ip = '192.168.56.139'
2.720 -
2.721 - #man.cygwin_path = 'c:\\cygwin64\\bin\\'
2.722 - #man.handleDeviceChange()
2.723 - #print man.listSDVM()
2.724 - #man.configureHostNetworking()
2.725 - #new_vm = man.generateSDVMName()
2.726 - #man.createVM(new_vm)
2.727 -
2.728 - #print Cygwin.cmd()
2.729 - #man.isAvailable('c:')
2.730 - #ip = man.getHostOnlyIP('SecurityDVM0')
2.731 - #man.mapNetworkDrive('h:', '\\\\' + ip + '\Download', None, None)
2.732 -
2.733 - #man.genCertificateISO(new_vm)
2.734 - #man.attachCertificateISO(new_vm)
2.735 -
2.736 - #man.attachCertificateISO(vm_name)
2.737 - #man.guestExecute(vm_name, "ls")
2.738 - #man.sshGuestX11Execute('SecurityDVM1', '/usr/bin/iceweasel')
2.739 - #time.sleep(60)
2.740 - #print man.cygwinPath("C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\.ssh\*")
2.741 - #man.genCertificateISO('SecurityDVM')
2.742 - #man.attachCertificateISO('SecurityDVM')
2.743 - #man.isStorageAttached('SecurityDVM')
2.744 - #man.guestExecute('SecurityDVM', 'sudo apt-get -y update')
2.745 - #man.guestExecute('SecurityDVM', 'sudo apt-get -y upgrade' )
2.746 -
2.747 - #man.stopVM('SecurityDVM')
2.748 - #man.storageDetach('SecurityDVM')
2.749 - #man.changeStorageType('C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\SecurityDVM.vmdk','immutable')
2.750 - #man.storageAttach('SecurityDVM')
2.751 -
2.752 -
2.753 - #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
2.754 - #man.execute(cmd)
2.755 ->>>>>>> other