# HG changeset patch # User BarthaM@N3SIM1218.D03.arc.local # Date 1405588810 -3600 # Node ID 59ebaa44c12cefb87e8989034f3342150831f411 # Parent cb04add9c85a2f83bc88e530261ad65edfbe4f50 Modified update_template to cope with unattached .vmdk Added start method to vmmanager Modified vmmanager to not start automatically over getInstance() invocation Modified cygwin to corectly get the root folder (OpenSecurity//bin) diff -r cb04add9c85a -r 59ebaa44c12c OpenSecurity/bin/cygwin.py --- a/OpenSecurity/bin/cygwin.py Tue Jul 01 10:50:48 2014 +0200 +++ b/OpenSecurity/bin/cygwin.py Thu Jul 17 10:20:10 2014 +0100 @@ -52,14 +52,14 @@ def once(theClass): """get the path to our local cygwin installment""" home_drive = os.path.expandvars("%HOMEDRIVE%") + os.sep + e = Environment('OpenSecurity') path_hint = [ - os.path.abspath(os.path.join(Environment('OpenSecurity').prefix_path, 'cygwin')), - os.path.abspath(os.path.join(Environment('OpenSecurity').prefix_path, 'cygwin64')), + os.path.abspath(os.path.join(e.prefix_path, 'cygwin')), + os.path.abspath(os.path.join(e.prefix_path, 'cygwin64')), os.path.abspath(os.path.join(home_drive, 'cygwin')), os.path.abspath(os.path.join(home_drive, 'cygwin64')) ] path_valid = [ p for p in path_hint if os.path.exists(p) ] - theClass.cygwin_root = path_valid[0] theClass.cygwin_bin = os.path.join(theClass.cygwin_root, 'bin') + os.path.sep theClass.cygwin_bash = os.path.join(theClass.cygwin_bin, 'bash.exe') @@ -150,8 +150,7 @@ _startupinfo.wShowWindow = _subprocess.SW_HIDE #logger.debug('trying to launch: ' + program + ' ' + ''.join(arguments)) - result, res_stdout, res_stderr = None, None, None - + result, res_stdout, res_stderr = None, None, None try: # quote the executable otherwise we run into troubles # when the path contains spaces and additonal arguments @@ -163,11 +162,11 @@ process = Popen(args, startupinfo = _startupinfo, stdin = stdin, stdout = stdout, stderr = stderr, shell = False) if not wait_return: return [0, 'working in background', ''] - + res_stdout, res_stderr = process.communicate() result = process.returncode logger.debug('Finished: ' + program + ' ' + ''.join(arguments)) - #result = process.wait() + #result = process.wait() #res_stdout = process.stdout.read(); #res_stderr = process.stderr.read(); @@ -178,10 +177,10 @@ return result, res_stdout, res_stderr @staticmethod - def vboxExecute(command, wait_return=True, window = False, bash_opts=''): + def vboxExecute(command, wait_return=True, window = False, bash_opts='', try_count = 3): retry = 0 result = None - while retry < 3: + while retry < try_count: if Cygwin.executeLock.acquire(True): result = Cygwin.execute(Cygwin.vbox_man, command, wait_return, window) Cygwin.executeLock.release() @@ -209,8 +208,8 @@ def sshExecute(command, address, user_name, certificate, wait_return=True, window = False): command = ' -v -o StrictHostKeyChecking=no -i "' + certificate + '" ' + user_name + '@' + address + ' ' + command return Cygwin.execute(Cygwin.cygwin_ssh, command, wait_return, window) - - # executes command over ssh on guest vm + + # executes command over ssh on guest vm @staticmethod def sshBackgroundExecute(command, address, user_name, certificate, wait_return=True, window = False): command = ' -f -v -o StrictHostKeyChecking=no -i "' + certificate + '" ' + user_name + '@' + address + ' ' + command @@ -263,12 +262,12 @@ if __name__ == "__main__": logger = setupLogger('Cygwin') c = Cygwin() - #logger.info(c.root()) - #logger.info(c.bin()) - #logger.info(c.bash()) - #logger.info(c.ssh()) - #logger.info(c.x11()) - #logger.info(c.home()) + logger.info(c.root()) + logger.info(c.bin()) + logger.info(c.bash()) + logger.info(c.ssh()) + logger.info(c.x11()) + logger.info(c.home()) #PSEXEC -i -s -d CMD #tasklist /v /fo list /fi "IMAGENAME eq explorer.exe" @@ -277,8 +276,6 @@ #runner.start() #Cygwin.start_X11() - - #time.sleep(500) diff -r cb04add9c85a -r 59ebaa44c12c OpenSecurity/bin/environment.py --- a/OpenSecurity/bin/environment.py Tue Jul 01 10:50:48 2014 +0200 +++ b/OpenSecurity/bin/environment.py Thu Jul 17 10:20:10 2014 +0100 @@ -46,6 +46,7 @@ """Hold some nifty environment stuff in a dedicated class.""" _log_warning_shown = False + _prefix_path = '' def __init__(self, application = None): @@ -66,7 +67,13 @@ if sys.platform == 'linux2': self._prefix_path = os.path.split(sys.path[0])[0] elif sys.platform == 'win32' or sys.platform == 'cygwin': - self._prefix_path = os.path.normpath(os.path.join(sys.path[0], '..')) + for app_path in sys.path: + if 'OpenSecurity\\bin' in app_path: + self._prefix_path = os.path.normpath(os.path.join(app_path, '..')) + break + + if self._prefix_path == '': + raise OSError() # the data path where all data files are stored if sys.platform == 'linux2': @@ -142,7 +149,7 @@ def test(): """Test: class Environment""" - e = Environment('My Application') + e = Environment('OpenSecurity') print('prefix_path: "{0}"'.format(e.prefix_path)) print(' data_path: "{0}"'.format(e.data_path)) print(' log_path: "{0}"'.format(e.log_path)) diff -r cb04add9c85a -r 59ebaa44c12c OpenSecurity/bin/opensecurity_util.py --- a/OpenSecurity/bin/opensecurity_util.py Tue Jul 01 10:50:48 2014 +0200 +++ b/OpenSecurity/bin/opensecurity_util.py Thu Jul 17 10:20:10 2014 +0100 @@ -1,12 +1,42 @@ #!/bin/env python # -*- coding: utf-8 -*- +# ------------------------------------------------------------ +# opensecurityd +# +# the opensecurityd as RESTful server +# +# Autor: Mihai Bartha, +# +# Copyright (C) 2013 AIT Austrian Institute of Technology +# AIT Austrian Institute of Technology GmbH +# Donau-City-Strasse 1 | 1220 Vienna | Austria +# http://www.ait.ac.at +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation version 2. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, +# Boston, MA 02110-1301, USA. +# ------------------------------------------------------------ + + +# ------------------------------------------------------------ +# imports + import logging import os import urllib import urllib2 - # local from environment import Environment diff -r cb04add9c85a -r 59ebaa44c12c OpenSecurity/bin/opensecurityd.pyw --- a/OpenSecurity/bin/opensecurityd.pyw Tue Jul 01 10:50:48 2014 +0200 +++ b/OpenSecurity/bin/opensecurityd.pyw Thu Jul 17 10:20:10 2014 +0100 @@ -3,10 +3,11 @@ # ------------------------------------------------------------ # opensecurityd -# +# # the opensecurityd as RESTful server # # Autor: Oliver Maurhart, +# Mihai Bartha, # # Copyright (C) 2013 AIT Austrian Institute of Technology # AIT Austrian Institute of Technology GmbH @@ -70,6 +71,7 @@ '/vms/(.*)', 'os_vm', # http://localhost:8080/vms/[VMNAME] GET '/update_template', 'os_update_template', # http://localhost:8080/update_template GET '/terminate', 'os_terminate', # http://localhost:8080/terminate GET + '/initialize', 'os_initialize', # http://localhost:8080/initialize GET '/', 'os_root' # http://localhost:8080/ GET ) @@ -377,6 +379,21 @@ server.stop() return None +class os_initialize: + """OpenSecurity '/initialize' handler + + - GET: initialize / starts the vmmanager. + + """ + + def GET(self): + log_call(web.ctx.environ) + global gvm_mgr + gvm_mgr.cleanup() + gvm_mgr.start() + global server + server.run() + return None class os_update_template: """OpenSecurity '/update_template' handler @@ -434,7 +451,7 @@ # ensure a VMManger is yet loaded gvm_mgr = vmmanager.VMManager.getInstance() - + gvm_mgr.start() # tweak sys.argv to control wep.py server start behavior sys.argv = [__file__, "8080"] server = web.application(opensecurity_urls, globals(), autoreload = False) diff -r cb04add9c85a -r 59ebaa44c12c OpenSecurity/bin/test_vmmanager.pyw --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/OpenSecurity/bin/test_vmmanager.pyw Thu Jul 17 10:20:10 2014 +0100 @@ -0,0 +1,155 @@ +#!/bin/env python +# -*- coding: utf-8 -*- + +# ------------------------------------------------------------ +# opensecurityd +# +# the opensecurityd as RESTful server +# +# Autor: Mihai Bartha, +# +# Copyright (C) 2013 AIT Austrian Institute of Technology +# AIT Austrian Institute of Technology GmbH +# Donau-City-Strasse 1 | 1220 Vienna | Austria +# http://www.ait.ac.at +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation version 2. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, +# Boston, MA 02110-1301, USA. +# ------------------------------------------------------------ + + +# ------------------------------------------------------------ +# imports + +import unittest + +import os +import os.path +import sys +import cygwin +import vmmanager +gvm_mgr = None + +class TestVMManager(unittest.TestCase): + + def setUp(self): + pass + + @classmethod + def setUpClass(self): + global gvm_mgr + gvm_mgr = vmmanager.VMManager.getInstance() + pass + + @unittest.skip("skipping") + def testGetTemplateUUID(self): + template = vmmanager.VMManager.getTemplateUUID() + self.assertIsNotNone(template, "returned no UUID for template") + + #@unittest.skip("skipping (requires running vmmanager)") + def testUpdateTemplate(self): + gvm_mgr.updateTemplate() + pass + + #@classmethod + #def tearOffClass(self): + # gvm_mgr.stop() + # gvm_mgr.cleanup() + + +if __name__ == '__main__': + TestVMManager.setUpClass() + + suite = unittest.TestLoader().loadTestsFromTestCase(TestVMManager) + unittest.TextTestRunner().run(suite) + +# logger = setupLogger('Cygwin') +# c = Cygwin() +# unittest.main() + #man = VMManager.getInstance() + #man.listVM() + #print man.getConnectedRSDs() + #print man.getNetworkDrives() + #man.genNetworkDrive() + #drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives() + #print list(itertools.compress(string.ascii_uppercase, map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1]))) + #print list(map(chr, range(68, 91))) + #print Cygwin.getRegEntry('SYSTEM\CurrentControlSet\Enum\USB', 'VID_1058&PID_0704')[0] + #devices = VMManager.getConnectedRSDS() + #print devices + + #drives = VMManager.getLogicalDrives() + #print drives + #print VMManager.getDriveType("E") + #print VMManager.getVolumeInfo("E") + #print VMManager.getNetworkPath("E") + + #vmm.backupFile() + #for device in devices.values(): + # #print device + # if VMManager.isMassStorageDevice(device): + # print device + + + + #time.sleep(-1) + #man.listVM() + #man.listVM() + #man.listVM() + #man.listVM() + #man.genCertificateISO('SecurityDVM0') + #man.guestExecute('SecurityDVM0', '/bin/ls -la') + #logger = setupLogger('VMManager') + #c = Cygwin() + + #man.sshExecute('/bin/ls -la', 'SecurityDVM0') + #man.sshExecuteX11('/usr/bin/iceweasel', 'SecurityDVM0') + #man.removeVM('SecurityDVM0') + #man.netUse('192.168.56.134', 'USB\\') + #ip = '192.168.56.139' + + #man.cygwin_path = 'c:\\cygwin64\\bin\\' + #man.handleDeviceChange() + #print man.listSDVM() + #man.configureHostNetworking() + #new_vm = man.generateSDVMName() + #man.createVM(new_vm) + + #print Cygwin.cmd() + #man.isAvailable('c:') + #ip = man.getHostOnlyIP('SecurityDVM0') + #man.mapNetworkDrive('h:', '\\\\' + ip + '\Download', None, None) + + #man.genCertificateISO(new_vm) + #man.attachCertificateISO(new_vm) + + #man.attachCertificateISO(vm_name) + #man.guestExecute(vm_name, "ls") + #man.sshGuestX11Execute('SecurityDVM1', '/usr/bin/iceweasel') + #time.sleep(60) + #print man.cygwinPath("C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\.ssh\*") + #man.genCertificateISO('SecurityDVM') + #man.attachCertificateISO('SecurityDVM') + #man.isStorageAttached('SecurityDVM') + #man.guestExecute('SecurityDVM', 'sudo apt-get -y update') + #man.guestExecute('SecurityDVM', 'sudo apt-get -y upgrade' ) + + #man.stopVM('SecurityDVM') + #man.storageDetach('SecurityDVM') + #man.changeStorageType('C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\SecurityDVM.vmdk','immutable') + #man.storageAttach('SecurityDVM') + + + #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\"" + #man.execute(cmd) \ No newline at end of file diff -r cb04add9c85a -r 59ebaa44c12c OpenSecurity/bin/vmmanager.pyw --- a/OpenSecurity/bin/vmmanager.pyw Tue Jul 01 10:50:48 2014 +0200 +++ b/OpenSecurity/bin/vmmanager.pyw Thu Jul 17 10:20:10 2014 +0100 @@ -1,8 +1,37 @@ -''' -Created on Nov 19, 2013 +#!/bin/env python +# -*- coding: utf-8 -*- -@author: BarthaM -''' +# ------------------------------------------------------------ +# opensecurityd +# +# the opensecurityd as RESTful server +# +# Autor: Mihai Bartha, +# +# Copyright (C) 2013 AIT Austrian Institute of Technology +# AIT Austrian Institute of Technology GmbH +# Donau-City-Strasse 1 | 1220 Vienna | Austria +# http://www.ait.ac.at +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation version 2. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, +# Boston, MA 02110-1301, USA. +# ------------------------------------------------------------ + + +# ------------------------------------------------------------ +# imports + import os import os.path from subprocess import Popen, PIPE, call, STARTUPINFO, _subprocess @@ -27,6 +56,7 @@ import win32wnet import urllib import urllib2 +import unittest DEBUG = True @@ -64,7 +94,14 @@ #def __getitem__(self, item): # return self.coords[item] - +def once(theClass): + theClass.systemProperties = theClass.getSystemProperties() + theClass.machineFolder = theClass.systemProperties["Default machine folder"] + theClass.hostonlyIFs = theClass.getHostOnlyIFs() + theClass.blacklistedRSD = theClass.loadRSDBlacklist() + return theClass + +@once class VMManager(object): vmRootName = "SecurityDVM" systemProperties = None @@ -78,14 +115,9 @@ def __init__(self): - self.systemProperties = self.getSystemProperties() - self.machineFolder = self.systemProperties["Default machine folder"] - self.hostonlyIFs = self.getHostOnlyIFs() - VMManager.blacklistedRSD = self.loadRSDBlacklist() # only proceed if we have a working background environment if self.backend_ok(): self.cleanup() - self.start() else: logger.critical(self.status_message) @@ -116,24 +148,24 @@ # return the folder containing the guest VMs def getMachineFolder(self): - return self.machineFolder + return VMManager.machineFolder def backend_ok(self): """check if the backend (VirtualBox) is sufficient for our task""" # ensure we have our system props - if self.systemProperties == None: - self.systemProperties = self.getSystemProperties() - if self.systemProperties == None: + if VMManager.systemProperties == None: + VMManager.systemProperties = self.getSystemProperties() + if VMManager.systemProperties == None: self.status_message = 'Failed to get backend system properties. Is Backend (VirtualBox?) installed?' return False # check for existing Extension pack - if not 'Remote desktop ExtPack' in self.systemProperties: + if not 'Remote desktop ExtPack' in VMManager.systemProperties: self.status_message = 'No remote desktop extension pack found. Please install the "Oracle VM VirtualBox Extension Pack" from https://www.virtualbox.org/wiki/Downloads.' return False - if self.systemProperties['Remote desktop ExtPack'] == 'Oracle VM VirtualBox Extension Pack ': + if VMManager.systemProperties['Remote desktop ExtPack'] == 'Oracle VM VirtualBox Extension Pack ': 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.' return False @@ -336,11 +368,11 @@ if self.isSDVMExisting(vm_name): return #remove eventually existing SDVM folder - machineFolder = Cygwin.cygPath(self.machineFolder) + machineFolder = Cygwin.cygPath(VMManager.machineFolder) Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '\\\"')) hostonly_if = self.getHostOnlyIFs() Cygwin.checkResult(Cygwin.vboxExecute('createvm --name ' + vm_name + ' --ostype Debian --register')) - Cygwin.checkResult(Cygwin.vboxExecute('modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat')) + Cygwin.checkResult(Cygwin.vboxExecute('modifyvm ' + vm_name + ' --memory 768 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat')) Cygwin.checkResult(Cygwin.vboxExecute('storagectl ' + vm_name + ' --name SATA --add sata --portcount 2')) #create new SecurityDVM with automatically generated name from template (thread safe) @@ -354,7 +386,7 @@ def storageAttach(self, vm_name): if self.isStorageAttached(vm_name): self.storageDetach(vm_name) - Cygwin.checkResult(Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium \"'+ self.machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"')) + Cygwin.checkResult(Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium \"'+ VMManager.machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"')) # return true if storage is attached def isStorageAttached(self, vm_name): @@ -379,19 +411,22 @@ # check for updates self.genCertificateISO(self.vmRootName) self.attachCertificateISO(self.vmRootName) - imageUUID = self.getVMInfo(self.vmRootName)["SATA-ImageUUID-0-0"] #TODO: // verify value + + #templateUUID = self.getVMInfo(self.vmRootName)["SATA-ImageUUID-0-0"] #TODO: // verify value + templateUUID = self.getTemplateUUID() + self.storageDetach(self.vmRootName) - self.removeSnapshots(imageUUID) + self.removeSnapshots(templateUUID) - template_storage = self.machineFolder + '\\' + self.vmRootName + '\\' + self.vmRootName + '.vmdk' + template_storage = VMManager.machineFolder + '\\' + self.vmRootName + '\\' + self.vmRootName + '.vmdk' #TODO:// modify to take vm name as argument self.changeStorageType(template_storage,'normal') self.storageAttach(self.vmRootName) self.startVM(self.vmRootName) - self.waitStartup(self.vmRootName) + self.waitStartup(self.vmRootName, timeout_ms = 30000) tmp_ip = self.getHostOnlyIP(self.vmRootName) - tmp_machine_folder = Cygwin.cygPath(self.machineFolder) + tmp_machine_folder = Cygwin.cygPath(VMManager.machineFolder) Cygwin.checkResult(Cygwin.sshExecute('"sudo apt-get -y update"', tmp_ip, 'osecuser', tmp_machine_folder + '/' + self.vmRootName + '/dvm_key')) Cygwin.checkResult(Cygwin.sshExecute('"sudo apt-get -y upgrade"', tmp_ip, 'osecuser', tmp_machine_folder + '/' + self.vmRootName + '/dvm_key')) @@ -403,17 +438,19 @@ self.startVM(self.vmRootName) self.waitStartup(self.vmRootName) - self.hibernateVM(self.vmRootName) + #self.hibernateVM(self.vmRootName) + self.stopVM(self.vmRootName) self.waitShutdown(self.vmRootName) self.storageDetach(self.vmRootName) self.changeStorageType(template_storage,'immutable') self.storageAttach(self.vmRootName) - self.start() + #self.start() #"SATA-0-0"="C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\Snapshots\{d0af827d-f13a-49be-8ac1-df20b13bda83}.vmdk" - #"SATA-ImageUUID-0-0"="d0af827d-f13a-49be-8ac1-df20b13bda83" - def getDiskImages(self): + #"SATA-ImageUUID-0-0"="d0af827d-f13a-49be-8ac1-df20b13bda83" + @staticmethod + def getDiskImages(): results = Cygwin.checkResult(Cygwin.vboxExecute('list hdds'))[1] results = results.replace('Parent UUID', 'Parent') items = list( "UUID:"+result for result in results.split('UUID:') if result != '') @@ -428,9 +465,10 @@ snaps[props['UUID']] = props return snaps - def getTemplateUUID(self): - images = self.getDiskImages() - template_storage = self.machineFolder + '\\' + self.vmRootName + '/' +self.vmRootName + '.vmdk' + @staticmethod + def getTemplateUUID(): + images = VMManager.getDiskImages() + template_storage = VMManager.machineFolder + '\\' + VMManager.vmRootName + '\\' + VMManager.vmRootName + '.vmdk' # find template uuid template_uuid = None for hdd in images.values(): @@ -462,18 +500,19 @@ self.removeVMFolder(vm_name) def removeVMFolder(self, vm_name): - machineFolder = Cygwin.cygPath(self.machineFolder) + machineFolder = Cygwin.cygPath(VMManager.machineFolder) Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '\\\"')) # start VM def startVM(self, vm_name): logger.info('Starting ' + vm_name) - result = Cygwin.checkResult(Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless' )) + #TODO: modify to use Cygwin.checkResult() of make it retry 3 times + result = Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless' ) while 'successfully started' not in result[1]: logger.error("Failed to start SDVM: " + vm_name + " retrying") logger.error("Command returned:\n" + result[2]) time.sleep(1) - result = Cygwin.checkResult(Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless')) + result = Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless') return result[0] # return wether VM is running or not @@ -483,12 +522,12 @@ # stop VM def stopVM(self, vm_name): logger.info('Sending shutdown signal to ' + vm_name) - Cygwin.checkResult(Cygwin.sshExecute( '"sudo shutdown -h now"', self.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + vm_name + '/dvm_key' )) + Cygwin.checkResult(Cygwin.sshExecute( '"sudo shutdown -h now"', self.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(VMManager.machineFolder) + '/' + vm_name + '/dvm_key' )) # stop VM def hibernateVM(self, vm_name): logger.info('Sending hibernate-disk signal to ' + vm_name) - Cygwin.checkResult(Cygwin.sshBackgroundExecute( '"sudo hibernate-disk"', self.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + vm_name + '/dvm_key', wait_return=False)) + Cygwin.checkResult(Cygwin.sshBackgroundExecute( '"sudo hibernate-disk"', self.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(VMManager.machineFolder) + '/' + vm_name + '/dvm_key', wait_return=False)) # poweroff VM def poweroffVM(self, vm_name): @@ -502,7 +541,7 @@ if vm_name == None: logger.info('Getting hostOnly IP address for Host') #TODO:// optimise to store on init local variable and return that value (avoid calling list hostonlyifs) - return self.hostonlyIFs['IPAddress'] + return VMManager.hostonlyIFs['IPAddress'] else: logger.info('Getting hostOnly IP address ' + vm_name) result = Cygwin.checkResult(Cygwin.vboxExecute('guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP')) @@ -521,7 +560,7 @@ #generates ISO containing authorized_keys for use with guest VM def genCertificateISO(self, vm_name): - machineFolder = Cygwin.cygPath(self.machineFolder) + machineFolder = Cygwin.cygPath(VMManager.machineFolder) # remove .ssh folder if exists Cygwin.checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"')) # remove .ssh folder if exists @@ -543,12 +582,12 @@ # attaches generated ssh public cert to guest vm def attachCertificateISO(self, vm_name): - result = Cygwin.checkResult(Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + self.machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"')) + 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\"')) return result # wait for machine to come up - def waitStartup(self, vm_name, timeout_ms = 30000): - Cygwin.checkResult(Cygwin.vboxExecute('guestproperty wait ' + vm_name + ' SDVMStarted --timeout ' + str(timeout_ms) + ' --fail-on-timeout')) + def waitStartup(self, vm_name, timeout_ms = 1000): + Cygwin.checkResult(Cygwin.vboxExecute('guestproperty wait ' + vm_name + ' SDVMStarted --timeout ' + str(timeout_ms) + ' --fail-on-timeout', try_count = 60)) return self.getHostOnlyIP(vm_name) # wait for machine to shutdown @@ -681,7 +720,6 @@ command = '-r -o StrictHostKeyChecking=no -i "' + certificate + '" "' + src + '" "osecuser@' + self.browsingManager.ip_addr + ':' + dest + '"' return Cygwin.execute(Cygwin.cygwin_scp, command, wait_return=True, window=False) - #handles browsing session creation class BrowsingHandler(threading.Thread): vmm = None @@ -748,8 +786,10 @@ self.vmm.storageAttach(self.vm_name) self.vmm.genCertificateISO(self.vm_name) self.vmm.attachCertificateISO(self.vm_name) + self.vmm.startVM(self.vm_name) - self.ip_addr = self.vmm.waitStartup(self.vm_name) + + self.ip_addr = self.vmm.waitStartup(self.vm_name, timeout_ms=30000) if self.ip_addr == None: logger.error("Failed to get ip address") continue @@ -797,8 +837,12 @@ self.started.set() logger.info("Browsing SDVM running.") self.restart.wait() + except OpenSecurityException, e: + logger.error(''.join(e)) except: + logger.error("Unexpected error: " + sys.exc_info()[0]) logger.error("BrowsingHandler failed. Cleaning up") + #self.running= False class DeviceHandler(threading.Thread): vmm = None @@ -881,82 +925,3 @@ continue self.existingRSDs = tmp_rsds - - -if __name__ == '__main__': - #man = VMManager.getInstance() - #man.listVM() - #print man.getConnectedRSDs() - #print man.getNetworkDrives() - #man.genNetworkDrive() - #drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives() - #print list(itertools.compress(string.ascii_uppercase, map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1]))) - #print list(map(chr, range(68, 91))) - #print Cygwin.getRegEntry('SYSTEM\CurrentControlSet\Enum\USB', 'VID_1058&PID_0704')[0] - #devices = VMManager.getConnectedRSDS() - #print devices - - drives = VMManager.getLogicalDrives() - print drives - print VMManager.getDriveType("E") - print VMManager.getVolumeInfo("E") - print VMManager.getNetworkPath("E") - - #vmm.backupFile() - #for device in devices.values(): - # #print device - # if VMManager.isMassStorageDevice(device): - # print device - - - - #time.sleep(-1) - #man.listVM() - #man.listVM() - #man.listVM() - #man.listVM() - #man.genCertificateISO('SecurityDVM0') - #man.guestExecute('SecurityDVM0', '/bin/ls -la') - #logger = setupLogger('VMManager') - #c = Cygwin() - - #man.sshExecute('/bin/ls -la', 'SecurityDVM0') - #man.sshExecuteX11('/usr/bin/iceweasel', 'SecurityDVM0') - #man.removeVM('SecurityDVM0') - #man.netUse('192.168.56.134', 'USB\\') - #ip = '192.168.56.139' - - #man.cygwin_path = 'c:\\cygwin64\\bin\\' - #man.handleDeviceChange() - #print man.listSDVM() - #man.configureHostNetworking() - #new_vm = man.generateSDVMName() - #man.createVM(new_vm) - - #print Cygwin.cmd() - #man.isAvailable('c:') - #ip = man.getHostOnlyIP('SecurityDVM0') - #man.mapNetworkDrive('h:', '\\\\' + ip + '\Download', None, None) - - #man.genCertificateISO(new_vm) - #man.attachCertificateISO(new_vm) - - #man.attachCertificateISO(vm_name) - #man.guestExecute(vm_name, "ls") - #man.sshGuestX11Execute('SecurityDVM1', '/usr/bin/iceweasel') - #time.sleep(60) - #print man.cygwinPath("C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\.ssh\*") - #man.genCertificateISO('SecurityDVM') - #man.attachCertificateISO('SecurityDVM') - #man.isStorageAttached('SecurityDVM') - #man.guestExecute('SecurityDVM', 'sudo apt-get -y update') - #man.guestExecute('SecurityDVM', 'sudo apt-get -y upgrade' ) - - #man.stopVM('SecurityDVM') - #man.storageDetach('SecurityDVM') - #man.changeStorageType('C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\SecurityDVM.vmdk','immutable') - #man.storageAttach('SecurityDVM') - - - #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\"" - #man.execute(cmd)