Example #1
0
 def get(self, request, share_id=None):
     hostname = os.uname()[1]
     prefs = self.request.GET.get("prefs", None)
     url_prefix = getsettings('url_prefix', '/')
     gateone_js = "%sstatic/gateone.js" % url_prefix
     minified_js_abspath = os.path.join(getsettings('BASE_DIR'),
                                        'static/gateone.min.js')
     # Use the minified version if it exists
     if os.path.exists(minified_js_abspath):
         gateone_js = "%sgateone.min.js" % getsettings('STATIC_URL')
     return render_to_response('share.html', locals())
Example #2
0
 def get(self, request, path, include_body=True):
     session_dir = getsettings(
         'session_dir', os.path.join(getsettings('BASE_DIR'),
                                     'sessions'))  #default session dir
     user = self.request.session.get('gateone_user')
     if user and 'session' in self.request.session.get('gateone_user'):
         session = user['session']
     else:
         return HttpResponse('User session is not valid')
     filepath = os.path.join(session_dir, session, 'downloads', path)
     abspath = os.path.abspath(filepath)
     if not os.path.exists(abspath):
         return HttpResponse(self.get_error_html(404), status=404)
     if not os.path.isfile(abspath):
         return HttpResponse("%s is not a file" % (path), status=403)
     import stat, mimetypes
     stat_result = os.stat(abspath)
     modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])
     response = HttpResponse()
     response["Last-Modified"] = modified
     mime_type, encoding = mimetypes.guess_type(abspath)
     if mime_type:
         response["Content-Type"] = mime_type
     # Set the Cache-Control header to private since this file is not meant
     # to be public.
     response["Cache-Control"] = "private"
     # Add some additional headers
     response['Access-Control-Allow-Origin'] = '*'
     # Check the If-Modified-Since, and don't send the result if the
     # content has not been modified
     ims_value = self.request.META.get('If-Modified-Since', None)
     if ims_value is not None:
         import email.utils
         date_tuple = email.utils.parsedate(ims_value)
         if_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))
         if if_since >= modified:
             response.status = 304
             return response
     # Finally, deliver the file
     with io.open(abspath, "rb") as file:
         data = file.read()
         hasher = hashlib.sha1()
         hasher.update(data)
         response["Etag"] = '"%s"' % hasher.hexdigest()
         if include_body:
             response.content = data
             response.status = 200
             return response
         else:
             assert self.request.method in ("HEAD", "head")
             response["Content-Length"] = len(data)
Example #3
0
def restore_term_settings(location, session):
    """
    Returns the terminal settings associated with the given *location* that are
    stored in the user's session directory.
    """
    if not session:
        return  # Just a viewer of a broadcast terminal
    session_dir = os.path.join(getsettings('BASE_DIR'), 'sessions')
    session_dir = os.path.join(session_dir, session)
    settings_path = os.path.join(session_dir, 'term_settings.json')
    if not os.path.exists(settings_path):
        return  # Nothing to do
    with io.open(settings_path, encoding='utf-8') as f:
        try:
            settings = json_decode(f.read())
        except ValueError:
            # Something wrong with the file.  Remove it
            term_log.error(
                _("Error decoding {0}.  File will be removed.").format(
                    settings_path))
            os.remove(settings_path)
            return {}
    #print 'restore_term_settings',settings
    #settings = {u'default': {u'1': {u'title': u'jimmy@jimmy-VirtualBox: /home/jimmy/Desktop/django-gateone', u'command': u'SSH', u'metadata': {}}}}
    return settings
Example #4
0
 def get(self, request):
     check = self.request.GET.get('check', False)
     if check in ['true', 'false',
                  False]:  #solve ast malformed string exception
         check = {'true': True, 'false': False}[str(check).lower()]
     else:
         check = ast.literal_eval(check)
     if self.request.user == 'AnonymousUser':
         user = {'upn': 'ANONYMOUS'}
     else:
         user = {'upn': str(self.request.user)}
     if check and self.request.user.is_authenticated():
         response = HttpResponse(u'authenticated')
         response["Access-Control-Allow-Origin"] = "*"
         response["Server"] = "GateOne"
         return response
     logout_get = self.request.GET.get("logout", None)
     if logout_get:
         logout(request)
         response = HttpResponse('/')
         response.delete_cookie('gateone_user')
         self.user_logout(request)
         return response
     next_url = self.request.GET.get("next", None)
     if next_url:
         return redirect(next_url)
     return redirect(getsettings('url_prefix', '/'))
