mb@90
|
1 |
'''
|
mb@90
|
2 |
Created on Nov 19, 2013
|
mb@90
|
3 |
|
mb@90
|
4 |
@author: BarthaM
|
mb@90
|
5 |
'''
|
mb@90
|
6 |
import os
|
mb@90
|
7 |
import os.path
|
mb@90
|
8 |
from subprocess import Popen, PIPE, call, STARTUPINFO, _subprocess
|
mb@90
|
9 |
import sys
|
mb@90
|
10 |
import re
|
mb@90
|
11 |
|
mb@90
|
12 |
from cygwin import Cygwin
|
mb@90
|
13 |
from environment import Environment
|
mb@90
|
14 |
import threading
|
mb@90
|
15 |
import time
|
mb@90
|
16 |
import string
|
mb@90
|
17 |
|
mb@90
|
18 |
import shutil
|
mb@90
|
19 |
import stat
|
mb@90
|
20 |
import tempfile
|
mb@90
|
21 |
from opensecurity_util import logger, setupLogger, OpenSecurityException
|
mb@90
|
22 |
import ctypes
|
mb@90
|
23 |
import itertools
|
mb@90
|
24 |
import _winreg
|
mb@90
|
25 |
DEBUG = True
|
mb@90
|
26 |
|
mb@90
|
27 |
class VMManagerException(Exception):
|
mb@90
|
28 |
def __init__(self, value):
|
mb@90
|
29 |
self.value = value
|
mb@90
|
30 |
def __str__(self):
|
mb@90
|
31 |
return repr(self.value)
|
mb@90
|
32 |
|
mb@90
|
33 |
class USBFilter:
|
mb@90
|
34 |
vendorid = ""
|
mb@90
|
35 |
productid = ""
|
mb@90
|
36 |
revision = ""
|
mb@90
|
37 |
|
mb@90
|
38 |
def __init__(self, vendorid, productid, revision):
|
mb@90
|
39 |
self.vendorid = vendorid.lower()
|
mb@90
|
40 |
self.productid = productid.lower()
|
mb@90
|
41 |
self.revision = revision.lower()
|
mb@90
|
42 |
return
|
mb@90
|
43 |
|
mb@90
|
44 |
def __eq__(self, other):
|
mb@90
|
45 |
return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
|
mb@90
|
46 |
|
mb@90
|
47 |
def __hash__(self):
|
mb@90
|
48 |
return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
|
mb@90
|
49 |
|
mb@90
|
50 |
def __repr__(self):
|
mb@90
|
51 |
return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
|
mb@90
|
52 |
|
mb@90
|
53 |
#def __getitem__(self, item):
|
mb@90
|
54 |
# return self.coords[item]
|
mb@90
|
55 |
|
mb@90
|
56 |
class VMManager(object):
|
mb@90
|
57 |
vmRootName = "SecurityDVM"
|
mb@90
|
58 |
systemProperties = None
|
mb@90
|
59 |
_instance = None
|
mb@90
|
60 |
machineFolder = ''
|
mb@90
|
61 |
rsdHandler = None
|
BarthaM@141
|
62 |
browsingManager = None
|
oliver@131
|
63 |
status_message = 'Starting up...'
|
oliver@131
|
64 |
|
oliver@131
|
65 |
|
oliver@131
|
66 |
def __init__(self):
|
oliver@131
|
67 |
|
oliver@131
|
68 |
self.systemProperties = self.getSystemProperties()
|
oliver@133
|
69 |
self.machineFolder = self.systemProperties["Default machine folder"]
|
oliver@131
|
70 |
|
oliver@131
|
71 |
# only proceed if we have a working background environment
|
oliver@131
|
72 |
if self.backend_ok():
|
oliver@131
|
73 |
self.cleanup()
|
oliver@131
|
74 |
self.rsdHandler = DeviceHandler(self)
|
oliver@131
|
75 |
self.rsdHandler.start()
|
BarthaM@141
|
76 |
self.browsingManager = BrowsingManager(self)
|
BarthaM@141
|
77 |
self.browsingManager.start()
|
oliver@131
|
78 |
else:
|
oliver@131
|
79 |
logger.critical(self.status_message)
|
mb@90
|
80 |
|
oliver@131
|
81 |
|
mb@90
|
82 |
@staticmethod
|
mb@90
|
83 |
def getInstance():
|
mb@90
|
84 |
if VMManager._instance == None:
|
mb@90
|
85 |
VMManager._instance = VMManager()
|
mb@90
|
86 |
return VMManager._instance
|
mb@90
|
87 |
|
oliver@131
|
88 |
|
oliver@131
|
89 |
def backend_ok(self):
|
oliver@131
|
90 |
|
oliver@131
|
91 |
"""check if the backend (VirtualBox) is sufficient for our task"""
|
oliver@131
|
92 |
|
oliver@131
|
93 |
# ensure we have our system props
|
oliver@131
|
94 |
if self.systemProperties == None:
|
oliver@131
|
95 |
self.systemProperties = self.getSystemProperties()
|
oliver@131
|
96 |
if self.systemProperties == None:
|
oliver@131
|
97 |
self.status_message = 'Failed to get backend system properties. Is Backend (VirtualBox?) installed?'
|
oliver@131
|
98 |
return False
|
oliver@131
|
99 |
|
oliver@131
|
100 |
# check for existing Extension pack
|
oliver@131
|
101 |
if not 'Remote desktop ExtPack' in self.systemProperties:
|
oliver@131
|
102 |
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
|
103 |
return False
|
oliver@131
|
104 |
if self.systemProperties['Remote desktop ExtPack'] == 'Oracle VM VirtualBox Extension Pack ':
|
oliver@131
|
105 |
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
|
106 |
return False
|
oliver@131
|
107 |
|
oliver@131
|
108 |
# check if we do have our root VMs installed
|
oliver@131
|
109 |
vms = self.listVM()
|
oliver@131
|
110 |
if not self.vmRootName in vms:
|
oliver@131
|
111 |
self.status_message = 'Unable to locate root SecurityDVM. Please download and setup the initial image.'
|
oliver@131
|
112 |
return False
|
oliver@131
|
113 |
|
oliver@131
|
114 |
# basically all seems nice and ready to rumble
|
oliver@131
|
115 |
self.status_message = 'All is ok.'
|
oliver@131
|
116 |
|
oliver@131
|
117 |
return True
|
oliver@131
|
118 |
|
oliver@131
|
119 |
|
mb@90
|
120 |
def cleanup(self):
|
mb@90
|
121 |
if self.rsdHandler != None:
|
mb@90
|
122 |
self.rsdHandler.stop()
|
mb@90
|
123 |
self.rsdHandler.join()
|
mb@90
|
124 |
drives = self.getNetworkDrives()
|
mb@90
|
125 |
for drive in drives.keys():
|
BarthaM@135
|
126 |
driveHandler = UnmapDriveHandler(self, drive)
|
BarthaM@135
|
127 |
driveHandler.start()
|
mb@90
|
128 |
for vm in self.listSDVM():
|
mb@90
|
129 |
self.poweroffVM(vm)
|
mb@90
|
130 |
self.removeVM(vm)
|
mb@90
|
131 |
|
mb@90
|
132 |
# return hosty system properties
|
mb@90
|
133 |
def getSystemProperties(self):
|
mb@90
|
134 |
result = checkResult(Cygwin.vboxExecute('list systemproperties'))
|
mb@90
|
135 |
if result[1]=='':
|
mb@90
|
136 |
return None
|
mb@90
|
137 |
props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
|
mb@90
|
138 |
return props
|
mb@90
|
139 |
|
mb@90
|
140 |
# return the folder containing the guest VMs
|
mb@90
|
141 |
def getMachineFolder(self):
|
mb@90
|
142 |
return self.machineFolder
|
mb@90
|
143 |
|
mb@90
|
144 |
# list all existing VMs registered with VBox
|
mb@90
|
145 |
def listVM(self):
|
mb@90
|
146 |
result = checkResult(Cygwin.vboxExecute('list vms'))[1]
|
mb@90
|
147 |
vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
|
mb@90
|
148 |
return vms
|
mb@90
|
149 |
|
mb@90
|
150 |
# list running VMs
|
mb@90
|
151 |
def listRunningVMS(self):
|
mb@90
|
152 |
result = checkResult(Cygwin.vboxExecute('list runningvms'))[1]
|
mb@90
|
153 |
vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
|
mb@90
|
154 |
return vms
|
mb@90
|
155 |
|
mb@90
|
156 |
# list existing SDVMs
|
mb@90
|
157 |
def listSDVM(self):
|
mb@90
|
158 |
vms = self.listVM()
|
mb@90
|
159 |
svdms = []
|
mb@90
|
160 |
for vm in vms:
|
mb@90
|
161 |
if vm.startswith(self.vmRootName) and vm != self.vmRootName:
|
mb@90
|
162 |
svdms.append(vm)
|
mb@90
|
163 |
return svdms
|
mb@90
|
164 |
|
mb@90
|
165 |
# generate valid (not already existing SDVM name). necessary for creating a new VM
|
mb@90
|
166 |
def generateSDVMName(self):
|
mb@90
|
167 |
vms = self.listVM()
|
mb@90
|
168 |
for i in range(0,999):
|
mb@90
|
169 |
if(not self.vmRootName+str(i) in vms):
|
mb@90
|
170 |
return self.vmRootName+str(i)
|
mb@90
|
171 |
return ''
|
mb@90
|
172 |
|
mb@90
|
173 |
# check if the device is mass storage type
|
mb@90
|
174 |
@staticmethod
|
mb@90
|
175 |
def isMassStorageDevice(device):
|
mb@90
|
176 |
keyname = 'SYSTEM\CurrentControlSet\Enum\USB' + '\VID_' + device.vendorid+'&'+'PID_'+ device.productid
|
mb@90
|
177 |
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keyname)
|
mb@90
|
178 |
#subkeys = _winreg.QueryInfoKey(key)[0]
|
mb@90
|
179 |
#for i in range(0, subkeys):
|
mb@90
|
180 |
# print _winreg.EnumKey(key, i)
|
mb@90
|
181 |
devinfokeyname = _winreg.EnumKey(key, 0)
|
mb@90
|
182 |
_winreg.CloseKey(key)
|
mb@90
|
183 |
|
mb@90
|
184 |
devinfokey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keyname+'\\'+devinfokeyname)
|
mb@90
|
185 |
value = _winreg.QueryValueEx(devinfokey, 'SERVICE')[0]
|
mb@90
|
186 |
_winreg.CloseKey(devinfokey)
|
mb@90
|
187 |
|
mb@90
|
188 |
return 'USBSTOR' in value
|
mb@90
|
189 |
|
mb@90
|
190 |
# return the RSDs connected to the host
|
mb@90
|
191 |
@staticmethod
|
mb@90
|
192 |
def getConnectedRSDS():
|
mb@90
|
193 |
results = checkResult(Cygwin.vboxExecute('list usbhost'))[1]
|
mb@90
|
194 |
results = results.split('Host USB Devices:')[1].strip()
|
mb@90
|
195 |
|
mb@90
|
196 |
items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
|
mb@90
|
197 |
rsds = dict()
|
mb@90
|
198 |
for item in items:
|
mb@90
|
199 |
props = dict()
|
mb@90
|
200 |
for line in item.splitlines():
|
mb@90
|
201 |
if line != "":
|
mb@90
|
202 |
k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
|
mb@90
|
203 |
props[k] = v
|
mb@90
|
204 |
|
mb@90
|
205 |
#if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
|
mb@90
|
206 |
|
mb@90
|
207 |
usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'],
|
mb@90
|
208 |
re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
|
mb@90
|
209 |
re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
|
mb@90
|
210 |
if VMManager.isMassStorageDevice(usb_filter):
|
mb@90
|
211 |
rsds[props['UUID']] = usb_filter;
|
mb@90
|
212 |
logger.debug(usb_filter)
|
mb@90
|
213 |
return rsds
|
mb@90
|
214 |
|
mb@90
|
215 |
# return the RSDs attached to all existing SDVMs
|
mb@90
|
216 |
def getAttachedRSDs(self):
|
mb@90
|
217 |
vms = self.listSDVM()
|
mb@90
|
218 |
attached_devices = dict()
|
mb@90
|
219 |
for vm in vms:
|
mb@90
|
220 |
rsd_filter = self.getUSBFilter(vm)
|
mb@90
|
221 |
if rsd_filter != None:
|
mb@90
|
222 |
attached_devices[vm] = rsd_filter
|
mb@90
|
223 |
return attached_devices
|
mb@90
|
224 |
|
mb@90
|
225 |
# configures hostonly networking and DHCP server. requires admin rights
|
mb@90
|
226 |
def configureHostNetworking(self):
|
mb@90
|
227 |
#cmd = 'vboxmanage list hostonlyifs'
|
mb@90
|
228 |
#Cygwin.vboxExecute(cmd)
|
mb@90
|
229 |
#cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
|
mb@90
|
230 |
#Cygwin.vboxExecute(cmd)
|
mb@90
|
231 |
#cmd = 'vboxmanage hostonlyif create'
|
mb@90
|
232 |
#Cygwin.vboxExecute(cmd)
|
mb@90
|
233 |
checkResult(Cygwin.vboxExecute('hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'))
|
mb@90
|
234 |
#cmd = 'vboxmanage dhcpserver add'
|
mb@90
|
235 |
#Cygwin.vboxExecute(cmd)
|
mb@90
|
236 |
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
|
237 |
|
BarthaM@125
|
238 |
def isSDVMExisting(self, vm_name):
|
BarthaM@125
|
239 |
sdvms = self.listSDVM()
|
BarthaM@125
|
240 |
return vm_name in sdvms
|
BarthaM@125
|
241 |
|
mb@90
|
242 |
#create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
|
mb@90
|
243 |
def createVM(self, vm_name):
|
BarthaM@125
|
244 |
if self.isSDVMExisting(vm_name):
|
BarthaM@125
|
245 |
return
|
BarthaM@125
|
246 |
#remove eventually existing SDVM folder
|
BarthaM@125
|
247 |
machineFolder = Cygwin.cygPath(self.machineFolder)
|
BarthaM@125
|
248 |
checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '\\\"'))
|
mb@90
|
249 |
hostonly_if = self.getHostOnlyIFs()
|
mb@90
|
250 |
checkResult(Cygwin.vboxExecute('createvm --name ' + vm_name + ' --ostype Debian --register'))
|
mb@90
|
251 |
checkResult(Cygwin.vboxExecute('modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat'))
|
mb@90
|
252 |
checkResult(Cygwin.vboxExecute('storagectl ' + vm_name + ' --name SATA --add sata --portcount 2'))
|
mb@90
|
253 |
return
|
mb@90
|
254 |
|
mb@90
|
255 |
# attach storage image to controller
|
mb@90
|
256 |
def storageAttach(self, vm_name):
|
mb@90
|
257 |
if self.isStorageAttached(vm_name):
|
mb@90
|
258 |
self.storageDetach(vm_name)
|
mb@90
|
259 |
checkResult(Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium \"'+ self.machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'))
|
mb@90
|
260 |
|
mb@90
|
261 |
# return true if storage is attached
|
mb@90
|
262 |
def isStorageAttached(self, vm_name):
|
mb@90
|
263 |
info = self.getVMInfo(vm_name)
|
mb@90
|
264 |
return (info['SATA-0-0']!='none')
|
mb@90
|
265 |
|
mb@90
|
266 |
# detach storage from controller
|
mb@90
|
267 |
def storageDetach(self, vm_name):
|
mb@90
|
268 |
if self.isStorageAttached(vm_name):
|
mb@90
|
269 |
checkResult(Cygwin.vboxExecute('storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium none'))
|
mb@90
|
270 |
|
mb@90
|
271 |
def changeStorageType(self, filename, storage_type):
|
mb@90
|
272 |
checkResult(Cygwin.vboxExecute('modifyhd \"' + filename + '\" --type ' + storage_type))
|
mb@90
|
273 |
|
mb@90
|
274 |
# list storage snaphots for VM
|
mb@90
|
275 |
def updateTemplate(self):
|
mb@95
|
276 |
|
mb@90
|
277 |
self.cleanup()
|
mb@90
|
278 |
self.poweroffVM('SecurityDVM')
|
mb@90
|
279 |
self.waitShutdown('SecurityDVM')
|
mb@90
|
280 |
|
mb@90
|
281 |
# check for updates
|
mb@90
|
282 |
self.genCertificateISO('SecurityDVM')
|
mb@90
|
283 |
self.attachCertificateISO('SecurityDVM')
|
mb@90
|
284 |
|
mb@90
|
285 |
self.storageDetach('SecurityDVM')
|
mb@90
|
286 |
results = checkResult(Cygwin.vboxExecute('list hdds'))[1]
|
mb@90
|
287 |
results = results.replace('Parent UUID', 'Parent')
|
mb@90
|
288 |
items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
|
mb@90
|
289 |
|
mb@90
|
290 |
snaps = dict()
|
mb@90
|
291 |
for item in items:
|
mb@90
|
292 |
props = dict()
|
mb@90
|
293 |
for line in item.splitlines():
|
mb@90
|
294 |
if line != "":
|
mb@90
|
295 |
k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
|
mb@90
|
296 |
props[k] = v;
|
mb@90
|
297 |
snaps[props['UUID']] = props
|
mb@90
|
298 |
|
mb@90
|
299 |
|
mb@90
|
300 |
template_storage = self.machineFolder + '\SecurityDVM\SecurityDVM.vmdk'
|
mb@90
|
301 |
|
mb@90
|
302 |
# find template uuid
|
mb@90
|
303 |
template_uuid = ''
|
mb@90
|
304 |
for hdd in snaps.values():
|
mb@90
|
305 |
if hdd['Location'] == template_storage:
|
mb@90
|
306 |
template_uuid = hdd['UUID']
|
mb@90
|
307 |
logger.debug('found parent uuid ' + template_uuid)
|
mb@90
|
308 |
|
mb@90
|
309 |
# remove snapshots
|
mb@90
|
310 |
for hdd in snaps.values():
|
mb@90
|
311 |
if hdd['Parent'] == template_uuid:
|
mb@90
|
312 |
#template_uuid = hdd['UUID']
|
mb@90
|
313 |
logger.debug('removing snapshot ' + hdd['UUID'])
|
mb@90
|
314 |
checkResult(Cygwin.vboxExecute('closemedium disk {' + hdd['UUID'] + '} --delete'))#[1]
|
mb@90
|
315 |
# parse result 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
|
mb@90
|
316 |
|
mb@90
|
317 |
self.changeStorageType(template_storage,'normal')
|
mb@90
|
318 |
self.storageAttach('SecurityDVM')
|
mb@90
|
319 |
self.startVM('SecurityDVM')
|
mb@90
|
320 |
self.waitStartup('SecurityDVM')
|
mb@90
|
321 |
checkResult(Cygwin.sshExecute('"sudo apt-get -y update"', VMManager.getHostOnlyIP('SecurityDVM'), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + 'SecurityDVM' + '/dvm_key'))
|
mb@90
|
322 |
checkResult(Cygwin.sshExecute('"sudo apt-get -y upgrade"', VMManager.getHostOnlyIP('SecurityDVM'), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + 'SecurityDVM' + '/dvm_key'))
|
mb@90
|
323 |
#self.stopVM('SecurityDVM')
|
mb@90
|
324 |
self.hibernateVM('SecurityDVM')
|
mb@90
|
325 |
self.waitShutdown('SecurityDVM')
|
mb@90
|
326 |
self.storageDetach('SecurityDVM')
|
mb@90
|
327 |
self.changeStorageType(template_storage,'immutable')
|
mb@90
|
328 |
self.storageAttach('SecurityDVM')
|
mb@90
|
329 |
self.rsdHandler = DeviceHandler(self)
|
mb@90
|
330 |
self.rsdHandler.start()
|
mb@90
|
331 |
|
mb@90
|
332 |
#remove VM from the system. should be used on VMs returned by listSDVMs
|
mb@90
|
333 |
def removeVM(self, vm_name):
|
mb@90
|
334 |
logger.info('Removing ' + vm_name)
|
mb@90
|
335 |
checkResult(Cygwin.vboxExecute('unregistervm ' + vm_name + ' --delete'))
|
mb@90
|
336 |
machineFolder = Cygwin.cygPath(self.machineFolder)
|
mb@97
|
337 |
checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '\\\"'))
|
mb@90
|
338 |
|
mb@90
|
339 |
# start VM
|
mb@90
|
340 |
def startVM(self, vm_name):
|
mb@90
|
341 |
logger.info('Starting ' + vm_name)
|
mb@90
|
342 |
result = checkResult(Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless' ))
|
mb@90
|
343 |
while 'successfully started' not in result[1]:
|
mb@90
|
344 |
logger.error("Failed to start SDVM: " + vm_name + " retrying")
|
oliver@129
|
345 |
logger.error("Command returned:\n" + result[2])
|
mb@90
|
346 |
time.sleep(1)
|
mb@90
|
347 |
result = checkResult(Cygwin.vboxExecute('startvm ' + vm_name + ' --type headless'))
|
mb@90
|
348 |
return result[0]
|
mb@90
|
349 |
|
mb@90
|
350 |
# return wether VM is running or not
|
mb@90
|
351 |
def isVMRunning(self, vm_name):
|
mb@90
|
352 |
return vm_name in self.listRunningVMS()
|
mb@90
|
353 |
|
mb@90
|
354 |
# stop VM
|
mb@90
|
355 |
def stopVM(self, vm_name):
|
mb@90
|
356 |
logger.info('Sending shutdown signal to ' + vm_name)
|
mb@90
|
357 |
checkResult(Cygwin.sshExecute( '"sudo shutdown -h now"', VMManager.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + vm_name + '/dvm_key' ))
|
mb@90
|
358 |
|
mb@90
|
359 |
# stop VM
|
mb@90
|
360 |
def hibernateVM(self, vm_name):
|
mb@95
|
361 |
logger.info('Sending hibernate-disk signal to ' + vm_name)
|
mb@90
|
362 |
checkResult(Cygwin.sshExecute( '"sudo hibernate-disk&"', VMManager.getHostOnlyIP(vm_name), 'osecuser', Cygwin.cygPath(self.machineFolder) + '/' + vm_name + '/dvm_key', wait_return=False))
|
mb@90
|
363 |
|
mb@90
|
364 |
# poweroff VM
|
mb@90
|
365 |
def poweroffVM(self, vm_name):
|
mb@90
|
366 |
if not self.isVMRunning(vm_name):
|
mb@90
|
367 |
return
|
mb@90
|
368 |
logger.info('Powering off ' + vm_name)
|
mb@90
|
369 |
return checkResult(Cygwin.vboxExecute('controlvm ' + vm_name + ' poweroff'))
|
mb@90
|
370 |
|
mb@90
|
371 |
#list the hostonly IFs exposed by the VBox host
|
mb@90
|
372 |
@staticmethod
|
mb@90
|
373 |
def getHostOnlyIFs():
|
mb@90
|
374 |
result = Cygwin.vboxExecute('list hostonlyifs')[1]
|
mb@90
|
375 |
if result=='':
|
mb@90
|
376 |
return None
|
mb@90
|
377 |
props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
|
mb@90
|
378 |
return props
|
mb@90
|
379 |
|
mb@90
|
380 |
# return the hostOnly IP for a running guest or the host
|
mb@90
|
381 |
@staticmethod
|
mb@90
|
382 |
def getHostOnlyIP(vm_name):
|
mb@90
|
383 |
if vm_name == None:
|
oliver@129
|
384 |
logger.info('Getting hostOnly IP address for Host')
|
mb@90
|
385 |
return VMManager.getHostOnlyIFs()['IPAddress']
|
mb@90
|
386 |
else:
|
oliver@129
|
387 |
logger.info('Getting hostOnly IP address ' + vm_name)
|
mb@90
|
388 |
result = checkResult(Cygwin.vboxExecute('guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'))
|
mb@90
|
389 |
if result=='':
|
mb@90
|
390 |
return None
|
mb@90
|
391 |
result = result[1]
|
mb@90
|
392 |
if result.startswith('No value set!'):
|
mb@90
|
393 |
return None
|
mb@90
|
394 |
return result[result.index(':')+1:].strip()
|
mb@90
|
395 |
|
mb@90
|
396 |
# attach removable storage device to VM by provision of filter
|
mb@90
|
397 |
def attachRSD(self, vm_name, rsd_filter):
|
mb@90
|
398 |
return checkResult(Cygwin.vboxExecute('usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision))
|
mb@90
|
399 |
|
mb@90
|
400 |
# detach removable storage from VM by
|
mb@90
|
401 |
def detachRSD(self, vm_name):
|
mb@90
|
402 |
return checkResult(Cygwin.vboxExecute('usbfilter remove 0 --target ' + vm_name))
|
mb@90
|
403 |
|
mb@90
|
404 |
# return the description set for an existing VM
|
mb@90
|
405 |
def getVMInfo(self, vm_name):
|
mb@90
|
406 |
results = checkResult(Cygwin.vboxExecute('showvminfo ' + vm_name + ' --machinereadable'))[1]
|
mb@90
|
407 |
props = dict((k.strip().strip('"'),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
|
mb@90
|
408 |
return props
|
mb@90
|
409 |
|
mb@90
|
410 |
# return the configured USB filter for an existing VM
|
mb@90
|
411 |
def getUSBFilter(self, vm_name):
|
mb@90
|
412 |
props = self.getVMInfo(vm_name)
|
mb@90
|
413 |
keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
|
mb@90
|
414 |
keyset = set(props.keys())
|
mb@90
|
415 |
usb_filter = None
|
mb@90
|
416 |
if keyset.issuperset(keys):
|
mb@90
|
417 |
usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
|
mb@90
|
418 |
return usb_filter
|
mb@90
|
419 |
|
mb@90
|
420 |
#generates ISO containing authorized_keys for use with guest VM
|
mb@90
|
421 |
def genCertificateISO(self, vm_name):
|
mb@90
|
422 |
machineFolder = Cygwin.cygPath(self.machineFolder)
|
mb@90
|
423 |
# remove .ssh folder if exists
|
mb@97
|
424 |
checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"'))
|
mb@90
|
425 |
# remove .ssh folder if exists
|
mb@97
|
426 |
checkResult(Cygwin.bashExecute('/usr/bin/rm -rf \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"'))
|
mb@90
|
427 |
# create .ssh folder in vm_name
|
mb@97
|
428 |
checkResult(Cygwin.bashExecute('/usr/bin/mkdir -p \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"'))
|
mb@90
|
429 |
# generate dvm_key pair in vm_name / .ssh
|
mb@97
|
430 |
checkResult(Cygwin.bashExecute('/usr/bin/ssh-keygen -q -t rsa -N \\\"\\\" -C \\\"' + vm_name + '\\\" -f \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\"'))
|
mb@90
|
431 |
# move out private key
|
mb@97
|
432 |
checkResult(Cygwin.bashExecute('/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\" \\\"' + machineFolder + '/' + vm_name + '\\\"'))
|
mb@90
|
433 |
# set permissions for private key
|
mb@97
|
434 |
checkResult(Cygwin.bashExecute('/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"'))
|
mb@90
|
435 |
# rename public key to authorized_keys
|
mb@97
|
436 |
checkResult(Cygwin.bashExecute('/usr/bin/mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key.pub\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"'))
|
mb@90
|
437 |
# set permissions for authorized_keys
|
mb@97
|
438 |
checkResult(Cygwin.bashExecute('/usr/bin/chmod 500 \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"'))
|
mb@90
|
439 |
# generate iso image with .ssh/authorized keys
|
mb@97
|
440 |
checkResult(Cygwin.bashExecute('/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '/' + vm_name + '/'+ vm_name + '.iso\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"'))
|
mb@90
|
441 |
|
mb@90
|
442 |
# attaches generated ssh public cert to guest vm
|
mb@90
|
443 |
def attachCertificateISO(self, vm_name):
|
mb@90
|
444 |
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\"'))
|
mb@90
|
445 |
return result
|
mb@90
|
446 |
|
mb@90
|
447 |
# wait for machine to come up
|
mb@90
|
448 |
def waitStartup(self, vm_name, timeout_ms = 30000):
|
mb@90
|
449 |
checkResult(Cygwin.vboxExecute('guestproperty wait ' + vm_name + ' SDVMStarted --timeout ' + str(timeout_ms) + ' --fail-on-timeout'))
|
mb@90
|
450 |
return VMManager.getHostOnlyIP(vm_name)
|
mb@90
|
451 |
|
mb@90
|
452 |
# wait for machine to shutdown
|
mb@90
|
453 |
def waitShutdown(self, vm_name):
|
mb@90
|
454 |
while vm_name in self.listRunningVMS():
|
mb@90
|
455 |
time.sleep(1)
|
mb@90
|
456 |
return
|
mb@90
|
457 |
|
BarthaM@135
|
458 |
#Small function to check if the mentioned location is a directory
|
mb@90
|
459 |
def isDirectory(self, path):
|
mb@90
|
460 |
result = checkResult(Cygwin.cmdExecute('dir ' + path + ' | FIND ".."'))
|
mb@90
|
461 |
return string.find(result[1], 'DIR',)
|
mb@90
|
462 |
|
mb@90
|
463 |
def mapNetworkDrive(self, drive, networkPath, user, password):
|
BarthaM@135
|
464 |
#self.unmapNetworkDrive(drive)
|
mb@90
|
465 |
#Check for drive availability
|
mb@90
|
466 |
if os.path.exists(drive):
|
mb@90
|
467 |
logger.error("Drive letter is already in use: " + drive)
|
mb@90
|
468 |
return -1
|
mb@90
|
469 |
#Check for network resource availability
|
mb@90
|
470 |
retry = 5
|
mb@90
|
471 |
while not os.path.exists(networkPath):
|
mb@90
|
472 |
time.sleep(1)
|
mb@90
|
473 |
if retry == 0:
|
mb@90
|
474 |
return -1
|
mb@90
|
475 |
logger.info("Path not accessible: " + networkPath + " retrying")
|
mb@90
|
476 |
retry-=1
|
mb@90
|
477 |
|
mb@90
|
478 |
command = 'USE ' + drive + ' ' + networkPath + ' /PERSISTENT:NO'
|
mb@90
|
479 |
if user != None:
|
mb@90
|
480 |
command += ' ' + password + ' /User' + user
|
mb@90
|
481 |
|
BarthaM@135
|
482 |
result = checkResult(Cygwin.execute('C:\\Windows\\system32\\NET ', command))
|
BarthaM@135
|
483 |
#result = checkResult(Cygwin.cmdExecute('NET ' + command))
|
mb@90
|
484 |
if string.find(result[1], 'successfully',) == -1:
|
mb@90
|
485 |
logger.error("Failed: NET " + command)
|
mb@90
|
486 |
return -1
|
mb@90
|
487 |
return 1
|
mb@90
|
488 |
|
mb@90
|
489 |
def unmapNetworkDrive(self, drive):
|
BarthaM@135
|
490 |
#drives = self.getNetworkDrives()
|
BarthaM@135
|
491 |
#if drive not in drives.keys():
|
BarthaM@135
|
492 |
# return 1
|
BarthaM@135
|
493 |
command = 'USE ' + drive + ' /DELETE /YES' #' ' + networkPath +
|
BarthaM@135
|
494 |
result = checkResult(Cygwin.execute('C:\\Windows\\system32\\net.exe', command))
|
BarthaM@135
|
495 |
#result = checkResult(Cygwin.cmdExecute('NET ' + command))
|
mb@90
|
496 |
if string.find(str(result[1]), 'successfully',) == -1:
|
mb@90
|
497 |
logger.error(result[2])
|
mb@90
|
498 |
return -1
|
mb@90
|
499 |
return 1
|
mb@90
|
500 |
|
mb@90
|
501 |
def getNetworkDrives(self):
|
mb@90
|
502 |
ip = VMManager.getHostOnlyIP(None)
|
mb@90
|
503 |
ip = ip[:ip.rindex('.')]
|
mb@90
|
504 |
drives = dict()
|
mb@90
|
505 |
result = checkResult(Cygwin.execute('C:\\Windows\\system32\\net.exe', 'USE'))
|
mb@90
|
506 |
for line in result[1].splitlines():
|
mb@90
|
507 |
if ip in line:
|
mb@90
|
508 |
parts = line.split()
|
mb@90
|
509 |
drives[parts[1]] = parts[2]
|
mb@90
|
510 |
return drives
|
mb@90
|
511 |
|
mb@90
|
512 |
def genNetworkDrive(self):
|
mb@90
|
513 |
network_drives = self.getNetworkDrives()
|
mb@90
|
514 |
logical_drives = VMManager.getLogicalDrives()
|
mb@90
|
515 |
drives = list(map(chr, range(68, 91)))
|
mb@90
|
516 |
for drive in drives:
|
mb@90
|
517 |
if drive+':' not in network_drives and drive not in logical_drives:
|
mb@90
|
518 |
return drive+':'
|
mb@90
|
519 |
|
mb@90
|
520 |
def getNetworkDrive(self, vm_name):
|
mb@90
|
521 |
ip = self.getHostOnlyIP(vm_name)
|
mb@90
|
522 |
result = checkResult(Cygwin.execute('C:\\Windows\\system32\\net.exe', 'USE'))
|
mb@90
|
523 |
for line in result[1].splitlines():
|
mb@90
|
524 |
if line != None and ip in line:
|
mb@90
|
525 |
parts = line.split()
|
BarthaM@135
|
526 |
return parts[1]
|
mb@90
|
527 |
@staticmethod
|
mb@90
|
528 |
def getLogicalDrives():
|
mb@90
|
529 |
drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
|
mb@90
|
530 |
return list(itertools.compress(string.ascii_uppercase, map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
|
mb@90
|
531 |
|
mb@90
|
532 |
@staticmethod
|
mb@90
|
533 |
def getDriveType(drive):
|
mb@90
|
534 |
return ctypes.cdll.kernel32.GetDriveTypeW(u"%s:\\"%drive)
|
mb@90
|
535 |
|
mb@90
|
536 |
@staticmethod
|
mb@90
|
537 |
def getVolumeInfo(drive):
|
mb@90
|
538 |
volumeNameBuffer = ctypes.create_unicode_buffer(1024)
|
mb@90
|
539 |
fileSystemNameBuffer = ctypes.create_unicode_buffer(1024)
|
mb@90
|
540 |
serial_number = None
|
mb@90
|
541 |
max_component_length = None
|
mb@90
|
542 |
file_system_flags = None
|
mb@90
|
543 |
|
mb@90
|
544 |
rc = ctypes.cdll.kernel32.GetVolumeInformationW(
|
mb@90
|
545 |
#ctypes.c_wchar_p("F:\\"),
|
mb@90
|
546 |
u"%s:\\"%drive,
|
mb@90
|
547 |
volumeNameBuffer,
|
mb@90
|
548 |
ctypes.sizeof(volumeNameBuffer),
|
mb@90
|
549 |
serial_number,
|
mb@90
|
550 |
max_component_length,
|
mb@90
|
551 |
file_system_flags,
|
mb@90
|
552 |
fileSystemNameBuffer,
|
mb@90
|
553 |
ctypes.sizeof(fileSystemNameBuffer)
|
mb@90
|
554 |
)
|
mb@90
|
555 |
|
mb@90
|
556 |
return volumeNameBuffer.value, fileSystemNameBuffer.value
|
BarthaM@141
|
557 |
|
BarthaM@141
|
558 |
# handles browsing request
|
BarthaM@141
|
559 |
def handleBrowsingRequest(self):
|
BarthaM@141
|
560 |
handler = BrowsingHandler(self)
|
BarthaM@141
|
561 |
handler.start()
|
BarthaM@141
|
562 |
return 'ok'
|
mb@90
|
563 |
|
mb@90
|
564 |
def checkResult(result):
|
mb@90
|
565 |
if result[0] != 0:
|
BarthaM@135
|
566 |
logger.error('Command failed:' + ''.join(result[2]))
|
mb@90
|
567 |
raise OpenSecurityException('Command failed:' + ''.join(result[2]))
|
mb@90
|
568 |
return result
|
mb@90
|
569 |
|
BarthaM@135
|
570 |
# handles browsing request
|
BarthaM@135
|
571 |
class UnmapDriveHandler(threading.Thread):
|
BarthaM@135
|
572 |
vmm = None
|
BarthaM@135
|
573 |
drive = None
|
BarthaM@135
|
574 |
running = True
|
BarthaM@135
|
575 |
#Cygwin.start_X11()
|
BarthaM@135
|
576 |
def __init__(self, vmmanager, drv):
|
BarthaM@135
|
577 |
threading.Thread.__init__(self)
|
BarthaM@135
|
578 |
self.vmm = vmmanager
|
BarthaM@135
|
579 |
self.drive = drv
|
BarthaM@135
|
580 |
|
BarthaM@135
|
581 |
def run(self):
|
BarthaM@135
|
582 |
while self.running:
|
BarthaM@135
|
583 |
self.vmm.unmapNetworkDrive(self.drive)
|
BarthaM@135
|
584 |
mappedDrives = self.vmm.getNetworkDrives()
|
BarthaM@135
|
585 |
#logger.info(mappedDrives)
|
BarthaM@135
|
586 |
#logger.info(self.drive)
|
BarthaM@135
|
587 |
if self.drive not in mappedDrives.keys():
|
BarthaM@135
|
588 |
self.running = False
|
BarthaM@135
|
589 |
|
BarthaM@141
|
590 |
|
BarthaM@141
|
591 |
#browser = '/usr/bin/iceweasel'
|
BarthaM@141
|
592 |
#browser = '/usr/bin/midori'
|
BarthaM@141
|
593 |
#browser = '/usr/bin/chromium '
|
BarthaM@141
|
594 |
#if Cygwin.is_X11_running()==True:
|
BarthaM@141
|
595 |
#result = checkResult(Cygwin.bashExecute('DISPLAY=:0 xhost '+new_ip))
|
BarthaM@141
|
596 |
|
BarthaM@141
|
597 |
#browser = '\\\"/usr/bin/chromium; pidof dbus-launch | xargs kill\\\"'
|
BarthaM@141
|
598 |
#Cygwin.start_X11()
|
BarthaM@141
|
599 |
#result = checkResult(Cygwin.sshExecuteX11(browser, new_ip, 'osecuser', Cygwin.cygPath(self.vmm.getMachineFolder()) + '/' + new_sdvm + '/dvm_key'))
|
BarthaM@141
|
600 |
|
BarthaM@141
|
601 |
#handles browsing session creation
|
BarthaM@141
|
602 |
class BrowsingHandler(threading.Thread):
|
mb@90
|
603 |
vmm = None
|
BarthaM@141
|
604 |
def __init__(self, vmmanager):
|
BarthaM@141
|
605 |
threading.Thread.__init__(self)
|
BarthaM@141
|
606 |
self.vmm = vmmanager
|
BarthaM@141
|
607 |
|
BarthaM@141
|
608 |
def run(self):
|
BarthaM@141
|
609 |
browser = '\\\"/usr/bin/chromium; pidof dbus-launch | xargs kill\\\"'
|
BarthaM@141
|
610 |
if Cygwin.is_X11_running()==False:
|
BarthaM@141
|
611 |
Cygwin.start_X11()
|
BarthaM@141
|
612 |
try:
|
BarthaM@141
|
613 |
self.vmm.browsingManager.started.wait()
|
BarthaM@141
|
614 |
result = checkResult(Cygwin.sshExecuteX11(browser, self.vmm.browsingManager.ip_addr, 'osecuser', Cygwin.cygPath(self.vmm.getMachineFolder()) + '/' + self.vmm.browsingManager.vm_name + '/dvm_key'))
|
BarthaM@141
|
615 |
except:
|
BarthaM@141
|
616 |
logger.error("BrowsingHandler closing. Cleaning up")
|
BarthaM@141
|
617 |
self.vmm.browsingManager.restart.set()
|
BarthaM@141
|
618 |
|
BarthaM@141
|
619 |
|
BarthaM@141
|
620 |
# handles browsing Vm creation and destruction
|
BarthaM@141
|
621 |
class BrowsingManager(threading.Thread):
|
BarthaM@141
|
622 |
vmm = None
|
BarthaM@141
|
623 |
running = True
|
BarthaM@141
|
624 |
restart = None
|
BarthaM@141
|
625 |
ip_addr = None
|
BarthaM@141
|
626 |
vm_name = None
|
BarthaM@141
|
627 |
drive = None
|
BarthaM@141
|
628 |
|
mb@90
|
629 |
def __init__(self, vmmanager):
|
mb@90
|
630 |
threading.Thread.__init__(self)
|
mb@90
|
631 |
self.vmm = vmmanager
|
BarthaM@141
|
632 |
self.restart = threading.Event()
|
BarthaM@141
|
633 |
self.started = threading.Event()
|
BarthaM@141
|
634 |
|
mb@90
|
635 |
|
mb@90
|
636 |
def run(self):
|
BarthaM@141
|
637 |
while self.running:
|
BarthaM@141
|
638 |
self.restart.clear()
|
BarthaM@141
|
639 |
self.started.clear()
|
BarthaM@141
|
640 |
if self.drive != None:
|
BarthaM@141
|
641 |
driveHandler = UnmapDriveHandler(self.vmm, self.drive)
|
BarthaM@141
|
642 |
driveHandler.start()
|
BarthaM@141
|
643 |
driveHandler.join()
|
BarthaM@141
|
644 |
self.drive = None
|
BarthaM@135
|
645 |
|
BarthaM@141
|
646 |
self.ip_addr = None
|
BarthaM@141
|
647 |
|
BarthaM@141
|
648 |
if self.vm_name != None:
|
BarthaM@141
|
649 |
self.vmm.poweroffVM(self.vm_name)
|
BarthaM@141
|
650 |
self.vmm.removeVM(self.vm_name)
|
BarthaM@141
|
651 |
|
BarthaM@141
|
652 |
try:
|
BarthaM@141
|
653 |
self.vm_name = self.vmm.generateSDVMName()
|
BarthaM@141
|
654 |
self.vmm.createVM(self.vm_name)
|
BarthaM@141
|
655 |
self.vmm.storageAttach(self.vm_name)
|
BarthaM@141
|
656 |
self.vmm.genCertificateISO(self.vm_name)
|
BarthaM@141
|
657 |
self.vmm.attachCertificateISO(self.vm_name)
|
BarthaM@141
|
658 |
self.vmm.startVM(self.vm_name)
|
BarthaM@141
|
659 |
self.ip_addr = self.vmm.waitStartup(self.vm_name)
|
BarthaM@141
|
660 |
if self.ip_addr == None:
|
BarthaM@141
|
661 |
continue
|
BarthaM@141
|
662 |
self.drive = self.vmm.genNetworkDrive()
|
BarthaM@141
|
663 |
if self.drive == None:
|
BarthaM@141
|
664 |
continue
|
BarthaM@141
|
665 |
networkPath = '\\\\' + self.ip_addr + '\\Download'
|
BarthaM@141
|
666 |
self.vmm.mapNetworkDrive(self.drive, networkPath, None, None)
|
BarthaM@141
|
667 |
self.started.set()
|
BarthaM@141
|
668 |
self.restart.wait()
|
BarthaM@141
|
669 |
|
BarthaM@141
|
670 |
except:
|
BarthaM@141
|
671 |
logger.error("BrowsingHandler failed. Cleaning up")
|
mb@90
|
672 |
|
mb@90
|
673 |
class DeviceHandler(threading.Thread):
|
mb@90
|
674 |
vmm = None
|
mb@90
|
675 |
attachedRSDs = None
|
mb@90
|
676 |
connectedRSDs = None
|
mb@90
|
677 |
running = True
|
mb@90
|
678 |
def __init__(self, vmmanger):
|
mb@90
|
679 |
threading.Thread.__init__(self)
|
mb@90
|
680 |
self.vmm = vmmanger
|
mb@90
|
681 |
|
mb@90
|
682 |
def stop(self):
|
mb@90
|
683 |
self.running = False
|
mb@90
|
684 |
|
mb@90
|
685 |
def run(self):
|
mb@90
|
686 |
self.connectedRSDs = dict()
|
BarthaM@135
|
687 |
|
mb@90
|
688 |
while self.running:
|
mb@90
|
689 |
tmp_rsds = self.vmm.getConnectedRSDS()
|
mb@95
|
690 |
|
mb@95
|
691 |
self.attachedRSDs = self.vmm.getAttachedRSDs()
|
mb@95
|
692 |
for vm_name in self.attachedRSDs.keys():
|
mb@95
|
693 |
if self.attachedRSDs[vm_name] not in tmp_rsds.values():
|
mb@95
|
694 |
drive = self.vmm.getNetworkDrive(vm_name)
|
mb@95
|
695 |
#self.stopVM(vm_name)
|
mb@95
|
696 |
self.vmm.detachRSD(vm_name)
|
mb@95
|
697 |
self.vmm.poweroffVM(vm_name)
|
mb@95
|
698 |
self.vmm.removeVM(vm_name)
|
BarthaM@135
|
699 |
if drive != None:
|
BarthaM@135
|
700 |
#self.vmm.unmapNetworkDrive(drive)
|
BarthaM@135
|
701 |
driveHandler = UnmapDriveHandler(self.vmm, drive)
|
BarthaM@135
|
702 |
driveHandler.start()
|
mb@95
|
703 |
break
|
mb@95
|
704 |
|
mb@95
|
705 |
|
mb@90
|
706 |
if tmp_rsds.keys() == self.connectedRSDs.keys():
|
mb@90
|
707 |
logger.debug("Nothing's changed. sleep(3)")
|
mb@90
|
708 |
time.sleep(3)
|
mb@90
|
709 |
continue
|
mb@90
|
710 |
|
mb@90
|
711 |
logger.info("Something's changed")
|
mb@90
|
712 |
self.connectedRSDs = tmp_rsds
|
BarthaM@135
|
713 |
|
mb@90
|
714 |
#create new vm for attached device if any
|
mb@90
|
715 |
self.attachedRSDs = self.vmm.getAttachedRSDs()
|
mb@90
|
716 |
self.connectedRSDs = self.vmm.getConnectedRSDS()
|
mb@90
|
717 |
|
mb@90
|
718 |
new_ip = None
|
mb@90
|
719 |
for connected_device in self.connectedRSDs.values():
|
mb@90
|
720 |
if (self.attachedRSDs and False) or (connected_device not in self.attachedRSDs.values()):
|
mb@90
|
721 |
new_sdvm = self.vmm.generateSDVMName()
|
mb@90
|
722 |
self.vmm.createVM(new_sdvm)
|
mb@90
|
723 |
self.vmm.storageAttach(new_sdvm)
|
mb@90
|
724 |
self.vmm.attachRSD(new_sdvm, connected_device)
|
mb@90
|
725 |
self.vmm.startVM(new_sdvm)
|
mb@90
|
726 |
new_ip = self.vmm.waitStartup(new_sdvm)
|
mb@90
|
727 |
drive = self.vmm.genNetworkDrive()
|
mb@90
|
728 |
if new_ip != None:
|
mb@90
|
729 |
self.vmm.mapNetworkDrive(drive, '\\\\' + new_ip + '\\USB', None, None)
|
mb@90
|
730 |
|
mb@90
|
731 |
if __name__ == '__main__':
|
mb@90
|
732 |
#man = VMManager.getInstance()
|
mb@90
|
733 |
#man.listVM()
|
mb@90
|
734 |
#print man.getConnectedRSDs()
|
mb@90
|
735 |
#print man.getNetworkDrives()
|
mb@90
|
736 |
#man.genNetworkDrive()
|
mb@90
|
737 |
#drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
|
mb@90
|
738 |
#print list(itertools.compress(string.ascii_uppercase, map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
|
mb@90
|
739 |
#print list(map(chr, range(68, 91)))
|
mb@90
|
740 |
#print Cygwin.getRegEntry('SYSTEM\CurrentControlSet\Enum\USB', 'VID_1058&PID_0704')[0]
|
mb@90
|
741 |
#devices = VMManager.getConnectedRSDS()
|
mb@90
|
742 |
#print devices
|
mb@90
|
743 |
|
mb@90
|
744 |
drives = VMManager.getLogicalDrives()
|
mb@90
|
745 |
print drives
|
mb@90
|
746 |
print VMManager.getDriveType("E")
|
mb@90
|
747 |
print VMManager.getVolumeInfo("E")
|
mb@90
|
748 |
#for device in devices.values():
|
mb@90
|
749 |
# #print device
|
mb@90
|
750 |
# if VMManager.isMassStorageDevice(device):
|
mb@90
|
751 |
# print device
|
mb@90
|
752 |
|
mb@90
|
753 |
|
mb@90
|
754 |
|
mb@90
|
755 |
#time.sleep(-1)
|
mb@90
|
756 |
#man.listVM()
|
mb@90
|
757 |
#man.listVM()
|
mb@90
|
758 |
#man.listVM()
|
mb@90
|
759 |
#man.listVM()
|
mb@90
|
760 |
#man.genCertificateISO('SecurityDVM0')
|
mb@90
|
761 |
#man.guestExecute('SecurityDVM0', '/bin/ls -la')
|
mb@90
|
762 |
#logger = setupLogger('VMManager')
|
mb@90
|
763 |
#c = Cygwin()
|
mb@90
|
764 |
|
mb@90
|
765 |
#man.sshExecute('/bin/ls -la', 'SecurityDVM0')
|
mb@90
|
766 |
#man.sshExecuteX11('/usr/bin/iceweasel', 'SecurityDVM0')
|
mb@90
|
767 |
#man.removeVM('SecurityDVM0')
|
mb@90
|
768 |
#man.netUse('192.168.56.134', 'USB\\')
|
mb@90
|
769 |
#ip = '192.168.56.139'
|
mb@90
|
770 |
|
mb@90
|
771 |
#man.cygwin_path = 'c:\\cygwin64\\bin\\'
|
mb@90
|
772 |
#man.handleDeviceChange()
|
mb@90
|
773 |
#print man.listSDVM()
|
mb@90
|
774 |
#man.configureHostNetworking()
|
mb@90
|
775 |
#new_vm = man.generateSDVMName()
|
mb@90
|
776 |
#man.createVM(new_vm)
|
mb@90
|
777 |
|
mb@90
|
778 |
#print Cygwin.cmd()
|
mb@90
|
779 |
#man.isAvailable('c:')
|
mb@90
|
780 |
#ip = man.getHostOnlyIP('SecurityDVM0')
|
mb@90
|
781 |
#man.mapNetworkDrive('h:', '\\\\' + ip + '\Download', None, None)
|
mb@90
|
782 |
|
mb@90
|
783 |
#man.genCertificateISO(new_vm)
|
mb@90
|
784 |
#man.attachCertificateISO(new_vm)
|
mb@90
|
785 |
|
mb@90
|
786 |
#man.attachCertificateISO(vm_name)
|
mb@90
|
787 |
#man.guestExecute(vm_name, "ls")
|
mb@90
|
788 |
#man.sshGuestX11Execute('SecurityDVM1', '/usr/bin/iceweasel')
|
mb@90
|
789 |
#time.sleep(60)
|
mb@90
|
790 |
#print man.cygwinPath("C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\.ssh\*")
|
mb@90
|
791 |
#man.genCertificateISO('SecurityDVM')
|
mb@90
|
792 |
#man.attachCertificateISO('SecurityDVM')
|
mb@90
|
793 |
#man.isStorageAttached('SecurityDVM')
|
mb@90
|
794 |
#man.guestExecute('SecurityDVM', 'sudo apt-get -y update')
|
mb@90
|
795 |
#man.guestExecute('SecurityDVM', 'sudo apt-get -y upgrade' )
|
mb@90
|
796 |
|
mb@90
|
797 |
#man.stopVM('SecurityDVM')
|
mb@90
|
798 |
#man.storageDetach('SecurityDVM')
|
mb@90
|
799 |
#man.changeStorageType('C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\SecurityDVM.vmdk','immutable')
|
mb@90
|
800 |
#man.storageAttach('SecurityDVM')
|
mb@90
|
801 |
|
mb@90
|
802 |
|
mb@90
|
803 |
#cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
|
mb@90
|
804 |
#man.execute(cmd)
|