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