Example #5
0
 def user_logout(self, request, redirect=None):
     if not redirect:
         # Try getting it from the query string
         redirect = self.request.GET.get("redirect", None)
     if redirect:
         return HttpResponse(redirect)
     else:
         return HttpResponse(getsettings('url_prefix', '/'))
Example #6
0
 def get_error_html(self, status_code, **kwargs):
     if status_code in [404, 500, 503, 403]:
         filename = os.path.join(
             os.path.join(getsettings('BASE_DIR'), 'templates'),
             '%d.html' % status_code)
         if os.path.exists(filename):
             with io.open(filename, 'r') as f:
                 data = f.read()
             return data
     import httplib
     return "<html><title>%(code)d: %(message)s</title>" \
             "<body class='bodyErrorPage'>%(code)d: %(message)s</body></html>" % {
         "code": status_code,
         "message": httplib.responses[status_code],
     }
Example #7
0
 def get(self, request):
     hostname = os.uname()[1]
     location = u'default'
     self.user_login(request)
     response = render_to_response('index.html', locals())
     response["Access-Control-Allow-Origin"] = "*"  #set django to cros mode
     expiration = getsettings(
         'auth_timeout',
         14 * 86400)  #set django user login session time to 14 day
     if not self.request.COOKIES.get('gateone_user', None):
         response.set_cookie(
             "gateone_user",
             signing.dumps(self.request.session['gateone_user']))
         self.request.session.set_expiry(expiration)
     #print self.request.session.get('gateone_user',None)
     return response
Example #8
0
 def user_login(self, request):
     self.request.session.clear_expired()
     if self.request.META.has_key('HTTP_X_FORWARDED_FOR'):
         ip = self.request.META['HTTP_X_FORWARDED_FOR']
     else:
         ip = self.request.META['REMOTE_ADDR']
     user = {u'upn': str(self.request.user), u'ip_address': ip}
     user_dir = os.path.join(getsettings('BASE_DIR'), 'users')
     user_dir = os.path.join(user_dir, user['upn'])
     if not os.path.exists(user_dir):
         mkdir_p(user_dir)
         os.chmod(user_dir, 0o700)
     if not self.request.session.get('session', None):
         session_info = {'session': generate_session_id()}
         if self.request.is_secure():
             protocol = 'https'
         else:
             protocol = 'http'
         session_info.update(user)
         session_info.update({'protocol': protocol})
         self.request.session['session'] = session_info['session']
         self.request.session['gateone_user'] = session_info
Example #9
0
def save_term_settings(term, location, session, settings):
    """
    Saves the *settings* associated with the given *term*, *location*, and
    *session* in the 'term_settings.json' file inside the user's session
    directory.

    When complete the given *callback* will be called (if given).
    """
    if not session:
        return  # Just a viewer of a broadcast terminal
    term = str(term)  # JSON wants strings as keys
    term_settings = RUDict()
    term_settings[location] = {term: settings}
    session_dir = os.path.join(getsettings('BASE_DIR'), 'sessions')
    session_dir = os.path.join(session_dir, session)
    settings_path = os.path.join(session_dir, 'term_settings.json')
    # First we read in the existing settings and then update them.
    if os.path.exists(settings_path):
        with io.open(settings_path, encoding='utf-8') as f:
            term_settings.update(json_decode(f.read()))
        term_settings[location][term].update(settings)
    with io.open(settings_path, 'w', encoding='utf-8') as f:
        f.write(json_encode(term_settings))
