OpenSecurity/bin/vmmanager.py
author mb
Tue, 10 Dec 2013 14:50:14 +0100
changeset 34 fe5fb244f008
parent 31 d95fe93d7a83
child 35 ba1ca3e5870b
permissions -rw-r--r--
added /sdvm_started notification edpoint and isSDVMStarted vmmanager method.
changed VMManager to sinleton. retrieve with VMManager.getInstance()
     1 '''
     2 Created on Nov 19, 2013
     3 
     4 @author: BarthaM
     5 '''
     6 import os
     7 import os.path
     8 from subprocess import Popen, PIPE, call
     9 import subprocess
    10 import sys
    11 import re
    12 import _winreg
    13 from cygwin import Cygwin
    14 
    15 
    16 DEBUG = True
    17 
    18 class USBFilter:
    19     vendorid = ""
    20     productid = ""
    21     revision = ""
    22     
    23     def __init__(self, vendorid, productid, revision):
    24         self.vendorid = vendorid.lower()
    25         self.productid = productid.lower()
    26         self.revision = revision.lower()
    27         return
    28     
    29     def __eq__(self, other):
    30         return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
    31     
    32     def __hash__(self):
    33         return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
    34     
    35     def __repr__(self):
    36         return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
    37         
    38 
    39 class VMManager(object):
    40     vmRootName = "SecurityDVM"
    41     systemProperties = None
    42     cygwin_path = 'c:\\cygwin64\\bin\\'
    43     vboxManage = 'VBoxManage'
    44     startNotifications = list()
    45     
    46     _instance = None
    47     #def __new__(cls, *args, **kwargs):
    48     #    if not cls._instance:
    49     #        cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
    50     #    return cls._instance
    51     
    52     def __init__(self):
    53         self.cygwin_path = os.path.join(Cygwin.root(), 'bin') + os.path.sep
    54         self.vboxManage = os.path.join(self.getVBoxManagePath(), 'VBoxManage')
    55         self.systemProperties = self.getSystemProperties()
    56         return
    57     
    58     @staticmethod
    59     def getInstance():
    60         if VMManager._instance == None:
    61             VMManager._instance = VMManager()
    62         return VMManager._instance
    63     
    64     def putStartNotification(self, ip):
    65         self.startNotifications.append(ip)
    66     
    67     def isSDVMStarted(self, ip):
    68         return self.startNotifications.contains(ip)
    69              
    70     def execute(self, cmd):
    71         if DEBUG:
    72             print('trying to launch: ' + cmd)
    73         process = Popen(cmd, stdout=PIPE, stderr=PIPE)
    74         if DEBUG:
    75             print('launched: ' + cmd)
    76         result = process.wait()
    77         res_stdout = process.stdout.read();
    78         res_stderr = process.stderr.read();
    79         if DEBUG:
    80             if res_stdout != "":
    81                 print res_stdout
    82             if res_stderr != "":
    83                 print res_stderr
    84         return result, res_stdout, res_stderr
    85     
    86     def getVBoxManagePath(self):
    87         """get the path to the VirtualBox installation on this system"""
    88         p = None
    89         try:
    90             k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
    91             p = _winreg.QueryValueEx(k, 'InstallDir')[0]
    92             _winreg.CloseKey(k)
    93         except:
    94             pass
    95         return p
    96     
    97     # return hosty system properties
    98     def getSystemProperties(self):
    99         cmd = self.vboxManage + ' list systemproperties'
   100         result = self.execute(cmd)
   101         if result[1]=='':
   102             return None
   103         props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
   104         return props
   105     
   106     # return the folder containing the guest VMs     
   107     def getDefaultMachineFolder(self):
   108         return self.systemProperties["Default machine folder"]
   109     
   110     #list the hostonly IFs exposed by the VBox host
   111     def getHostOnlyIFs(self):
   112         cmd = 'VBoxManage list hostonlyifs'
   113         result = self.execute(cmd)[1]
   114         if result=='':
   115             return None
   116         props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
   117         return props
   118         
   119     def listRSDS(self):
   120         cmd = 'VBoxManage list usbhost'
   121         results = self.execute(cmd)[1]
   122         results = results.split('Host USB Devices:')[1].strip()
   123         
   124         items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
   125         rsds = dict()   
   126         for item in items:
   127             props = dict()
   128             for line in item.splitlines():
   129                 if line != "":         
   130                     k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
   131                     props[k] = v;
   132             
   133             if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
   134                 usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], 
   135                                         re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
   136                                         re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
   137                 rsds[props['UUID']] = usb_filter;
   138                 if DEBUG:
   139                     print usb_filter
   140         return rsds
   141 
   142     # list all existing VMs registered with VBox
   143     def listVM(self):
   144         cmd = 'VBoxManage list vms'
   145         result = self.execute(cmd)[1]
   146         vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
   147         return vms
   148     
   149     # list existing SDVMs
   150     def listSDVM(self):
   151         vms = self.listVM()
   152         svdms = []
   153         for vm in vms:
   154             if vm.startswith(self.vmRootName) and vm != self.vmRootName:
   155                 svdms.append(vm)
   156         return svdms
   157     
   158     # generate valid (not already existing SDVM name). necessary for creating a new VM
   159     def generateSDVMName(self):
   160         vms = self.listVM()
   161         for i in range(0,999):
   162             if(not self.vmRootName+str(i) in vms):
   163                 return self.vmRootName+str(i)
   164         return ''
   165     
   166     # return the RSDs attached to all existing SDVMs
   167     def getAttachedRSDs(self):
   168         vms = self.listSDVM()
   169         attached_devices = dict()
   170         for vm in vms:
   171             rsd_filter = self.getUSBFilter(vm)
   172             if rsd_filter != None:
   173                 attached_devices[vm] = rsd_filter
   174         return attached_devices
   175     
   176     # configures hostonly networking and DHCP server. requires admin rights
   177     def configureHostNetworking(self):
   178         #cmd = 'vboxmanage list hostonlyifs'
   179         #self.execute(cmd)
   180         #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
   181         #self.execute(cmd)
   182         #cmd = 'vboxmanage hostonlyif create'
   183         #self.execute(cmd)
   184         cmd = 'VBoxManage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
   185         self.execute(cmd)
   186         #cmd = 'vboxmanage dhcpserver add'
   187         #self.execute(cmd)
   188         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'
   189         self.execute(cmd)
   190     
   191     #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
   192     def createVM(self, vm_name):
   193         hostonly_if = self.getHostOnlyIFs()
   194         machineFolder = self.getDefaultMachineFolder()
   195         cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
   196         self.execute(cmd)
   197         cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat' 
   198         self.execute(cmd)
   199         cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
   200         self.execute(cmd)
   201         cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
   202         #--mtype immutable
   203         self.execute(cmd)
   204         return
   205     
   206     #remove VM from the system. should be used on VMs returned by listSDVMs    
   207     def removeVM(self, vm_name):
   208         print('removing ' + vm_name)
   209         cmd = 'VBoxManage unregistervm', vm_name, '--delete'
   210         print self.execute(cmd)
   211         machineFolder = self.getDefaultMachineFolder()
   212         cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
   213         print self.execute(cmd)
   214     
   215     # start VM
   216     def startVM(self, vm_name):
   217         print('starting ' +  vm_name)
   218         cmd = 'VBoxManage startvm ' + vm_name + ' --type headless'
   219         print self.execute(cmd)
   220         
   221     # stop VM    
   222     def stopVM(self, vm_name):
   223         print('stopping ' + vm_name)
   224         cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
   225         print self.execute(cmd)
   226     
   227     # return the hostOnly IP for a running guest    
   228     def getHostOnlyIP(self, vm_name):
   229         print('gettting hostOnly IP address ' + vm_name)
   230         cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
   231         result = self.execute(cmd)
   232         if result=='':
   233             return None
   234         result = result[1]
   235         return result[result.index(':')+1:].strip()
   236     
   237     # attach removable storage device to VM by provision of filter
   238     def attachRSD(self, vm_name, rsd_filter):
   239         cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
   240         print self.execute(cmd)
   241         
   242     
   243     # return the description set for an existing VM
   244     def getVMInfo(self, vm_name):
   245         cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
   246         results = self.execute(cmd)[1]
   247         props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
   248         return props
   249     
   250     # return the configured USB filter for an existing VM 
   251     def getUSBFilter(self, vm_name):
   252         props = self.getVMInfo(vm_name)
   253         keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
   254         keyset = set(props.keys())
   255         usb_filter = None
   256         if keyset.issuperset(keys):
   257             usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
   258         return usb_filter
   259     
   260     #generates ISO containing authorized_keys for use with guest VM
   261     def genCertificateISO(self, vm_name):
   262         machineFolder = self.getDefaultMachineFolder()
   263         # create .ssh folder in vm_name
   264         cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
   265         result = self.execute(cmd)
   266         # generate dvm_key pair in vm_name / .ssh     
   267         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" |',
   268         result = self.execute(cmd)
   269         # set permissions for keys
   270         #TODO: test without chmod
   271         cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
   272         result = self.execute(cmd)
   273         # move out private key
   274         cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
   275         result = self.execute(cmd)
   276         # rename public key to authorized_keys
   277         cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
   278         result = self.execute(cmd)
   279         # generate iso image with .ssh/authorized keys
   280         cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
   281         result = self.execute(cmd)
   282     
   283     # attaches generated ssh public cert to guest vm
   284     def attachCertificateISO(self, vm_name):
   285         machineFolder = self.getDefaultMachineFolder()
   286         cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
   287         result = self.execute(cmd)
   288         return result
   289     
   290     # handles device change events
   291     def handleDeviceChange(self):
   292         attached_devices = self.getAttachedRSDs()
   293         connected_devices = self.listRSDS()
   294         for vm_name in attached_devices.keys():
   295             if connected_devices and attached_devices[vm_name] not in connected_devices.values():
   296                 # self.netUse(vm_name)
   297                 self.stopVM(vm_name)
   298                 self.removeVM(vm_name)
   299         
   300         attached_devices = self.getAttachedRSDs()
   301         for connected_device in connected_devices.values():
   302             if attached_devices or connected_device not in attached_devices.values():
   303                 new_sdvm = self.generateSDVMName()
   304                 self.createVM(new_sdvm)
   305                 self.attachRSD(new_sdvm, connected_device)
   306                 self.startVM(new_sdvm)
   307                 self.netUse(new_sdvm)
   308     
   309     def handleBrowsingRequest(self):
   310         new_sdvm = self.generateSDVMName()
   311         self.createVM(new_sdvm)
   312         self.genCertificateISO(new_sdvm)
   313         self.attachCertificateISO(new_sdvm)
   314         return new_sdvm
   315     
   316     # executes command over ssh on guest vm
   317     def sshGuestExecute(self, vm_name, prog, user_name='opensec'):
   318         # get vm ip
   319         address = self.getHostOnlyIP(vm_name)
   320         machineFolder = self.getDefaultMachineFolder()
   321         # run command
   322         cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  ' + user_name + '@' + address + ' ' + prog + '\"'
   323         return self.execute(cmd)
   324     
   325     # executes command over ssh on guest vm with X forwarding
   326     def sshGuestX11Execute(self, vm_name, prog, user_name='opensec'):
   327         #TODO: verify if X server is running on user account 
   328         #TODO: set DISPLAY accordingly
   329         address = self.getHostOnlyIP(vm_name)
   330         machineFolder = self.getDefaultMachineFolder()
   331         # run command
   332         cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  '  + user_name + '@' + address + ' ' + prog + '\"'
   333         return self.execute(cmd)    
   334         
   335     # executes NET USE and connects to samba share on guestos 
   336     def netUse(self, vm_name):
   337         ip = self.getHostOnlyIP(vm_name)
   338         cmd = 'net use H: \\' + ip + '\USB'
   339         return self.execute(cmd)
   340         
   341     
   342 #if __name__ == '__main__':
   343     #man = VMManager()
   344     #man.cygwin_path = 'c:\\cygwin64\\bin\\'
   345     #man.handleDeviceChange()
   346     #print man.listSDVM()
   347     #man.configureHostNetworking()
   348     #new_vm = man.generateSDVMName()
   349     #man.createVM(new_vm)
   350     #man.genCertificateISO(new_vm)
   351     #man.attachCertificateISO(new_vm)
   352     
   353     #man.attachCertificateISO(vm_name)
   354     #man.sshGuestExecute(vm_name, "ls")
   355     #man.sshGuestX11Execute(vm_name, "iceweasel")
   356     #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
   357     #man.execute(cmd)
   358