OpenSecurity/bin/opensecurityd.pyw
author Oliver Maurhart <oliver.maurhart@ait.ac.at>
Wed, 05 Mar 2014 12:00:11 +0100
changeset 89 7a925dd96e2d
parent 88 f4f813ef9b33
child 90 bfd41c38d156
permissions -rwxr-xr-x
uuups ... what an awkward typo ... =)
     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 os
    36 import os.path
    37 import subprocess
    38 import sys
    39 import web
    40 from cygwin import Cygwin
    41 
    42 import vmmanager
    43 
    44 # local
    45 from environment import Environment
    46 from opensecurity_util import logger
    47 
    48 
    49 # ------------------------------------------------------------
    50 # const
    51 
    52 __version__ = "0.2"
    53 
    54 
    55 """All the URLs we know mapping to class handler"""
    56 opensecurity_urls = (
    57     '/browsing',                        'os_browsing',          # http://localhost:8080/browsing                                GET
    58     '/sdvms',                           'os_sdvms',             # http://localhost:8080/sdvms                                   GET, PUT
    59     '/sdvms/(.*)/application/(.*)',     'os_sdvm_application',  # http://localhost:8080/sdvms/[VMNAME]/application/[COMMAND]    GET
    60     '/sdvms/(.*)/ip',                   'os_sdvm_ip',           # http://localhost:8080/sdvms/[VMNAME]/ip                       GET
    61     '/sdvms/(.*)/start',                'os_sdvm_start',        # http://localhost:8080/sdvms/[VMNAME]/start                    GET
    62     '/sdvms/(.*)/stop',                 'os_sdvm_stop',         # http://localhost:8080/sdvms/[VMNAME]/stop                     GET
    63     '/sdvms/(.*)',                      'os_sdvm',              # http://localhost:8080/sdvms/[VMNAME]                          GET, DELETE
    64     '/vms',                             'os_vms',               # http://localhost:8080/vms                                     GET
    65     '/vms/(.*)',                        'os_vm',                # http://localhost:8080/vms/[VMNAME]                            GET
    66     '/update_template',                 'os_update_template',   # http://localhost:8080/update_template                         GET
    67     '/terminate',                       'os_terminate',         # http://localhost:8080/terminate                               GET
    68     '/',                                'os_root'               # http://localhost:8080/                                        GET
    69 )
    70 
    71 
    72 # ------------------------------------------------------------
    73 # vars
    74 
    75 # Global VMManager instance
    76 gvm_mgr = None
    77 
    78 
    79 # ------------------------------------------------------------
    80 # code
    81 
    82 
    83 class os_browsing:
    84     """OpenSecurity '/browsing' handler
    85     
    86     - GET: Start and prepare a new SecurityVM for Internet Browsing. Return the name of the VM.
    87     """
    88     
    89     def GET(self):
    90         log_call(web.ctx.environ)
    91         global gvm_mgr
    92         try:
    93             browsingVM = gvm_mgr.handleBrowsingRequest()
    94             return browsingVM
    95         except:
    96             raise web.internalerror()
    97 
    98        
    99 class os_root:
   100     """OpenSecurity '/' handler
   101     
   102     - GET: give information about current installation.
   103     """
   104     
   105     def GET(self):
   106         log_call(web.ctx.environ)
   107         global gvm_mgr
   108         res = "'os_server': { "
   109         res += "'version': '" + __version__ + "', "
   110         res += "'machine_folder': '" + gvm_mgr.machineFolder + "' "
   111         res += "}"
   112         return res
   113 
   114 
   115 class os_sdvm:
   116     """OpenSecurity '/sdvms/[VM]' handler
   117     
   118     - GET: Information about a specific SecurityVM
   119     - DELETE: Remove a specific
   120     """
   121     
   122     def GET(self, name):
   123         log_call(web.ctx.environ)
   124         global gvm_mgr
   125         return gvm_mgr.getVMInfo(name)
   126 
   127     def DELETE(self, name):
   128         log_call(web.ctx.environ)
   129         global gvm_mgr
   130         return gvm_mgr.removeVM(name)
   131             
   132 
   133 class os_sdvm_application:
   134     """OpenSecurity '/sdvms/[VM]/application/[CMD]' handler
   135     
   136     - GET: start application with given command in the VM.
   137     """
   138     
   139     def GET(self, name, command):
   140         log_call(web.ctx.environ)
   141         global gvm_mgr
   142         command = '/' + command
   143         result = Cygwin.sshExecuteX11(command, gvm_mgr.getHostOnlyIP(name), 'osecuser', Cygwin.cygPath(gvm_mgr.getMachineFolder()) + '/' + name + '/dvm_key'  )
   144         self.poweroffVM(name)
   145         return gvm_mgr.removeVM(name)
   146     
   147 
   148 class os_sdvm_ip:
   149     """OpenSecurity '/sdvms/[VM]/ip' handler
   150     
   151     - GET: give IP of SecurityVM.
   152     """
   153     
   154     def GET(self, name):
   155         log_call(web.ctx.environ)
   156         global gvm_mgr
   157         return gvm_mgr.getHostOnlyIP(name)
   158             
   159 
   160 class os_sdvm_start:
   161     """OpenSecurity '/sdvms/[VM]/start' handler
   162     
   163     - GET: Start specific SecuirtyVM.
   164     """
   165     
   166     def GET(self, name):
   167         log_call(web.ctx.environ)
   168         global gvm_mgr
   169         return gvm_mgr.startVM(name)
   170             
   171 
   172 class os_sdvm_stop:
   173     """OpenSecurity '/sdvms/[VM]/stop' handler
   174     
   175     - GET: stop specific Secuirty VM.
   176     """
   177     
   178     def GET(self, name):
   179         log_call(web.ctx.environ)
   180         global gvm_mgr
   181         return gvm_mgr.stopVM(name)
   182             
   183 
   184 class os_sdvms:
   185     """OpenSecurity '/sdvms' handler
   186     
   187     - GET: list all available secuirty VMs.
   188     - POST: create new security vm.
   189     """
   190     
   191     def GET(self):
   192         """get the list of SDVMs"""
   193         log_call(web.ctx.environ)
   194         global gvm_mgr
   195         return gvm_mgr.listSDVM() 
   196             
   197     def POST(self):
   198         """create a new SDVM"""
   199         log_call(web.ctx.environ)
   200         global gvm_mgr
   201         
   202         # get a new vm-name
   203         name = gvm_mgr.generateSDVMName()
   204         try:
   205             gvm_mgr.createVM(name)
   206         except:
   207             raise web.internalerror()
   208             
   209         return name
   210             
   211 
   212 class os_terminate:
   213     """OpenSecurity '/terminate' handler
   214     
   215     - GET: terminate the opensecurityd.
   216 
   217     YES: this here is bonkers. But the web.py http
   218     server runs infinite until a SystemExit exception
   219     or KeyboardInterrupt exception is raised.
   220 
   221     see: site-packages/web/httpserver.py - line 157ff
   222     see: site-packages/web/wsgiserver/__init__.py - line 1682ff
   223 
   224     So, we invoke a sys.exit(0) here to trigger server.stop().
   225 
   226     TODO: need to find a better way doing this, and not via the
   227           REST api. Maybe hack web.py server code?
   228     """
   229     
   230     def GET(self):
   231         log_call(web.ctx.environ)
   232         global gvm_mgr
   233         gvm_mgr.cleanup()
   234         sys.exit(0)
   235         return None
   236 
   237 
   238 class os_update_template:
   239     """OpenSecurity '/update_template' handler
   240     
   241     - GET: update template vm
   242     """
   243     
   244     def GET(self):
   245         #return gvm_mgr.guestExecute('SecurityDVM', 'sudo apt-get -y update')
   246         global gvm_mgr
   247         log_call(web.ctx.environ)
   248         return gvm_mgr.updateTemplate()
   249 
   250 
   251 class os_vm:
   252     """OpenSecurity '/vms/[VM]' handler
   253     
   254     - GET: list information of arbitrary VM.
   255     """
   256     
   257     def GET(self, name):
   258         log_call(web.ctx.environ)
   259         global gvm_mgr
   260         return gvm_mgr.getVMInfo(name)
   261             
   262 
   263 class os_vms:
   264     """OpenSecurity '/vms' handler
   265     
   266     - GET: list all (also non Security) VMs.
   267     """
   268     
   269     def GET(self):
   270         log_call(web.ctx.environ)
   271         global gvm_mgr
   272         return gvm_mgr.listVM() 
   273             
   274 
   275 def log_call(web_environ):
   276     """log the incoming call to the REST api"""
   277     try:
   278         call = 'REST ' +  web_environ['REQUEST_METHOD'] + ' ' + web_environ['REQUEST_URI'] + ' from ' + web_environ['REMOTE_ADDR'] + ':' + web_environ['REMOTE_PORT']
   279         logger.debug(call)
   280     except:
   281         pass
   282 
   283 
   284 def main():
   285     """main startup for the opensecuirityd"""
   286 
   287     logger.debug('Starting OpenSecurity REST server')
   288 
   289     # ensure a VMManger is yet loaded
   290     global gvm_mgr
   291     gvm_mgr = vmmanager.VMManager.getInstance()
   292     
   293     server = web.application(opensecurity_urls, globals(), autoreload = False)
   294     server.run()
   295     
   296     logger.debug('Stopped OpenSecurity REST server')
   297 
   298 
   299 def stop():
   300     """stop the opensecuirityd"""
   301 
   302     # calling sys.exit() raises a SystemExit exception
   303     # of the WSGI Server to let it wind down
   304     # gracefully
   305     sys.exit(0)
   306 
   307 
   308 
   309 # start
   310 if __name__ == "__main__":
   311     main()
   312