예제 #1
0
    def renderForHtml(self, userService, transport, ip, os, user, password):

        prefs = user.prefs('nx')

        username = user.getUsernameForAuth()
        proc = username.split('@')
        username = proc[0]
        if self._fixedName is not '':
            username = self._fixedName
        if self._fixedPassword is not '':
            password = self._fixedPassword
        if self._useEmptyCreds is True:
            username, password = '', ''

        width, height = CommonPrefs.getWidthHeight(prefs)
        cache = Cache('pam')

        tunuser = ''.join(random.choice(string.letters + string.digits) for _i in range(12)) + ("%f" % time.time()).split('.')[1]
        tunpass = ''.join(random.choice(string.letters + string.digits) for _i in range(12))
        cache.put(tunuser, tunpass, 60 * 10)  # Credential valid for ten minutes, and for 1 use only

        sshHost, sshPort = self._tunnelServer.split(':')

        logger.debug('Username generated: {0}, password: {1}'.format(tunuser, tunpass))
        tun = "{0} {1} {2} {3} {4} {5} {6}".format(tunuser, tunpass, sshHost, sshPort, ip, self._listenPort, '9')

        # Extra data
        extra = {
            'width': width,
            'height': height,
            'connection': self._connection,
            'session': self._session,
            'cacheDisk': self._cacheDisk,
            'cacheMem': self._cacheMem,
            'tun': tun
        }

        # Fix username/password acording to os manager
        username, password = userService.processUserPassword(username, password)

        return generateHtmlForNX(self, userService.uuid, transport.uuid, os, username, password, extra)
예제 #2
0
class Ticket(object):
    '''
    Manages tickets & ticketing save/loading
    Right now, uses cache as backend
    '''

    def __init__(self, key=None, data=None):
        self.uuidGenerator = lambda: (cryptoManager().uuid() + cryptoManager().uuid()).replace('-', '')
        self.cache = Cache(TICKET_OWNER)
        self.data = data
        self.key = key
        if key is not None:
            self.load()
        else:
            self.key = self.uuidGenerator()

    def save(self, data=None, validity=Cache.DEFAULT_VALIDITY):
        '''
        Stores data inside ticket, and make data persistent (store in db)
        '''
        if data is not None:
            self.data = data
        self.cache.put(self.key, self.data, validity)
        return self.key

    def load(self):
        '''
        Load data (if still valid) for a ticket
        '''
        self.data = self.cache.get(self.key, None)
        return self.data

    def delete(self):
        '''
        Removes a ticket from storage (db)
        '''
        self.cache.remove(self.key)

    def __unicode__(self):
        return "Ticket: {}, {}".format(self.key, self.data)
예제 #3
0
class Ticket(object):
    '''
    Manages tickets & ticketing save/loading
    Right now, uses cache as backend
    '''
    def __init__(self, key=None, data=None):
        self.uuidGenerator = lambda: (cryptoManager().uuid() + cryptoManager().
                                      uuid()).replace('-', '')
        self.cache = Cache(TICKET_OWNER)
        self.data = data
        self.key = key
        if key is not None:
            self.load()
        else:
            self.key = self.uuidGenerator()

    def save(self, data=None, validity=Cache.DEFAULT_VALIDITY):
        '''
        Stores data inside ticket, and make data persistent (store in db)
        '''
        if data is not None:
            self.data = data
        self.cache.put(self.key, self.data, validity)
        return self.key

    def load(self):
        '''
        Load data (if still valid) for a ticket
        '''
        self.data = self.cache.get(self.key, None)
        return self.data

    def delete(self):
        '''
        Removes a ticket from storage (db)
        '''
        self.cache.remove(self.key)

    def __unicode__(self):
        return "Ticket: {}, {}".format(self.key, self.data)
