예제 #1
0
  /**
   * @param req http request
   * @return an AuthToken object, or null if auth data is not present for any of the enabled
   *     providers
   * @throws ServiceException
   */
  public static AuthToken getAuthToken(HttpServletRequest req, boolean isAdminReq)
      throws AuthTokenException {
    AuthToken at = null;
    List<AuthProvider> providers = getProviders();
    for (AuthProvider ap : providers) {
      try {
        at = ap.authToken(req, isAdminReq);
        if (at == null) {
          throw new AuthTokenException("auth provider " + ap.getName() + " returned null");
        } else {
          return at;
        }
      } catch (AuthProviderException e) {
        // if there is no auth data for this provider, log and continue with next provider
        if (e.canIgnore()) {
          logger().debug(ap.getName() + ":" + e.getMessage());
        } else {
          throw new AuthTokenException("auth provider error", e);
        }
      } catch (AuthTokenException e) {
        // log and rethrow
        logger()
            .debug("getAuthToken error: provider=" + ap.getName() + ", err=" + e.getMessage(), e);
        throw e;
      }
    }

    // there is no auth data for any of the enabled providers
    return null;
  }
예제 #2
0
  /**
   * Creates an AuthToken object from token string.
   *
   * @param encoded
   * @return
   * @throws AuthTokenException
   * @see #authToken(String)
   */
  public static AuthToken getAuthToken(String encoded) throws AuthTokenException {
    AuthToken at = null;
    List<AuthProvider> providers = getProviders();
    for (AuthProvider ap : providers) {
      try {
        at = ap.authToken(encoded);
        if (at == null) {
          throw new AuthTokenException("auth provider " + ap.getName() + " returned null");
        } else {
          return at;
        }
      } catch (AuthProviderException e) {
        // if there is no auth data for this provider, log and continue with next provider
        if (e.canIgnore()) {
          logger().warn(ap.getName() + ":" + e.getMessage());
        } else {
          throw new AuthTokenException("auth provider error", e);
        }
      } catch (AuthTokenException e) {
        // log and rethrow
        logger()
            .debug("getAuthToken error: provider=" + ap.getName() + ", err=" + e.getMessage(), e);
        throw e;
      }
    }

    // there is no auth data for any of the enabled providers
    logger().error("unable to get AuthToken from encoded " + encoded);
    return null;
  }
예제 #3
0
 public static boolean allowAccessKeyAuth(HttpServletRequest req, ZimbraServlet servlet) {
   List<AuthProvider> providers = getProviders();
   for (AuthProvider ap : providers) {
     if (ap.allowURLAccessKeyAuth(req, servlet)) {
       return true;
     }
   }
   return false;
 }
예제 #4
0
  public static synchronized void register(AuthProvider ap) {
    String name = ap.getName();
    logger().info("Adding auth provider: " + name + " " + ap.getClass().getName());

    if (registeredProviders.get(name) == null) {
      registeredProviders.put(name, ap);
    } else {
      logger()
          .error(
              "auth provider " + name + " already exists, not adding " + ap.getClass().getName());
    }
  }
예제 #5
0
  public static AuthToken getAuthToken(Account acct, long expires) throws AuthProviderException {
    List<AuthProvider> providers = getProviders();
    for (AuthProvider ap : providers) {
      try {
        AuthToken at = ap.authToken(acct, expires);
        if (at == null) {
          throw AuthProviderException.FAILURE("auth provider " + ap.getName() + " returned null");
        } else {
          return at;
        }
      } catch (AuthProviderException e) {
        if (e.canIgnore()) {
          logger().debug(ap.getName() + ":" + e.getMessage());
        } else {
          throw e;
        }
      }
    }

    throw AuthProviderException.FAILURE("cannot get authtoken from account " + acct.getName());
  }
