2 # -*- coding: utf-8 -*-
4 # ------------------------------------------------------------
5 # opensecurity_client_restful_server
7 # the OpenSecurity client RESTful server
9 # Autor: Oliver Maurhart, <oliver.maurhart@ait.ac.at>
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
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.
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.
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 # ------------------------------------------------------------
32 # ------------------------------------------------------------
51 from opensecurity_util import logger, setupLogger, OpenSecurityException
52 if sys.platform == 'win32' or sys.platform == 'cygwin':
53 from cygwin import Cygwin
56 import __init__ as opensecurity
57 from environment import Environment
60 # ------------------------------------------------------------
64 """All the URLs we know mapping to class handler"""
66 '/credentials', 'os_credentials',
67 '/keyfile', 'os_keyfile',
69 '/notification', 'os_notification',
70 '/password', 'os_password',
71 '/netmount', 'os_netmount',
72 '/netumount', 'os_netumount',
77 # ------------------------------------------------------------
81 """lock for read/write log file"""
82 log_file_lock = threading.Lock()
84 """timer for the log file bouncer"""
85 log_file_bouncer = None
88 """The REST server object"""
92 # ------------------------------------------------------------
98 """OpenSecurity '/credentials' handler.
100 This is called on GET /credentials?text=TEXT.
101 Ideally this should pop up a user dialog to insert his
102 credentials based the given TEXT.
111 if not "text" in args:
112 raise web.badrequest('no text given')
115 remote_ip = web.ctx.environ['REMOTE_ADDR']
117 # create the process which queries the user
118 dlg_image = os.path.join(sys.path[0], 'opensecurity_dialog.pyw')
119 process_command = [sys.executable, dlg_image, 'credentials', args.text]
120 process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE)
122 # run process result handling in seprate thread (not to block main one)
123 bouncer = ProcessResultBouncer(process, remote_ip, '/credentials')
126 return 'user queried for credentials'
131 """OpenSecurity '/keyfile' handler.
133 This is called on GET /keyfile?text=TEXT.
134 Ideally this should pop up a user dialog to insert his
135 password along with a keyfile.
144 if not "text" in args:
145 raise web.badrequest('no text given')
148 remote_ip = web.ctx.environ['REMOTE_ADDR']
150 # create the process which queries the user
151 dlg_image = os.path.join(sys.path[0], 'opensecurity_dialog.pyw')
152 process_command = [sys.executable, dlg_image, 'keyfile', args.text]
153 process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE)
155 # run process result handling in seprate thread (not to block main one)
156 bouncer = ProcessResultBouncer(process, remote_ip, '/keyfile')
159 return 'user queried for password and keyfile'
164 """OpenSecurity '/log' handler.
166 This is called on GET or POST on the log function /log
179 args['user'] = getpass.getuser()
180 args['system'] = platform.node() + " " + platform.system() + " " + platform.release()
182 # add these to new data to log
184 log_file_name = os.path.join(Environment('OpenSecurity').log_path, 'vm_new.log')
185 log_file_lock.acquire()
186 pickle.dump(args, open(log_file_name, 'ab'))
187 log_file_lock.release()
192 class os_notification:
194 """OpenSecurity '/notification' handler.
196 This is called on GET /notification?msgtype=TYPE&text=TEXT.
197 This will pop up an OpenSecurity notifcation window
206 if not "msgtype" in args:
207 raise web.badrequest('no msgtype given')
209 if not args.msgtype in ['information', 'warning', 'critical']:
210 raise web.badrequest('Unknown value for msgtype')
213 if not "text" in args:
214 raise web.badrequest('no text given')
216 # invoke the user dialog as a subprocess
217 dlg_image = os.path.join(sys.path[0], 'opensecurity_dialog.py')
218 process_command = [sys.executable, dlg_image, 'notification-' + args.msgtype, args.text]
219 process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE)
226 """OpenSecurity '/password' handler.
228 This is called on GET /password?text=TEXT.
229 Ideally this should pop up a user dialog to insert his
230 password based device name.
239 if not "text" in args:
240 raise web.badrequest('no text given')
243 remote_ip = web.ctx.environ['REMOTE_ADDR']
245 # create the process which queries the user
246 dlg_image = os.path.join(sys.path[0], 'opensecurity_dialog.pyw')
247 process_command = [sys.executable, dlg_image, 'password', args.text]
248 process = subprocess.Popen(process_command, shell = False, stdout = subprocess.PIPE)
250 # run process result handling in seprate thread (not to block main one)
251 bouncer = ProcessResultBouncer(process, remote_ip, '/password')
254 return 'user queried for password'
256 # handles netumount request
257 class MountNetworkDriveHandler(threading.Thread):
261 def __init__(self, drv, net_path):
262 threading.Thread.__init__(self)
264 self.networkPath = net_path
267 #Check for drive availability
268 if os.path.exists(self.drive):
269 logger.error("Drive letter is already in use: " + self.drive)
272 #Check for network resource availability
274 while not os.path.exists(self.networkPath):
278 logger.info("Path not accessible: " + self.networkPath + " retrying")
281 command = 'USE ' + self.drive + ' ' + self.networkPath + ' /PERSISTENT:NO'
283 result = Cygwin.checkResult(Cygwin.execute('C:\\Windows\\system32\\NET', command))
284 if string.find(result[1], 'successfully',) == -1:
285 logger.error("Failed: NET " + command)
291 """OpenSecurity '/netmount' handler"""
297 # we _need_ a net_resource
298 if not "net_resource" in args:
299 raise web.badrequest('no net_resource given')
301 # we _need_ a drive_letter
302 if not "drive_letter" in args:
303 raise web.badrequest('no drive_letter given')
305 driveHandler = MountNetworkDriveHandler(args['drive_letter'], args['net_resource'])
311 # handles netumount request
312 class UmountNetworkDriveHandler(threading.Thread):
316 def __init__(self, drv):
317 threading.Thread.__init__(self)
322 result = Cygwin.checkResult(Cygwin.execute('C:\\Windows\\system32\\net.exe', 'USE'))
323 mappedDrives = list()
324 for line in result[1].splitlines():
325 if 'USB' in line or 'Download' in line:
327 mappedDrives.append(parts[1])
329 logger.info(mappedDrives)
330 logger.info(self.drive)
331 if self.drive not in mappedDrives:
334 command = 'USE ' + self.drive + ' /DELETE /YES'
335 result = Cygwin.checkResult(Cygwin.execute('C:\\Windows\\system32\\net.exe', command))
336 if string.find(str(result[1]), 'successfully',) == -1:
337 logger.error(result[2])
343 """OpenSecurity '/netumount' handler"""
349 # we _need_ a drive_letter
350 if not "drive_letter" in args:
351 raise web.badrequest('no drive_letter given')
353 driveHandler = UmountNetworkDriveHandler(args['drive_letter'])
360 """OpenSecurity '/' handler"""
364 res = "OpenSecurity-Client RESTFul Server { \"version\": \"%s\" }" % opensecurity.__version__
366 # add some sample links
372 (copy paste this into your browser's address field after the host:port)
374 /password?text=Give+me+a+password+for+device+%22My+USB+Drive%22+(ID%3A+32090-AAA-X0)
376 (eg.: http://127.0.0.1:8090/password?text=Give+me+a+password+for+device+%22My+USB+Drive%22+(ID%3A+32090-AAA-X0))
377 NOTE: check yout taskbar, the dialog window may not pop up in front of your browser window.
380 Request a combination of user and password:
381 (copy paste this into your browser's address field after the host:port)
383 /credentials?text=Tell+the+NSA+which+credentials+to+use+in+order+to+avoid+hacking+noise+on+wire.
385 (eg.: http://127.0.0.1:8090/credentials?text=Tell+the+NSA+which+credentials+to+use+in+order+to+avoid+hacking+noise+on+wire.)
386 NOTE: check yout taskbar, the dialog window may not pop up in front of your browser window.
389 Request a combination of password and keyfile:
390 (copy paste this into your browser's address field after the host:port)
392 /keyfile?text=Your%20private%20RSA%20Keyfile%3A
394 (eg.: http://127.0.0.1:8090//keyfile?text=Your%20private%20RSA%20Keyfile%3A)
395 NOTE: check yout taskbar, the dialog window may not pop up in front of your browser window.
399 (copy paste this into your browser's address field after the host:port)
401 /application?vm=Debian+7&app=Browser
403 (e.g. http://127.0.0.1:8090/application?vm=Debian+7&app=Browser)
409 class ProcessResultBouncer(threading.Thread):
411 """A class to post the result of a given process - assuming it to be in JSON - to a REST Api."""
413 def __init__(self, process, remote_ip, resource):
417 threading.Thread.__init__(self)
418 self._process = process
419 self._remote_ip = remote_ip
420 self._resource = resource
433 # invoke the user dialog as a subprocess
434 result = self._process.communicate()[0]
435 if self._process.returncode != 0:
436 print 'user request has been aborted.'
439 # all ok, tell send request back appropriate destination
441 j = json.loads(result)
443 print 'error in password parsing'
446 # TODO: it would be WAY easier and secure if we just
447 # add the result json to a HTTP-POST here.
448 url_addr = 'http://' + self._remote_ip + ':58080' + self._resource
450 # by provided a 'data' we turn this into a POST statement
451 req = urllib2.Request(url_addr, urllib.urlencode(j))
453 res = urllib2.urlopen(req)
455 print 'failed to contact: ' + url_addr
459 class RESTServerThread(threading.Thread):
461 """Thread for serving the REST API."""
463 def __init__(self, port):
466 threading.Thread.__init__(self)
482 def is_already_running(port = 8090):
484 """check if this is started twice"""
487 s = socket.create_connection(('127.0.0.1', port), 0.5)
494 def _bounce_vm_logs():
496 """grab all logs from the VMs and push them to the log servers"""
500 # pick the highest current number
502 for f in glob.iglob(os.path.join(Environment('OpenSecurity').log_path, 'vm_cur.log.*')):
504 n = f.split('.')[-1:][0]
512 # first add new vm logs to our existing one: rename the log file
513 log_file_name_new = os.path.join(Environment('OpenSecurity').log_path, 'vm_new.log')
514 log_file_name_cur = os.path.join(Environment('OpenSecurity').log_path, 'vm_cur.log.' + str(cur))
515 log_file_lock.acquire()
517 os.rename(log_file_name_new, log_file_name_cur)
518 print('new log file: ' + log_file_name_cur)
521 log_file_lock.release()
523 # now we have a list of next log files to dump
524 log_files = glob.glob(os.path.join(Environment('OpenSecurity').log_path, 'vm_cur.log.*'))
526 for log_file in log_files:
529 f = open(log_file, 'rb')
539 logger.warning('tried to delete log file (pushed to EOF) "' + log_file + '" but failed')
542 logger.warning('encountered error while pushing log file "' + log_file + '"')
544 # start bouncer again ...
545 global log_file_bouncer
546 log_file_bouncer = threading.Timer(5.0, _bounce_vm_logs)
547 log_file_bouncer.start()
551 """POST a single log to log server
553 @param log the log POST param
556 url_addr = 'http://GIMME-SERVER-TO-LOG-TO/log'
558 # by provided a 'data' we turn this into a POST statement
559 d = urllib.urlencode(log)
560 req = urllib2.Request(url_addr, d)
562 logger.debug('pushed log to server: ' + str(log))
567 """Start the REST server"""
571 # start the VM-log bouncer timer
572 global log_file_bouncer
573 log_file_bouncer = threading.Timer(5.0, _bounce_vm_logs)
574 log_file_bouncer.start()
576 # trick the web.py server
577 sys.argv = [__file__, str(port)]
578 server = web.application(opensecurity_urls, globals())
582 def serve(port = 8090, background = False):
584 """Start serving the REST Api
585 port ... port number to listen on
586 background ... cease into background (spawn thread) and return immediately"""
588 # start threaded or direct version
589 if background == True:
590 t = RESTServerThread(port)
597 """Stop serving the REST Api"""
603 global log_file_bouncer
604 if log_file_bouncer is not None:
605 log_file_bouncer.cancel()
610 if __name__ == "__main__":