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