예제 #6
0
  public static AuthToken getAuthToken(Account acct, boolean isAdmin, AuthMech authMech)
      throws AuthProviderException {
    List<AuthProvider> providers = getProviders();
    for (AuthProvider ap : providers) {
      try {
        AuthToken at = ap.authToken(acct, isAdmin, authMech);
        if (at == null) {
          throw AuthProviderException.FAILURE("auth provider " + ap.getName() + " returned null");
        } else {
          return at;
        }
      } catch (AuthProviderException e) {
        if (e.canIgnore()) {
          logger().debug(ap.getName() + ":" + e.getMessage());
        } else {
          throw e;
        }
      }
    }

    String acctName = acct != null ? acct.getName() : "null";
    throw AuthProviderException.FAILURE("cannot get authtoken from account " + acctName);
  }
예제 #7
0
  public Element handle(Element request, Map<String, Object> context) throws ServiceException {
    ZimbraSoapContext zsc = getZimbraSoapContext(context);

    Element a = request.getElement(AdminConstants.E_ACCOUNT);
    String key = a.getAttribute(AdminConstants.A_BY);
    String value = a.getText();

    long lifetime =
        request.getAttributeLong(AdminConstants.A_DURATION, DEFAULT_AUTH_LIFETIME) * 1000;

    Provisioning prov = Provisioning.getInstance();

    Account account = null;

    if (key.equals(BY_NAME)) {
      account = prov.get(AccountBy.name, value, zsc.getAuthToken());
    } else if (key.equals(BY_ID)) {
      account = prov.get(AccountBy.id, value, zsc.getAuthToken());
    } else {
      throw ServiceException.INVALID_REQUEST("unknown value for by: " + key, null);
    }

    if (account == null) throw AccountServiceException.NO_SUCH_ACCOUNT(value);

    checkAdminLoginAsRight(zsc, prov, account);

    ZimbraLog.security.info(
        ZimbraLog.encodeAttrs(
            new String[] {
              "cmd", "DelegateAuth", "accountId", account.getId(), "accountName", account.getName()
            }));

    Element response = zsc.createElement(AdminConstants.DELEGATE_AUTH_RESPONSE);
    long maxLifetime =
        account.getTimeInterval(
            Provisioning.A_zimbraAuthTokenLifetime, DEFAULT_AUTH_LIFETIME * 1000);

    // take the min of requested lifetime vs maxLifetime
    long expires = System.currentTimeMillis() + Math.min(lifetime, maxLifetime);
    String token;
    Account adminAcct = prov.get(AccountBy.id, zsc.getAuthtokenAccountId(), zsc.getAuthToken());
    if (adminAcct == null)
      throw AccountServiceException.NO_SUCH_ACCOUNT(zsc.getAuthtokenAccountId());

    AuthToken at = AuthProvider.getAuthToken(account, expires, false, adminAcct);
    at.encodeAuthResp(response, true);
    response.addAttribute(AdminConstants.E_LIFETIME, lifetime, Element.Disposition.CONTENT);
    return response;
  }
예제 #8
0
 public RemoteCollection(DavContext ctxt, String path, Account user)
     throws DavException, ServiceException {
   super(path, user.getName());
   ZAuthToken zat = AuthProvider.getAuthToken(ctxt.getAuthAccount()).toZAuthToken();
   ZMailbox mbox = getRemoteMailbox(zat, user.getId());
   ZFolder folder = mbox.getFolderByPath(path);
   if (folder == null) throw MailServiceException.NO_SUCH_FOLDER(path);
   mOwnerId = user.getId();
   mId = new ItemId(folder.getId(), mOwnerId).getId();
   mPath = path;
   mSubject = folder.getName();
   type = MailItem.Type.FOLDER;
   ZFolder.View zview = folder.getDefaultView();
   if (zview != null) view = MailItem.Type.of(zview.name());
 }
