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 java.io.IOException;
023import java.security.Principal;
024import java.util.HashMap;
025import java.util.List;
026import java.util.Map;
027import java.util.Random;
028import java.util.concurrent.TimeUnit;
029
030import javax.security.auth.login.LoginException;
031import javax.servlet.http.HttpServletRequest;
032import javax.servlet.http.HttpServletResponse;
033import javax.servlet.http.HttpSession;
034
035import org.apache.commons.logging.Log;
036import org.apache.commons.logging.LogFactory;
037import org.nuxeo.common.utils.URIUtils;
038import org.nuxeo.ecm.core.api.NuxeoPrincipal;
039import org.nuxeo.ecm.platform.api.login.UserIdentificationInfo;
040import org.nuxeo.ecm.platform.login.LoginPlugin;
041import org.nuxeo.ecm.platform.login.LoginPluginDescriptor;
042import org.nuxeo.ecm.platform.login.LoginPluginRegistry;
043import org.nuxeo.ecm.platform.ui.web.auth.NXAuthConstants;
044import org.nuxeo.ecm.platform.ui.web.auth.plugins.FormAuthenticator;
045import org.nuxeo.ecm.platform.usermanager.NuxeoPrincipalImpl;
046import org.nuxeo.ecm.platform.usermanager.UserManager;
047import org.nuxeo.runtime.RuntimeService;
048import org.nuxeo.runtime.api.Framework;
049
050import com.duosecurity.DuoWeb;
051import com.google.common.cache.Cache;
052import com.google.common.cache.CacheBuilder;
053import static org.nuxeo.ecm.platform.ui.web.auth.NXAuthConstants.REQUESTED_URL;
054import static org.nuxeo.ecm.platform.ui.web.auth.NXAuthConstants.START_PAGE_SAVE_KEY;
055
056/**
057 * Authentication filter handles two factors authentication via Duo
058 *
059 * @since 5.9.5
060 */
061public class DuoFactorsAuthenticator extends FormAuthenticator {
062
063    private static final Log log = LogFactory.getLog(FormAuthenticator.class);
064
065    private static final String DUO_FACTOR_PAGE = "duofactors.jsp";
066
067    private static final String POST_URL = "nxstartup.faces";
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 + POST_URL;
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            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 Principal createIdentity(String username) throws LoginException {
211        UserManager manager = Framework.getService(UserManager.class);
212        Random random = new Random(System.currentTimeMillis());
213        log.debug("createIdentity: " + username);
214        try {
215            NuxeoPrincipal principal;
216            if (manager == null) {
217                principal = new NuxeoPrincipalImpl(username);
218            } else {
219                principal = manager.getPrincipal(username);
220                if (principal == null) {
221                    throw new LoginException(String.format("principal %s does not exist", username));
222                }
223            }
224            String principalId = String.valueOf(random.nextLong());
225            principal.setPrincipalId(principalId);
226            return principal;
227        } catch (LoginException e) {
228            log.error("createIdentity failed", e);
229            LoginException le = new LoginException("createIdentity failed for" + " user " + username);
230            le.initCause(e);
231            throw le;
232        }
233    }
234
235    protected NuxeoPrincipal validateUserIdentity() throws LoginException {
236        UserManager manager = Framework.getService(UserManager.class);
237        final RuntimeService runtime = Framework.getRuntime();
238        LoginPluginRegistry loginPluginManager = (LoginPluginRegistry) runtime.getComponent(LoginPluginRegistry.NAME);
239        String loginPluginName = userIdent.getLoginPluginName();
240        if (loginPluginName == null) {
241            // we don't use a specific plugin
242            if (manager.checkUsernamePassword(userIdent.getUserName(), userIdent.getPassword())) {
243                return (NuxeoPrincipal) createIdentity(userIdent.getUserName());
244            } else {
245                return null;
246            }
247        } else {
248            LoginPlugin lp = loginPluginManager.getPlugin(loginPluginName);
249            if (lp == null) {
250                log.error("Can't authenticate against a null loginModule " + "plugin");
251                return null;
252            }
253            // set the parameters and reinit if needed
254            LoginPluginDescriptor lpd = loginPluginManager.getPluginDescriptor(loginPluginName);
255            if (!lpd.getInitialized()) {
256                Map<String, String> existingParams = lp.getParameters();
257                if (existingParams == null) {
258                    existingParams = new HashMap<>();
259                }
260                Map<String, String> loginParams = userIdent.getLoginParameters();
261                if (loginParams != null) {
262                    existingParams.putAll(loginParams);
263                }
264                boolean init = lp.initLoginModule();
265                if (init) {
266                    lpd.setInitialized(true);
267                } else {
268                    log.error("Unable to initialize LoginModulePlugin " + lp.getName());
269                    return null;
270                }
271            }
272
273            String username = lp.validatedUserIdentity(userIdent);
274            if (username == null) {
275                return null;
276            } else {
277                return (NuxeoPrincipal) createIdentity(username);
278            }
279        }
280    }
281
282    protected String getRequestedUrl(HttpServletRequest httpRequest) {
283        String completeURI = httpRequest.getRequestURI();
284        String qs = httpRequest.getQueryString();
285        String context = httpRequest.getContextPath() + '/';
286        String requestPage = completeURI.substring(context.length());
287        if (qs != null && qs.length() > 0) {
288            // remove conversationId if present
289            if (qs.contains("conversationId")) {
290                qs = qs.replace("conversationId", "old_conversationId");
291            }
292            requestPage = requestPage + '?' + qs;
293        }
294        return requestPage;
295    }
296}
297