use of com.zimbra.cs.account.AuthToken.TokenType in project zm-mailbox by Zimbra.
the class Auth method handle.
@Override
public Element handle(Element request, Map<String, Object> context) throws ServiceException {
ZimbraSoapContext zsc = getZimbraSoapContext(context);
Provisioning prov = Provisioning.getInstance();
// Look up the specified account. It is optional in the <authToken> case.
String acctValuePassedIn = null, acctValue = null, acctByStr = null;
AccountBy acctBy = null;
Account acct = null;
Element acctEl = request.getOptionalElement(AccountConstants.E_ACCOUNT);
boolean csrfSupport = request.getAttributeBool(AccountConstants.A_CSRF_SUPPORT, false);
String reqTokenType = request.getAttribute(AccountConstants.A_TOKEN_TYPE, "");
TokenType tokenType = TokenType.fromCode(reqTokenType);
if (TokenType.JWT.equals(tokenType)) {
// in case of jwt, csrfSupport has no significance
csrfSupport = false;
}
ZimbraLog.account.debug("auth: reqTokenType: %s, tokenType: %s", reqTokenType, tokenType);
if (acctEl != null) {
acctValuePassedIn = acctEl.getText();
acctValue = acctValuePassedIn;
acctByStr = acctEl.getAttribute(AccountConstants.A_BY, AccountBy.name.name());
acctBy = AccountBy.fromString(acctByStr);
if (acctBy == AccountBy.name) {
Element virtualHostEl = request.getOptionalElement(AccountConstants.E_VIRTUAL_HOST);
String virtualHost = virtualHostEl == null ? null : virtualHostEl.getText().toLowerCase();
if (virtualHost != null && acctValue.indexOf('@') == -1) {
Domain d = prov.get(Key.DomainBy.virtualHostname, virtualHost);
if (d != null)
acctValue = acctValue + "@" + d.getName();
}
}
acct = prov.get(acctBy, acctValue);
}
TrustedDeviceToken trustedToken = null;
if (acct != null) {
TrustedDevices trustedDeviceManager = TwoFactorAuth.getFactory().getTrustedDevices(acct);
if (trustedDeviceManager != null) {
trustedToken = trustedDeviceManager.getTokenFromRequest(request, context);
if (trustedToken != null && trustedToken.isExpired()) {
TrustedDevice device = trustedDeviceManager.getTrustedDeviceByTrustedToken(trustedToken);
if (device != null) {
device.revoke();
}
}
}
}
String password = request.getAttribute(AccountConstants.E_PASSWORD, null);
String recoveryCode = request.getAttribute(AccountConstants.E_RECOVERY_CODE, null);
boolean generateDeviceId = request.getAttributeBool(AccountConstants.A_GENERATE_DEVICE_ID, false);
String twoFactorCode = request.getAttribute(AccountConstants.E_TWO_FACTOR_CODE, null);
String newDeviceId = generateDeviceId ? UUIDUtil.generateUUID() : null;
Element authTokenEl = request.getOptionalElement(AccountConstants.E_AUTH_TOKEN);
Element jwtTokenElement = request.getOptionalElement(AccountConstants.E_JWT_TOKEN);
boolean validationSuccess = tokenTypeAndElementValidation(tokenType, authTokenEl, jwtTokenElement);
if (!validationSuccess) {
throw AuthFailedServiceException.AUTH_FAILED("auth: incorrect tokenType and Element combination");
}
boolean acctAutoProvisioned = false;
Claims claims = null;
// if jwtToken is present in request then use it
if (jwtTokenElement != null && authTokenEl == null) {
String jwt = jwtTokenElement.getText();
String salt = JWTUtil.getSalt(null, context);
claims = JWTUtil.validateJWT(jwt, salt);
acct = prov.getAccountById(claims.getSubject());
if (acct == null) {
throw AccountServiceException.NO_SUCH_ACCOUNT(claims.getSubject());
}
acctAutoProvisioned = true;
}
// if authToken is present in request then use it
if (authTokenEl != null) {
boolean verifyAccount = authTokenEl.getAttributeBool(AccountConstants.A_VERIFY_ACCOUNT, false);
if (verifyAccount && acctEl == null) {
throw ServiceException.INVALID_REQUEST("missing required element: " + AccountConstants.E_ACCOUNT, null);
}
try {
AuthToken at = AuthProvider.getAuthToken(authTokenEl, acct);
addAccountToLogContextByAuthToken(prov, at);
// so the account will show in log context
if (!checkPasswordSecurity(context))
throw ServiceException.INVALID_REQUEST("clear text password is not allowed", null);
AuthToken.Usage usage = at.getUsage();
if (usage != Usage.AUTH && usage != Usage.TWO_FACTOR_AUTH) {
throw AuthFailedServiceException.AUTH_FAILED("invalid auth token");
}
Account authTokenAcct = AuthProvider.validateAuthToken(prov, at, false, usage);
if (verifyAccount) {
// can treat the auth token as an opaque string.
if (acct == null || !acct.getId().equalsIgnoreCase(authTokenAcct.getId())) {
throw new AuthTokenException("auth token doesn't match the named account");
}
}
if (usage == Usage.AUTH) {
ServletRequest httpReq = (ServletRequest) context.get(SoapServlet.SERVLET_REQUEST);
httpReq.setAttribute(CsrfFilter.AUTH_TOKEN, at);
if (csrfSupport && !at.isCsrfTokenEnabled()) {
// handle case where auth token was originally generated with csrf support
// and now client sends the same auth token but saying csrfSupport is turned off
// in that case do not disable CSRF check for this authToken.
at.setCsrfTokenEnabled(csrfSupport);
}
return doResponse(request, at, zsc, context, authTokenAcct, csrfSupport, trustedToken, newDeviceId);
} else {
acct = authTokenAcct;
}
} catch (AuthTokenException e) {
throw ServiceException.AUTH_REQUIRED();
}
}
if (!checkPasswordSecurity(context)) {
throw ServiceException.INVALID_REQUEST("clear text password is not allowed", null);
}
Element preAuthEl = request.getOptionalElement(AccountConstants.E_PREAUTH);
String deviceId = request.getAttribute(AccountConstants.E_DEVICE_ID, null);
long expires = 0;
Map<String, Object> authCtxt = new HashMap<String, Object>();
authCtxt.put(AuthContext.AC_ORIGINATING_CLIENT_IP, context.get(SoapEngine.ORIG_REQUEST_IP));
authCtxt.put(AuthContext.AC_REMOTE_IP, context.get(SoapEngine.SOAP_REQUEST_IP));
authCtxt.put(AuthContext.AC_ACCOUNT_NAME_PASSEDIN, acctValuePassedIn);
authCtxt.put(AuthContext.AC_USER_AGENT, zsc.getUserAgent());
AuthMode mode = AuthMode.PASSWORD;
String code = password;
if (StringUtils.isEmpty(password) && StringUtils.isNotEmpty(recoveryCode)) {
mode = AuthMode.RECOVERY_CODE;
code = recoveryCode;
}
authCtxt.put(Provisioning.AUTH_MODE_KEY, mode);
if (acct == null) {
// try LAZY auto provision if it is enabled
if (acctBy == AccountBy.name || acctBy == AccountBy.krb5Principal) {
try {
if (acctBy == AccountBy.name) {
EmailAddress email = new EmailAddress(acctValue, false);
String domainName = email.getDomain();
Domain domain = domainName == null ? null : prov.get(Key.DomainBy.name, domainName);
if (password != null) {
acct = prov.autoProvAccountLazy(domain, acctValuePassedIn, password, null);
} else if (preAuthEl != null) {
long timestamp = preAuthEl.getAttributeLong(AccountConstants.A_TIMESTAMP);
expires = preAuthEl.getAttributeLong(AccountConstants.A_EXPIRES, 0);
String preAuth = preAuthEl.getTextTrim();
prov.preAuthAccount(domain, acctValue, acctByStr, timestamp, expires, preAuth, authCtxt);
acct = prov.autoProvAccountLazy(domain, acctValuePassedIn, null, AutoProvAuthMech.PREAUTH);
}
} else {
if (password != null) {
Domain domain = Krb5Principal.getDomainByKrb5Principal(acctValuePassedIn);
if (domain != null) {
acct = prov.autoProvAccountLazy(domain, acctValuePassedIn, password, null);
}
}
}
if (acct != null) {
acctAutoProvisioned = true;
}
} catch (AuthFailedServiceException e) {
ZimbraLog.account.debug("auth failed, unable to auto provisioing acct " + acctValue, e);
} catch (ServiceException e) {
ZimbraLog.account.info("unable to auto provisioing acct " + acctValue, e);
}
}
}
if (acct == null) {
// try ZMG Proxy auto provision if it is enabled
if (acctBy == AccountBy.name && password != null) {
Pair<Account, Boolean> result = null;
try {
result = prov.autoProvZMGProxyAccount(acctValuePassedIn, password);
} catch (AuthFailedServiceException e) {
// Most likely in error with user creds
} catch (ServiceException e) {
ZimbraLog.account.info("unable to auto provision acct " + acctValuePassedIn, e);
}
if (result != null) {
acct = result.getFirst();
acctAutoProvisioned = result.getSecond();
}
}
}
if (acct == null) {
throw AuthFailedServiceException.AUTH_FAILED(acctValue, acctValuePassedIn, "account not found");
}
AccountUtil.addAccountToLogContext(prov, acct.getId(), ZimbraLog.C_NAME, ZimbraLog.C_ID, null);
Boolean registerTrustedDevice = false;
TwoFactorAuth twoFactorManager = TwoFactorAuth.getFactory().getTwoFactorAuth(acct);
if (twoFactorManager.twoFactorAuthEnabled()) {
registerTrustedDevice = trustedToken == null && request.getAttributeBool(AccountConstants.A_TRUSTED_DEVICE, false);
}
// if account was auto provisioned, we had already authenticated the principal
if (!acctAutoProvisioned) {
boolean trustedDeviceOverride = false;
if (trustedToken != null && acct.isFeatureTrustedDevicesEnabled()) {
if (trustedToken.isExpired()) {
ZimbraLog.account.debug("trusted token is expired");
registerTrustedDevice = false;
} else {
Map<String, Object> attrs = getTrustedDeviceAttrs(zsc, deviceId);
try {
verifyTrustedDevice(acct, trustedToken, attrs);
trustedDeviceOverride = true;
} catch (AuthFailedServiceException e) {
ZimbraLog.account.info("trusted device not verified");
}
}
}
boolean usingTwoFactorAuth = acct != null && twoFactorManager.twoFactorAuthRequired() && !trustedDeviceOverride;
boolean twoFactorAuthWithToken = usingTwoFactorAuth && authTokenEl != null;
if (password != null || recoveryCode != null || twoFactorAuthWithToken) {
// authentication logic can be reached with either a password, or a 2FA auth token
if (usingTwoFactorAuth && twoFactorCode == null && (password != null || recoveryCode != null)) {
int mtaAuthPort = acct.getServer().getMtaAuthPort();
boolean supportsAppSpecificPaswords = acct.isFeatureAppSpecificPasswordsEnabled() && zsc.getPort() == mtaAuthPort;
if (supportsAppSpecificPaswords && password != null) {
// if we are here, it means we are authenticating SMTP,
// so app-specific passwords are accepted. Other protocols (pop, imap)
// doesn't touch this code, so their authentication happens in ZimbraAuth.
AppSpecificPasswords appPasswords = TwoFactorAuth.getFactory().getAppSpecificPasswords(acct, acctValuePassedIn);
appPasswords.authenticate(password);
} else {
prov.authAccount(acct, code, AuthContext.Protocol.soap, authCtxt);
return needTwoFactorAuth(acct, twoFactorManager, zsc, tokenType);
}
} else {
if (password != null || recoveryCode != null) {
prov.authAccount(acct, code, AuthContext.Protocol.soap, authCtxt);
} else {
// it's ok to not have a password if the client is using a 2FA auth token for the 2nd step of 2FA
if (!twoFactorAuthWithToken) {
throw ServiceException.AUTH_REQUIRED();
}
}
if (usingTwoFactorAuth) {
// check that 2FA has been enabled, in case the client is passing in a twoFactorCode prior to setting up 2FA
if (!twoFactorManager.twoFactorAuthEnabled()) {
throw AccountServiceException.TWO_FACTOR_SETUP_REQUIRED();
}
AuthToken twoFactorToken = null;
if (password == null) {
try {
twoFactorToken = AuthProvider.getAuthToken(authTokenEl, acct);
Account twoFactorTokenAcct = AuthProvider.validateAuthToken(prov, twoFactorToken, false, Usage.TWO_FACTOR_AUTH);
boolean verifyAccount = authTokenEl.getAttributeBool(AccountConstants.A_VERIFY_ACCOUNT, false);
if (verifyAccount && !twoFactorTokenAcct.getId().equalsIgnoreCase(acct.getId())) {
throw new AuthTokenException("two-factor auth token doesn't match the named account");
}
} catch (AuthTokenException e) {
throw AuthFailedServiceException.AUTH_FAILED("bad auth token");
}
}
TwoFactorAuth manager = TwoFactorAuth.getFactory().getTwoFactorAuth(acct);
if (twoFactorCode != null) {
manager.authenticate(twoFactorCode);
} else {
throw AuthFailedServiceException.AUTH_FAILED("no two-factor code provided");
}
if (twoFactorToken != null) {
try {
twoFactorToken.deRegister();
} catch (AuthTokenException e) {
throw ServiceException.FAILURE("cannot de-register two-factor auth token", e);
}
}
}
}
} else if (preAuthEl != null) {
long timestamp = preAuthEl.getAttributeLong(AccountConstants.A_TIMESTAMP);
expires = preAuthEl.getAttributeLong(AccountConstants.A_EXPIRES, 0);
String preAuth = preAuthEl.getTextTrim();
prov.preAuthAccount(acct, acctValue, acctByStr, timestamp, expires, preAuth, authCtxt);
} else {
throw ServiceException.INVALID_REQUEST("must specify " + AccountConstants.E_PASSWORD, null);
}
}
AuthToken at = expires == 0 ? AuthProvider.getAuthToken(acct, tokenType) : AuthProvider.getAuthToken(acct, expires, tokenType);
if (registerTrustedDevice && (trustedToken == null || trustedToken.isExpired())) {
// generate a new trusted device token if there is no existing one or if the current one is no longer valid
Map<String, Object> attrs = getTrustedDeviceAttrs(zsc, newDeviceId == null ? deviceId : newDeviceId);
TrustedDevices trustedDeviceManager = TwoFactorAuth.getFactory().getTrustedDevices(acct);
if (trustedDeviceManager != null) {
trustedToken = trustedDeviceManager.registerTrustedDevice(attrs);
}
}
ServletRequest httpReq = (ServletRequest) context.get(SoapServlet.SERVLET_REQUEST);
// For CSRF filter so that token generation can happen
if (csrfSupport && !at.isCsrfTokenEnabled()) {
// handle case where auth token was originally generated with csrf support
// and now client sends the same auth token but saying csrfSupport is turned off
// in that case do not disable CSRF check for this authToken.
at.setCsrfTokenEnabled(csrfSupport);
}
httpReq.setAttribute(CsrfFilter.AUTH_TOKEN, at);
return doResponse(request, at, zsc, context, acct, csrfSupport, trustedToken, newDeviceId);
}
Aggregations