Search in sources :

Example 1 with AuthResult

use of com.google.gerrit.server.account.AuthResult in project gerrit by GerritCodeReview.

the class ProjectBasicAuthFilter method verify.

private boolean verify(HttpServletRequest req, Response rsp) throws IOException {
    final String hdr = req.getHeader(AUTHORIZATION);
    if (hdr == null || !hdr.startsWith(LIT_BASIC)) {
        // session cookie instead of basic authentication.
        return true;
    }
    final byte[] decoded = Base64.decodeBase64(hdr.substring(LIT_BASIC.length()));
    String usernamePassword = new String(decoded, encoding(req));
    int splitPos = usernamePassword.indexOf(':');
    if (splitPos < 1) {
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
    String username = usernamePassword.substring(0, splitPos);
    String password = usernamePassword.substring(splitPos + 1);
    if (Strings.isNullOrEmpty(password)) {
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
    if (authConfig.isUserNameToLowerCase()) {
        username = username.toLowerCase(Locale.US);
    }
    final AccountState who = accountCache.getByUsername(username);
    if (who == null || !who.getAccount().isActive()) {
        log.warn("Authentication failed for " + username + ": account inactive or not provisioned in Gerrit");
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
    GitBasicAuthPolicy gitBasicAuthPolicy = authConfig.getGitBasicAuthPolicy();
    if (gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP || gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP_LDAP) {
        if (who.checkPassword(password, username)) {
            return succeedAuthentication(who);
        }
    }
    if (gitBasicAuthPolicy == GitBasicAuthPolicy.HTTP) {
        return failAuthentication(rsp, username);
    }
    AuthRequest whoAuth = AuthRequest.forUser(username);
    whoAuth.setPassword(password);
    try {
        AuthResult whoAuthResult = accountManager.authenticate(whoAuth);
        setUserIdentified(whoAuthResult.getAccountId());
        return true;
    } catch (NoSuchUserException e) {
        if (who.checkPassword(password, who.getUserName())) {
            return succeedAuthentication(who);
        }
        log.warn("Authentication failed for " + username, e);
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    } catch (AuthenticationFailedException e) {
        log.warn("Authentication failed for " + username + ": " + e.getMessage());
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    } catch (AccountException e) {
        log.warn("Authentication failed for " + username, e);
        rsp.sendError(SC_UNAUTHORIZED);
        return false;
    }
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountException(com.google.gerrit.server.account.AccountException) AuthenticationFailedException(com.google.gerrit.server.account.AuthenticationFailedException) NoSuchUserException(com.google.gerrit.server.auth.NoSuchUserException) GitBasicAuthPolicy(com.google.gerrit.extensions.client.GitBasicAuthPolicy) AuthResult(com.google.gerrit.server.account.AuthResult) AccountState(com.google.gerrit.server.account.AccountState)

Example 2 with AuthResult

use of com.google.gerrit.server.account.AuthResult in project gerrit by GerritCodeReview.

the class HttpsClientSslCertAuthFilter method doFilter.

@Override
public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException {
    X509Certificate[] certs = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
    if (certs == null || certs.length == 0) {
        throw new ServletException("Couldn't get the attribute javax.servlet.request.X509Certificate from the request");
    }
    String name = certs[0].getSubjectDN().getName();
    Matcher m = REGEX_USERID.matcher(name);
    String userName;
    if (m.find()) {
        userName = m.group(1);
    } else {
        throw new ServletException("Couldn't extract username from your certificate");
    }
    final AuthRequest areq = AuthRequest.forUser(userName);
    final AuthResult arsp;
    try {
        arsp = accountManager.authenticate(areq);
    } catch (AccountException e) {
        String err = "Unable to authenticate user \"" + userName + "\"";
        log.error(err, e);
        throw new ServletException(err, e);
    }
    webSession.get().login(arsp, true);
    chain.doFilter(req, rsp);
}
Also used : ServletException(javax.servlet.ServletException) AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountException(com.google.gerrit.server.account.AccountException) Matcher(java.util.regex.Matcher) AuthResult(com.google.gerrit.server.account.AuthResult) X509Certificate(java.security.cert.X509Certificate)

Example 3 with AuthResult

use of com.google.gerrit.server.account.AuthResult in project gerrit by GerritCodeReview.

the class LdapLoginServlet method doPost.

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    req.setCharacterEncoding(UTF_8.name());
    String username = Strings.nullToEmpty(req.getParameter("username")).trim();
    String password = Strings.nullToEmpty(req.getParameter("password"));
    String remember = Strings.nullToEmpty(req.getParameter("rememberme"));
    if (username.isEmpty() || password.isEmpty()) {
        sendForm(req, res, "Invalid username or password.");
        return;
    }
    AuthRequest areq = AuthRequest.forUser(username);
    areq.setPassword(password);
    AuthResult ares;
    try {
        ares = accountManager.authenticate(areq);
    } catch (AccountUserNameException e) {
        sendForm(req, res, e.getMessage());
        return;
    } catch (AuthenticationUnavailableException e) {
        sendForm(req, res, "Authentication unavailable at this time.");
        return;
    } catch (AccountException e) {
        log.info(String.format("'%s' failed to sign in: %s", username, e.getMessage()));
        sendForm(req, res, "Invalid username or password.");
        return;
    } catch (RuntimeException e) {
        log.error("LDAP authentication failed", e);
        sendForm(req, res, "Authentication unavailable at this time.");
        return;
    }
    StringBuilder dest = new StringBuilder();
    dest.append(urlProvider.get(req));
    dest.append(LoginUrlToken.getToken(req));
    CacheHeaders.setNotCacheable(res);
    webSession.get().login(ares, "1".equals(remember));
    res.sendRedirect(dest.toString());
}
Also used : AuthRequest(com.google.gerrit.server.account.AuthRequest) AccountUserNameException(com.google.gerrit.server.account.AccountUserNameException) AuthenticationUnavailableException(com.google.gerrit.server.auth.AuthenticationUnavailableException) AccountException(com.google.gerrit.server.account.AccountException) AuthResult(com.google.gerrit.server.account.AuthResult)

Example 4 with AuthResult

use of com.google.gerrit.server.account.AuthResult in project gerrit by GerritCodeReview.

the class OAuthSessionOverOpenID method authenticateAndRedirect.

private void authenticateAndRedirect(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
    com.google.gerrit.server.account.AuthRequest areq = new com.google.gerrit.server.account.AuthRequest(ExternalId.Key.parse(user.getExternalId()));
    AuthResult arsp = null;
    try {
        String claimedIdentifier = user.getClaimedIdentity();
        Optional<Account.Id> actualId = accountManager.lookup(user.getExternalId());
        Optional<Account.Id> claimedId = Optional.empty();
        // That why we query it here, not to lose linking mode.
        if (!Strings.isNullOrEmpty(claimedIdentifier)) {
            claimedId = accountManager.lookup(claimedIdentifier);
            if (!claimedId.isPresent()) {
                log.debug("Claimed identity is unknown");
            }
        }
        // and user account exists for this identity
        if (claimedId.isPresent()) {
            log.debug("Claimed identity is set and is known");
            if (actualId.isPresent()) {
                if (claimedId.get().equals(actualId.get())) {
                    // Both link to the same account, that's what we expected.
                    log.debug("Both link to the same account. All is fine.");
                } else {
                    // This is (for now) a fatal error. There are two records
                    // for what might be the same user. The admin would have to
                    // link the accounts manually.
                    log.error("OAuth accounts disagree over user identity:\n" + "  Claimed ID: " + claimedId.get() + " is " + claimedIdentifier + "\n" + "  Delgate ID: " + actualId.get() + " is " + user.getExternalId());
                    rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            } else {
                // Claimed account already exists: link to it.
                log.debug("Claimed account already exists: link to it.");
                try {
                    accountManager.link(claimedId.get(), areq);
                } catch (OrmException | ConfigInvalidException e) {
                    log.error("Cannot link: " + user.getExternalId() + " to user identity:\n" + "  Claimed ID: " + claimedId.get() + " is " + claimedIdentifier);
                    rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            }
        } else if (linkMode) {
            // Use case 2: link mode activated from the UI
            Account.Id accountId = identifiedUser.get().getAccountId();
            try {
                log.debug("Linking \"{}\" to \"{}\"", user.getExternalId(), accountId);
                accountManager.link(accountId, areq);
            } catch (OrmException | ConfigInvalidException e) {
                log.error("Cannot link: " + user.getExternalId() + " to user identity: " + accountId);
                rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            } finally {
                linkMode = false;
            }
        }
        areq.setUserName(user.getUserName());
        areq.setEmailAddress(user.getEmailAddress());
        areq.setDisplayName(user.getDisplayName());
        arsp = accountManager.authenticate(areq);
    } catch (AccountException e) {
        log.error("Unable to authenticate user \"" + user + "\"", e);
        rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    webSession.get().login(arsp, true);
    StringBuilder rdr = new StringBuilder(urlProvider.get(req));
    rdr.append(Url.decode(redirectToken));
    rsp.sendRedirect(rdr.toString());
}
Also used : ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) AuthResult(com.google.gerrit.server.account.AuthResult) AccountException(com.google.gerrit.server.account.AccountException) OrmException(com.google.gwtorm.server.OrmException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId)

Example 5 with AuthResult

use of com.google.gerrit.server.account.AuthResult in project gerrit by GerritCodeReview.

the class BecomeAnyAccountLoginServlet method doPost.

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException, ServletException {
    CacheHeaders.setNotCacheable(rsp);
    final AuthResult res;
    if ("create_account".equals(req.getParameter("action"))) {
        res = create();
    } else if (req.getParameter("user_name") != null) {
        res = byUserName(req.getParameter("user_name"));
    } else if (req.getParameter("preferred_email") != null) {
        res = byPreferredEmail(req.getParameter("preferred_email"));
    } else if (req.getParameter("account_id") != null) {
        res = byAccountId(req.getParameter("account_id"));
    } else {
        byte[] raw;
        try {
            raw = prepareHtmlOutput();
        } catch (OrmException e) {
            throw new ServletException(e);
        }
        rsp.setContentType("text/html");
        rsp.setCharacterEncoding(HtmlDomUtil.ENC.name());
        rsp.setContentLength(raw.length);
        try (OutputStream out = rsp.getOutputStream()) {
            out.write(raw);
        }
        return;
    }
    if (res != null) {
        webSession.get().login(res, false);
        final StringBuilder rdr = new StringBuilder();
        rdr.append(req.getContextPath());
        rdr.append("/");
        if (res.isNew()) {
            rdr.append('#' + PageLinks.REGISTER);
        } else {
            rdr.append(LoginUrlToken.getToken(req));
        }
        rsp.sendRedirect(rdr.toString());
    } else {
        rsp.setContentType("text/html");
        rsp.setCharacterEncoding(HtmlDomUtil.ENC.name());
        try (Writer out = rsp.getWriter()) {
            out.write("<html>");
            out.write("<body>");
            out.write("<h1>Account Not Found</h1>");
            out.write("</body>");
            out.write("</html>");
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) OrmException(com.google.gwtorm.server.OrmException) OutputStream(java.io.OutputStream) AuthResult(com.google.gerrit.server.account.AuthResult) Writer(java.io.Writer)

Aggregations

AuthResult (com.google.gerrit.server.account.AuthResult)8 AccountException (com.google.gerrit.server.account.AccountException)7 AuthRequest (com.google.gerrit.server.account.AuthRequest)6 OrmException (com.google.gwtorm.server.OrmException)3 AccountState (com.google.gerrit.server.account.AccountState)2 ServletException (javax.servlet.ServletException)2 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)2 GitBasicAuthPolicy (com.google.gerrit.extensions.client.GitBasicAuthPolicy)1 AccountUserNameException (com.google.gerrit.server.account.AccountUserNameException)1 AuthenticationFailedException (com.google.gerrit.server.account.AuthenticationFailedException)1 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)1 AuthenticationUnavailableException (com.google.gerrit.server.auth.AuthenticationUnavailableException)1 NoSuchUserException (com.google.gerrit.server.auth.NoSuchUserException)1 OutputStream (java.io.OutputStream)1 Writer (java.io.Writer)1 X509Certificate (java.security.cert.X509Certificate)1 Matcher (java.util.regex.Matcher)1 ServletOutputStream (javax.servlet.ServletOutputStream)1 Cookie (javax.servlet.http.Cookie)1 Document (org.w3c.dom.Document)1