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