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