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