Search in sources :

Example 21 with AuthTokenException

use of com.zimbra.cs.account.AuthTokenException in project zm-mailbox by Zimbra.

the class OAuthServiceProvider method markAsAuthorized.

/**
     * Mark OAuth consumer as authorized and update accessor properties.
     */
public static synchronized void markAsAuthorized(OAuthAccessor accessor, String userId, String zauthtoken) throws OAuthException {
    accessor.setProperty("user", userId);
    accessor.setProperty("authorized", Boolean.TRUE);
    accessor.setProperty("ZM_AUTH_TOKEN", zauthtoken);
    AuthToken zimbraAuthToken;
    try {
        zimbraAuthToken = ZimbraAuthToken.getAuthToken(zauthtoken);
        final Account account = zimbraAuthToken.getAccount();
        setAccountPropertiesForAccessor(account, accessor);
    } catch (AuthTokenException | UnsupportedEncodingException | ServiceException e) {
        throw new OAuthException(e);
    }
    accessor.consumer.setProperty("approved_on", Long.toString(System.currentTimeMillis()));
}
Also used : Account(com.zimbra.cs.account.Account) ServiceException(com.zimbra.common.service.ServiceException) AuthTokenException(com.zimbra.cs.account.AuthTokenException) OAuthException(net.oauth.OAuthException) ZimbraAuthToken(com.zimbra.cs.account.ZimbraAuthToken) AuthToken(com.zimbra.cs.account.AuthToken) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 22 with AuthTokenException

