-
Notifications
You must be signed in to change notification settings - Fork 925
/
gateone.py
executable file
·2317 lines (2187 loc) · 97.1 KB
/
gateone.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 Liftoff Software Corporation
#
# For license information see LICENSE.txt
# 1.0 TODO:
# * DOCUMENTATION!
# * Write init scripts to stop/start/restart Gate One safely. Also make sure that .deb and .rpm packages safely restart Gate One without impacting running sessions. The setup.py should also attempt to minify the .css and .js files.
# Meta
__version__ = '1.0rc1'
__license__ = "AGPLv3 or Proprietary (see LICENSE.txt)"
__version_info__ = (1, 0)
__author__ = 'Dan McDougall <daniel.mcdougall@liftoffsoftware.com>'
# NOTE: Docstring includes reStructuredText markup for use with Sphinx.
__doc__ = '''\
.. _gateone.py:
Gate One
========
Gate One is a web-based terminal emulator written in Python using the Tornado
web framework. This module runs the primary daemon process and acts as a
central controller for all running terminals and terminal programs. It supports
numerous configuration options and can also be called with the --kill switch
to kill all running terminal programs (if using dtach--otherwise they die on
their own when gateone.py is stopped).
Dependencies
------------
Gate One requires Python 2.6+ but runs best with Python 2.7+. It also depends
on the following 3rd party Python modules:
* `Tornado <http://www.tornadoweb.org/>`_ 2.2+ - A non-blocking web server framework that powers FriendFeed.
The following modules are optional and can provide Gate One with additional
functionality:
* `pyOpenSSL <https://launchpad.net/pyopenssl>`_ 0.10+ - An OpenSSL module/wrapper for Python. Only used to generate self-signed SSL keys and certificates. If pyOpenSSL isn't available Gate One will fall back to using the 'openssl' command to generate self-signed certificates.
* `kerberos <http://pypi.python.org/pypi/kerberos>`_ 1.0+ - A high-level Kerberos interface for Python. Only necessary if you plan to use the Kerberos authentication module.
* `python-pam <http://packages.debian.org/lenny/python-pam>`_ 0.4.2+ - A Python module for interacting with PAM (the Pluggable Authentication Module present on nearly every Unix). Only necessary if you plan to use PAM authentication.
With the exception of python-pam, both the required and optional modules can usually be installed via one of these commands:
.. ansi-block::
\x1b[1;34muser\x1b[0m@modern-host\x1b[1;34m:~ $\x1b[0m sudo pip install tornado pyopenssl kerberos
...or:
.. ansi-block::
\x1b[1;34muser\x1b[0m@legacy-host\x1b[1;34m:~ $\x1b[0m sudo easy_install tornado pyopenssl kerberos
.. note:: The use of pip is recommended. See http://www.pip-installer.org/en/latest/installing.html if you don't have it.
The python-pam module is available in most Linux distribution repositories. Simply executing one of the following should take care of it:
.. ansi-block::
\x1b[1;34muser\x1b[0m@debian-or-ubuntu-host\x1b[1;34m:~ $\x1b[0m sudo apt-get install python-pam
.. ansi-block::
\x1b[1;34muser\x1b[0m@redhat-host\x1b[1;34m:~ $\x1b[0m sudo yum install python-pam
.. ansi-block::
\x1b[1;34muser\x1b[0m@gentoo-host\x1b[1;34m:~ $\x1b[0m sudo emerge python-pam
.. ansi-block::
\x1b[1;34muser\x1b[0m@suse-host\x1b[1;34m:~ $\x1b[0m sudo yast -i python-pam
Settings
--------
All of Gate One's configurable options can be controlled either via command line
switches or by settings in the server.conf file (they match up 1-to-1). If no
server.conf exists one will be created using defaults (i.e. when Gate One is run
for the first time). Settings in the server.conf file use the following format::
<setting> = <value>
Here's an example::
address = "127.0.0.1;::1;10.1.1.4" # Strings are surrounded by quotes
port = 443 # Numbers don't need quotes
There are a few important differences between the configuration file and
command line switches in regards to boolean values (True/False). A switch such
as --debug evaluates to "debug = True" and this is exactly how it would be
configured in server.conf::
debug = True # Booleans don't need quotes either
.. note:: The following values in server.conf are case sensitive: True, False and None (and should not be placed in quotes).
Running gateone.py with the --help switch will print the usage information as
well as descriptions of what each configurable option does:
.. ansi-block::
\x1b[1;31mroot\x1b[0m@host\x1b[1;34m:~ $\x1b[0m ./gateone.py --help
Usage: ./gateone.py [OPTIONS]
Options:
--help show this help information
--log_file_max_size max size of log files before rollover
--log_file_num_backups number of log files to keep
--log_file_prefix=PATH Path prefix for log files. Note that if you are running multiple tornado processes, log_file_prefix must be different for each of them (e.g. include the port number)
--log_to_stderr Send log output to stderr (colorized if possible). By default use stderr if --log_file_prefix is not set and no other logging is configured.
--logging=debug|info|warning|error|none Set the Python log level. If 'none', tornado won't touch the logging configuration.
./gateone.py
--address Run on the given address. Default is all addresses (IPv6 included). Multiple address can be specified using a semicolon as a separator (e.g. '127.0.0.1;::1;10.1.1.100').
--auth Authentication method to use. Valid options are: none, api, google, kerberos, pam
--certificate Path to the SSL certificate. Will be auto-generated if none is provided.
--command Run the given command when a user connects (e.g. '/bin/login').
--config Path to the config file. Default: /opt/gateone/server.conf
--cookie_secret Use the given 45-character string for cookie encryption.
--debug Enable debugging features such as auto-restarting when files are modified.
--disable_ssl If enabled, Gate One will run without SSL (generally not a good idea).
--dtach Wrap terminals with dtach. Allows sessions to be resumed even if Gate One is stopped and started (which is a sweet feature).
--embedded Run Gate One in Embedded Mode (no toolbar, only one terminal allowed, etc. See docs).
--https_redirect If enabled, a separate listener will be started on port 80 that redirects users to the configured port using HTTPS.
--js_init A JavaScript object (string) that will be used when running GateOne.init() inside index.html. Example: --js_init="{scheme: 'white'}" would result in GateOne.init({scheme: 'white'})
--keyfile Path to the SSL keyfile. Will be auto-generated if none is provided.
--kill Kill any running Gate One terminal processes including dtach'd processes.
--locale The locale (e.g. pt_PT) Gate One should use for translations. If not provided, will default to $LANG (which is 'en_US' in your current shell), or en_US if not set.
--new_api_key Generate a new API key that an external application can use toembed Gate One.
--pam_realm Basic auth REALM to display when authenticating clients. Default: hostname. Only relevant if PAM authentication is enabled.
--pam_service PAM service to use. Defaults to 'login'. Only relevant if PAM authentication is enabled.
--port Run on the given port.
--session_dir Path to the location where session information will be stored.
--session_logging If enabled, logs of user sessions will be saved in <user_dir>/<user>/logs. Default: Enabled
--session_timeout Amount of time that a session should be kept alive after the client has logged out. Accepts <num>X where X could be one of s, m, h, or d for seconds, minutes, hours, and days. Default is '5d' (5 days).
--sso_realm Kerberos REALM (aka DOMAIN) to use when authenticating clients. Only relevant if Kerberos authentication is enabled.
--sso_service Kerberos service (aka application) to use. Defaults to HTTP. Only relevant if Kerberos authentication is enabled.
--syslog_facility Syslog facility to use when logging to syslog (if syslog_session_logging is enabled). Must be one of: auth, cron, daemon, kern, local0, local1, local2, local3, local4, local5, local6, local7, lpr, mail, news, syslog, user, uucp. Default: daemon
--syslog_host Remote host to send syslog messages to if syslog_logging is enabled. Default: None (log to the local syslog daemon directly). NOTE: This setting is required on platforms that don't include Python's syslog module.
--syslog_session_logging If enabled, logs of user sessions will be written to syslog.
--url_prefix An optional prefix to place before all Gate One URLs. e.g. '/gateone/'. Use this if Gate One will be running behind a reverse proxy where you want it to be located at some sub-URL path.
--user_dir Path to the location where user files will be stored.
.. note:: Some of these options (e.g. log_file_prefix) are inherent to the Tornado framework. You won't find them anywhere in gateone.py.
File Paths
----------
Gate One stores its files, temporary session information, and persistent user
data in the following locations (Note: Many of these are configurable):
================= ==================================================================================
File/Directory Description
================= ==================================================================================
authpam.py Contains the PAM authentication Mixin used by auth.py.
auth.py Authentication classes.
certificate.pem The default certificate Gate One will use in SSL communications.
docs/ Gate One's documentation.
gateone.py Gate One's primary executable/script. Also, the file containing this documentation
i18n/ Gate One's internationalization (i18n) support and locale/translation files.
keyfile.pem The default private key used with SSL communications.
logviewer.py A utility to view Gate One session logs.
plugins/ Plugins go here in the form of ./plugins/<plugin name>/<plugin files|directories>
remote_syslog.py A module that supports sending syslog messages over UDP to a remote syslog host.
server.conf Gate One's configuration file.
sso.py A Kerberos Single Sign-on module for Tornado (used by auth.py)
static/ Non-dynamic files that get served to clients (e.g. gateone.js, gateone.css, etc).
templates/ Tornado template files such as index.html.
terminal.py A Pure Python terminal emulator module.
termio.py Terminal input/output control module.
tests/ Various scripts and tools to test Gate One's functionality.
utils.py Various supporting functions.
users/ Persistent user data in the form of ./users/<username>/<user-specific files>
users/<user>/logs This is where session logs get stored if session_logging is set.
/tmp/gateone Temporary session data in the form of /tmp/gateone/<session ID>/<files>
================= ==================================================================================
Running
-------
Executing Gate One is as simple as:
.. ansi-block::
\x1b[1;31mroot\x1b[0m@host\x1b[1;34m:~ $\x1b[0m ./gateone.py
.. note:: By default Gate One will run on port 443 which requires root on most systems. Use `--port=(something higher than 1024)` for non-root users.
Plugins
-------
Gate One includes support for any combination of the following types of plugins:
* Python
* JavaScript
* CSS
Python plugins can integrate with Gate One in three ways:
* Adding or overriding tornado.web.RequestHandlers (with a given regex).
* Adding or overriding methods (aka "commands") in TerminalWebSocket.
* Adding special plugin-specific escape sequence handlers (see the plugin development documentation for details on what/how these are/work).
JavaScript plugins will be added to the <body> tag of Gate One's base index.html
template by way of a single file (`{{gateone_js}}` below) that is the
concatenation of all plugins' JS templates:
.. code-block:: html
<script type="text/javascript" src="{{gateone_js}}"></script>
CSS plugins are similar to JavaScript but instead of being appended to the
<body> they are added to the <head> by way of a WebSocket download and some
fancy JavaScript inside of gateone.js:
.. code-block:: javascript
CSSPluginAction: function(url) {
// Loads the CSS for a given plugin by adding a <link> tag to the <head>
var queries = url.split('?')[1].split('&'), // So we can parse out the plugin name and the template
plugin = queries[0].split('=')[1],
file = queries[1].split('=')[1].split('.')[0];
// The /cssrender method needs the prefix and the container
url = url + '&container=' + GateOne.prefs.goDiv.substring(1);
url = url + '&prefix=' + GateOne.prefs.prefix;
url = GateOne.prefs.url + url.substring(1);
GateOne.Utils.loadCSS(url, plugin+'_'+file);
}
There are also hooks throughout Gate One's code for plugins to add or override
Gate One's functionality. Documentation on how to write plugins can be found in
the Plugin Development docs. From the perspective of gateone.py, it performs
the following tasks in relation to plugins:
* Imports Python plugins and connects their hooks.
* Creates symbolic links inside ./static/ that point to each plugin's respective /static/ directory and serves them to clients.
* Serves the index.html that includes plugins' respective .js and .css files.
Class Docstrings
================
'''
# Standard library modules
import os
import sys
import logging
import threading
import time
from functools import partial, wraps
from datetime import datetime, timedelta
# Tornado modules (yeah, we use all this stuff)
try:
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.auth
import tornado.template
from tornado.websocket import WebSocketHandler
from tornado.escape import json_decode
from tornado.options import define, options
from tornado import locale
from tornado import version as tornado_version
from tornado import version_info as tornado_version_info
except ImportError:
print("\x1b[31;1mERROR:\x1b[0m Gate One requires the Tornado framework. "
"You probably want to run something like, \x1b[1m'pip install "
"--upgrade tornado'\x1b[0m.")
sys.exit(1)
if tornado_version_info[0] < 2 and tornado_version_info[1] < 2:
print("\x1b[31;1mERROR:\x1b[0m Gate One requires version 2.2+ of the "
"Tornado framework. The installed version of Tornado is version "
"%s." % tornado_version)
sys.exit(1)
# We want this turned on right away
tornado.options.enable_pretty_logging()
# Our own modules
import termio, terminal
from auth import NullAuthHandler, KerberosAuthHandler, GoogleAuthHandler
from auth import PAMAuthHandler
from utils import str2bool, generate_session_id, cmd_var_swap, mkdir_p
from utils import gen_self_signed_ssl, killall, get_plugins, load_plugins
from utils import create_plugin_links, merge_handlers, none_fix, short_hash
from utils import convert_to_timedelta, kill_dtached_proc, FACILITIES, which
from utils import process_opt_esc_sequence, create_data_uri, MimeTypeFail
from utils import string_to_syslog_facility, fallback_bell, json_encode
# Setup the locale functions before anything else
locale.set_default_locale('en_US')
user_locale = None # Replaced with the actual user locale object in __main__
def _(string):
"""
Wraps user_locale.translate so we can .encode('UTF-8') when writing to
stdout. This function will get overridden by the regular translate()
function in __main__
"""
return user_locale.translate(string).encode('UTF-8')
# Globals
SESSIONS = {} # We store the crux of most session info here
CMD = None # Will be overwritten by options.command
TIMEOUT = timedelta(days=5) # Gets overridden by options.session_timeout
GATEONE_DIR = os.path.dirname(os.path.abspath(__file__))
PLUGINS = get_plugins(os.path.join(GATEONE_DIR, 'plugins'))
PLUGIN_WS_CMDS = {} # Gives plugins the ability to extend/enhance TerminalWebSocket
PLUGIN_HOOKS = {} # Gives plugins the ability to hook into various things.
PLUGIN_AUTH_HOOKS = [] # For plugins to register functions to be called after a
# user successfully authenticates
# Gate One registers a handler for for terminal.py's CALLBACK_OPT special escape
# sequence callback. Whenever this escape sequence is encountered, Gate One
# will parse the sequence's contained characters looking for the following
# format:
# <plugin name>|<whatever>
# The <whatever> part will be passed to any plugin matching <plugin name> if the
# plugin has 'Escape': <function> registered in its hooks.
PLUGIN_ESC_HANDLERS = {}
# Secondary locale setup
locale_dir = os.path.join(GATEONE_DIR, 'i18n')
locale.load_gettext_translations(locale_dir, 'gateone')
# NOTE: The locale gets set in __main__
# A HUGE thank you to Micah Elliott (http://MicahElliott.com) for posting these
# values here: https://gist.github.com/719710
# This gets used by StyleHandler to generate the CSS that supports 256-colors:
COLORS_256 = {
# 8-color equivalents:
0: "000000",
1: "800000",
2: "008000",
3: "808000",
4: "000080",
5: "800080",
6: "008080",
7: "c0c0c0",
# "Bright" (16-color) equivalents:
8: "808080",
9: "ff0000",
10: "00ff00",
11: "ffff00",
12: "0000ff",
13: "ff00ff",
14: "00ffff",
15: "ffffff",
# The rest of the 256-colors:
16: "000000",
17: "00005f",
18: "000087",
19: "0000af",
20: "0000d7",
21: "0000ff",
22: "005f00",
23: "005f5f",
24: "005f87",
25: "005faf",
26: "005fd7",
27: "005fff",
28: "008700",
29: "00875f",
30: "008787",
31: "0087af",
32: "0087d7",
33: "0087ff",
34: "00af00",
35: "00af5f",
36: "00af87",
37: "00afaf",
38: "00afd7",
39: "00afff",
40: "00d700",
41: "00d75f",
42: "00d787",
43: "00d7af",
44: "00d7d7",
45: "00d7ff",
46: "00ff00",
47: "00ff5f",
48: "00ff87",
49: "00ffaf",
50: "00ffd7",
51: "00ffff",
52: "5f0000",
53: "5f005f",
54: "5f0087",
55: "5f00af",
56: "5f00d7",
57: "5f00ff",
58: "5f5f00",
59: "5f5f5f",
60: "5f5f87",
61: "5f5faf",
62: "5f5fd7",
63: "5f5fff",
64: "5f8700",
65: "5f875f",
66: "5f8787",
67: "5f87af",
68: "5f87d7",
69: "5f87ff",
70: "5faf00",
71: "5faf5f",
72: "5faf87",
73: "5fafaf",
74: "5fafd7",
75: "5fafff",
76: "5fd700",
77: "5fd75f",
78: "5fd787",
79: "5fd7af",
80: "5fd7d7",
81: "5fd7ff",
82: "5fff00",
83: "5fff5f",
84: "5fff87",
85: "5fffaf",
86: "5fffd7",
87: "5fffff",
88: "870000",
89: "87005f",
90: "870087",
91: "8700af",
92: "8700d7",
93: "8700ff",
94: "875f00",
95: "875f5f",
96: "875f87",
97: "875faf",
98: "875fd7",
99: "875fff",
100: "878700",
101: "87875f",
102: "878787",
103: "8787af",
104: "8787d7",
105: "8787ff",
106: "87af00",
107: "87af5f",
108: "87af87",
109: "87afaf",
110: "87afd7",
111: "87afff",
112: "87d700",
113: "87d75f",
114: "87d787",
115: "87d7af",
116: "87d7d7",
117: "87d7ff",
118: "87ff00",
119: "87ff5f",
120: "87ff87",
121: "87ffaf",
122: "87ffd7",
123: "87ffff",
124: "af0000",
125: "af005f",
126: "af0087",
127: "af00af",
128: "af00d7",
129: "af00ff",
130: "af5f00",
131: "af5f5f",
132: "af5f87",
133: "af5faf",
134: "af5fd7",
135: "af5fff",
136: "af8700",
137: "af875f",
138: "af8787",
139: "af87af",
140: "af87d7",
141: "af87ff",
142: "afaf00",
143: "afaf5f",
144: "afaf87",
145: "afafaf",
146: "afafd7",
147: "afafff",
148: "afd700",
149: "afd75f",
150: "afd787",
151: "afd7af",
152: "afd7d7",
153: "afd7ff",
154: "afff00",
155: "afff5f",
156: "afff87",
157: "afffaf",
158: "afffd7",
159: "afffff",
160: "d70000",
161: "d7005f",
162: "d70087",
163: "d700af",
164: "d700d7",
165: "d700ff",
166: "d75f00",
167: "d75f5f",
168: "d75f87",
169: "d75faf",
170: "d75fd7",
171: "d75fff",
172: "d78700",
173: "d7875f",
174: "d78787",
175: "d787af",
176: "d787d7",
177: "d787ff",
178: "d7af00",
179: "d7af5f",
180: "d7af87",
181: "d7afaf",
182: "d7afd7",
183: "d7afff",
184: "d7d700",
185: "d7d75f",
186: "d7d787",
187: "d7d7af",
188: "d7d7d7",
189: "d7d7ff",
190: "d7ff00",
191: "d7ff5f",
192: "d7ff87",
193: "d7ffaf",
194: "d7ffd7",
195: "d7ffff",
196: "ff0000",
197: "ff005f",
198: "ff0087",
199: "ff00af",
200: "ff00d7",
201: "ff00ff",
202: "ff5f00",
203: "ff5f5f",
204: "ff5f87",
205: "ff5faf",
206: "ff5fd7",
207: "ff5fff",
208: "ff8700",
209: "ff875f",
210: "ff8787",
211: "ff87af",
212: "ff87d7",
213: "ff87ff",
214: "ffaf00",
215: "ffaf5f",
216: "ffaf87",
217: "ffafaf",
218: "ffafd7",
219: "ffafff",
220: "ffd700",
221: "ffd75f",
222: "ffd787",
223: "ffd7af",
224: "ffd7d7",
225: "ffd7ff",
226: "ffff00",
227: "ffff5f",
228: "ffff87",
229: "ffffaf",
230: "ffffd7",
231: "ffffff",
# Grayscale:
232: "080808",
233: "121212",
234: "1c1c1c",
235: "262626",
236: "303030",
237: "3a3a3a",
238: "444444",
239: "4e4e4e",
240: "585858",
241: "626262",
242: "6c6c6c",
243: "767676",
244: "808080",
245: "8a8a8a",
246: "949494",
247: "9e9e9e",
248: "a8a8a8",
249: "b2b2b2",
250: "bcbcbc",
251: "c6c6c6",
252: "d0d0d0",
253: "dadada",
254: "e4e4e4",
255: "eeeeee"
}
# Helper functions
def require_auth(method):
"""
An equivalent to tornado.web.authenticated for WebSockets
(TerminalWebSocket, specifically).
"""
@wraps(method)
def wrapper(self, *args, **kwargs):
if not self.get_current_user():
self.write_message(_("Only valid users please. Thanks!"))
self.close() # Close the WebSocket
return method(self, *args, **kwargs)
return wrapper
# Classes
class HTTPSRedirectHandler(tornado.web.RequestHandler):
"""
A handler to redirect clients from HTTP to HTTPS.
"""
def get(self):
"""Just redirects the client from HTTP to HTTPS"""
port = self.settings['port']
url_prefix = self.settings['url_prefix']
host = self.request.headers.get('Host', 'localhost')
self.redirect(
'https://%s:%s%s' % (host, port, url_prefix))
class BaseHandler(tornado.web.RequestHandler):
"""
A base handler that all Gate One RequestHandlers will inherit methods from.
"""
# Right now it's just the one function...
def get_current_user(self):
"""Tornado standard method--implemented our way."""
user_json = self.get_secure_cookie("gateone_user")
if user_json:
user = json_decode(user_json)
if user and 'upn' not in user:
return None
return user
# More may be added in the future
class MainHandler(BaseHandler):
"""
Renders index.html which loads Gate One.
Will include the minified version of gateone.js if available as
gateone.min.js.
Will encode GATEONE_DIR/static/bell.ogg as a data:URI and put it as the
<source> of the <audio> tag inside the index.html template. Gate One
administrators can replace bell.ogg with whatever they like but the file
size should be less than 32k when encoded to Base64.
"""
# TODO: Add the ability for users to define their own individual bells.
@tornado.web.authenticated
def get(self):
hostname = os.uname()[1]
gateone_js = "%sstatic/gateone.js" % self.settings['url_prefix']
minified_js_abspath = os.path.join(GATEONE_DIR, 'static')
minified_js_abspath = os.path.join(
minified_js_abspath, 'gateone.min.js')
bell_path = os.path.join(GATEONE_DIR, 'static')
bell_path = os.path.join(bell_path, 'bell.ogg')
if os.path.exists(bell_path):
try:
bell_data_uri = create_data_uri(bell_path)
except MimeTypeFail:
bell_data_uri = fallback_bell
else: # There's always the fallback
bell_data_uri = fallback_bell
js_init = self.settings['js_init']
# Use the minified version if it exists
if os.path.exists(minified_js_abspath):
gateone_js = "%sstatic/gateone.min.js" % self.settings['url_prefix']
template_path = os.path.join(GATEONE_DIR, 'templates')
index_path = os.path.join(template_path, 'index.html')
self.render(
index_path,
hostname=hostname,
gateone_js=gateone_js,
jsplugins=PLUGINS['js'],
cssplugins=PLUGINS['css'],
js_init=js_init,
bell_data_uri=bell_data_uri,
url_prefix=self.settings['url_prefix']
)
class StyleHandler(BaseHandler):
"""
Serves up our CSS templates (themes, colors, etc) and enumerates what's
available depending on the given arguments:
If 'enumerate' is given, returna JSON-encoded object containing lists of
our themes/colors in the form of:
{'themes': themes, 'colors': colors}
NOTE: The .css part of filenames will be stripped when sent to the client.
If 'theme' or 'colors' are provided (along with the requisite 'container'
and 'prefix' arguments), returns the content of the requested CSS file.
"""
# Disabled authentication for this so we could get embedding working without
# requiring a cookie to be set. Stylesheet enumeration isn't exactly a
# compelling attack vector.
def get(self):
enum = self.get_argument("enumerate", None)
templates_path = os.path.join(GATEONE_DIR, 'templates')
themes_path = os.path.join(templates_path, 'themes')
colors_path = os.path.join(templates_path, 'term_colors')
if enum:
themes = os.listdir(themes_path)
themes = [a.replace('.css', '') for a in themes]
colors = os.listdir(colors_path)
colors = [a.replace('.css', '') for a in colors]
self.set_header ('Content-Type', 'application/json')
message = {'themes': themes, 'colors': colors}
self.write(json_encode(message))
self.finish()
else:
container = self.get_argument("container")
prefix = self.get_argument("prefix")
theme = self.get_argument("theme", None)
colors = self.get_argument("colors", None)
# Setup our 256-color support CSS:
colors_256 = ""
for i in xrange(256):
fg = "#%s span.fx%s {color: #%s;}" % (
container, i, COLORS_256[i])
bg = "#%s span.bx%s {background-color: #%s;} " % (
container, i, COLORS_256[i])
fg_rev = "#%s span.reverse.fx%s {background-color: #%s; color: inherit;}" % (
container, i, COLORS_256[i])
bg_rev = "#%s span.reverse.bx%s {color: #%s; background-color: inherit;} " % (
container, i, COLORS_256[i])
colors_256 += "%s %s %s %s" % (fg, bg, fg_rev, bg_rev)
colors_256 += "\n"
self.set_header ('Content-Type', 'text/css')
if theme:
try:
theme_path = os.path.join(themes_path, "%s.css" % theme)
self.render(
theme_path,
container=container,
prefix=prefix,
colors_256=colors_256,
url_prefix=self.settings['url_prefix']
)
except IOError:
# Given theme was not found
logging.error(_("%s was not found" % theme_path))
elif colors:
try:
color_path = os.path.join(colors_path, "%s.css" % colors)
self.render(
color_path,
container=container,
prefix=prefix,
url_prefix=self.settings['url_prefix']
)
except IOError:
# Given theme was not found
logging.error(_("%s was not found" % color_path))
class PluginCSSTemplateHandler(BaseHandler):
"""
Renders plugin CSS template files, passing them the same *prefix* and
*container* variables used by the StyleHandler. This is so we don't need a
CSS template rendering function in every plugin that needs to use {{prefix}}
or {{container}}.
gateone.js will automatically load all \*.css files in plugin template
directories using this method.
"""
# Had to disable authentication for this for the embedded stuff to work.
# Not a big deal... Just some stylesheets. To an attacker it's like
# peering into a window and seeing the wallpaper.
def get(self):
container = self.get_argument("container")
prefix = self.get_argument("prefix")
plugin = self.get_argument("plugin")
template = self.get_argument("template")
templates_path = os.path.join(GATEONE_DIR, 'templates')
plugin_templates_path = os.path.join(templates_path, plugin)
plugin_template = os.path.join(plugin_templates_path, "%s.css" % plugin)
self.set_header ('Content-Type', 'text/css')
try:
self.render(
plugin_template,
container=container,
prefix=prefix,
url_prefix=self.settings['url_prefix']
)
except IOError:
# The provided plugin/template combination was not found
logging.error(_("%s.css was not found" % plugin_template))
class JSPluginsHandler(BaseHandler):
"""
Combines all JavaScript plugins into a single file to keep things simple and
speedy.
"""
# No auth for this... Not really necessary (just serves up a static file).
def get(self):
self.set_header ('Content-Type', 'application/javascript')
plugins = get_plugins(os.path.join(GATEONE_DIR, "plugins"))
static_dir = os.path.join(GATEONE_DIR, "static")
combined_plugins = os.path.join(static_dir, "combined_plugins.js")
if os.path.exists(combined_plugins):
with open(combined_plugins) as f:
js_data = f.read()
if len(js_data) < 100: # Needs to be created
self.write(self._combine_plugins())
return
else: # It hasn't changed, send it as-is
self.write(js_data)
else: # File doesn't exist, create it and send it to the client
self.write(self._combine_plugins())
def _combine_plugins(self):
"""
Combines all plugin .js files into one (combined_plugins.js)
"""
plugins = get_plugins(os.path.join(GATEONE_DIR, "plugins"))
static_dir = os.path.join(GATEONE_DIR, "static")
combined_plugins = os.path.join(static_dir, "combined_plugins.js")
out = ""
for js_plugin in plugins['js']:
js_path = os.path.join(GATEONE_DIR, js_plugin.lstrip('/'))
with open(js_path) as f:
out += f.read()
with open(combined_plugins, 'w') as f:
f.write(out)
return out
class TerminalWebSocket(WebSocketHandler):
"""
The main WebSocket interface for Gate One, this class is setup to call
'commands' which are methods registered in self.commands. Methods that are
registered this way will be exposed and directly callable over the
WebSocket.
"""
def __init__(self, application, request):
WebSocketHandler.__init__(self, application, request)
self.commands = {
'ping': self.pong,
'authenticate': self.authenticate,
'new_terminal': self.new_terminal,
'set_terminal': self.set_terminal,
'kill_terminal': self.kill_terminal,
'c': self.char_handler, # Just 'c' to keep the bandwidth down
'refresh': self.refresh_screen,
'full_refresh': self.full_refresh,
'resize': self.resize,
'get_webworker': self.get_webworker,
'debug_terminal': self.debug_terminal
}
self.terms = {}
# So we can keep track and avoid sending unnecessary messages:
self.titles = {}
self.api_user = None
self.em_dimensions = None
def get_current_user(self):
"""
Mostly identical to the function of the same name in MainHandler. The
difference being that when API authentication is enabled the WebSocket
will expect and perform its own auth of the client.
"""
if self.settings['auth'] == 'api':
return self.api_user
user_json = self.get_secure_cookie("gateone_user")
if not user_json:
return None
return json_decode(user_json)
def open(self):
"""Called when a new WebSocket is opened."""
# TODO: Make it so that idle WebSockets that haven't passed authentication tests get auto-closed within N seconds in order to prevent a DoS scenario where the attacker keeps all possible ports open indefinitely.
# client_id is unique to the browser/client whereas session_id is unique
# to the user. It isn't used much right now but it will be useful in
# the future once more stuff is running over WebSockets.
self.client_id = generate_session_id()
user = self.get_current_user()
if user and 'upn' in user:
logging.info(
_("WebSocket opened (%s).") % user['upn'])
else:
logging.info(_("WebSocket opened (unknown user)."))
if user and 'upn' not in user: # Invalid user info
logging.error(_("Unauthenticated WebSocket attempt."))
# In case this is a legitimate client that simply had its auth info
# expire/go bad, tell it to re-auth by calling the appropriate
# action on the other side.
message = {'reauthenticate': True}
self.write_message(json_encode(message))
self.close() # Close the WebSocket
def on_message(self, message):
"""Called when we receive a message from the client."""
# This is super useful when debugging:
logging.debug("message: %s" % repr(message))
message_obj = None
try:
message_obj = json_decode(message) # JSON FTW!
if not isinstance(message_obj, dict):
self.write_message(_("'Error: Message bust be a JSON dict.'"))
return
except ValueError: # We didn't get JSON
self.write_message(_("'Error: We only accept JSON here.'"))
return
if message_obj:
for key, value in message_obj.items():
try: # Plugins first so they can override behavior if they wish
PLUGIN_WS_CMDS[key](value, tws=self)# tws==TerminalWebSocket
except (KeyError, TypeError, AttributeError):
try:
if value:
self.commands[key](value)
else:
# Try, try again
self.commands[key]()
except (KeyError, TypeError, AttributeError):
pass # Ignore commands we don't understand
def on_close(self):
"""
Called when the client terminates the connection.
.. note:: Normally self.refresh_screen() catches the disconnect first and this method won't end up being called.
"""
logging.debug("on_close()")
user = self.get_current_user()
# Remove all attached callbacks so we're not wasting memory/CPU on
# disconnected clients
if user and user['session'] in SESSIONS:
for term in SESSIONS[user['session']]:
if isinstance(term, int):
try:
multiplex = SESSIONS[user['session']][term]['multiplex']
multiplex.remove_all_callbacks(self.callback_id)
term_emulator = multiplex.term
term_emulator.remove_all_callbacks(self.callback_id)
except AttributeError:
# User never completed opening a terminal so
# self.callback_id is missing. Nothing to worry about
pass
if user and 'upn' in user:
logging.info(
_("WebSocket closed (%s).") % user['upn'])
else:
logging.info(_("WebSocket closed (unknown user)."))
def pong(self, timestamp):
"""
Responds to a client 'ping' request... Just returns the given
timestamp back to the client so it can measure round-trip time.
"""
message = {'pong': timestamp}
self.write_message(json_encode(message))
def authenticate(self, settings):
"""
Authenticates the client by first trying to use the 'gateone_user'
cookie or if Gate One is configured to use API authentication it will
use *settings['auth']*. Additionally, it will accept
*settings['container']* and *settings['prefix']* to apply those to the
equivalent properties (self.container and self.prefix).
"""
logging.debug("authenticate(): %s" % settings)
# Make sure the client is authenticated if authentication is enabled
if self.settings['auth'] and self.settings['auth'] != 'api':
try:
user = self.get_current_user()
if not user:
logging.error(_("Unauthenticated WebSocket attempt."))
# This usually happens when the cookie_secret gets changed
# resulting in "Invalid cookie..." errors. If we tell the
# client to re-auth the problem should correct itself.
message = {'reauthenticate': True}
self.write_message(json_encode(message))
self.close() # Close the WebSocket
elif user and user['upn'] == 'ANONYMOUS':
logging.error(_("Unauthenticated WebSocket attempt."))
# This can happen when a client logs in with no auth type
# configured and then later the server is configured to use
# authentication. The client must be told to re-auth:
message = {'reauthenticate': True}
self.write_message(json_encode(message))
self.close() # Close the WebSocket
except KeyError: # 'upn' wasn't in user
# Force them to authenticate
message = {'reauthenticate': True}
self.write_message(json_encode(message))
self.close() # Close the WebSocket
elif self.settings['auth'] and self.settings['auth'] == 'api':
if 'auth' in settings.keys():
# 'auth' message should look like this:
# {
# 'api_key': 'MjkwYzc3MDI2MjhhNGZkNDg1MjJkODgyYjBmN2MyMTM4M',
# 'upn': 'joe@company.com',
# 'timestamp': 1323391717238,
# 'signature': <gibberish>,
# 'signature_method': 'HMAC-SHA1',
# 'api_version': '1.0'
# }
#
# *api_key* is the first half of what gets generated when you