⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 defaultlogoncontroller.java

📁 这是linux下ssl vpn的实现程序
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
        if (lockedUsers.containsKey(username) && ((AccountLock) lockedUsers.get(username)).getLocks() > 0) {
            return ACCOUNT_LOCKED;
        } else if (getSessionInfo(username, -1) != null) {
            return ACCOUNT_ACTIVE;
        } else {
            User user = CoreServlet.getServlet().getUserDatabase().getAccount(username);
            if (user == null) {
                return ACCOUNT_UNKNOWN;
            } else {
                boolean disabled = !PolicyUtil.isEnabled(user);
                // if (!admin && disabled) {
                if (disabled) {
                    return ACCOUNT_DISABLED;
                } else {
                    // boolean admin = isAdministrator(user, true, false, true);
                    boolean logonAuthorized = PolicyUtil.canLogin(user);
                    // if (!admin && !logonAuthorized) {
                    if (!logonAuthorized) {
                        return ACCOUNT_REVOKED;
                    } else {
                        return ACCOUNT_GRANTED;
                    }
                }
            }
        }
    }

    public String logonClient(HttpServletRequest request, HttpServletResponse response, String username, String password,
                              Properties properties) throws InvalidTicketException, UserDatabaseException,
                    InvalidLoginCredentialsException, AccountLockedException, UnknownHostException {
        // Check if the embedded client is allowed to logon using username /
        // password

        AuthenticationSchemeSequence seq = AuthenticationModuleManager.getInstance().getSchemeForAuthenticationModuleInUse(
            EmbeddedClientAuthenticationModule.MODULE_NAME);
        if (seq == null || !seq.getEnabled()) {
            throw new InvalidLoginCredentialsException(
                            "Username / Password authentication is not allowed for the Embedded SSL-Explorer Agent. Please contact your adiministrator.");
        }
        // Actually logon and get the account
        User user = doClientLogon(username, password);
        PolicyUtil.checkLogin(user);
        // Check that the password matches the current policy, if not then
        // request a
        // new one
        if (CoreServlet.getServlet().getUserDatabase().supportsPasswordChange()) {
            try {
                String pattern = CoreServlet.getServlet().getPropertyDatabase().getProperty(0, null, "security.password.pattern");
                Pattern p = ReplacementEngine.getPatternPool().getPattern(pattern, false, false);
                try {
                    if (!p.matcher(password).matches()) {
                        throw new UserDatabaseException("Password does not match current policy.");
                    }
                } finally {
                    ReplacementEngine.getPatternPool().releasePattern(p);
                }
            } catch (Exception e) {
                throw new InvalidLoginCredentialsException("Could not check password against current policy.");
            }
            // Check if the password has expired
            try {
                if (user.getLastPasswordChange() != null) {
                    GregorianCalendar lastChange = new GregorianCalendar();
                    lastChange.setTimeInMillis(user.getLastPasswordChange().getTime());
                    GregorianCalendar warningOn = new GregorianCalendar();
                    int warningInDays = Integer.parseInt(CoreServlet.getServlet().getPropertyDatabase().getProperty(0, null,
                        "security.password.daysBeforeExpiryWarning"));
                    warningOn.setTimeInMillis(user.getLastPasswordChange().getTime());
                    warningOn.add(Calendar.DATE, warningInDays);
                    GregorianCalendar expiresOn = new GregorianCalendar();
                    int expiryInDays = Integer.parseInt(CoreServlet.getServlet().getPropertyDatabase().getProperty(0, null,
                        "security.password.daysBeforeExpiry"));
                    expiresOn.setTimeInMillis(user.getLastPasswordChange().getTime());
                    expiresOn.add(Calendar.DATE, expiryInDays);
                    GregorianCalendar now = new GregorianCalendar();
                    if (expiresOn.before(now) && expiryInDays > 0) {
                        throw new InvalidLoginCredentialsException("Password has expired.");
                    }
                }
            } catch (InvalidLoginCredentialsException ilce) {
                throw ilce;
            } catch (Exception e) {
                throw new UserDatabaseException("Could not check password against current policy.", e);
            }
        }
        InetAddress address = InetAddress.getByName(request.getRemoteAddr());
        checkForMultipleSessions(user, address, SessionInfo.UI);
        SessionInfo info = addLogonTicket(request, response, user, address, SessionInfo.VPN_CLIENT);
        initialiseSession(request.getSession(), user, true);
        return registerVPNClient(request, setupVPNSession(request, info), -1, properties, VPNSession.STANDALONE_VPN_CLIENT);
    }

    private void checkForMultipleSessions(User user, InetAddress address, int sessionType) throws UserDatabaseException {
        int type = 0;
        try {
            type = Integer.parseInt(CoreServlet.getServlet().getPropertyDatabase()
                            .getProperty(0, null, "security.multipleSessions"));
        } catch (Exception e) {
            throw new UserDatabaseException("Cound not get multiple sessions restriction. " + e.getMessage());
        }
        List activeSessions;
        switch (type) {
            case 0:
                break; // No restrction
            case 1:
                activeSessions = getSessionInfo(user.getPrincipalName(), sessionType);
                if (activeSessions != null) {
                    throw new UserDatabaseException(
                                    "You are already logged on, and this systems policy is to only allow one session per user.");
                }
                break;
            case 2:
                activeSessions = getSessionInfo(user.getPrincipalName(), sessionType);
                if (activeSessions != null) {
                    for (Iterator i = activeSessions.iterator(); i.hasNext();) {
                        SessionInfo info = (SessionInfo) i.next();
                        if (!info.getAddress().equals(address)) {
                            throw new UserDatabaseException(
                                            "You are already logged on at a different address, and this systems policy is to only allow one session per user / address.");
                        }
                    }
                }
                break;
            default:
                throw new UserDatabaseException("Unknown multiple session restrictions type " + type + ".");
        }
    }

    public void initialiseSession(HttpSession session, User user, boolean requiresProfile) throws UserDatabaseException {
    	if (log.isInfoEnabled())
    		log.info("Initialising session " + session.getId() + " with user " + (user == null ? "[none]" : user.getPrincipalName()));
        PropertyProfile profile = (PropertyProfile) session.getAttribute(Constants.SELECTED_PROFILE);
        // if (user != null && user != session.getAttribute(Constants.USER)) {
        session.setAttribute(Constants.USER, user);
        String logonInfo = MessageResources.getMessageResources("com.sslexplorer.navigation.ApplicationResources").getMessage(
            "footer.info", user.getPrincipalName(), SimpleDateFormat.getDateTimeInstance().format(new Date()));
        session.setAttribute(Constants.LOGON_INFO, logonInfo);
        try {
            List profiles = ResourceUtil.filterResources(user, CoreServlet.getServlet().getPropertyDatabase().getPropertyProfiles(
                            user.getPrincipalName(), true), false);

            
            session.setAttribute(Constants.PROFILES, profiles);
            if (profiles.size() == 0) {
                throw new UserDatabaseException("You do not have permission to use any profiles.");
            }
            if ((profile != null && requiresProfile)
                            || (!"true".equals(CoreServlet.getServlet().getPropertyDatabase().getProperty(0, null,
                                "profiles.promptForProfileAtLogon")) || profiles.size() < 2)) {
                // TODO use the last known profile
                int profileId = Integer.parseInt(user.getAttributes().getProperty(User.USER_DEFAULT_PROPERTY_PROFILE, "-1"));
                profile = profileId == -1 ? CoreServlet.getServlet().getPropertyDatabase().getPropertyProfile(
                    user.getPrincipalName(), "Default") : CoreServlet.getServlet().getPropertyDatabase().getPropertyProfile(
                    profileId);
                if (profile == null) {
                    profile = CoreServlet.getServlet().getPropertyDatabase().getPropertyProfile(null, "Default");
                }
            }
            if (profile != null) {
            	if (log.isInfoEnabled())
            		log.info("Switching user " + user.getPrincipalName() + " to profile " + profile.getResourceName());
                session.setAttribute(Constants.SELECTED_PROFILE, profile);
            }
        } catch (Exception e) {
            throw new UserDatabaseException("Failed to initialise profiles.", e);
        }
        final String logonTicket = (String) session.getAttribute(Constants.LOGON_TICKET);
        session.setAttribute(Constants.LOGOFF_HOOK, new HttpSessionBindingListener() {
            public void valueBound(HttpSessionBindingEvent evt) {
            }

            public void valueUnbound(HttpSessionBindingEvent evt) {
            	if (log.isDebugEnabled())
            		log.debug("Session unbound");
                // We should should only log off completely if no other
                // session has
                // the logon ticket
                SessionInfo currentTicketSessionInfo = ((SessionInfo) logons.get(logonTicket));
                if (currentTicketSessionInfo == null
                                || evt.getSession().getId().equals(currentTicketSessionInfo.getHttpSession().getId())) {
                	if (log.isDebugEnabled())
                		log.debug("Session (" + evt.getSession().getId() + ") unbound is the current session for ticket " + logonTicket
                                    + " so a logoff will be performed.");
                    logoff(logonTicket);
                } else {
                	if (log.isDebugEnabled())
                		log.debug("Session unbound is NOT the current session, ignoring.");
                }
            }
        });
        // }
        // else {
        // Util.removeMe("Not initialising session, user hasnt changed");
        // }
        if (log.isDebugEnabled())
        	log.debug("Using profile: " + (profile == null ? "DEFAULT" : profile.getResourceName()) + ")");
        session.removeAttribute(Constants.SESSION_LOCKED);
        
        // add the global warnings.
        List servletContextGlabalWarnings = (List) session.getServletContext().getAttribute(Constants.SESSION_GLOBAL_WARNINGS) ;
        if (servletContextGlabalWarnings != null){
            Iterator iter = servletContextGlabalWarnings.iterator();
            while (iter.hasNext()) {
                GlobalWarning gw = (GlobalWarning)iter.next();
                try {
                    if(gw.getType() == GlobalWarning.SUPER_USER && isAdministrator(user)) {
                        CoreUtil.addSingleSessionGlobalWarning(session, gw.getMessage()) ;
                    }
                    else if(gw.getType() == GlobalWarning.MANAGEMENT_USERS && CoreServlet.getServlet().getPolicyDatabase().isAnyResourcePermissionAllowed(user,
                        true, true, false)) {
                        CoreUtil.addSingleSessionGlobalWarning(session, gw.getMessage()) ;
                    }
                    else if(gw.getType() == GlobalWarning.USERS_WITH_PERMISSIONS && 
                                    CoreServlet.getServlet().getPolicyDatabase().isResourcePermissionAllowed(gw.getRequiredResourceType(), gw.getRequiredPermissions(), user, false)) {
                        CoreUtil.addSingleSessionGlobalWarning(session, gw.getMessage()) ;
                    }
                    else if(gw.getType() == GlobalWarning.ALL_USERS) {
                        CoreUtil.addSingleSessionGlobalWarning(session, gw.getMessage()) ;                        
                    }
                }
                catch(Exception e) {
                    log.error("Failed to add global message. ", e);
                }
            }
        }
        
        
        resetSessionTimeout(user, profile, session);
    }

    public void resetSessionTimeout(User user, PropertyProfile profile, HttpSession session) {
        try {
            Map sessionTimeoutBlocks = (Map) session.getAttribute(Constants.SESSION_TIMEOUT_BLOCKS);
            int minutes = 0;
            if (sessionTimeoutBlocks == null || sessionTimeoutBlocks.size() == 0) {
                minutes = Integer.parseInt(CoreServlet.getServlet().getPropertyDatabase().getProperty(
                    profile == null ? 0 : profile.getResourceId(), user == null ? null : user.getPrincipalName(),
                    "webServer.sessionInactivityTimeout"));
            }
            if (log.isDebugEnabled())
            	log.debug("Resetting timeout for session " + session.getId() + " to " + minutes + " minutes");
            session.setMaxInactiveInterval(minutes == 0 ? -1 : minutes * 60);
        } catch (Exception e) {
            log.error("Failed to reset session timeout.", e);
        }
    }

    public AccountLock checkForAccountLock(String username) throws AuthenticationException, AccountLockedException {
        // Get the user lockout policy
        int maxLogonAttemptsBeforeLock = 0;
        int lockDuration = 0;
        try {
            maxLogonAttemptsBeforeLock = Integer.parseInt(CoreServlet.getServlet().getPropertyDatabase().getProperty(0, null,
                "security.maxLogonAttemptsBeforeLock"));
            lockDuration = Integer.parseInt(CoreServlet.getServlet().getPropertyDatabase().getProperty(0, null,
                "security.lockDuration"));
        } catch (Exception e) {
            throw new AuthenticationException("Failed to determine password lockout policy.", e);
        }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -