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