OpenSecurity/bin/opensecurityd.pyw
author Oliver Maurhart <oliver.maurhart@ait.ac.at>
Wed, 25 Jun 2014 20:56:40 +0200
changeset 204 0c3136908f4f
parent 203 0cc33b647a4e
child 212 59ebaa44c12c
permissions -rwxr-xr-x
yet even more sex to the configuration dialog
     1 #!/bin/env python
     2 # -*- coding: utf-8 -*-
     3 
     4 # ------------------------------------------------------------
     5 # opensecurityd
     6 # 
     7 # the opensecurityd as RESTful server
     8 #
     9 # Autor: Oliver Maurhart, <oliver.maurhart@ait.ac.at>
    10 #
    11 # Copyright (C) 2013 AIT Austrian Institute of Technology
    12 # AIT Austrian Institute of Technology GmbH
    13 # Donau-City-Strasse 1 | 1220 Vienna | Austria
    14 # http://www.ait.ac.at
    15 #
    16 # This program is free software; you can redistribute it and/or
    17 # modify it under the terms of the GNU General Public License
    18 # as published by the Free Software Foundation version 2.
    19 # 
    20 # This program is distributed in the hope that it will be useful,
    21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
    22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    23 # GNU General Public License for more details.
    24 # 
    25 # You should have received a copy of the GNU General Public License
    26 # along with this program; if not, write to the Free Software
    27 # Foundation, Inc., 51 Franklin Street, Fifth Floor, 
    28 # Boston, MA  02110-1301, USA.
    29 # ------------------------------------------------------------
    30 
    31 
    32 # ------------------------------------------------------------
    33 # imports
    34 
    35 import json
    36 import os
    37 import os.path
    38 import subprocess
    39 import sys
    40 import tempfile
    41 import web
    42 
    43 import vmmanager
    44 
    45 # local
    46 import __init__ as opensecurity
    47 from cygwin import Cygwin
    48 from environment import Environment
    49 from opensecurity_util import logger, showTrayMessage
    50 
    51 
    52 
    53 # ------------------------------------------------------------
    54 # const
    55 
    56 """All the URLs we know mapping to class handler"""
    57 opensecurity_urls = (
    58     '/browsing',                        'os_browsing',          # http://localhost:8080/browsing                                GET
    59     '/fetch_initial_image',             'os_fetch_image',       # http://localhost:8080/fetch_initial_image                     GET
    60     '/init',                            'os_init',              # http://localhost:8080/init                                    GET
    61     '/initial_image',                   'os_initial_image',     # http://localhost:8080/initial_image                           GET
    62     '/sdvms',                           'os_sdvms',             # http://localhost:8080/sdvms                                   GET, PUT
    63     '/sdvms/(.*)/application/(.*)',     'os_sdvm_application',  # http://localhost:8080/sdvms/[VMNAME]/application/[COMMAND]    GET
    64     '/sdvms/(.*)/ip',                   'os_sdvm_ip',           # http://localhost:8080/sdvms/[VMNAME]/ip                       GET
    65     '/sdvms/(.*)/start',                'os_sdvm_start',        # http://localhost:8080/sdvms/[VMNAME]/start                    GET
    66     '/sdvms/(.*)/stop',                 'os_sdvm_stop',         # http://localhost:8080/sdvms/[VMNAME]/stop                     GET
    67     '/sdvms/(.*)',                      'os_sdvm',              # http://localhost:8080/sdvms/[VMNAME]                          GET, DELETE
    68     '/setup',                           'os_setup',             # http://localhost:8080/setup                                   GET
    69     '/vms',                             'os_vms',               # http://localhost:8080/vms                                     GET
    70     '/vms/(.*)',                        'os_vm',                # http://localhost:8080/vms/[VMNAME]                            GET
    71     '/update_template',                 'os_update_template',   # http://localhost:8080/update_template                         GET
    72     '/terminate',                       'os_terminate',         # http://localhost:8080/terminate                               GET
    73     '/',                                'os_root'               # http://localhost:8080/                                        GET
    74 )
    75 
    76 
    77 # ------------------------------------------------------------
    78 # vars
    79 
    80 # Global VMManager instance
    81 gvm_mgr = None
    82 
    83 # server instance
    84 server = None
    85 
    86 
    87 # ------------------------------------------------------------
    88 # code
    89 
    90 
    91 class os_browsing:
    92     """OpenSecurity '/browsing' handler
    93     
    94     - GET: Start and prepare a new SecurityVM for Internet Browsing. Return the name of the VM.
    95     """
    96     
    97     def GET(self):
    98         log_call(web.ctx.environ)
    99         global gvm_mgr
   100         try:
   101             result = gvm_mgr.handleBrowsingRequest()
   102             return result
   103         except:
   104             raise web.internalerror()
   105 
   106        
   107 class os_fetch_image:
   108     """OpenSecurity '/fetch_initial_image' handler
   109     
   110     - GET: fetch the initial image from the X-Net Servers
   111             The initial image is stored in the
   112             Virtual Box default machine path.
   113             The result to this call is a temprary file
   114             which shows the progress (or error state)
   115             of this call.
   116     """
   117     
   118     def GET(self):
   119         
   120         log_call(web.ctx.environ)
   121         global gvm_mgr
   122 
   123         trace_file_name = os.path.join(Environment('OpenSecurity').log_path, 'OpenSecurity_fetch_image.log')
   124         trace_file = open(trace_file_name, 'w+')
   125 
   126         machine_folder = Cygwin.cygPath(gvm_mgr.getMachineFolder()) 
   127         download_initial_image_script = Cygwin.cygPath(os.path.abspath(os.path.join(os.path.split(__file__)[0], 'download_initial_image.sh')))
   128         Cygwin.bashExecute('\\"' + download_initial_image_script + '\\" \'' + machine_folder + '\'', wait_return = False, stdout = trace_file, stderr = trace_file) 
   129 
   130         res = '{ "fetch_log": "' + trace_file_name.replace('\\', '\\\\') + '" }'
   131         return res
   132 
   133 
   134 class os_init:
   135     """OpenSecurity '/init' handler
   136     
   137     - GET: Do initial import of OsecVM.ova
   138     """
   139     
   140     def GET(self):
   141         log_call(web.ctx.environ)
   142         global gvm_mgr
   143 
   144         gvm_mgr.stop()
   145         gvm_mgr.cleanup()
   146         
   147         if gvm_mgr.vmRootName in gvm_mgr.listVM():
   148             gvm_mgr.poweroffVM(gvm_mgr.vmRootName)
   149             tmplateUUID = gvm_mgr.getTemplateUUID()
   150             if tmplateUUID != None:
   151                 logger.debug('found parent uuid ' + tmplateUUID)
   152                 gvm_mgr.storageDetach(gvm_mgr.vmRootName)
   153                 gvm_mgr.removeSnapshots(tmplateUUID)
   154                 gvm_mgr.removeImage(tmplateUUID)
   155             else:
   156                 logger.debug('parent uuid not found')
   157             gvm_mgr.removeVM(gvm_mgr.vmRootName)
   158         
   159         trace_file_name = os.path.join(Environment('OpenSecurity').log_path, 'OpenSecurity_initial_import.log')
   160         trace_file = open(trace_file_name, 'w+')
   161 
   162         vm_image = Cygwin.cygPath(gvm_mgr.getMachineFolder()) + '/OsecVM.ova'
   163         initial_import_script = Cygwin.cygPath(os.path.abspath(os.path.join(os.path.split(__file__)[0], 'initial_vm.sh')))
   164         Cygwin.bashExecute('\\"' + initial_import_script + '\\" \'' + vm_image + '\'', wait_return = False, stdout = trace_file, stderr = trace_file) 
   165 
   166         res = '{ "init_log": "' + trace_file_name.replace('\\', '\\\\') + '" }'
   167         return res
   168 
   169 
   170 class os_initial_image:
   171     """OpenSecurity '/initial_image' handler
   172     
   173     - GET: Return what we have as initial image.
   174     """
   175     
   176     def GET(self):
   177         log_call(web.ctx.environ)
   178         global gvm_mgr
   179         t = os.path.join(gvm_mgr.systemProperties['Default machine folder'], 'OsecVM.ova')
   180         res = ''
   181         if os.path.isfile(t):
   182             res = '{"initial_template": { '
   183             res += '"name": "OsecVM.ova", '
   184             res += '"path": "' + t.replace('\\', '\\\\') + '", '
   185             res += '"size": ' + str(os.path.getsize(t)) + ', ' 
   186             res += '"date": ' + str(os.path.getmtime(t)) + ''
   187             res += '}}'
   188         return res
   189 
   190 
   191 class os_root:
   192     """OpenSecurity '/' handler
   193     
   194     - GET: give information about current installation.
   195     """
   196     
   197     def GET(self):
   198         log_call(web.ctx.environ)
   199         global gvm_mgr
   200 
   201         # create a json string and pretty print it
   202         res = '{"os_server": { '
   203         res += '"version": "' + opensecurity.__version__ + '" '
   204         res += ', "virtual box systemproperties": ' + str(gvm_mgr.systemProperties).replace("'", '"') 
   205         res += ', "current temporary folder": "' + tempfile.gettempdir().replace('\\', '\\\\') + '"'
   206         res += ', "current log folder": "' + Environment('OpenSecurity').log_path.replace('\\', '\\\\') + '"'
   207 
   208         try:
   209             res += ', "whoami": "' + Cygwin.bashExecute('whoami')[1].strip() + '"'
   210         except:
   211             res += ', "whoami": "FAILED"'
   212 
   213         try:
   214             res += ', "mount": ' + str(Cygwin.bashExecute('mount')[1].split('\n')[:-1]).replace("'", '"')
   215         except:
   216             res += ', "mount": "FAILED"'
   217 
   218         try:
   219             res += ', "cygpath --windows ~": "' + Cygwin.bashExecute('cygpath --windows ~')[1].strip().replace('\\', '\\\\') + '"'
   220         except:
   221             res += ', "cygpath --windows ~": "FAILED"'
   222 
   223 
   224         res += ', "status message": "' + gvm_mgr.status_message.replace('"', "'") + '"'
   225 
   226         res += '}}'
   227 
   228         # loading it into json and print it again ensures
   229         # we really do have a valid RFC conform json string
   230         # created (as long as the python json module is RFC conform)
   231         return json.dumps(json.loads(res), indent = 4)
   232 
   233 
   234 
   235 class os_sdvm:
   236     """OpenSecurity '/sdvms/[VM]' handler
   237     
   238     - GET: Information about a specific SecurityVM
   239     - DELETE: Remove a specific
   240     """
   241     
   242     def GET(self, name):
   243         log_call(web.ctx.environ)
   244         global gvm_mgr
   245         return json.dumps(gvm_mgr.getVMInfo(name), indent = 4)
   246 
   247     def DELETE(self, name):
   248         log_call(web.ctx.environ)
   249         global gvm_mgr
   250         return gvm_mgr.removeVM(name)
   251             
   252 
   253 class os_sdvm_application:
   254     """OpenSecurity '/sdvms/[VM]/application/[CMD]' handler
   255     
   256     - GET: start application with given command in the VM.
   257     """
   258     
   259     def GET(self, name, command):
   260         log_call(web.ctx.environ)
   261         global gvm_mgr
   262         command = '/' + command
   263         showTrayMessage('Launching application in isolated VM...', 7000)
   264         result = Cygwin.sshExecuteX11(command, gvm_mgr.getHostOnlyIP(name), 'osecuser', Cygwin.cygPath(gvm_mgr.getMachineFolder()) + '/' + name + '/dvm_key'  )
   265         return 'Command ' + str(command) + ' started on VM "' + name + '" with IP ' + gvm_mgr.getHostOnlyIP(name)
   266     
   267 
   268 class os_sdvm_ip:
   269     """OpenSecurity '/sdvms/[VM]/ip' handler
   270     
   271     - GET: give IP of SecurityVM.
   272     """
   273     
   274     def GET(self, name):
   275         log_call(web.ctx.environ)
   276         global gvm_mgr
   277         return gvm_mgr.getHostOnlyIP(name)
   278             
   279 
   280 class os_sdvm_start:
   281     """OpenSecurity '/sdvms/[VM]/start' handler
   282     
   283     - GET: Start specific SecuirtyVM.
   284     """
   285     
   286     def GET(self, name):
   287         log_call(web.ctx.environ)
   288         global gvm_mgr
   289         return gvm_mgr.startVM(name)
   290             
   291 
   292 class os_sdvm_stop:
   293     """OpenSecurity '/sdvms/[VM]/stop' handler
   294     
   295     - GET: stop specific Secuirty VM.
   296     """
   297     
   298     def GET(self, name):
   299         log_call(web.ctx.environ)
   300         global gvm_mgr
   301         return gvm_mgr.stopVM(name)
   302             
   303 
   304 class os_sdvms:
   305     """OpenSecurity '/sdvms' handler
   306     
   307     - GET: list all available secuirty VMs.
   308     - POST: create new security vm.
   309     """
   310     
   311     def GET(self):
   312         """get the list of SDVMs"""
   313         log_call(web.ctx.environ)
   314         global gvm_mgr
   315 
   316         d = {}
   317         for sdvm in gvm_mgr.listSDVM():
   318             d[sdvm] = gvm_mgr.getHostOnlyIP(sdvm)
   319 
   320         return json.dumps(d, indent = 4)
   321             
   322     def POST(self):
   323         """create a new SDVM"""
   324         log_call(web.ctx.environ)
   325         global gvm_mgr
   326         
   327         # get a new vm-name
   328         name = gvm_mgr.generateSDVMName()
   329         try:
   330             gvm_mgr.createVM(name)
   331         except:
   332             raise web.internalerror()
   333             
   334         return name
   335             
   336 
   337 class os_setup:
   338     """OpenSecurity '/setup' handler
   339     
   340     - GET: Give user some info how to setup the OpenSecurity environment
   341     """
   342     
   343     def GET(self):
   344 
   345         log_call(web.ctx.environ)
   346 
   347         page = """
   348         <html>
   349         <body>
   350         <h1>Setup OpenSecurity</h1>
   351         In order to setup OpenSecurity an inital VM image has to be downloaded and imported:<br/>
   352         <ul>
   353             <li>Download initial VM image: <a href="/fetch_initial_image">fetch_initial_image</a>
   354             <li>Import initial VM: <a href="/init">init</a>
   355         </ul>
   356         </body>
   357         </html>
   358         """
   359         return page
   360 
   361 
   362 class os_terminate:
   363     """OpenSecurity '/terminate' handler
   364     
   365     - GET: terminate the opensecurityd.
   366 
   367     TODO: need to find a better way doing this, and not via the
   368           REST api. Maybe hack web.py server code?
   369     """
   370     
   371     def GET(self):
   372         log_call(web.ctx.environ)
   373         global gvm_mgr
   374         gvm_mgr.stop()
   375         gvm_mgr.cleanup()
   376         global server
   377         server.stop()
   378         return None
   379 
   380 
   381 class os_update_template:
   382     """OpenSecurity '/update_template' handler
   383     
   384     - GET: update template vm
   385     """
   386     
   387     def GET(self):
   388         #return gvm_mgr.guestExecute('SecurityDVM', 'sudo apt-get -y update')
   389         global gvm_mgr
   390         log_call(web.ctx.environ)
   391         return gvm_mgr.updateTemplate()
   392 
   393 
   394 class os_vm:
   395     """OpenSecurity '/vms/[VM]' handler
   396     
   397     - GET: list information of arbitrary VM.
   398     """
   399     
   400     def GET(self, name):
   401         log_call(web.ctx.environ)
   402         global gvm_mgr
   403         return gvm_mgr.getVMInfo(name)
   404             
   405 
   406 class os_vms:
   407     """OpenSecurity '/vms' handler
   408     
   409     - GET: list all (also non Security) VMs.
   410     """
   411     
   412     def GET(self):
   413         log_call(web.ctx.environ)
   414         global gvm_mgr
   415         return str(gvm_mgr.listVM()).replace("'",'"')
   416             
   417 
   418 def log_call(web_environ):
   419     """log the incoming call to the REST api"""
   420     try:
   421         call = 'REST ' +  web_environ['REQUEST_METHOD'] + ' ' + web_environ['REQUEST_URI'] + ' from ' + web_environ['REMOTE_ADDR'] + ':' + web_environ['REMOTE_PORT']
   422         logger.debug(call)
   423     except:
   424         pass
   425 
   426 
   427 def main():
   428     """main startup for the opensecuirityd"""
   429 
   430     global gvm_mgr
   431     global server
   432 
   433     logger.debug('Starting OpenSecurity REST server')
   434 
   435     # ensure a VMManger is yet loaded
   436     gvm_mgr = vmmanager.VMManager.getInstance()
   437     
   438     # tweak sys.argv to control wep.py server start behavior
   439     sys.argv = [__file__, "8080"]
   440     server = web.application(opensecurity_urls, globals(), autoreload = False)
   441     server.run()
   442     
   443     logger.debug('Stopped OpenSecurity REST server')
   444 
   445 
   446 def stop():
   447     """stop the opensecuirityd"""
   448 
   449     # calling sys.exit() raises a SystemExit exception
   450     # of the WSGI Server to let it wind down
   451     # gracefully
   452     sys.exit(0)
   453 
   454 # start
   455 if __name__ == "__main__":
   456     main()
   457     sys.exit(0)
   458