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