예제 #9
0
파일: ImapProxy.java 프로젝트: koem/Zimbra
  ImapProxy(final ImapHandler handler, final ImapPath path) throws ServiceException {
    mHandler = handler;
    mPath = path;

    Account acct = handler.getCredentials().getAccount();
    Server server = Provisioning.getInstance().getServer(path.getOwnerAccount());
    String host = server.getServiceHostname();
    if (acct == null)
      throw ServiceException.PROXY_ERROR(
          new Exception("no such authenticated user"), path.asImapPath());

    ImapConfig config = new ImapConfig();
    config.setAuthenticationId(acct.getName());
    config.setMechanism(ZimbraAuthenticator.MECHANISM);
    config.setAuthenticatorFactory(sAuthenticatorFactory);
    config.setReadTimeout(LC.javamail_imap_timeout.intValue());
    config.setConnectTimeout(config.getReadTimeout());
    config.setHost(host);
    if (server.isImapServerEnabled()) {
      config.setPort(server.getIntAttr(Provisioning.A_zimbraImapBindPort, ImapConfig.DEFAULT_PORT));
    } else if (server.isImapSSLServerEnabled()) {
      config.setPort(
          server.getIntAttr(Provisioning.A_zimbraImapSSLBindPort, ImapConfig.DEFAULT_SSL_PORT));
      config.setSecurity(MailConfig.Security.SSL);
    } else {
      throw ServiceException.PROXY_ERROR(
          new Exception("no open IMAP port for server " + host), path.asImapPath());
    }

    ZimbraLog.imap.info(
        "opening proxy connection (user="******", host="
            + host
            + ", path="
            + path.getReferent().asImapPath()
            + ')');

    ImapConnection conn = mConnection = new ImapConnection(config);
    try {
      conn.connect();
      conn.authenticate(AuthProvider.getAuthToken(acct).getEncoded());
    } catch (Exception e) {
      dropConnection();
      throw ServiceException.PROXY_ERROR(e, null);
    }
  }
예제 #10
0
 protected void getMountpointTarget(DavContext ctxt) throws ServiceException {
   ZAuthToken zat = AuthProvider.getAuthToken(ctxt.getAuthAccount()).toZAuthToken();
   ZMailbox zmbx = getRemoteMailbox(zat, mRemoteOwnerId);
   if (zmbx == null) return;
   ZFolder folder = zmbx.getFolder(new ItemId(mRemoteOwnerId, mRemoteId).toString(mOwnerId));
   if (folder == null) return;
   mCtag = CtagInfo.makeCtag(folder);
   setProperty(DavElements.E_GETCTAG, mCtag);
   mRights = ACL.stringToRights(folder.getEffectivePerms());
   addProperty(Acl.getCurrentUserPrivilegeSet(mRights));
   addProperty(Acl.getMountpointTargetPrivilegeSet(mRights));
   String targetUrl =
       UrlNamespace.getResourceUrl(
           Provisioning.getInstance().get(Key.AccountBy.id, mRemoteOwnerId),
           folder.getPath() + "/");
   ResourceProperty mp = new ResourceProperty(DavElements.E_MOUNTPOINT_TARGET_URL);
   mp.addChild(DavElements.E_HREF).setText(targetUrl);
   addProperty(mp);
 }