use of com.zimbra.cs.account.AuthTokenException 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);
    AuthToken at = null;
    Account acct = null;
    Provisioning prov = Provisioning.getInstance();
    boolean csrfSupport = request.getAttributeBool(AccountConstants.A_CSRF_SUPPORT, false);
    String name = request.getAttribute(AdminConstants.E_NAME, null);
    Element acctEl = request.getOptionalElement(AccountConstants.E_ACCOUNT);
    //only perform auth-token authentication if other credentials are not provided
    if (name == null && acctEl == null) {
        //get an auth token from cookie
        at = zsc.getAuthToken();
        if (at == null) {
            //if auth token is not in the cookie check for auth token in SOAP
            Element authTokenEl = request.getOptionalElement(AdminConstants.E_AUTH_TOKEN);
            if (authTokenEl != null) {
                try {
                    at = AuthProvider.getAuthToken(request, new HashMap<String, Object>());
                } catch (AuthTokenException e) {
                    throw ServiceException.AUTH_REQUIRED();
                }
            }
        }
        if (at == null) {
            //neither login credentials nor valid auth token could be retrieved
            throw ServiceException.AUTH_REQUIRED();
        }
        com.zimbra.cs.service.account.Auth.addAccountToLogContextByAuthToken(prov, at);
        if (at.isExpired())
            throw ServiceException.AUTH_EXPIRED();
        if (!at.isRegistered())
            throw ServiceException.AUTH_EXPIRED("authtoken is invalid");
        // make sure that the authenticated account is active and has not been deleted/disabled since the last request
        acct = prov.get(AccountBy.id, at.getAccountId(), at);
        if (acct == null || !acct.getAccountStatus(prov).equals(Provisioning.ACCOUNT_STATUS_ACTIVE))
            throw ServiceException.AUTH_EXPIRED();
        // make sure the authenticated account is an admin account
        checkAdmin(acct);
    } else {
        /*
             * only one of
             *     <name>...</name>
             * or
             *     <account by="name|id|foreignPrincipal">...</account>
             * can/must be specified
             */
        if (name != null && acctEl != null)
            throw ServiceException.INVALID_REQUEST("only one of <name> or <account> can be specified", null);
        if (name == null && acctEl == null)
            throw ServiceException.INVALID_REQUEST("missing <name> or <account>", null);
        String password = request.getAttribute(AdminConstants.E_PASSWORD);
        String twoFactorCode = request.getAttribute(AccountConstants.E_TWO_FACTOR_CODE, null);
        Element virtualHostEl = request.getOptionalElement(AccountConstants.E_VIRTUAL_HOST);
        String virtualHost = virtualHostEl == null ? null : virtualHostEl.getText().toLowerCase();
        String valuePassedIn;
        AccountBy by;
        String value;
        if (name != null) {
            valuePassedIn = name;
            by = AccountBy.name;
        } else {
            valuePassedIn = acctEl.getText();
            String byStr = acctEl.getAttribute(AccountConstants.A_BY, AccountBy.name.name());
            by = AccountBy.fromString(byStr);
        }
        value = valuePassedIn;
        try {
            if (by == AccountBy.name && value.indexOf("@") == -1) {
                // first try to get by adminName, which resolves the account under cn=admins,cn=zimbra
                // and does not need a domain
                acct = prov.get(AccountBy.adminName, value, zsc.getAuthToken());
                // not found, try applying virtual host name
                if (acct == null) {
                    if (virtualHost != null) {
                        Domain d = prov.get(Key.DomainBy.virtualHostname, virtualHost);
                        if (d != null)
                            value = value + "@" + d.getName();
                    }
                }
            }
            if (acct == null)
                acct = prov.get(by, value);
            if (acct == null)
                throw AuthFailedServiceException.AUTH_FAILED(value, valuePassedIn, "account not found");
            AccountUtil.addAccountToLogContext(prov, acct.getId(), ZimbraLog.C_NAME, ZimbraLog.C_ID, null);
            ZimbraLog.security.info(ZimbraLog.encodeAttrs(new String[] { "cmd", "AdminAuth", "account", value }));
            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, valuePassedIn);
            authCtxt.put(AuthContext.AC_USER_AGENT, zsc.getUserAgent());
            authCtxt.put(AuthContext.AC_AS_ADMIN, Boolean.TRUE);
            prov.authAccount(acct, password, AuthContext.Protocol.soap, authCtxt);
            TwoFactorAuth twoFactorAuth = TwoFactorAuth.getFactory().getTwoFactorAuth(acct);
            boolean usingTwoFactorAuth = twoFactorAuth.twoFactorAuthEnabled();
            if (usingTwoFactorAuth) {
                if (twoFactorCode != null) {
                    twoFactorAuth.authenticate(twoFactorCode);
                }
            }
            checkAdmin(acct);
            AuthMech authedByMech = (AuthMech) authCtxt.get(AuthContext.AC_AUTHED_BY_MECH);
            at = AuthProvider.getAuthToken(acct, true, authedByMech);
        } catch (ServiceException se) {
            ZimbraLog.security.warn(ZimbraLog.encodeAttrs(new String[] { "cmd", "AdminAuth", "account", value, "error", se.getMessage() }));
            throw se;
        }
    }
    if (at != null) {
        at.setCsrfTokenEnabled(csrfSupport);
    }
    ServletRequest httpReq = (ServletRequest) context.get(SoapServlet.SERVLET_REQUEST);
    httpReq.setAttribute(CsrfFilter.AUTH_TOKEN, at);
    return doResponse(request, at, zsc, context, acct, csrfSupport);
}
Also used : Account(com.zimbra.cs.account.Account) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HashMap(java.util.HashMap) Element(com.zimbra.common.soap.Element) Provisioning(com.zimbra.cs.account.Provisioning) AccountBy(com.zimbra.common.account.Key.AccountBy) AuthMech(com.zimbra.cs.account.auth.AuthMechanism.AuthMech) ServiceException(com.zimbra.common.service.ServiceException) AuthFailedServiceException(com.zimbra.cs.account.AccountServiceException.AuthFailedServiceException) ZimbraSoapContext(com.zimbra.soap.ZimbraSoapContext) TwoFactorAuth(com.zimbra.cs.account.auth.twofactor.TwoFactorAuth) AuthTokenException(com.zimbra.cs.account.AuthTokenException) AuthToken(com.zimbra.cs.account.AuthToken) Domain(com.zimbra.cs.account.Domain)

Example 23 with AuthTokenException

use of com.zimbra.cs.account.AuthTokenException in project zm-mailbox by Zimbra.

the class ProxyTarget method disableCsrfFlagInAuthToken.

/**
     * @param envelope
     * @param authToken
     * @param qName
     * @return
     * @throws ServiceException
     */
private void disableCsrfFlagInAuthToken(Element envelope, AuthToken authToken, QName qName) throws ServiceException {
    Element header = envelope.getOptionalElement("Header");
    if (header != null) {
        Element context = header.getOptionalElement(HeaderConstants.CONTEXT);
        if (context != null) {
            Element token = context.getOptionalElement(HeaderConstants.E_AUTH_TOKEN);
            if (token != null) {
                try {
                    token.setText(authToken.getEncoded());
                } catch (AuthTokenException ate) {
                    throw ServiceException.PROXY_ERROR(ate, qName.getName());
                }
            }
        }
    }
    ZimbraLog.soap.debug("Modified auth token in soap envelope, csrf token flag is disabled. The new envelope : %s", envelope);
}
Also used : Element(com.zimbra.common.soap.Element) AuthTokenException(com.zimbra.cs.account.AuthTokenException)

