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