Example #10
0
def define_options():
    """
    Calls `tornado.options.define` for all of Gate One's command-line options.

    If *installed* is ``False`` the defaults will be set under the assumption
    that the user is non-root and running Gate One out of a download/cloned
    directory.
    """
    # NOTE: To test this function interactively you must import tornado.options
    # and call tornado.options.parse_config_file(*some_config_path*).  After you
    # do that the options will wind up in tornado.options.options
    # Simplify the auth option help message
    auths = "none, api, cas, google, ssl"
    #from applications.auth.authentication import PAMAuthHandler, KerberosAuthHandler
    #if KerberosAuthHandler:
        #auths += ", kerberos"
    #if PAMAuthHandler:
        #auths += ", pam"
    ## Simplify the syslog_facility option help message
    #facilities = list(FACILITIES.keys())
    #facilities.sort()
    # Figure out the default origins
    default_origins = [
        'localhost',
        '127.0.0.1',
    ]
    # Used both http and https above to demonstrate that both are acceptable
    try:
        additional_origins = socket.gethostbyname_ex(socket.gethostname())
    except socket.gaierror:
        # Couldn't get any IPs from the hostname
        additional_origins = []
    for host in additional_origins:
        if isinstance(host, str):
            default_origins.append('%s' % host)
        else: # It's a list
            for _host in host:
                default_origins.append('%s' % _host)
    default_origins = ";".join(default_origins)
    settings_base = getsettings('BASE_DIR')
    settings_default = os.path.join(settings_base, 'conf.d')
    settings_dir = settings_default
    if not os.path.isdir(settings_dir):
        mkdir_p(settings_dir)
    port_default = 8000
    log_default = os.path.join(settings_base, 'logs', 'gateone.log')
    user_dir_default = os.path.join(settings_base, 'users')
    pid_default = os.path.join(settings_base, 'pid', 'gateone.pid')
    session_dir_default = os.path.join(settings_base, 'sessions')
    cache_dir_default = os.path.join(settings_base, 'cache')
    ssl_dir = os.path.join(settings_base, 'ssl')
    debug = False
    cookie_secret = getsettings('SECRET_KEY')
    address = ""
    enable_unix_socket = False
    unix_socket_path = "/tmp/gateone.sock"
    unix_socket_mode = "0600"
    disable_ssl = False
    certificate = os.path.join(ssl_dir, "certificate.pem")
    keyfile = os.path.join(ssl_dir, "keyfile.pem")
    ca_certs = None
    ssl_auth = 'none'
    user_dir = user_dir_default 
    uid = str(os.getuid())
    gid = str(os.getgid()) 
    if not os.path.exists(user_dir):
        mkdir_p(user_dir)
        os.chmod(user_dir, 0o770)
    #if uid == 0 and os.getuid() != 0: 
        #if not check_write_permissions(uid, user_dir):
            #recursive_chown(user_dir, uid, gid)
    user_logs_max_age = "30d"
    session_dir = session_dir_default
    if not os.path.exists(session_dir):
        mkdir_p(session_dir)
        os.chmod(session_dir, 0o770)
    #if not check_write_permissions(uid, session_dir):
        #recursive_chown(session_dir, uid, gid)    
    syslog_facility = "daemon"
    session_timeout = "5d"
    new_api_key = False
    auth = "none"
    api_timestamp_window ="30s"
    sso_realm = None
    sso_service = "HTTP"
    pam_realm = os.uname()[1]
    pam_service = "login"
    embedded = False
    js_init = ""
    https_redirect = False
    url_prefix = "/"
    origins = default_origins
    pid_file = pid_default
    api_keys = ""
    combine_js = ""
    combine_css = ""
    combine_css_container = "gateone"
    multiprocessing_workers = None
    configure = False
    login_url ='/auth'
    static_url_prefix = '/static/'
    log_rotate_mode = 'size'
    logging = 'info'
    static_url = os.path.join(settings_base, 'static')
    session_logging = True
    log_file_num_backups = 10
    log_file_prefix = os.path.join(settings_base, 'log')
    if not os.path.exists(log_file_prefix):
        mkdir_p(log_file_prefix)
        os.chmod(log_file_prefix, 0o770)
    #if not check_write_permissions(uid, log_file_prefix):
        #recursive_chown(log_file_prefix, uid, gid)
    if not url_prefix.endswith('/'):
        url_prefix += '/' 
    global TIMEOUT
    TIMEOUT = convert_to_timedelta(session_timeout)
    api_timestamp_window = convert_to_timedelta(api_timestamp_window)
    auth = none_fix(auth)
    # Check to make sure we have a certificate and keyfile and generate fresh
    # ones if not.
    if not disable_ssl:
        if not os.path.exists(keyfile):
            ssl_base = os.path.dirname(keyfile)
            if not os.path.exists(ssl_base):
                mkdir_p(ssl_base)
            gen_self_signed_ssl(path=ssl_base)
        if not os.path.exists(certificate):
            ssl_base = os.path.dirname(certificate)
            gen_self_signed_ssl(path=ssl_base)   
    ssl_auth = ssl_auth.lower()
    log_file_max_size = 100000000
    global _
    global PLUGINS
    global APPLICATIONS
    cli_commands = {'gateone': {}} # CLI commands provided by plugins/apps
    settings = {}    
    global user_locale
    # Default to using the shell's LANG variable as the locale
    try:
        default_locale = os.environ['LANG'].split('.')[0]
    except KeyError: # $LANG isn't set
        default_locale = "en_US"
    #from django.utils.translation import ugettext as _
    #from django.utils.translation import ugettext_lazy as _
    #from django.utils.translation import activate, get_language_info
    #from django.utils.translation import activate
    #from django.utils import translation
    #user_language = 'fr'
    #translation.activate(user_language)    
    #activate('fr')
    #i = get_language_info('de')
    locales = default_locale
    user_locale = getsettings('LANGUAGE_CODE', 'en_US')
    # NOTE: The locale setting above is only for the --help messages.
    # Re-do the locale in case the user supplied something as --locale
    server_locale = locale.get(user_locale)
    _ = server_locale.translate # Also replaces our wrapper so no more .encode()
    # Set our global session timeout    
    https_redirect = False
    syslog_session_logging = False
    sso_keytab = None
    configure = False
    settings.update({
            u'dtach': True,
            'version': None,
            u'locale': locales,
            u'address': address,
            u'pam_service': pam_service,
            u'syslog_facility': syslog_facility,
            'cookie_secret': cookie_secret,
            u'enable_unix_socket': enable_unix_socket,
            u'port': port_default,
            u'uid': str(uid),
            u'url_prefix': url_prefix,
            u'user_dir': user_dir,
            'settings_dir': settings_dir,
            u'unix_socket_mode': unix_socket_mode,
            u'multiprocessing_workers': multiprocessing_workers,
            u'certificate': certificate,
            u'log_rotate_interval': 1,
            u'log_to_stderr': None,
            u'log_rotate_when': u'midnight',
            u'gid': str(gid),
            u'pid_file': pid_file,
            'command': None,
            'gzip': True,
            u'pam_realm': pam_realm,
            'login_url': login_url,
            'configure': configure,
            u'sso_service': sso_service,
            'cli_overrides': [],
            u'https_redirect': https_redirect,
            u'auth': auth,
            'api_keys': api_keys,
            u'disable_ssl': disable_ssl,
            u'ca_certs': ca_certs,
            u'cache_dir': cache_dir_default,
            u'syslog_session_logging': syslog_session_logging,
            u'user_logs_max_age': user_logs_max_age,
            u'sso_keytab': sso_keytab,
            u'api_timestamp_window': api_timestamp_window,
            'static_url_prefix': static_url_prefix,
            u'log_rotate_mode': log_rotate_mode,
            u'log_file_num_backups': log_file_num_backups,
            u'logging': logging,
            u'embedded': embedded,
            u'origins': default_origins,
            u'session_logging': session_logging,
            u'keyfile': keyfile,
            u'session_dir': session_dir,
            'static_url': static_url,
            u'ssl_auth': ssl_auth,
            u'log_file_max_size': log_file_max_size,
            u'session_timeout': TIMEOUT,
            u'sso_realm': sso_realm,
            u'debug': debug,
            u'js_init': js_init,
            u'unix_socket_path': unix_socket_path,
            u'log_file_prefix': os.path.join(log_file_prefix,'django-gateone.log'),
            u'kill': False,#new variable
            u'use_client_cache': True
    })
    return settings
