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