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