Example 24 with AuthTokenException

use of com.zimbra.cs.account.AuthTokenException in project zm-mailbox by Zimbra.

the class ImapPath method getOwnerZMailbox.

ZMailbox getOwnerZMailbox() throws ServiceException {
    if (useReferent()) {
        return getReferent().getOwnerZMailbox();
    }
    if (mMailbox instanceof ZMailbox) {
        return (ZMailbox) mMailbox;
    } else if (mCredentials == null) {
        return null;
    }
    Account target = getOwnerAccount();
    if (target == null) {
        throw AccountServiceException.NO_SUCH_ACCOUNT(getOwner());
    }
    Account acct = Provisioning.getInstance().get(AccountBy.id, mCredentials.getAccountId());
    if (acct == null) {
        throw AccountServiceException.NO_SUCH_ACCOUNT(mCredentials.getUsername());
    }
    try {
        ZMailbox.Options options = new ZMailbox.Options(AuthProvider.getAuthToken(acct).getEncoded(), AccountUtil.getSoapUri(target));
        options.setTargetAccount(target.getName());
        options.setNoSession(true);
        return ZMailbox.getMailbox(options);
    } catch (AuthTokenException ate) {
        throw ServiceException.FAILURE("error generating auth token", ate);
    }
}
Also used : Account(com.zimbra.cs.account.Account) ZMailbox(com.zimbra.client.ZMailbox) AuthTokenException(com.zimbra.cs.account.AuthTokenException)

Example 25 with AuthTokenException

use of com.zimbra.cs.account.AuthTokenException in project zm-mailbox by Zimbra.

the class ImapPath method getReferent.

