001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.security.auth.session;
016    
017    import com.liferay.portal.events.EventsProcessorUtil;
018    import com.liferay.portal.kernel.cluster.ClusterExecutorUtil;
019    import com.liferay.portal.kernel.cluster.ClusterNode;
020    import com.liferay.portal.kernel.exception.PortalException;
021    import com.liferay.portal.kernel.json.JSONFactoryUtil;
022    import com.liferay.portal.kernel.json.JSONObject;
023    import com.liferay.portal.kernel.messaging.DestinationNames;
024    import com.liferay.portal.kernel.messaging.MessageBusUtil;
025    import com.liferay.portal.kernel.security.auth.AuthException;
026    import com.liferay.portal.kernel.security.auth.AuthenticatedUserUUIDStoreUtil;
027    import com.liferay.portal.kernel.security.auth.Authenticator;
028    import com.liferay.portal.kernel.security.auth.session.AuthenticatedSessionManager;
029    import com.liferay.portal.kernel.security.pacl.DoPrivileged;
030    import com.liferay.portal.kernel.util.CookieKeys;
031    import com.liferay.portal.kernel.util.GetterUtil;
032    import com.liferay.portal.kernel.util.Http;
033    import com.liferay.portal.kernel.util.MapUtil;
034    import com.liferay.portal.kernel.util.PropsKeys;
035    import com.liferay.portal.kernel.util.StringPool;
036    import com.liferay.portal.kernel.util.StringUtil;
037    import com.liferay.portal.kernel.util.Validator;
038    import com.liferay.portal.kernel.util.WebKeys;
039    import com.liferay.portal.liveusers.LiveUsers;
040    import com.liferay.portal.model.Company;
041    import com.liferay.portal.model.CompanyConstants;
042    import com.liferay.portal.model.User;
043    import com.liferay.portal.model.UserTracker;
044    import com.liferay.portal.service.CompanyLocalServiceUtil;
045    import com.liferay.portal.service.UserLocalServiceUtil;
046    import com.liferay.portal.util.PortalUtil;
047    import com.liferay.portal.util.PropsValues;
048    import com.liferay.util.Encryptor;
049    
050    import java.util.ArrayList;
051    import java.util.Enumeration;
052    import java.util.HashMap;
053    import java.util.List;
054    import java.util.Map;
055    
056    import javax.servlet.http.Cookie;
057    import javax.servlet.http.HttpServletRequest;
058    import javax.servlet.http.HttpServletResponse;
059    import javax.servlet.http.HttpSession;
060    
061    /**
062     * @author Tomas Polesovsky
063     */
064    @DoPrivileged
065    public class AuthenticatedSessionManagerImpl
066            implements AuthenticatedSessionManager {
067    
068            @Override
069            public long getAuthenticatedUserId(
070                            HttpServletRequest request, String login, String password,
071                            String authType)
072                    throws PortalException {
073    
074                    long userId = GetterUtil.getLong(login);
075    
076                    Company company = PortalUtil.getCompany(request);
077    
078                    String requestURI = request.getRequestURI();
079    
080                    String contextPath = PortalUtil.getPathContext();
081    
082                    if (requestURI.startsWith(contextPath.concat("/api/liferay"))) {
083                            throw new AuthException();
084                    }
085                    else {
086                            Map<String, String[]> headerMap = new HashMap<>();
087    
088                            Enumeration<String> enu1 = request.getHeaderNames();
089    
090                            while (enu1.hasMoreElements()) {
091                                    String name = enu1.nextElement();
092    
093                                    Enumeration<String> enu2 = request.getHeaders(name);
094    
095                                    List<String> headers = new ArrayList<>();
096    
097                                    while (enu2.hasMoreElements()) {
098                                            String value = enu2.nextElement();
099    
100                                            headers.add(value);
101                                    }
102    
103                                    headerMap.put(
104                                            name, headers.toArray(new String[headers.size()]));
105                            }
106    
107                            Map<String, String[]> parameterMap = request.getParameterMap();
108                            Map<String, Object> resultsMap = new HashMap<>();
109    
110                            if (Validator.isNull(authType)) {
111                                    authType = company.getAuthType();
112                            }
113    
114                            int authResult = Authenticator.FAILURE;
115    
116                            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
117                                    authResult = UserLocalServiceUtil.authenticateByEmailAddress(
118                                            company.getCompanyId(), login, password, headerMap,
119                                            parameterMap, resultsMap);
120    
121                                    userId = MapUtil.getLong(resultsMap, "userId", userId);
122                            }
123                            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
124                                    authResult = UserLocalServiceUtil.authenticateByScreenName(
125                                            company.getCompanyId(), login, password, headerMap,
126                                            parameterMap, resultsMap);
127    
128                                    userId = MapUtil.getLong(resultsMap, "userId", userId);
129                            }
130                            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
131                                    authResult = UserLocalServiceUtil.authenticateByUserId(
132                                            company.getCompanyId(), userId, password, headerMap,
133                                            parameterMap, resultsMap);
134                            }
135    
136                            if (authResult != Authenticator.SUCCESS) {
137                                    User user = UserLocalServiceUtil.fetchUser(userId);
138    
139                                    if (user != null) {
140                                            UserLocalServiceUtil.checkLockout(user);
141                                    }
142    
143                                    throw new AuthException();
144                            }
145                    }
146    
147                    return userId;
148            }
149    
150            @Override
151            public void login(
152                            HttpServletRequest request, HttpServletResponse response,
153                            String login, String password, boolean rememberMe, String authType)
154                    throws Exception {
155    
156                    request = PortalUtil.getOriginalServletRequest(request);
157    
158                    CookieKeys.validateSupportCookie(request);
159    
160                    HttpSession session = request.getSession();
161    
162                    Company company = PortalUtil.getCompany(request);
163    
164                    long userId = getAuthenticatedUserId(
165                            request, login, password, authType);
166    
167                    if (!PropsValues.AUTH_SIMULTANEOUS_LOGINS) {
168                            signOutSimultaneousLogins(userId);
169                    }
170    
171                    if (PropsValues.SESSION_ENABLE_PHISHING_PROTECTION) {
172                            session = renewSession(request, session);
173                    }
174    
175                    // Set cookies
176    
177                    String domain = CookieKeys.getDomain(request);
178    
179                    User user = UserLocalServiceUtil.getUserById(userId);
180    
181                    String userIdString = String.valueOf(userId);
182    
183                    session.setAttribute("j_username", userIdString);
184    
185                    if (PropsValues.PORTAL_JAAS_PLAIN_PASSWORD) {
186                            session.setAttribute("j_password", password);
187                    }
188                    else {
189                            session.setAttribute("j_password", user.getPassword());
190                    }
191    
192                    session.setAttribute("j_remoteuser", userIdString);
193    
194                    if (PropsValues.SESSION_STORE_PASSWORD) {
195                            session.setAttribute(WebKeys.USER_PASSWORD, password);
196                    }
197    
198                    Cookie companyIdCookie = new Cookie(
199                            CookieKeys.COMPANY_ID, String.valueOf(company.getCompanyId()));
200    
201                    if (Validator.isNotNull(domain)) {
202                            companyIdCookie.setDomain(domain);
203                    }
204    
205                    companyIdCookie.setPath(StringPool.SLASH);
206    
207                    Cookie idCookie = new Cookie(
208                            CookieKeys.ID,
209                            Encryptor.encrypt(company.getKeyObj(), userIdString));
210    
211                    if (Validator.isNotNull(domain)) {
212                            idCookie.setDomain(domain);
213                    }
214    
215                    idCookie.setPath(StringPool.SLASH);
216    
217                    Cookie passwordCookie = new Cookie(
218                            CookieKeys.PASSWORD,
219                            Encryptor.encrypt(company.getKeyObj(), password));
220    
221                    if (Validator.isNotNull(domain)) {
222                            passwordCookie.setDomain(domain);
223                    }
224    
225                    passwordCookie.setPath(StringPool.SLASH);
226    
227                    Cookie rememberMeCookie = new Cookie(
228                            CookieKeys.REMEMBER_ME, Boolean.TRUE.toString());
229    
230                    if (Validator.isNotNull(domain)) {
231                            rememberMeCookie.setDomain(domain);
232                    }
233    
234                    rememberMeCookie.setPath(StringPool.SLASH);
235    
236                    int loginMaxAge = PropsValues.COMPANY_SECURITY_AUTO_LOGIN_MAX_AGE;
237    
238                    String userUUID = userIdString.concat(StringPool.PERIOD).concat(
239                            String.valueOf(System.nanoTime()));
240    
241                    Cookie userUUIDCookie = new Cookie(
242                            CookieKeys.USER_UUID,
243                            Encryptor.encrypt(company.getKeyObj(), userUUID));
244    
245                    userUUIDCookie.setPath(StringPool.SLASH);
246    
247                    session.setAttribute(WebKeys.USER_UUID, userUUID);
248    
249                    if (PropsValues.SESSION_DISABLED) {
250                            rememberMe = true;
251                    }
252    
253                    if (rememberMe) {
254                            companyIdCookie.setMaxAge(loginMaxAge);
255                            idCookie.setMaxAge(loginMaxAge);
256                            passwordCookie.setMaxAge(loginMaxAge);
257                            rememberMeCookie.setMaxAge(loginMaxAge);
258                            userUUIDCookie.setMaxAge(loginMaxAge);
259                    }
260                    else {
261    
262                            // This was explicitly changed from 0 to -1 so that the cookie lasts
263                            // as long as the browser. This allows an external servlet wrapped
264                            // in AutoLoginFilter to work throughout the client connection. The
265                            // cookies ARE removed on an actual logout, so there is no security
266                            // issue. See LEP-4678 and LEP-5177.
267    
268                            companyIdCookie.setMaxAge(-1);
269                            idCookie.setMaxAge(-1);
270                            passwordCookie.setMaxAge(-1);
271                            rememberMeCookie.setMaxAge(0);
272                            userUUIDCookie.setMaxAge(-1);
273                    }
274    
275                    Cookie loginCookie = new Cookie(CookieKeys.LOGIN, login);
276    
277                    if (Validator.isNotNull(domain)) {
278                            loginCookie.setDomain(domain);
279                    }
280    
281                    loginCookie.setMaxAge(loginMaxAge);
282                    loginCookie.setPath(StringPool.SLASH);
283    
284                    Cookie screenNameCookie = new Cookie(
285                            CookieKeys.SCREEN_NAME,
286                            Encryptor.encrypt(company.getKeyObj(), user.getScreenName()));
287    
288                    if (Validator.isNotNull(domain)) {
289                            screenNameCookie.setDomain(domain);
290                    }
291    
292                    screenNameCookie.setMaxAge(loginMaxAge);
293                    screenNameCookie.setPath(StringPool.SLASH);
294    
295                    boolean secure = request.isSecure();
296    
297                    if (secure && !PropsValues.COMPANY_SECURITY_AUTH_REQUIRES_HTTPS &&
298                            !StringUtil.equalsIgnoreCase(
299                                    Http.HTTPS, PropsValues.WEB_SERVER_PROTOCOL)) {
300    
301                            Boolean httpsInitial = (Boolean)session.getAttribute(
302                                    WebKeys.HTTPS_INITIAL);
303    
304                            if ((httpsInitial == null) || !httpsInitial.booleanValue()) {
305                                    secure = false;
306                            }
307                    }
308    
309                    CookieKeys.addCookie(request, response, companyIdCookie, secure);
310                    CookieKeys.addCookie(request, response, idCookie, secure);
311                    CookieKeys.addCookie(request, response, userUUIDCookie, secure);
312    
313                    if (rememberMe) {
314                            CookieKeys.addCookie(request, response, loginCookie, secure);
315                            CookieKeys.addCookie(request, response, passwordCookie, secure);
316                            CookieKeys.addCookie(request, response, rememberMeCookie, secure);
317                            CookieKeys.addCookie(request, response, screenNameCookie, secure);
318                    }
319    
320                    AuthenticatedUserUUIDStoreUtil.register(userUUID);
321            }
322    
323            @Override
324            public void logout(HttpServletRequest request, HttpServletResponse response)
325                    throws Exception {
326    
327                    HttpSession session = request.getSession();
328    
329                    EventsProcessorUtil.process(
330                            PropsKeys.LOGOUT_EVENTS_PRE, PropsValues.LOGOUT_EVENTS_PRE, request,
331                            response);
332    
333                    String domain = CookieKeys.getDomain(request);
334    
335                    deleteCookie(request, response, CookieKeys.COMPANY_ID, domain);
336                    deleteCookie(request, response, CookieKeys.GUEST_LANGUAGE_ID, domain);
337                    deleteCookie(request, response, CookieKeys.ID, domain);
338                    deleteCookie(request, response, CookieKeys.PASSWORD, domain);
339    
340                    boolean rememberMe = GetterUtil.getBoolean(
341                            CookieKeys.getCookie(request, CookieKeys.REMEMBER_ME));
342    
343                    if (!rememberMe) {
344                            deleteCookie(request, response, CookieKeys.LOGIN, domain);
345                    }
346    
347                    deleteCookie(request, response, CookieKeys.REMEMBER_ME, domain);
348    
349                    try {
350                            session.invalidate();
351                    }
352                    catch (Exception e) {
353                    }
354    
355                    EventsProcessorUtil.process(
356                            PropsKeys.LOGOUT_EVENTS_POST, PropsValues.LOGOUT_EVENTS_POST,
357                            request, response);
358            }
359    
360            @Override
361            public HttpSession renewSession(
362                            HttpServletRequest request, HttpSession session)
363                    throws Exception {
364    
365                    // Invalidate the previous session to prevent session fixation attacks
366    
367                    String[] protectedAttributeNames =
368                            PropsValues.SESSION_PHISHING_PROTECTED_ATTRIBUTES;
369    
370                    Map<String, Object> protectedAttributes = new HashMap<>();
371    
372                    for (String protectedAttributeName : protectedAttributeNames) {
373                            Object protectedAttributeValue = session.getAttribute(
374                                    protectedAttributeName);
375    
376                            if (protectedAttributeValue == null) {
377                                    continue;
378                            }
379    
380                            protectedAttributes.put(
381                                    protectedAttributeName, protectedAttributeValue);
382                    }
383    
384                    session.invalidate();
385    
386                    session = request.getSession(true);
387    
388                    for (String protectedAttributeName : protectedAttributeNames) {
389                            Object protectedAttributeValue = protectedAttributes.get(
390                                    protectedAttributeName);
391    
392                            if (protectedAttributeValue == null) {
393                                    continue;
394                            }
395    
396                            session.setAttribute(
397                                    protectedAttributeName, protectedAttributeValue);
398                    }
399    
400                    return session;
401            }
402    
403            @Override
404            public void signOutSimultaneousLogins(long userId) throws Exception {
405                    long companyId = CompanyLocalServiceUtil.getCompanyIdByUserId(userId);
406    
407                    Map<String, UserTracker> sessionUsers = LiveUsers.getSessionUsers(
408                            companyId);
409    
410                    List<UserTracker> userTrackers = new ArrayList<>(sessionUsers.values());
411    
412                    for (UserTracker userTracker : userTrackers) {
413                            if (userId != userTracker.getUserId()) {
414                                    continue;
415                            }
416    
417                            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
418    
419                            ClusterNode clusterNode = ClusterExecutorUtil.getLocalClusterNode();
420    
421                            if (clusterNode != null) {
422                                    jsonObject.put("clusterNodeId", clusterNode.getClusterNodeId());
423                            }
424    
425                            jsonObject.put("command", "signOut");
426                            jsonObject.put("companyId", companyId);
427                            jsonObject.put("sessionId", userTracker.getSessionId());
428                            jsonObject.put("userId", userId);
429    
430                            MessageBusUtil.sendMessage(
431                                    DestinationNames.LIVE_USERS, jsonObject.toString());
432                    }
433            }
434    
435            protected void deleteCookie(
436                    HttpServletRequest request, HttpServletResponse response,
437                    String cookieName, String domain) {
438    
439                    Cookie cookie = new Cookie(cookieName, StringPool.BLANK);
440    
441                    if (Validator.isNotNull(domain)) {
442                            cookie.setDomain(domain);
443                    }
444    
445                    cookie.setMaxAge(0);
446                    cookie.setPath(StringPool.SLASH);
447    
448                    CookieKeys.addCookie(request, response, cookie);
449            }
450    
451    }