예제 #4
0
def login(request, tag=None):
    '''
    View responsible of logging in an user
    :param request:  http request
    :param tag: tag of login auth
    '''
    # request.session.set_expiry(GlobalConfig.USER_SESSION_LENGTH.getInt())

    host = request.META.get('HTTP_HOST') or request.META.get('SERVER_NAME') or 'auth_host'  # Last one is a placeholder in case we can't locate host name

    # Get Authenticators limitation
    logger.debug('Host: {0}'.format(host))
    if GlobalConfig.DISALLOW_GLOBAL_LOGIN.getBool(True) is True:
        if tag is None:
            try:
                Authenticator.objects.get(small_name=host)
                tag = host
            except Exception:
                try:
                    tag = Authenticator.objects.order_by('priority')[0].small_name
                except Exception:  # There is no authenticators yet, simply allow global login to nowhere.. :-)
                    tag = None

    logger.debug('Tag: {0}'.format(tag))

    logger.debug(request.method)
    if request.method == 'POST':
        if 'uds' not in request.COOKIES:
            logger.debug('Request does not have uds cookie')
            return errors.errorView(request, errors.COOKIES_NEEDED)  # We need cookies to keep session data
        request.session.cycle_key()
        form = LoginForm(request.POST, tag=tag)
        if form.is_valid():
            os = OsDetector.getOsFromUA(request.META.get('HTTP_USER_AGENT'))
            try:
                authenticator = Authenticator.objects.get(pk=form.cleaned_data['authenticator'])
            except Exception:
                authenticator = Authenticator()
            userName = form.cleaned_data['user']

            cache = Cache('auth')
            cacheKey = str(authenticator.id) + userName
            tries = cache.get(cacheKey)
            if tries is None:
                tries = 0
            if authenticator.getInstance().blockUserOnLoginFailures is True and tries >= GlobalConfig.MAX_LOGIN_TRIES.getInt():
                form.add_form_error('Too many authentication errors. User temporarily  blocked.')
                authLogLogin(request, authenticator, userName, 'Temporarily blocked')
            else:
                user = authenticate(userName, form.cleaned_data['password'], authenticator)
                logger.debug('User: {}'.format(user))

                if user is None:
                    logger.debug("Invalid credentials for user {0}".format(userName))
                    tries += 1
                    cache.put(cacheKey, tries, GlobalConfig.LOGIN_BLOCK.getInt())
                    form.add_form_error('Invalid credentials')
                    authLogLogin(request, authenticator, userName, 'Invalid credentials')
                else:
                    logger.debug('User {} has logged in'.format(userName))
                    cache.remove(cacheKey)  # Valid login, remove cached tries
                    response = HttpResponseRedirect(reverse('uds.web.views.index'))
                    webLogin(request, response, user, form.cleaned_data['password'])
                    # Add the "java supported" flag to session
                    request.session['OS'] = os
                    authLogLogin(request, authenticator, user.name)
                    return response
    else:
        form = LoginForm(tag=tag)

    response = render_to_response(theme.template('login.html'), {'form': form, 'customHtml': GlobalConfig.CUSTOM_HTML_LOGIN.get(True)},
                                  context_instance=RequestContext(request))

    getUDSCookie(request, response)

    return response
예제 #5
0
def login(request, tag=None):
    '''
    View responsible of logging in an user
    :param request:  http request
    :param tag: tag of login auth
    '''
    # request.session.set_expiry(GlobalConfig.USER_SESSION_LENGTH.getInt())

    host = request.META.get('HTTP_HOST') or request.META.get('SERVER_NAME') or 'auth_host'  # Last one is a placeholder in case we can't locate host name

    # Get Authenticators limitation
    logger.debug('Host: {0}'.format(host))
    if GlobalConfig.DISALLOW_GLOBAL_LOGIN.getBool(False) is True:
        if tag is None:
            try:
                Authenticator.objects.get(small_name=host)
                tag = host
            except Exception:
                try:
                    tag = Authenticator.objects.order_by('priority')[0].small_name
                except Exception:  # There is no authenticators yet, simply allow global login to nowhere.. :-)
                    tag = None

    logger.debug('Tag: {0}'.format(tag))

    logger.debug(request.method)
    if request.method == 'POST':
        if 'uds' not in request.COOKIES:
            logger.debug('Request does not have uds cookie')
            return errors.errorView(request, errors.COOKIES_NEEDED)  # We need cookies to keep session data
        request.session.cycle_key()
        form = LoginForm(request.POST, tag=tag)
        if form.is_valid():
            os = request.os
            try:
                authenticator = Authenticator.objects.get(pk=form.cleaned_data['authenticator'])
            except Exception:
                authenticator = Authenticator()
            userName = form.cleaned_data['user']
            if GlobalConfig.LOWERCASE_USERNAME.getBool(True) is True:
                userName = userName.lower()

            cache = Cache('auth')
            cacheKey = str(authenticator.id) + userName
            tries = cache.get(cacheKey)
            if tries is None:
                tries = 0
            if authenticator.getInstance().blockUserOnLoginFailures is True and tries >= GlobalConfig.MAX_LOGIN_TRIES.getInt():
                form.add_error(None, 'Too many authentication errors. User temporarily  blocked.')
                authLogLogin(request, authenticator, userName, 'Temporarily blocked')
            else:
                password = form.cleaned_data['password']
                user = None
                if password == '':
                    password = '******'
                user = authenticate(userName, password, authenticator)
                logger.debug('User: {}'.format(user))

                if user is None:
                    logger.debug("Invalid credentials for user {0}".format(userName))
                    tries += 1
                    cache.put(cacheKey, tries, GlobalConfig.LOGIN_BLOCK.getInt())
                    form.add_error(None, ugettext('Invalid credentials'))
                    authLogLogin(request, authenticator, userName, 'Invalid credentials')
                else:
                    logger.debug('User {} has logged in'.format(userName))
                    cache.remove(cacheKey)  # Valid login, remove cached tries
                    response = HttpResponseRedirect(reverse('uds.web.views.index'))
                    webLogin(request, response, user, form.cleaned_data['password'])
                    # Add the "java supported" flag to session
                    request.session['OS'] = os
                    if form.cleaned_data['logouturl'] != '':
                        logger.debug('The logoout url will be {}'.format(form.cleaned_data['logouturl']))
                        request.session['logouturl'] = form.cleaned_data['logouturl']
                    authLogLogin(request, authenticator, user.name)
                    return response
        else:
            logger.info('Invalid form received')
    else:
        form = LoginForm(tag=tag)

    response = render_to_response(
        theme.template('login.html'),
        {
            'form': form,
            'customHtml': GlobalConfig.CUSTOM_HTML_LOGIN.get(True),
            'version': VERSION

        },
        context_instance=RequestContext(request)
    )

    getUDSCookie(request, response)

    return response
예제 #6
0
def checkLogin(request, form, tag=None):
    host = request.META.get('HTTP_HOST') or request.META.get('SERVER_NAME') or 'auth_host'  # Last one is a placeholder in case we can't locate host name

    # Get Authenticators limitation
    logger.debug('Host: {0}'.format(host))
    if GlobalConfig.DISALLOW_GLOBAL_LOGIN.getBool(False) is True:
        if tag is None:
            try:
                Authenticator.objects.get(small_name=host)
                tag = host
            except Exception:
                try:
                    tag = Authenticator.objects.order_by('priority')[0].small_name
                except Exception:  # There is no authenticators yet, simply allow global login to nowhere.. :-)
                    tag = None

    logger.debug('Tag: {0}'.format(tag))

    if 'uds' not in request.COOKIES:
        logger.debug('Request does not have uds cookie')
        return (None, errors.COOKIES_NEEDED)
    if form.is_valid():
        os = request.os
        try:
            authenticator = Authenticator.objects.get(uuid=processUuid(form.cleaned_data['authenticator']))
        except Exception:
            authenticator = Authenticator()
        userName = form.cleaned_data['user']
        if GlobalConfig.LOWERCASE_USERNAME.getBool(True) is True:
            userName = userName.lower()

        cache = Cache('auth')
        cacheKey = str(authenticator.id) + userName
        tries = cache.get(cacheKey)
        if tries is None:
            tries = 0
        if authenticator.getInstance().blockUserOnLoginFailures is True and tries >= GlobalConfig.MAX_LOGIN_TRIES.getInt():
            authLogLogin(request, authenticator, userName, 'Temporarily blocked')
            return (None, _('Too many authentication errrors. User temporarily blocked'))
        else:
            password = form.cleaned_data['password']
            user = None
            if password == '':
                password = '******'  # Random string, in fact, just a placeholder that will not be used :)
            user = authenticate(userName, password, authenticator)
            logger.debug('User: {}'.format(user))

            if user is None:
                logger.debug("Invalid user {0} (access denied)".format(userName))
                tries += 1
                cache.put(cacheKey, tries, GlobalConfig.LOGIN_BLOCK.getInt())
                authLogLogin(request, authenticator, userName, 'Access denied (user not allowed by UDS)')
                return (None, _('Access denied'))
            else:
                request.session.cycle_key()

                logger.debug('User {} has logged in'.format(userName))
                cache.remove(cacheKey)  # Valid login, remove cached tries

                # Add the "java supported" flag to session
                request.session['OS'] = os
                if form.cleaned_data['logouturl'] != '':
                    logger.debug('The logoout url will be {}'.format(form.cleaned_data['logouturl']))
                    request.session['logouturl'] = form.cleaned_data['logouturl']
                authLogLogin(request, authenticator, user.name)
                return (user, form.cleaned_data['password'])

    logger.info('Invalid form received')
    return (None, _('Invalid data'))