ImapPath getReferent() throws ServiceException {
    if (mReferent != null) {
        return mReferent;
    }
    // while calculating, use the base
    mReferent = this;
    // only follow the authenticated user's own mountpoints
    if (mScope == Scope.REFERENCE || mScope == Scope.UNPARSED || !belongsTo(mCredentials)) {
        return mReferent;
    }
    ItemId iidRemote;
    String subpathRemote = null;
    Object mboxobj = getOwnerMailbox();
    if (mboxobj instanceof Mailbox) {
        try {
            if (mFolder == null) {
                Pair<Folder, String> resolved = ((Mailbox) mboxobj).getFolderByPathLongestMatch(getContext(), Mailbox.ID_FOLDER_USER_ROOT, asZimbraPath());
                subpathRemote = resolved.getSecond();
                boolean isMountpoint = resolved.getFirst() instanceof Mountpoint;
                if (isMountpoint || resolved.getSecond() == null) {
                    mFolder = resolved.getFirst();
                    mItemId = new ItemId(resolved.getFirst());
                }
                if (!isMountpoint) {
                    return mReferent;
                }
            } else if (!(mFolder instanceof Mountpoint)) {
                return mReferent;
            }
            // somewhere along the specified path is a visible mountpoint owned by the user
            iidRemote = ((Mountpoint) mFolder).getTarget();
        } catch (ServiceException e) {
            return mReferent;
        }
    } else if (mboxobj instanceof ZMailbox) {
        String accountId = mCredentials == null ? null : mCredentials.getAccountId();
        if (mFolder == null) {
            ZMailbox zmbx = (ZMailbox) mboxobj;
            String path = asZimbraPath();
            try {
                for (int index = path.length(); index != -1; index = path.lastIndexOf('/', index - 1)) {
                    ZFolder zfolder = zmbx.getFolderByPath(path.substring(0, index));
                    if (zfolder != null) {
                        subpathRemote = path.substring(Math.min(path.length(), index + 1));
                        if (zfolder instanceof ZMountpoint || subpathRemote.isEmpty()) {
                            mFolder = zfolder;
                            mItemId = new ItemId(zfolder.getId(), accountId);
                        }
                        break;
                    }
                }
            } catch (ServiceException e) {
            }
        }
        if (!(mFolder instanceof ZMountpoint)) {
            return mReferent;
        }
        // somewhere along the specified path is a visible mountpoint owned by the user
        iidRemote = new ItemId(((ZMountpoint) mFolder).getCanonicalRemoteId(), accountId);
    } else {
        return mReferent;
    }
    // don't allow mountpoints that point at the same mailbox (as it can cause infinite loops)
    if (belongsTo(iidRemote.getAccountId())) {
        return mReferent;
    }
    Account target = Provisioning.getInstance().get(AccountBy.id, iidRemote.getAccountId());
    if (target == null) {
        return mReferent;
    }
    String owner = mCredentials != null && mCredentials.getAccountId().equalsIgnoreCase(target.getId()) ? null : target.getName();
    if (Provisioning.onLocalServer(target)) {
        try {
            Mailbox mbox = MailboxManager.getInstance().getMailboxByAccount(target);
            Folder folder = mbox.getFolderById(getContext(), iidRemote.getId());
            if (subpathRemote == null) {
                mReferent = new ImapPath(owner, folder, mCredentials);
            } else {
                (mReferent = new ImapPath(owner, folder.getPath() + (folder.getPath().equals("/") ? "" : "/") + subpathRemote, mCredentials)).mMailbox = mbox;
            }
        } catch (ServiceException e) {
        }
    } else {
        Account acct = mCredentials == null ? null : Provisioning.getInstance().get(AccountBy.id, mCredentials.getAccountId());
        if (acct == null)
            return mReferent;
        try {
            ZMailbox.Options options = new ZMailbox.Options(AuthProvider.getAuthToken(acct).getEncoded(), AccountUtil.getSoapUri(target));
            options.setTargetAccount(target.getName());
            options.setNoSession(true);
            ZMailbox zmbx = ZMailbox.getMailbox(options);
            ZFolder zfolder = zmbx.getFolderById(iidRemote.toString(mCredentials.getAccountId()));
            if (zfolder == null) {
                return mReferent;
            }
            if (subpathRemote == null) {
                mReferent = new ImapPath(owner, zfolder, mCredentials);
            } else {
                (mReferent = new ImapPath(owner, zfolder.getPath() + (zfolder.getPath().equals("/") ? "" : "/") + subpathRemote, mCredentials)).mMailbox = zmbx;
            }
        } catch (AuthTokenException ate) {
            throw ServiceException.FAILURE("error generating auth token", ate);
        } catch (ServiceException e) {
        }
    }
    if (mReferent != this) {
        mReferent.mScope = Scope.REFERENCE;
    }
    return mReferent;
}
Also used : ZMountpoint(com.zimbra.client.ZMountpoint) Account(com.zimbra.cs.account.Account) ZSearchFolder(com.zimbra.client.ZSearchFolder) ZFolder(com.zimbra.client.ZFolder) SearchFolder(com.zimbra.cs.mailbox.SearchFolder) Folder(com.zimbra.cs.mailbox.Folder) ItemId(com.zimbra.cs.service.util.ItemId) ZMailbox(com.zimbra.client.ZMailbox) Mailbox(com.zimbra.cs.mailbox.Mailbox) ZMailbox(com.zimbra.client.ZMailbox) AccountServiceException(com.zimbra.cs.account.AccountServiceException) ServiceException(com.zimbra.common.service.ServiceException) MailServiceException(com.zimbra.cs.mailbox.MailServiceException) AuthTokenException(com.zimbra.cs.account.AuthTokenException) ZFolder(com.zimbra.client.ZFolder) ZMountpoint(com.zimbra.client.ZMountpoint) Mountpoint(com.zimbra.cs.mailbox.Mountpoint)

Aggregations

AuthTokenException (com.zimbra.cs.account.AuthTokenException)37 AuthToken (com.zimbra.cs.account.AuthToken)25 ServiceException (com.zimbra.common.service.ServiceException)24 Account (com.zimbra.cs.account.Account)20 Provisioning (com.zimbra.cs.account.Provisioning)8 ZimbraAuthToken (com.zimbra.cs.account.ZimbraAuthToken)7 IOException (java.io.IOException)7 HttpClient (org.apache.commons.httpclient.HttpClient)7 GetMethod (org.apache.commons.httpclient.methods.GetMethod)7 ZimbraSoapContext (com.zimbra.soap.ZimbraSoapContext)6 ServletException (javax.servlet.ServletException)6 Element (com.zimbra.common.soap.Element)5 Server (com.zimbra.cs.account.Server)5 HttpMethod (org.apache.commons.httpclient.HttpMethod)5 Domain (com.zimbra.cs.account.Domain)4 GuestAccount (com.zimbra.cs.account.GuestAccount)4 HashMap (java.util.HashMap)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 ZMailbox (com.zimbra.client.ZMailbox)3 AccountBy (com.zimbra.common.account.Key.AccountBy)3