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