예제 #7
0
def checkLogin(request, form, tag=None):
    host = request.META.get('HTTP_HOST') or request.META.get(
        'SERVER_NAME'
    ) or 'auth_host'  # Last one is a placeholder in case we can't locate host name

    # Get Authenticators limitation
    logger.debug('Host: {0}'.format(host))
    if GlobalConfig.DISALLOW_GLOBAL_LOGIN.getBool(False) is True:
        if tag is None:
            try:
                Authenticator.objects.get(small_name=host)
                tag = host
            except Exception:
                try:
                    tag = Authenticator.objects.order_by(
                        'priority')[0].small_name
                except Exception:  # There is no authenticators yet, simply allow global login to nowhere.. :-)
                    tag = None

    logger.debug('Tag: {0}'.format(tag))

    if 'uds' not in request.COOKIES:
        logger.debug('Request does not have uds cookie')
        return (None, errors.COOKIES_NEEDED)
    if form.is_valid():
        os = request.os
        try:
            authenticator = Authenticator.objects.get(
                uuid=processUuid(form.cleaned_data['authenticator']))
        except Exception:
            authenticator = Authenticator()
        userName = form.cleaned_data['user']
        if GlobalConfig.LOWERCASE_USERNAME.getBool(True) is True:
            userName = userName.lower()

        cache = Cache('auth')
        cacheKey = str(authenticator.id) + userName
        tries = cache.get(cacheKey)
        if tries is None:
            tries = 0
        if authenticator.getInstance(
        ).blockUserOnLoginFailures is True and tries >= GlobalConfig.MAX_LOGIN_TRIES.getInt(
        ):
            authLogLogin(request, authenticator, userName,
                         'Temporarily blocked')
            return (
                None,
                _('Too many authentication errrors. User temporarily blocked'))
        else:
            password = form.cleaned_data['password']
            user = None
            if password == '':
                password = '******'  # Random string, in fact, just a placeholder that will not be used :)
            user = authenticate(userName, password, authenticator)
            logger.debug('User: {}'.format(user))

            if user is None:
                logger.debug(
                    "Invalid user {0} (access denied)".format(userName))
                tries += 1
                cache.put(cacheKey, tries, GlobalConfig.LOGIN_BLOCK.getInt())
                authLogLogin(request, authenticator, userName,
                             'Access denied (user not allowed by UDS)')
                return (None, _('Access denied'))
            else:
                request.session.cycle_key()

                logger.debug('User {} has logged in'.format(userName))
                cache.remove(cacheKey)  # Valid login, remove cached tries

                # Add the "java supported" flag to session
                request.session['OS'] = os
                if form.cleaned_data['logouturl'] != '':
                    logger.debug('The logoout url will be {}'.format(
                        form.cleaned_data['logouturl']))
                    request.session['logouturl'] = form.cleaned_data[
                        'logouturl']
                authLogLogin(request, authenticator, user.name)
                return (user, form.cleaned_data['password'])

    logger.info('Invalid form received')
    return (None, _('Invalid data'))