mb@7
|
1 |
'''
|
mb@7
|
2 |
Created on Nov 19, 2013
|
mb@7
|
3 |
|
mb@7
|
4 |
@author: BarthaM
|
mb@7
|
5 |
'''
|
mb@7
|
6 |
import os
|
mb@7
|
7 |
import os.path
|
mb@7
|
8 |
from subprocess import Popen, PIPE, call
|
mb@7
|
9 |
import subprocess
|
mb@7
|
10 |
import sys
|
mb@7
|
11 |
import re
|
om@19
|
12 |
import _winreg
|
om@18
|
13 |
from cygwin import Cygwin
|
mb@36
|
14 |
import threading
|
mb@40
|
15 |
import time
|
mb@40
|
16 |
import string
|
mb@7
|
17 |
|
dyle@52
|
18 |
#import shutil
|
dyle@52
|
19 |
#import stat
|
dyle@52
|
20 |
|
om@19
|
21 |
|
om@42
|
22 |
DEBUG = True
|
mb@46
|
23 |
class VMManagerException(Exception):
|
mb@46
|
24 |
def __init__(self, value):
|
mb@46
|
25 |
self.value = value
|
mb@46
|
26 |
def __str__(self):
|
mb@46
|
27 |
return repr(self.value)
|
mb@7
|
28 |
|
mb@7
|
29 |
class USBFilter:
|
mb@7
|
30 |
vendorid = ""
|
mb@7
|
31 |
productid = ""
|
mb@7
|
32 |
revision = ""
|
mb@7
|
33 |
|
mb@7
|
34 |
def __init__(self, vendorid, productid, revision):
|
mb@7
|
35 |
self.vendorid = vendorid.lower()
|
mb@7
|
36 |
self.productid = productid.lower()
|
mb@7
|
37 |
self.revision = revision.lower()
|
mb@7
|
38 |
return
|
mb@7
|
39 |
|
mb@7
|
40 |
def __eq__(self, other):
|
mb@7
|
41 |
return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
|
mb@7
|
42 |
|
mb@7
|
43 |
def __hash__(self):
|
mb@7
|
44 |
return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
|
mb@7
|
45 |
|
mb@7
|
46 |
def __repr__(self):
|
mb@7
|
47 |
return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
|
mb@7
|
48 |
|
mb@7
|
49 |
|
mb@7
|
50 |
class VMManager(object):
|
mb@7
|
51 |
vmRootName = "SecurityDVM"
|
mb@7
|
52 |
systemProperties = None
|
mb@7
|
53 |
cygwin_path = 'c:\\cygwin64\\bin\\'
|
om@19
|
54 |
vboxManage = 'VBoxManage'
|
mb@34
|
55 |
startNotifications = list()
|
mb@34
|
56 |
|
mb@34
|
57 |
_instance = None
|
mb@34
|
58 |
#def __new__(cls, *args, **kwargs):
|
mb@34
|
59 |
# if not cls._instance:
|
mb@34
|
60 |
# cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
|
mb@34
|
61 |
# return cls._instance
|
mb@7
|
62 |
|
mb@33
|
63 |
_instance = None
|
mb@33
|
64 |
#def __new__(cls, *args, **kwargs):
|
mb@33
|
65 |
# if not cls._instance:
|
mb@33
|
66 |
# cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
|
mb@33
|
67 |
# return cls._instance
|
mb@33
|
68 |
|
mb@7
|
69 |
def __init__(self):
|
om@31
|
70 |
self.cygwin_path = os.path.join(Cygwin.root(), 'bin') + os.path.sep
|
om@22
|
71 |
self.vboxManage = os.path.join(self.getVBoxManagePath(), 'VBoxManage')
|
mb@7
|
72 |
self.systemProperties = self.getSystemProperties()
|
mb@7
|
73 |
return
|
mb@33
|
74 |
|
mb@33
|
75 |
@staticmethod
|
mb@33
|
76 |
def getInstance():
|
mb@33
|
77 |
if VMManager._instance == None:
|
mb@33
|
78 |
VMManager._instance = VMManager()
|
mb@33
|
79 |
return VMManager._instance
|
mb@34
|
80 |
|
mb@34
|
81 |
def putStartNotification(self, ip):
|
mb@34
|
82 |
self.startNotifications.append(ip)
|
mb@34
|
83 |
|
mb@34
|
84 |
def isSDVMStarted(self, ip):
|
mb@34
|
85 |
return self.startNotifications.contains(ip)
|
mb@33
|
86 |
|
mb@46
|
87 |
def execute(self, cmd, wait_return=True ):
|
mb@7
|
88 |
if DEBUG:
|
mb@7
|
89 |
print('trying to launch: ' + cmd)
|
mb@40
|
90 |
process = Popen(cmd, stdout=PIPE, stderr=PIPE) #shell = True
|
mb@7
|
91 |
if DEBUG:
|
mb@7
|
92 |
print('launched: ' + cmd)
|
mb@46
|
93 |
if not wait_return:
|
mb@46
|
94 |
return [0, 'working in background', '']
|
mb@7
|
95 |
result = process.wait()
|
mb@7
|
96 |
res_stdout = process.stdout.read();
|
mb@7
|
97 |
res_stderr = process.stderr.read();
|
mb@7
|
98 |
if DEBUG:
|
mb@7
|
99 |
if res_stdout != "":
|
mb@7
|
100 |
print res_stdout
|
mb@7
|
101 |
if res_stderr != "":
|
mb@7
|
102 |
print res_stderr
|
mb@46
|
103 |
if result !=0:
|
mb@46
|
104 |
raise VMManagerException(res_stderr)
|
mb@7
|
105 |
return result, res_stdout, res_stderr
|
mb@7
|
106 |
|
om@19
|
107 |
def getVBoxManagePath(self):
|
om@19
|
108 |
"""get the path to the VirtualBox installation on this system"""
|
om@19
|
109 |
p = None
|
om@19
|
110 |
try:
|
om@19
|
111 |
k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
|
om@19
|
112 |
p = _winreg.QueryValueEx(k, 'InstallDir')[0]
|
om@19
|
113 |
_winreg.CloseKey(k)
|
om@19
|
114 |
except:
|
om@19
|
115 |
pass
|
om@19
|
116 |
return p
|
om@19
|
117 |
|
BarthaM@8
|
118 |
# return hosty system properties
|
mb@7
|
119 |
def getSystemProperties(self):
|
om@22
|
120 |
cmd = self.vboxManage + ' list systemproperties'
|
mb@7
|
121 |
result = self.execute(cmd)
|
mb@7
|
122 |
if result[1]=='':
|
mb@7
|
123 |
return None
|
mb@7
|
124 |
props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
|
mb@7
|
125 |
return props
|
BarthaM@8
|
126 |
|
BarthaM@8
|
127 |
# return the folder containing the guest VMs
|
mb@7
|
128 |
def getDefaultMachineFolder(self):
|
mb@7
|
129 |
return self.systemProperties["Default machine folder"]
|
mb@7
|
130 |
|
BarthaM@8
|
131 |
#list the hostonly IFs exposed by the VBox host
|
mb@7
|
132 |
def getHostOnlyIFs(self):
|
mb@11
|
133 |
cmd = 'VBoxManage list hostonlyifs'
|
mb@11
|
134 |
result = self.execute(cmd)[1]
|
mb@7
|
135 |
if result=='':
|
mb@7
|
136 |
return None
|
mb@7
|
137 |
props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
|
mb@7
|
138 |
return props
|
mb@7
|
139 |
|
mb@7
|
140 |
def listRSDS(self):
|
mb@7
|
141 |
cmd = 'VBoxManage list usbhost'
|
mb@12
|
142 |
results = self.execute(cmd)[1]
|
mb@7
|
143 |
results = results.split('Host USB Devices:')[1].strip()
|
mb@7
|
144 |
|
mb@7
|
145 |
items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
|
mb@7
|
146 |
rsds = dict()
|
mb@7
|
147 |
for item in items:
|
mb@7
|
148 |
props = dict()
|
mb@7
|
149 |
for line in item.splitlines():
|
mb@7
|
150 |
if line != "":
|
mb@7
|
151 |
k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
|
mb@7
|
152 |
props[k] = v;
|
mb@7
|
153 |
|
mb@7
|
154 |
if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
|
mb@7
|
155 |
usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'],
|
mb@7
|
156 |
re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
|
mb@7
|
157 |
re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
|
mb@7
|
158 |
rsds[props['UUID']] = usb_filter;
|
mb@7
|
159 |
if DEBUG:
|
mb@33
|
160 |
print usb_filter
|
mb@7
|
161 |
return rsds
|
mb@7
|
162 |
|
BarthaM@8
|
163 |
# list all existing VMs registered with VBox
|
mb@7
|
164 |
def listVM(self):
|
mb@7
|
165 |
cmd = 'VBoxManage list vms'
|
mb@11
|
166 |
result = self.execute(cmd)[1]
|
mb@7
|
167 |
vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
|
mb@7
|
168 |
return vms
|
mb@7
|
169 |
|
BarthaM@8
|
170 |
# list existing SDVMs
|
mb@7
|
171 |
def listSDVM(self):
|
mb@7
|
172 |
vms = self.listVM()
|
mb@7
|
173 |
svdms = []
|
mb@7
|
174 |
for vm in vms:
|
mb@7
|
175 |
if vm.startswith(self.vmRootName) and vm != self.vmRootName:
|
mb@7
|
176 |
svdms.append(vm)
|
mb@7
|
177 |
return svdms
|
mb@7
|
178 |
|
BarthaM@8
|
179 |
# generate valid (not already existing SDVM name). necessary for creating a new VM
|
mb@7
|
180 |
def generateSDVMName(self):
|
mb@7
|
181 |
vms = self.listVM()
|
mb@7
|
182 |
for i in range(0,999):
|
mb@7
|
183 |
if(not self.vmRootName+str(i) in vms):
|
mb@7
|
184 |
return self.vmRootName+str(i)
|
mb@7
|
185 |
return ''
|
mb@7
|
186 |
|
BarthaM@8
|
187 |
# return the RSDs attached to all existing SDVMs
|
BarthaM@8
|
188 |
def getAttachedRSDs(self):
|
BarthaM@8
|
189 |
vms = self.listSDVM()
|
BarthaM@8
|
190 |
attached_devices = dict()
|
BarthaM@8
|
191 |
for vm in vms:
|
BarthaM@8
|
192 |
rsd_filter = self.getUSBFilter(vm)
|
mb@12
|
193 |
if rsd_filter != None:
|
BarthaM@8
|
194 |
attached_devices[vm] = rsd_filter
|
BarthaM@8
|
195 |
return attached_devices
|
BarthaM@8
|
196 |
|
BarthaM@8
|
197 |
# configures hostonly networking and DHCP server. requires admin rights
|
BarthaM@8
|
198 |
def configureHostNetworking(self):
|
BarthaM@8
|
199 |
#cmd = 'vboxmanage list hostonlyifs'
|
BarthaM@8
|
200 |
#self.execute(cmd)
|
BarthaM@8
|
201 |
#cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
|
BarthaM@8
|
202 |
#self.execute(cmd)
|
BarthaM@8
|
203 |
#cmd = 'vboxmanage hostonlyif create'
|
BarthaM@8
|
204 |
#self.execute(cmd)
|
mb@33
|
205 |
cmd = 'VBoxManage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
|
BarthaM@8
|
206 |
self.execute(cmd)
|
BarthaM@8
|
207 |
#cmd = 'vboxmanage dhcpserver add'
|
BarthaM@8
|
208 |
#self.execute(cmd)
|
mb@33
|
209 |
cmd = 'VBoxManage 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'
|
BarthaM@8
|
210 |
self.execute(cmd)
|
BarthaM@8
|
211 |
|
mb@11
|
212 |
#create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
|
BarthaM@8
|
213 |
def createVM(self, vm_name):
|
BarthaM@8
|
214 |
hostonly_if = self.getHostOnlyIFs()
|
BarthaM@8
|
215 |
machineFolder = self.getDefaultMachineFolder()
|
mb@11
|
216 |
cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
|
BarthaM@8
|
217 |
self.execute(cmd)
|
mb@11
|
218 |
cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat'
|
BarthaM@8
|
219 |
self.execute(cmd)
|
mb@11
|
220 |
cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
|
BarthaM@8
|
221 |
self.execute(cmd)
|
mb@46
|
222 |
cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"' #--mtype immutable
|
BarthaM@8
|
223 |
self.execute(cmd)
|
BarthaM@8
|
224 |
return
|
BarthaM@8
|
225 |
|
BarthaM@8
|
226 |
#remove VM from the system. should be used on VMs returned by listSDVMs
|
BarthaM@8
|
227 |
def removeVM(self, vm_name):
|
BarthaM@8
|
228 |
print('removing ' + vm_name)
|
mb@36
|
229 |
cmd = 'VBoxManage unregistervm ' + vm_name + ' --delete'
|
BarthaM@8
|
230 |
print self.execute(cmd)
|
BarthaM@8
|
231 |
machineFolder = self.getDefaultMachineFolder()
|
mb@36
|
232 |
cmd = self.cygwin_path + 'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
|
BarthaM@8
|
233 |
print self.execute(cmd)
|
BarthaM@8
|
234 |
|
BarthaM@8
|
235 |
# start VM
|
BarthaM@8
|
236 |
def startVM(self, vm_name):
|
BarthaM@8
|
237 |
print('starting ' + vm_name)
|
mb@40
|
238 |
cmd = 'VBoxManage startvm ' + vm_name + ' --type headless'
|
mb@46
|
239 |
result = self.execute(cmd)
|
mb@46
|
240 |
while not string.find(str(result), 'successfully started',):
|
mb@46
|
241 |
print "Failed to start SDVM: ", vm_name, " retrying"
|
mb@46
|
242 |
time.sleep(1)
|
mb@46
|
243 |
result = self.execute(cmd)
|
mb@46
|
244 |
return result[0]
|
BarthaM@8
|
245 |
|
BarthaM@8
|
246 |
# stop VM
|
BarthaM@8
|
247 |
def stopVM(self, vm_name):
|
BarthaM@8
|
248 |
print('stopping ' + vm_name)
|
BarthaM@8
|
249 |
cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
|
mb@46
|
250 |
self.execute(cmd)
|
BarthaM@8
|
251 |
|
BarthaM@8
|
252 |
# return the hostOnly IP for a running guest
|
BarthaM@8
|
253 |
def getHostOnlyIP(self, vm_name):
|
BarthaM@8
|
254 |
print('gettting hostOnly IP address ' + vm_name)
|
BarthaM@8
|
255 |
cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
|
BarthaM@8
|
256 |
result = self.execute(cmd)
|
BarthaM@8
|
257 |
if result=='':
|
BarthaM@8
|
258 |
return None
|
BarthaM@8
|
259 |
result = result[1]
|
mb@40
|
260 |
if result.startswith('No value set!'):
|
mb@40
|
261 |
return None
|
BarthaM@8
|
262 |
return result[result.index(':')+1:].strip()
|
BarthaM@8
|
263 |
|
BarthaM@8
|
264 |
# attach removable storage device to VM by provision of filter
|
BarthaM@8
|
265 |
def attachRSD(self, vm_name, rsd_filter):
|
BarthaM@8
|
266 |
cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
|
BarthaM@8
|
267 |
print self.execute(cmd)
|
BarthaM@8
|
268 |
|
BarthaM@8
|
269 |
|
BarthaM@8
|
270 |
# return the description set for an existing VM
|
mb@7
|
271 |
def getVMInfo(self, vm_name):
|
mb@7
|
272 |
cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
|
mb@12
|
273 |
results = self.execute(cmd)[1]
|
mb@7
|
274 |
props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
|
mb@7
|
275 |
return props
|
mb@7
|
276 |
|
BarthaM@8
|
277 |
# return the configured USB filter for an existing VM
|
mb@7
|
278 |
def getUSBFilter(self, vm_name):
|
mb@7
|
279 |
props = self.getVMInfo(vm_name)
|
mb@7
|
280 |
keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
|
mb@7
|
281 |
keyset = set(props.keys())
|
mb@7
|
282 |
usb_filter = None
|
mb@7
|
283 |
if keyset.issuperset(keys):
|
mb@7
|
284 |
usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
|
mb@7
|
285 |
return usb_filter
|
mb@7
|
286 |
|
mb@7
|
287 |
#generates ISO containing authorized_keys for use with guest VM
|
mb@7
|
288 |
def genCertificateISO(self, vm_name):
|
mb@7
|
289 |
machineFolder = self.getDefaultMachineFolder()
|
dyle@52
|
290 |
|
dyle@52
|
291 |
## create a SSH key pair in a machine subfolder
|
dyle@52
|
292 |
#vm_folder = os.path.join(machineFolder, vm_name)
|
dyle@52
|
293 |
#ssh_folder = os.path.join(vm_folder, '.ssh')
|
dyle@52
|
294 |
#try:
|
dyle@52
|
295 |
# os.mkdir(ssh_folder)
|
dyle@52
|
296 |
#except:
|
dyle@52
|
297 |
# pass
|
dyle@52
|
298 |
#ssh_keyfile = os.path.join(ssh_folder, 'dvm_key')
|
dyle@52
|
299 |
#
|
dyle@52
|
300 |
# delete old key file (if existing)
|
dyle@52
|
301 |
#try:
|
dyle@52
|
302 |
# os.remove(ssh_keyfile)
|
dyle@52
|
303 |
#except:
|
dyle@52
|
304 |
# pass
|
dyle@52
|
305 |
#
|
dyle@52
|
306 |
## create new key file
|
dyle@52
|
307 |
#try:
|
dyle@52
|
308 |
# p = Cygwin()(['/bin/ssh-keygen', '-q', '-t', 'rsa', '-N', '', '-C', vm_name, '-f', ssh_keyfile])
|
dyle@52
|
309 |
# p.wait()
|
dyle@52
|
310 |
#except:
|
dyle@52
|
311 |
# sys.stderr.write('failed to create a new SSH key pair as: ' + ssh_keyfile + '\n')
|
dyle@52
|
312 |
# return
|
dyle@52
|
313 |
#try:
|
dyle@52
|
314 |
# os.chmod(ssh_keyfile, stat.S_IREAD)
|
dyle@52
|
315 |
#except:
|
dyle@52
|
316 |
# pass
|
dyle@52
|
317 |
#
|
dyle@52
|
318 |
## move out private key
|
dyle@52
|
319 |
#try:
|
dyle@52
|
320 |
# os.rename(ssh_keyfile, os.path.join(vm_folder, 'dvm_key'))
|
dyle@52
|
321 |
#except :
|
dyle@52
|
322 |
# sys.stderr.write('failed to move private SSH key\n')
|
dyle@52
|
323 |
# return
|
dyle@52
|
324 |
#
|
dyle@52
|
325 |
## rename public key to 'authorized_keys'
|
dyle@52
|
326 |
#try:
|
dyle@52
|
327 |
# os.rename(ssh_keyfile + '.pub', os.path.join(ssh_folder, 'authorized_keys'))
|
dyle@52
|
328 |
#except:
|
dyle@52
|
329 |
# sys.stderr.write('failed to rename public key to "authorized_keys"\n')
|
dyle@52
|
330 |
# return
|
dyle@52
|
331 |
#
|
dyle@52
|
332 |
## generate ISO image
|
dyle@52
|
333 |
#iso_file = os.path.join(vm_folder, vm_name + '.iso')
|
dyle@52
|
334 |
#try:
|
dyle@52
|
335 |
# p = Cygwin()(['/bin/genisoimage', '-J', '-R', '-o', iso_file, ssh_folder])
|
dyle@52
|
336 |
# p.wait()
|
dyle@52
|
337 |
#except:
|
dyle@52
|
338 |
# sys.stderr.write('failed to create ISO image.\n')
|
dyle@52
|
339 |
# return
|
dyle@52
|
340 |
|
mb@7
|
341 |
# create .ssh folder in vm_name
|
mb@7
|
342 |
cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
|
mb@46
|
343 |
self.execute(cmd)
|
mb@7
|
344 |
# generate dvm_key pair in vm_name / .ssh
|
mb@7
|
345 |
cmd = self.cygwin_path+'bash.exe --login -c \"ssh-keygen -q -t rsa -N \\"\\" -C \\\"' + vm_name + '\\\" -f \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\"\"' #'echo -e "y\\n" |',
|
mb@46
|
346 |
self.execute(cmd)
|
mb@7
|
347 |
# set permissions for keys
|
mb@7
|
348 |
#TODO: test without chmod
|
mb@7
|
349 |
cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
|
mb@46
|
350 |
self.execute(cmd)
|
mb@7
|
351 |
# move out private key
|
mb@7
|
352 |
cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
|
mb@46
|
353 |
self.execute(cmd)
|
mb@7
|
354 |
# rename public key to authorized_keys
|
mb@7
|
355 |
cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
|
mb@46
|
356 |
self.execute(cmd)
|
mb@7
|
357 |
# generate iso image with .ssh/authorized keys
|
mb@7
|
358 |
cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
|
mb@46
|
359 |
self.execute(cmd)
|
mb@7
|
360 |
|
mb@7
|
361 |
# attaches generated ssh public cert to guest vm
|
mb@7
|
362 |
def attachCertificateISO(self, vm_name):
|
mb@7
|
363 |
machineFolder = self.getDefaultMachineFolder()
|
mb@7
|
364 |
cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
|
mb@7
|
365 |
result = self.execute(cmd)
|
mb@7
|
366 |
return result
|
mb@7
|
367 |
|
mb@36
|
368 |
handleDeviceChangeLock = threading.Lock()
|
mb@36
|
369 |
|
mb@7
|
370 |
# handles device change events
|
mb@7
|
371 |
def handleDeviceChange(self):
|
mb@36
|
372 |
if VMManager.handleDeviceChangeLock.acquire(True):
|
mb@36
|
373 |
#destroy unused vms
|
mb@40
|
374 |
new_ip = None
|
mb@36
|
375 |
attached_devices = self.getAttachedRSDs()
|
mb@36
|
376 |
connected_devices = self.listRSDS()
|
mb@36
|
377 |
for vm_name in attached_devices.keys():
|
mb@36
|
378 |
if attached_devices[vm_name] not in connected_devices.values():
|
mb@40
|
379 |
self.unmapNetworkDrive('h:')
|
mb@36
|
380 |
self.stopVM(vm_name)
|
mb@36
|
381 |
self.removeVM(vm_name)
|
mb@36
|
382 |
#create new vm for attached device if any
|
mb@36
|
383 |
attached_devices = self.getAttachedRSDs()
|
mb@36
|
384 |
for connected_device in connected_devices.values():
|
mb@36
|
385 |
if (attached_devices and False) or (connected_device not in attached_devices.values()):
|
mb@36
|
386 |
new_sdvm = self.generateSDVMName()
|
mb@36
|
387 |
self.createVM(new_sdvm)
|
mb@36
|
388 |
self.attachRSD(new_sdvm, connected_device)
|
mb@46
|
389 |
|
mb@46
|
390 |
|
mb@36
|
391 |
self.startVM(new_sdvm)
|
mb@46
|
392 |
# wait for machine to come up
|
mb@40
|
393 |
while new_ip == None:
|
mb@40
|
394 |
time.sleep(1)
|
mb@40
|
395 |
new_ip = self.getHostOnlyIP(new_sdvm)
|
mb@40
|
396 |
while new_ip not in self.startNotifications:
|
mb@40
|
397 |
time.sleep(1)
|
mb@46
|
398 |
if new_ip != None:
|
mb@46
|
399 |
self.mapNetworkDrive('h:', '\\\\' + new_ip + '\\USB', None, None)
|
mb@40
|
400 |
#TODO: cleanup notifications somwhere else (eg. machine shutdown)
|
mb@40
|
401 |
self.startNotifications.remove(new_ip)
|
mb@36
|
402 |
VMManager.handleDeviceChangeLock.release()
|
mb@40
|
403 |
return new_ip
|
mb@12
|
404 |
|
mb@12
|
405 |
def handleBrowsingRequest(self):
|
mb@46
|
406 |
if VMManager.handleDeviceChangeLock.acquire(True):
|
mb@46
|
407 |
new_ip = None
|
mb@46
|
408 |
new_sdvm = self.generateSDVMName()
|
mb@46
|
409 |
self.createVM(new_sdvm)
|
mb@46
|
410 |
self.genCertificateISO(new_sdvm)
|
mb@46
|
411 |
self.attachCertificateISO(new_sdvm)
|
mb@46
|
412 |
self.startVM(new_sdvm)
|
mb@46
|
413 |
# wait for machine to come up
|
mb@46
|
414 |
while new_ip == None:
|
mb@46
|
415 |
time.sleep(1)
|
mb@46
|
416 |
new_ip = self.getHostOnlyIP(new_sdvm)
|
mb@46
|
417 |
while new_ip not in self.startNotifications:
|
mb@46
|
418 |
time.sleep(1)
|
mb@46
|
419 |
if new_ip != None:
|
mb@46
|
420 |
self.mapNetworkDrive('g:', '\\\\' + new_ip + '\\Download', None, None)
|
mb@46
|
421 |
#TODO: cleanup notifications somwhere else (eg. machine shutdown)
|
mb@46
|
422 |
self.startNotifications.remove(new_ip)
|
mb@46
|
423 |
VMManager.handleDeviceChangeLock.release()
|
om@31
|
424 |
return new_sdvm
|
mb@7
|
425 |
|
mb@7
|
426 |
# executes command over ssh on guest vm
|
mb@46
|
427 |
def sshGuestExecute(self, vm_name, prog, user_name='osecuser'):
|
mb@7
|
428 |
# get vm ip
|
mb@7
|
429 |
address = self.getHostOnlyIP(vm_name)
|
mb@7
|
430 |
machineFolder = self.getDefaultMachineFolder()
|
mb@7
|
431 |
# run command
|
BarthaM@8
|
432 |
cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
|
mb@7
|
433 |
return self.execute(cmd)
|
mb@7
|
434 |
|
mb@7
|
435 |
# executes command over ssh on guest vm with X forwarding
|
mb@46
|
436 |
def sshGuestX11Execute(self, vm_name, prog, user_name='osecuser'):
|
mb@7
|
437 |
#TODO: verify if X server is running on user account
|
mb@7
|
438 |
#TODO: set DISPLAY accordingly
|
mb@7
|
439 |
address = self.getHostOnlyIP(vm_name)
|
mb@7
|
440 |
machineFolder = self.getDefaultMachineFolder()
|
mb@7
|
441 |
# run command
|
mb@46
|
442 |
#--login
|
mb@46
|
443 |
#cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -v -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
|
mb@46
|
444 |
cmd = self.cygwin_path+'mintty.exe -e /bin/env DISPLAY=:0 /usr/bin/ssh -v -Y -i \"' + machineFolder + '\\' + vm_name + '\\dvm_key\" ' + user_name + '@' + address + ' ' + prog + ''
|
mb@46
|
445 |
#cmd = self.cygwin_path+'mintty.exe -e /bin/bash --login -c \"DISPLAY=:0 /usr/bin/ssh -v -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\" ' + user_name + '@' + address + ' ' + prog + '\"'
|
mb@46
|
446 |
if DEBUG:
|
mb@46
|
447 |
print('trying to launch: ' + cmd)
|
mb@46
|
448 |
process = Popen(cmd)
|
mb@46
|
449 |
if DEBUG:
|
mb@46
|
450 |
print('launched: ' + cmd)
|
mb@46
|
451 |
return
|
mb@7
|
452 |
|
mb@40
|
453 |
#Small function to check the availability of network resource.
|
mb@40
|
454 |
def isAvailable(self, path):
|
mb@40
|
455 |
cmd = 'IF EXIST ' + path + ' echo YES'
|
mb@40
|
456 |
result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
|
mb@40
|
457 |
return string.find(str(result), 'YES',)
|
mb@40
|
458 |
|
mb@40
|
459 |
#Small function to check if the mention location is a directory
|
mb@40
|
460 |
def isDirectory(self, path):
|
mb@40
|
461 |
cmd = 'dir ' + path + ' | FIND ".."'
|
mb@40
|
462 |
result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
|
mb@40
|
463 |
return string.find(str(result), 'DIR',)
|
mb@40
|
464 |
|
mb@40
|
465 |
def mapNetworkDrive(self, drive, networkPath, user, password):
|
mb@40
|
466 |
self.unmapNetworkDrive('h:')
|
mb@40
|
467 |
#Check for drive availability
|
mb@40
|
468 |
if self.isAvailable(drive) > -1:
|
mb@40
|
469 |
print "Drive letter is already in use: ", drive
|
mb@40
|
470 |
return -1
|
mb@40
|
471 |
#Check for network resource availability
|
mb@40
|
472 |
while self.isAvailable(networkPath) == -1:
|
mb@40
|
473 |
time.sleep(1)
|
mb@40
|
474 |
print "Path not accessible: ", networkPath, " retrying"
|
mb@40
|
475 |
#return -1
|
mb@40
|
476 |
|
mb@40
|
477 |
#Prepare 'NET USE' commands
|
mb@40
|
478 |
cmd = 'NET USE ' + drive + ' ' + networkPath
|
mb@40
|
479 |
if user != None:
|
mb@40
|
480 |
cmd = cmd + ' ' + password + ' /User' + user
|
mb@40
|
481 |
|
mb@40
|
482 |
print "cmd = ", cmd
|
mb@40
|
483 |
#Execute 'NET USE' command with authentication
|
mb@40
|
484 |
result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
|
mb@40
|
485 |
print "Executed: ", cmd
|
mb@40
|
486 |
if string.find(str(result), 'successfully',) == -1:
|
mb@40
|
487 |
print cmd, " FAILED"
|
mb@40
|
488 |
return -1
|
mb@40
|
489 |
#Mapped with first try
|
mb@40
|
490 |
return 1
|
mb@40
|
491 |
|
mb@40
|
492 |
def unmapNetworkDrive(self, drive):
|
mb@40
|
493 |
#Check if the drive is in use
|
mb@40
|
494 |
if self.isAvailable(drive) == -1:
|
mb@40
|
495 |
#Drive is not in use
|
mb@40
|
496 |
return -1
|
mb@40
|
497 |
#Prepare 'NET USE' command
|
mb@40
|
498 |
cmd = 'net use ' + drive + ' /DELETE'
|
mb@40
|
499 |
result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
|
mb@40
|
500 |
if string.find(str(result), 'successfully',) == -1:
|
mb@40
|
501 |
return -1
|
mb@40
|
502 |
return 1
|
mb@40
|
503 |
|
mb@40
|
504 |
if __name__ == '__main__':
|
mb@40
|
505 |
man = VMManager.getInstance()
|
mb@40
|
506 |
#man.removeVM('SecurityDVM0')
|
mb@40
|
507 |
#man.netUse('192.168.56.134', 'USB\\')
|
mb@46
|
508 |
#ip = '192.168.56.139'
|
mb@46
|
509 |
#man.mapNetworkDrive('h:', '\\\\' + ip + '\USB', None, None)
|
mb@33
|
510 |
#man.cygwin_path = 'c:\\cygwin64\\bin\\'
|
mb@7
|
511 |
#man.handleDeviceChange()
|
mb@7
|
512 |
#print man.listSDVM()
|
mb@11
|
513 |
#man.configureHostNetworking()
|
mb@33
|
514 |
#new_vm = man.generateSDVMName()
|
mb@33
|
515 |
#man.createVM(new_vm)
|
mb@33
|
516 |
#man.genCertificateISO(new_vm)
|
mb@33
|
517 |
#man.attachCertificateISO(new_vm)
|
mb@11
|
518 |
|
mb@7
|
519 |
#man.attachCertificateISO(vm_name)
|
mb@7
|
520 |
#man.sshGuestExecute(vm_name, "ls")
|
mb@46
|
521 |
man.sshGuestX11Execute('SecurityDVM1', '/usr/bin/iceweasel')
|
mb@46
|
522 |
time.sleep(60)
|
mb@7
|
523 |
#cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
|
mb@7
|
524 |
#man.execute(cmd)
|
dyle@52
|
525 |
|