예제 #11
0
 public Element sendRequestWithNotification(Element request) throws ServiceException {
   Server server =
       Provisioning.getInstance()
           .get(Key.ServerBy.name, OfflineConstants.SYNC_SERVER_PREFIX + getAccountId());
   if (server != null) {
     // when we first add an account, server is still null
     List<Session> soapSessions = getListeners(Session.Type.SOAP);
     Session session = null;
     if (soapSessions.size() == 1) {
       session = soapSessions.get(0);
     } else if (soapSessions.size() > 1) {
       // this occurs if user refreshes web browser (or opens ZD in two different browsers); older
       // session does not time out so there are now two listening
       // only the most recent is 'active'
       for (Session ses : soapSessions) {
         if (session == null || ses.accessedAfter(session.getLastAccessTime())) {
           session = ses;
         }
       }
     }
     if (session != null) {
       ZAuthToken zat = getAuthToken();
       if (zat != null) {
         AuthToken at =
             AuthProvider.getAuthToken(OfflineProvisioning.getOfflineInstance().getLocalAccount());
         at.setProxyAuthToken(zat.getValue());
         ProxyTarget proxy = new ProxyTarget(server, at, getSoapUri());
         // zscProxy needs to be for the 'ffffff-' account, but with target of *this* mailbox's
         // acct
         // currently UI receives SoapJS in its responses, we ask for that protocol so
         // notifications are handled correctly
         ZimbraSoapContext zscIn =
             new ZimbraSoapContext(
                 at, at.getAccountId(), SoapProtocol.Soap12, SoapProtocol.SoapJS);
         ZimbraSoapContext zscProxy = new ZimbraSoapContext(zscIn, getAccountId(), session);
         proxy.setTimeouts(OfflineLC.zdesktop_request_timeout.intValue());
         return DocumentHandler.proxyWithNotification(request, proxy, zscProxy, session);
       }
     }
   }
   return sendRequest(request);
 }
예제 #12
0
 public static AuthToken getAdminAuthToken() throws ServiceException {
   Account acct = Provisioning.getInstance().get(AccountBy.adminName, LC.zimbra_ldap_user.value());
   return AuthProvider.getAuthToken(acct, true);
 }
