AuthenticatingIMAPClient.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.net.imap;

  18. import java.io.IOException;
  19. import java.security.InvalidKeyException;
  20. import java.security.NoSuchAlgorithmException;
  21. import java.security.spec.InvalidKeySpecException;
  22. import java.util.Base64;

  23. import javax.crypto.Mac;
  24. import javax.crypto.spec.SecretKeySpec;
  25. import javax.net.ssl.SSLContext;

  26. /**
  27.  * An IMAP Client class with authentication support.
  28.  *
  29.  * @see IMAPSClient
  30.  */
  31. public class AuthenticatingIMAPClient extends IMAPSClient {

  32.     /**
  33.      * The enumeration of currently-supported authentication methods.
  34.      */
  35.     public enum AUTH_METHOD {

  36.         /** The standardized (RFC4616) PLAIN method, which sends the password unencrypted (insecure). */

  37.         PLAIN("PLAIN"),
  38.         /** The standardized (RFC2195) CRAM-MD5 method, which doesn't send the password (secure). */

  39.         CRAM_MD5("CRAM-MD5"),

  40.         /** The standardized Microsoft LOGIN method, which sends the password unencrypted (insecure). */
  41.         LOGIN("LOGIN"),

  42.         /** XOAUTH */
  43.         XOAUTH("XOAUTH"),

  44.         /** XOAUTH 2 */
  45.         XOAUTH2("XOAUTH2");

  46.         private final String authName;

  47.         AUTH_METHOD(final String name) {
  48.             this.authName = name;
  49.         }

  50.         /**
  51.          * Gets the name of the given authentication method suitable for the server.
  52.          *
  53.          * @return The name of the given authentication method suitable for the server.
  54.          */
  55.         public final String getAuthName() {
  56.             return authName;
  57.         }
  58.     }

  59.     /** {@link Mac} algorithm. */
  60.     private static final String MAC_ALGORITHM = "HmacMD5";

  61.     /**
  62.      * Constructor for AuthenticatingIMAPClient that delegates to IMAPSClient. Sets security mode to explicit (isImplicit = false).
  63.      */
  64.     public AuthenticatingIMAPClient() {
  65.         this(DEFAULT_PROTOCOL, false);
  66.     }

  67.     /**
  68.      * Constructor for AuthenticatingIMAPClient that delegates to IMAPSClient.
  69.      *
  70.      * @param implicit The security mode (Implicit/Explicit).
  71.      */
  72.     public AuthenticatingIMAPClient(final boolean implicit) {
  73.         this(DEFAULT_PROTOCOL, implicit);
  74.     }

  75.     /**
  76.      * Constructor for AuthenticatingIMAPClient that delegates to IMAPSClient.
  77.      *
  78.      * @param implicit The security mode(Implicit/Explicit).
  79.      * @param ctx      A pre-configured SSL Context.
  80.      */
  81.     public AuthenticatingIMAPClient(final boolean implicit, final SSLContext ctx) {
  82.         this(DEFAULT_PROTOCOL, implicit, ctx);
  83.     }

  84.     /**
  85.      * Constructor for AuthenticatingIMAPClient that delegates to IMAPSClient.
  86.      *
  87.      * @param context A pre-configured SSL Context.
  88.      */
  89.     public AuthenticatingIMAPClient(final SSLContext context) {
  90.         this(false, context);
  91.     }

  92.     /**
  93.      * Constructor for AuthenticatingIMAPClient that delegates to IMAPSClient.
  94.      *
  95.      * @param proto the protocol.
  96.      */
  97.     public AuthenticatingIMAPClient(final String proto) {
  98.         this(proto, false);
  99.     }

  100.     /**
  101.      * Constructor for AuthenticatingIMAPClient that delegates to IMAPSClient.
  102.      *
  103.      * @param proto    the protocol.
  104.      * @param implicit The security mode(Implicit/Explicit).
  105.      */
  106.     public AuthenticatingIMAPClient(final String proto, final boolean implicit) {
  107.         this(proto, implicit, null);
  108.     }

  109.     /**
  110.      * Constructor for AuthenticatingIMAPClient that delegates to IMAPSClient.
  111.      *
  112.      * @param proto    the protocol.
  113.      * @param implicit The security mode(Implicit/Explicit).
  114.      * @param ctx      the context
  115.      */
  116.     public AuthenticatingIMAPClient(final String proto, final boolean implicit, final SSLContext ctx) {
  117.         super(proto, implicit, ctx);
  118.     }

  119.     /**
  120.      * Authenticate to the IMAP server by sending the AUTHENTICATE command with the selected mechanism, using the given user and the given password.
  121.      *
  122.      * @param method   the method name
  123.      * @param user user
  124.      * @param password password
  125.      * @return True if successfully completed, false if not.
  126.      * @throws IOException              If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
  127.      * @throws NoSuchAlgorithmException If the CRAM hash algorithm cannot be instantiated by the Java runtime system.
  128.      * @throws InvalidKeyException      If the CRAM hash algorithm failed to use the given password.
  129.      * @throws InvalidKeySpecException  If the CRAM hash algorithm failed to use the given password.
  130.      */
  131.     public boolean auth(final AuthenticatingIMAPClient.AUTH_METHOD method, final String user, final String password)
  132.             throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
  133.         if (!IMAPReply.isContinuation(sendCommand(IMAPCommand.AUTHENTICATE, method.getAuthName()))) {
  134.             return false;
  135.         }

  136.         switch (method) {
  137.         case PLAIN: {
  138.             // the server sends an empty response ("+ "), so we don't have to read it.
  139.             final int result = sendData(Base64.getEncoder().encodeToString(("\000" + user + "\000" + password).getBytes(getCharset())));
  140.             if (result == IMAPReply.OK) {
  141.                 setState(IMAP.IMAPState.AUTH_STATE);
  142.             }
  143.             return result == IMAPReply.OK;
  144.         }
  145.         case CRAM_MD5: {
  146.             // get the CRAM challenge (after "+ ")
  147.             final byte[] serverChallenge = Base64.getDecoder().decode(getReplyString().substring(2).trim());
  148.             // get the Mac instance
  149.             final Mac hmacMd5 = Mac.getInstance(MAC_ALGORITHM);
  150.             hmacMd5.init(new SecretKeySpec(password.getBytes(getCharset()), MAC_ALGORITHM));
  151.             // compute the result:
  152.             final byte[] hmacResult = convertToHexString(hmacMd5.doFinal(serverChallenge)).getBytes(getCharset());
  153.             // join the byte arrays to form the reply
  154.             final byte[] usernameBytes = user.getBytes(getCharset());
  155.             final byte[] toEncode = new byte[usernameBytes.length + 1 /* the space */ + hmacResult.length];
  156.             System.arraycopy(usernameBytes, 0, toEncode, 0, usernameBytes.length);
  157.             toEncode[usernameBytes.length] = ' ';
  158.             System.arraycopy(hmacResult, 0, toEncode, usernameBytes.length + 1, hmacResult.length);
  159.             // send the reply and read the server code:
  160.             final int result = sendData(Base64.getEncoder().encodeToString(toEncode));
  161.             if (result == IMAPReply.OK) {
  162.                 setState(IMAP.IMAPState.AUTH_STATE);
  163.             }
  164.             return result == IMAPReply.OK;
  165.         }
  166.         case LOGIN: {
  167.             // the server sends fixed responses (base64("UserName") and
  168.             // base64("Password")), so we don't have to read them.
  169.             if (sendData(Base64.getEncoder().encodeToString(user.getBytes(getCharset()))) != IMAPReply.CONT) {
  170.                 return false;
  171.             }
  172.             final int result = sendData(Base64.getEncoder().encodeToString(password.getBytes(getCharset())));
  173.             if (result == IMAPReply.OK) {
  174.                 setState(IMAP.IMAPState.AUTH_STATE);
  175.             }
  176.             return result == IMAPReply.OK;
  177.         }
  178.         case XOAUTH:
  179.         case XOAUTH2: {
  180.             final int result = sendData(user);
  181.             if (result == IMAPReply.OK) {
  182.                 setState(IMAP.IMAPState.AUTH_STATE);
  183.             }
  184.             return result == IMAPReply.OK;
  185.         }
  186.         }
  187.         return false; // safety check
  188.     }

  189.     /**
  190.      * Authenticate to the IMAP server by sending the AUTHENTICATE command with the selected mechanism, using the given user and the given password.
  191.      *
  192.      * @param method   the method name
  193.      * @param user user
  194.      * @param password password
  195.      * @return True if successfully completed, false if not.
  196.      * @throws IOException              If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
  197.      * @throws NoSuchAlgorithmException If the CRAM hash algorithm cannot be instantiated by the Java runtime system.
  198.      * @throws InvalidKeyException      If the CRAM hash algorithm failed to use the given password.
  199.      * @throws InvalidKeySpecException  If the CRAM hash algorithm failed to use the given password.
  200.      */
  201.     public boolean authenticate(final AuthenticatingIMAPClient.AUTH_METHOD method, final String user, final String password)
  202.             throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
  203.         return auth(method, user, password);
  204.     }

  205.     /**
  206.      * Converts the given byte array to a String containing the hexadecimal values of the bytes. For example, the byte 'A' will be converted to '41', because
  207.      * this is the ASCII code (and the byte value) of the capital letter 'A'.
  208.      *
  209.      * @param a The byte array to convert.
  210.      * @return The resulting String of hexadecimal codes.
  211.      */
  212.     private String convertToHexString(final byte[] a) {
  213.         final StringBuilder result = new StringBuilder(a.length * 2);
  214.         for (final byte element : a) {
  215.             if ((element & 0x0FF) <= 15) {
  216.                 result.append("0");
  217.             }
  218.             result.append(Integer.toHexString(element & 0x0FF));
  219.         }
  220.         return result.toString();
  221.     }
  222. }