001/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     vpasquier <vpasquier@nuxeo.com>
018 */
019
020package org.nuxeo.duoweb.authentication;
021
022import static org.nuxeo.ecm.platform.ui.web.auth.NXAuthConstants.REQUESTED_URL;
023import static org.nuxeo.ecm.platform.ui.web.auth.NXAuthConstants.START_PAGE_SAVE_KEY;
024
025import java.io.IOException;
026import java.security.Principal;
027import java.security.SecureRandom;
028import java.util.HashMap;
029import java.util.List;
030import java.util.Map;
031import java.util.Random;
032import java.util.concurrent.TimeUnit;
033
034import javax.security.auth.login.LoginException;
035import javax.servlet.http.HttpServletRequest;
036import javax.servlet.http.HttpServletResponse;
037import javax.servlet.http.HttpSession;
038
039import org.apache.commons.logging.Log;
040import org.apache.commons.logging.LogFactory;
041import org.nuxeo.common.utils.URIUtils;
042import org.nuxeo.ecm.core.api.NuxeoPrincipal;
043import org.nuxeo.ecm.platform.api.login.UserIdentificationInfo;
044import org.nuxeo.ecm.platform.login.LoginPlugin;
045import org.nuxeo.ecm.platform.login.LoginPluginDescriptor;
046import org.nuxeo.ecm.platform.login.LoginPluginRegistry;
047import org.nuxeo.ecm.platform.ui.web.auth.LoginScreenHelper;
048import org.nuxeo.ecm.platform.ui.web.auth.NXAuthConstants;
049import org.nuxeo.ecm.platform.ui.web.auth.plugins.FormAuthenticator;
050import org.nuxeo.ecm.platform.usermanager.NuxeoPrincipalImpl;
051import org.nuxeo.ecm.platform.usermanager.UserManager;
052import org.nuxeo.runtime.RuntimeService;
053import org.nuxeo.runtime.api.Framework;
054
055import com.duosecurity.DuoWeb;
056import com.google.common.cache.Cache;
057import com.google.common.cache.CacheBuilder;
058
059/**
060 * Authentication filter handles two factors authentication via Duo
061 *
062 * @since 5.9.5
063 */
064public class DuoFactorsAuthenticator extends FormAuthenticator {
065
066    private static final Log log = LogFactory.getLog(FormAuthenticator.class);
067
068    protected static final Random RANDOM = new SecureRandom();
069
070    private static final String DUO_FACTOR_PAGE = "duofactors.jsp";
071
072    private static final String SIG_REQUEST = "sig_request";
073
074    private static final String SIG_RESPONSE = "sig_response";
075
076    private static final String HOST_REQUEST = "host";
077
078    private static final String POST_ACTION = "post_action";
079
080    private static final String ONE_FACTOR_CHECK = "oneFactorCheck";
081
082    private static final String TWO_FACTORS_CHECK = "twoFactorsCheck";
083
084    private static final String HASHCODE = "hash";
085
086    protected static final Integer CACHE_CONCURRENCY_LEVEL = 10;
087
088    protected static final Integer CACHE_MAXIMUM_SIZE = 1000;
089
090    // DuoWeb timeout is 1 minute => taking 4 minutes in case
091    protected static final Integer CACHE_TIMEOUT = 4;
092
093    private UserIdentificationInfo userIdent;
094
095    private String IKEY;
096
097    private String SKEY;
098
099    private String AKEY;
100
101    private String HOST;
102
103    private Cache<String, UserIdentificationInfo> credentials = CacheBuilder.newBuilder().concurrencyLevel(CACHE_CONCURRENCY_LEVEL).maximumSize(
104            CACHE_MAXIMUM_SIZE).expireAfterWrite(CACHE_TIMEOUT, TimeUnit.MINUTES).build();
105
106    @Override
107    public Boolean handleLoginPrompt(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String baseURL) {
108        HttpSession session = httpRequest.getSession(false);
109        if (session == null || session.getAttribute(ONE_FACTOR_CHECK) == null
110                || !(Boolean) session.getAttribute(ONE_FACTOR_CHECK)) {
111            if (session != null)
112                session.setAttribute(START_PAGE_SAVE_KEY, getRequestedUrl
113                        (httpRequest));
114            super.handleLoginPrompt(httpRequest, httpResponse, baseURL);
115            return Boolean.TRUE;
116        } else if ((Boolean) session.getAttribute(ONE_FACTOR_CHECK)
117                && (session.getAttribute(TWO_FACTORS_CHECK) == null || !(Boolean) session.getAttribute(TWO_FACTORS_CHECK))) {
118            String redirectUrl = baseURL + DUO_FACTOR_PAGE;
119            String postUrl = baseURL + LoginScreenHelper.getStartupPagePath();
120            Map<String, String> parameters = new HashMap<>();
121            try {
122                String userName = httpRequest.getParameter(usernameKey);
123                if (userName == null) {
124                    session.setAttribute(ONE_FACTOR_CHECK, Boolean.FALSE);
125                    return Boolean.FALSE;
126                }
127                String request_sig = DuoWeb.signRequest(IKEY, SKEY, AKEY, userName);
128                parameters.put(SIG_REQUEST, request_sig);
129                parameters.put(HOST_REQUEST, HOST);
130                // Handle callback context
131                String key = Integer.toHexString(userIdent.hashCode());
132                credentials.put(key, userIdent);
133                parameters.put(POST_ACTION, postUrl + "?" + HASHCODE + "=" + key);
134                parameters.put(REQUESTED_URL, httpRequest.getParameter(REQUESTED_URL));
135                redirectUrl = URIUtils.addParametersToURIQuery(redirectUrl, parameters);
136                httpResponse.sendRedirect(redirectUrl);
137            } catch (IOException e) {
138                log.error(e, e);
139                return Boolean.FALSE;
140            }
141        }
142        return Boolean.TRUE;
143    }
144
145    @Override
146    public UserIdentificationInfo handleRetrieveIdentity(HttpServletRequest httpRequest,
147            HttpServletResponse httpResponse) {
148        HttpSession session = httpRequest.getSession(false);
149        if (session == null) {
150            return null;
151        }
152        if (session.getAttribute(ONE_FACTOR_CHECK) == null || !(Boolean) session.getAttribute(ONE_FACTOR_CHECK)) {
153            userIdent = super.handleRetrieveIdentity(httpRequest, httpResponse);
154            session = httpRequest.getSession(true);
155            if (userIdent != null) {
156                try {
157                    NuxeoPrincipal principal = validateUserIdentity();
158                    if (principal != null) {
159                        session.setAttribute(ONE_FACTOR_CHECK, Boolean.TRUE);
160                        return null;
161                    } else {
162                        httpRequest.setAttribute(NXAuthConstants.LOGIN_ERROR, NXAuthConstants.LOGIN_FAILED);
163                        return null;
164                    }
165                } catch (LoginException e) {
166                    log.error(e, e);
167                    return null;
168                }
169            } else {
170                session.setAttribute(ONE_FACTOR_CHECK, Boolean.FALSE);
171                return null;
172            }
173        } else if (session.getAttribute(TWO_FACTORS_CHECK) == null
174                || !(Boolean) session.getAttribute(TWO_FACTORS_CHECK)) {
175            String sigResponse = httpRequest.getParameter(SIG_RESPONSE);
176            String hashResponse = httpRequest.getParameter(HASHCODE);
177            String response = DuoWeb.verifyResponse(IKEY, SKEY, AKEY, sigResponse);
178            userIdent = credentials.getIfPresent(hashResponse);
179            session.setAttribute(TWO_FACTORS_CHECK, response != null ? Boolean.TRUE : Boolean.FALSE);
180            if (response == null) {
181                return null;
182            }
183            return userIdent;
184        }
185        return userIdent;
186    }
187
188    @Override
189    public Boolean needLoginPrompt(HttpServletRequest httpRequest) {
190        return true;
191    }
192
193    @Override
194    public void initPlugin(Map<String, String> parameters) {
195        if (parameters.get("IKEY") != null) {
196            IKEY = parameters.get("IKEY");
197        }
198        if (parameters.get("SKEY") != null) {
199            SKEY = parameters.get("SKEY");
200        }
201        if (parameters.get("AKEY") != null) {
202            AKEY = parameters.get("AKEY");
203        }
204        if (parameters.get("HOST") != null) {
205            HOST = parameters.get("HOST");
206        }
207    }
208
209    @Override
210    public List<String> getUnAuthenticatedURLPrefix() {
211        return null;
212    }
213
214    public NuxeoPrincipal createIdentity(String username) throws LoginException {
215        UserManager manager = Framework.getService(UserManager.class);
216        log.debug("createIdentity: " + username);
217        try {
218            NuxeoPrincipal principal;
219            if (manager == null) {
220                principal = new NuxeoPrincipalImpl(username);
221            } else {
222                principal = Framework.doPrivileged(() -> manager.getPrincipal(username));
223                if (principal == null) {
224                    throw new LoginException(String.format("principal %s does not exist", username));
225                }
226            }
227            String principalId = String.valueOf(RANDOM.nextLong());
228            principal.setPrincipalId(principalId);
229            return principal;
230        } catch (LoginException e) {
231            log.error("createIdentity failed", e);
232            LoginException le = new LoginException("createIdentity failed for" + " user " + username);
233            le.initCause(e);
234            throw le;
235        }
236    }
237
238    protected NuxeoPrincipal validateUserIdentity() throws LoginException {
239        UserManager manager = Framework.getService(UserManager.class);
240        final RuntimeService runtime = Framework.getRuntime();
241        LoginPluginRegistry loginPluginManager = (LoginPluginRegistry) runtime.getComponent(LoginPluginRegistry.NAME);
242        String loginPluginName = userIdent.getLoginPluginName();
243        if (loginPluginName == null) {
244            // we don't use a specific plugin
245            if (manager.checkUsernamePassword(userIdent.getUserName(), userIdent.getPassword())) {
246                return createIdentity(userIdent.getUserName());
247            } else {
248                return null;
249            }
250        } else {
251            LoginPlugin lp = loginPluginManager.getPlugin(loginPluginName);
252            if (lp == null) {
253                log.error("Can't authenticate against a null loginModule " + "plugin");
254                return null;
255            }
256            // set the parameters and reinit if needed
257            LoginPluginDescriptor lpd = loginPluginManager.getPluginDescriptor(loginPluginName);
258            if (!lpd.getInitialized()) {
259                Map<String, String> existingParams = lp.getParameters();
260                if (existingParams == null) {
261                    existingParams = new HashMap<>();
262                }
263                Map<String, String> loginParams = userIdent.getLoginParameters();
264                if (loginParams != null) {
265                    existingParams.putAll(loginParams);
266                }
267                boolean init = lp.initLoginModule();
268                if (init) {
269                    lpd.setInitialized(true);
270                } else {
271                    log.error("Unable to initialize LoginModulePlugin " + lp.getName());
272                    return null;
273                }
274            }
275
276            String username = lp.validatedUserIdentity(userIdent);
277            if (username == null) {
278                return null;
279            } else {
280                return createIdentity(username);
281            }
282        }
283    }
284
285    protected String getRequestedUrl(HttpServletRequest httpRequest) {
286        String completeURI = httpRequest.getRequestURI();
287        String qs = httpRequest.getQueryString();
288        String context = httpRequest.getContextPath() + '/';
289        String requestPage = completeURI.substring(context.length());
290        if (qs != null && qs.length() > 0) {
291            // remove conversationId if present
292            if (qs.contains("conversationId")) {
293                qs = qs.replace("conversationId", "old_conversationId");
294            }
295            requestPage = requestPage + '?' + qs;
296        }
297        return requestPage;
298    }
299}
300