예제 #13
0
  static void dispatchJspRest(Servlet servlet, UserServletContext context)
      throws ServiceException, ServletException, IOException {
    AuthToken auth = null;
    long expiration = System.currentTimeMillis() + AUTH_EXPIRATION;
    if (context.basicAuthHappened) {
      Account acc = context.getAuthAccount();
      if (acc instanceof GuestAccount) {
        auth =
            AuthToken.getAuthToken(
                acc.getId(), acc.getName(), null, ((GuestAccount) acc).getDigest(), expiration);
      } else {
        auth = AuthProvider.getAuthToken(context.getAuthAccount(), expiration);
      }
    } else if (context.cookieAuthHappened) {
      auth = UserServlet.getAuthTokenFromCookie(context.req, context.resp, true);
    } else {
      auth = AuthToken.getAuthToken(GuestAccount.GUID_PUBLIC, null, null, null, expiration);
    }
    if (auth != null
        && context.targetAccount != null
        && context.targetAccount != context.getAuthAccount()) {
      auth.setProxyAuthToken(
          Provisioning.getInstance().getProxyAuthToken(context.targetAccount.getId()));
    }
    String authString = null;
    try {
      if (auth != null) authString = auth.getEncoded();
    } catch (AuthTokenException e) {
      throw new ServletException("error generating the authToken", e);
    }

    Account targetAccount = context.targetAccount;
    MailItem targetItem = context.target;
    String uri = (String) context.req.getAttribute("requestedPath");

    if (targetItem instanceof Mountpoint
        && ((Mountpoint) targetItem).getDefaultView() != MailItem.TYPE_APPOINTMENT) {
      Mountpoint mp = (Mountpoint) targetItem;
      Provisioning prov = Provisioning.getInstance();
      targetAccount = prov.getAccountById(mp.getOwnerId());
      Pair<Header[], HttpInputStream> remoteItem =
          UserServlet.getRemoteResourceAsStream(
              (auth == null) ? null : auth.toZAuthToken(), mp.getTarget(), context.extraPath);
      remoteItem.getSecond().close();
      String remoteItemId = null;
      String remoteItemType = null;
      String remoteItemName = null;
      String remoteItemPath = null;
      for (Header h : remoteItem.getFirst())
        if (h.getName().compareToIgnoreCase("X-Zimbra-ItemId") == 0) remoteItemId = h.getValue();
        else if (h.getName().compareToIgnoreCase("X-Zimbra-ItemType") == 0)
          remoteItemType = h.getValue();
        else if (h.getName().compareToIgnoreCase("X-Zimbra-ItemName") == 0)
          remoteItemName = h.getValue();
        else if (h.getName().compareToIgnoreCase("X-Zimbra-ItemPath") == 0)
          remoteItemPath = h.getValue();

      context.req.setAttribute(ATTR_TARGET_ITEM_ID, remoteItemId);
      context.req.setAttribute(ATTR_TARGET_ITEM_TYPE, remoteItemType);
      context.req.setAttribute(ATTR_TARGET_ITEM_NAME, remoteItemName);
      context.req.setAttribute(ATTR_TARGET_ITEM_PATH, remoteItemPath);
      context.req.setAttribute(ATTR_TARGET_ITEM_COLOR, mp.getColor());
      context.req.setAttribute(ATTR_TARGET_ITEM_VIEW, MailItem.getNameForType(mp.getDefaultView()));
      targetItem = null;
    }

    context.req.setAttribute(ATTR_INTERNAL_DISPATCH, "yes");
    context.req.setAttribute(ATTR_REQUEST_URI, uri != null ? uri : context.req.getRequestURI());
    context.req.setAttribute(ATTR_AUTH_TOKEN, authString);
    if (targetAccount != null) {
      context.req.setAttribute(ATTR_TARGET_ACCOUNT_NAME, targetAccount.getName());
      context.req.setAttribute(ATTR_TARGET_ACCOUNT_ID, targetAccount.getId());
      context.req.setAttribute(
          ATTR_TARGET_ACCOUNT_PREF_TIME_ZONE,
          targetAccount.getAttr(Provisioning.A_zimbraPrefTimeZoneId));
      context.req.setAttribute(
          ATTR_TARGET_ACCOUNT_PREF_SKIN, targetAccount.getAttr(Provisioning.A_zimbraPrefSkin));
      context.req.setAttribute(
          ATTR_TARGET_ACCOUNT_PREF_LOCALE, targetAccount.getAttr(Provisioning.A_zimbraPrefLocale));
      context.req.setAttribute(
          ATTR_TARGET_ACCOUNT_PREF_CALENDAR_FIRST_DAY_OF_WEEK,
          targetAccount.getAttr(Provisioning.A_zimbraPrefCalendarFirstDayOfWeek));
      context.req.setAttribute(
          ATTR_TARGET_ACCOUNT_PREF_CALENDAR_DAY_HOUR_START,
          targetAccount.getAttr(Provisioning.A_zimbraPrefCalendarDayHourStart));
      context.req.setAttribute(
          ATTR_TARGET_ACCOUNT_PREF_CALENDAR_DAY_HOUR_END,
          targetAccount.getAttr(Provisioning.A_zimbraPrefCalendarDayHourEnd));
    }
    if (targetItem != null) {
      context.req.setAttribute(ATTR_TARGET_ITEM_ID, targetItem.getId());
      context.req.setAttribute(ATTR_TARGET_ITEM_TYPE, MailItem.getNameForType(targetItem));
      context.req.setAttribute(ATTR_TARGET_ITEM_PATH, targetItem.getPath());
      context.req.setAttribute(ATTR_TARGET_ITEM_NAME, targetItem.getName());

      context.req.setAttribute(ATTR_TARGET_ITEM_COLOR, targetItem.getColor());
      if (targetItem instanceof Folder)
        context.req.setAttribute(
            ATTR_TARGET_ITEM_VIEW, MailItem.getNameForType(((Folder) targetItem).getDefaultView()));
    }

    String mailUrl = PATH_MAIN_CONTEXT;
    try {
      mailUrl = Provisioning.getInstance().getLocalServer().getMailURL();
    } catch (Exception e) {
    }
    ServletContext targetContext =
        servlet.getServletConfig().getServletContext().getContext(mailUrl);
    RequestDispatcher dispatcher = targetContext.getRequestDispatcher(PATH_JSP_REST_PAGE);
    dispatcher.forward(context.req, context.resp);
  }