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