Example #11
0
# Import stdlib stuff
import os, sys, re, io, gzip, fcntl, termios, struct, shutil, tempfile
from time import sleep
from datetime import datetime
from optparse import OptionParser
from applications.utils import getsettings

try:
    import curses
except ImportError:
    curses = None

# Import our own stuff
#from gateone import GATEONE_DIR
GATEONE_DIR = getsettings('BASE_DIR')
from applications.utils import raw
from applications.configuration import get_settings, combine_css

# 3rd party imports
from tornado.escape import json_encode, json_decode
import tornado.template

__doc__ = """\
.. _log_viewer:

Log Viewer
==========
Allows the user to play back a given log file like a video (default) or display
it in a syslog-like format.  To view usage information, run it with the --help
switch:
Example #12
0
def generate_server_conf(installed=True):
    """
    Generates a fresh settings/10server.conf file using the arguments provided
    on the command line to override defaults.

    If *installed* is ``False`` the defaults will be set under the assumption
    that the user is non-root and running Gate One out of a download/cloned
    directory.
    """
    logger.info(
        _(u"Gate One settings are incomplete.  A new <settings_dir>/10server.conf"
          u" will be generated."))
    auth_settings = {}  # Auth stuff goes in 20authentication.conf
    options_config = define_options()
    all_setttings = options_to_settings(
        options_config)  # NOTE: options is global
    settings_path = options_config['settings_dir']
    server_conf_path = os.path.join(settings_path, '10server.conf')
    if os.path.exists(server_conf_path):
        logger.error(
            _("You have a 10server.conf but it is either invalid (syntax "
              "error) or missing essential settings."))
        #sys.exit(1)
        return
    config_defaults = all_setttings['*']['gateone']
    # Don't need this in the actual settings file:
    del config_defaults['settings_dir']
    non_options = [
        # These are things that don't really belong in settings
        'new_api_key',
        'help',
        'kill',
        'config',
        'version',
        'combine_css',
        'combine_js',
        'combine_css_container',
        'configure'
    ]
    # Don't need non-options in there either:
    for non_option in non_options:
        if non_option in config_defaults:
            del config_defaults[non_option]
    # Generate a new cookie_secret
    config_defaults['cookie_secret'] = generate_session_id()
    # Separate out the authentication settings
    authentication_options = [
        # These are here only for logical separation in the .conf files
        'api_timestamp_window',
        'auth',
        'pam_realm',
        'pam_service',
        'sso_keytab',
        'sso_realm',
        'sso_service',
        'ssl_auth'
    ]
    # Provide some kerberos (sso) defaults
    auth_settings['sso_realm'] = "EXAMPLE.COM"
    auth_settings['sso_keytab'] = None  # Allow /etc/krb5.conf to control it
    for key, value in list(config_defaults.items()):
        if key in authentication_options:
            auth_settings.update({key: value})
            del config_defaults[key]
        if key == 'origins':
            # As a convenience to the user, add any --port to the origins
            if config_defaults['port'] not in [80, 443]:
                for i, origin in enumerate(list(value)):
                    value[i] = "{origin}:{port}".format(
                        origin=origin, port=config_defaults['port'])
    # Make sure we have a valid log_file_prefix
    if config_defaults['log_file_prefix'] == None:
        web_log_dir = os.path.join(os.path.sep, "var", "log", "gateone")
        if installed:
            here = os.path.dirname(os.path.abspath(__file__))
            web_log_dir = os.path.normpath(
                os.path.join(here, '..', '..', 'logs'))
        web_log_path = os.path.join(web_log_dir, 'gateone.log')
        config_defaults['log_file_prefix'] = web_log_path
    else:
        web_log_dir = os.path.split(config_defaults['log_file_prefix'])[0]
    if not os.path.exists(web_log_dir):
        # Make sure the directory exists
        mkdir_p(web_log_dir)
    if not os.path.exists(config_defaults['log_file_prefix']):
        # Make sure the file is present
        io.open(config_defaults['log_file_prefix'], mode='w',
                encoding='utf-8').write(u'')
    auth_conf_path = os.path.join(settings_path, '20authentication.conf')
    template_path = os.path.join(getsettings('BASE_DIR'),
                                 'templates/settings/generic.conf')
    new_settings = settings_template(template_path, settings=config_defaults)
    with io.open(server_conf_path, mode='w') as s:
        s.write(u"// This is Gate One's main settings file.\n")
        s.write(new_settings)
    #print auth_settings
    new_auth_settings = settings_template(template_path,
                                          settings=auth_settings)
    with io.open(auth_conf_path, mode='w') as s:
        s.write(u"// This is Gate One's authentication settings file.\n")
        s.write(new_auth_settings)