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.SecureRandom;
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.ui.web.auth.LoginScreenHelper;
044import org.nuxeo.ecm.platform.ui.web.auth.NXAuthConstants;
045import org.nuxeo.ecm.platform.ui.web.auth.plugins.FormAuthenticator;
046import org.nuxeo.ecm.platform.usermanager.NuxeoPrincipalImpl;
047import org.nuxeo.ecm.platform.usermanager.UserManager;
048import org.nuxeo.runtime.RuntimeService;
049import org.nuxeo.runtime.api.Framework;
050
051import com.duosecurity.DuoWeb;
052import com.google.common.cache.Cache;
053import com.google.common.cache.CacheBuilder;
054
055/**
056 * Authentication filter handles two factors authentication via Duo
057 *
058 * @since 5.9.5
059 */
060public class DuoFactorsAuthenticator extends FormAuthenticator {
061
062    private static final Log log = LogFactory.getLog(FormAuthenticator.class);
063
064    protected static final Random RANDOM = new SecureRandom();
065
066    private static final String DUO_FACTOR_PAGE = "duofactors.jsp";
067
068    private static final String SIG_REQUEST = "sig_request";
069
070    private static final String SIG_RESPONSE = "sig_response";
071
072    private static final String HOST_REQUEST = "host";
073
074    private static final String POST_ACTION = "post_action";
075
076    private static final String ONE_FACTOR_CHECK = "oneFactorCheck";
077
078    private static final String TWO_FACTORS_CHECK = "twoFactorsCheck";
079
080    private static final String HASHCODE = "hash";
081
082    protected static final Integer CACHE_CONCURRENCY_LEVEL = 10;
083
084    protected static final Integer CACHE_MAXIMUM_SIZE = 1000;
085
086    // DuoWeb timeout is 1 minute => taking 4 minutes in case
087    protected static final Integer CACHE_TIMEOUT = 4;
088
089    private UserIdentificationInfo userIdent;
090
091    private String IKEY;
092
093    private String SKEY;
094
095    private String AKEY;
096
097    private String HOST;
098
099    private Cache<String, UserIdentificationInfo> credentials = CacheBuilder.newBuilder().concurrencyLevel(CACHE_CONCURRENCY_LEVEL).maximumSize(
100            CACHE_MAXIMUM_SIZE).expireAfterWrite(CACHE_TIMEOUT, TimeUnit.MINUTES).build();
101
102    @Override
103    public Boolean handleLoginPrompt(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String baseURL) {
104        HttpSession session = httpRequest.getSession(false);
105        if (session == null || session.getAttribute(ONE_FACTOR_CHECK) == null
106                || !(Boolean) session.getAttribute(ONE_FACTOR_CHECK)) {
107            if (session != null)
108                session.setAttribute(START_PAGE_SAVE_KEY, getRequestedUrl
109                        (httpRequest));
110            super.handleLoginPrompt(httpRequest, httpResponse, baseURL);
111            return Boolean.TRUE;
112        } else if ((Boolean) session.getAttribute(ONE_FACTOR_CHECK)
113                && (session.getAttribute(TWO_FACTORS_CHECK) == null || !(Boolean) session.getAttribute(TWO_FACTORS_CHECK))) {
114            String redirectUrl = baseURL + DUO_FACTOR_PAGE;
115            String postUrl = baseURL + LoginScreenHelper.getStartupPagePath();
116            Map<String, String> parameters = new HashMap<>();
117            try {
118                String userName = httpRequest.getParameter(usernameKey);
119                if (userName == null) {
120                    session.setAttribute(ONE_FACTOR_CHECK, Boolean.FALSE);
121                    return Boolean.FALSE;
122                }
123                String request_sig = DuoWeb.signRequest(IKEY, SKEY, AKEY, userName);
124                parameters.put(SIG_REQUEST, request_sig);
125                parameters.put(HOST_REQUEST, HOST);
126                // Handle callback context
127                String key = Integer.toHexString(userIdent.hashCode());
128                credentials.put(key, userIdent);
129                parameters.put(POST_ACTION, postUrl + "?" + HASHCODE + "=" + key);
130                parameters.put(REQUESTED_URL, httpRequest.getParameter(REQUESTED_URL));
131                redirectUrl = URIUtils.addParametersToURIQuery(redirectUrl, parameters);
132                httpResponse.sendRedirect(redirectUrl);
133            } catch (IOException e) {
134                log.error(e, e);
135                return Boolean.FALSE;
136            }
137        }
138        return Boolean.TRUE;
139    }
140
141    @Override
142    public UserIdentificationInfo handleRetrieveIdentity(HttpServletRequest httpRequest,
143            HttpServletResponse httpResponse) {
144        HttpSession session = httpRequest.getSession(false);
145        if (session == null) {
146            return null;
147        }
148        if (session.getAttribute(ONE_FACTOR_CHECK) == null || !(Boolean) session.getAttribute(ONE_FACTOR_CHECK)) {
149            userIdent = super.handleRetrieveIdentity(httpRequest, httpResponse);
150            session = httpRequest.getSession(true);
151            if (userIdent != null) {
152                try {
153                    NuxeoPrincipal principal = validateUserIdentity();
154                    if (principal != null) {
155                        session.setAttribute(ONE_FACTOR_CHECK, Boolean.TRUE);
156                        return null;
157                    } else {
158                        httpRequest.setAttribute(NXAuthConstants.LOGIN_ERROR, NXAuthConstants.LOGIN_FAILED);
159                        return null;
160                    }
161                } catch (LoginException e) {
162                    log.error(e, e);
163                    return null;
164                }
165            } else {
166                session.setAttribute(ONE_FACTOR_CHECK, Boolean.FALSE);
167                return null;
168            }
169        } else if (session.getAttribute(TWO_FACTORS_CHECK) == null
170                || !(Boolean) session.getAttribute(TWO_FACTORS_CHECK)) {
171            String sigResponse = httpRequest.getParameter(SIG_RESPONSE);
172            String hashResponse = httpRequest.getParameter(HASHCODE);
173            String response = DuoWeb.verifyResponse(IKEY, SKEY, AKEY, sigResponse);
174            userIdent = credentials.getIfPresent(hashResponse);
175            session.setAttribute(TWO_FACTORS_CHECK, response != null ? Boolean.TRUE : Boolean.FALSE);
176            if (response == null) {
177                return null;
178            }
179            return userIdent;
180        }
181        return userIdent;
182    }
183
184    @Override
185    public Boolean needLoginPrompt(HttpServletRequest httpRequest) {
186        return true;
187    }
188
189    @Override
190    public void initPlugin(Map<String, String> parameters) {
191        if (parameters.get("IKEY") != null) {
192            IKEY = parameters.get("IKEY");
193        }
194        if (parameters.get("SKEY") != null) {
195            SKEY = parameters.get("SKEY");
196        }
197        if (parameters.get("AKEY") != null) {
198            AKEY = parameters.get("AKEY");
199        }
200        if (parameters.get("HOST") != null) {
201            HOST = parameters.get("HOST");
202        }
203    }
204
205    @Override
206    public List<String> getUnAuthenticatedURLPrefix() {
207        return null;
208    }
209
210    public NuxeoPrincipal createIdentity(String username) throws LoginException {
211        UserManager manager = Framework.getService(UserManager.class);
212        log.debug("createIdentity: " + username);
213        try {
214            NuxeoPrincipal principal;
215            if (manager == null) {
216                principal = new NuxeoPrincipalImpl(username);
217            } else {
218                principal = Framework.doPrivileged(() -> manager.getPrincipal(username));
219                if (principal == null) {
220                    throw new LoginException(String.format("principal %s does not exist", username));
221                }
222            }
223            String principalId = String.valueOf(RANDOM.nextLong());
224            principal.setPrincipalId(principalId);
225            return principal;
226        } catch (LoginException e) {
227            log.error("createIdentity failed", e);
228            LoginException le = new LoginException("createIdentity failed for" + " user " + username);
229            le.initCause(e);
230            throw le;
231        }
232    }
233
234    protected NuxeoPrincipal validateUserIdentity() throws LoginException {
235        UserManager manager = Framework.getService(UserManager.class);
236        if (manager.checkUsernamePassword(userIdent.getUserName(), userIdent.getPassword())) {
237            return createIdentity(userIdent.getUserName());
238        } else {
239            return null;
240        }
241    }
242
243    protected String getRequestedUrl(HttpServletRequest httpRequest) {
244        String completeURI = httpRequest.getRequestURI();
245        String qs = httpRequest.getQueryString();
246        String context = httpRequest.getContextPath() + '/';
247        String requestPage = completeURI.substring(context.length());
248        if (qs != null && qs.length() > 0) {
249            // remove conversationId if present
250            if (qs.contains("conversationId")) {
251                qs = qs.replace("conversationId", "old_conversationId");
252            }
253            requestPage = requestPage + '?' + qs;
254        }
255        return requestPage;
256    }
257}