View Javadoc
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  
18  package org.apache.commons.net.imap;
19  
20  import java.io.IOException;
21  import java.security.InvalidKeyException;
22  import java.security.NoSuchAlgorithmException;
23  import java.security.spec.InvalidKeySpecException;
24  
25  import javax.crypto.Mac;
26  import javax.crypto.spec.SecretKeySpec;
27  import javax.net.ssl.SSLContext;
28  import org.apache.commons.net.util.Base64;
29  
30  /**
31   * An IMAP Client class with authentication support.
32   * @see IMAPSClient
33   */
34  public class AuthenticatingIMAPClient extends IMAPSClient
35  {
36      /**
37       * Constructor for AuthenticatingIMAPClient that delegates to IMAPSClient.
38       * Sets security mode to explicit (isImplicit = false).
39       */
40      public AuthenticatingIMAPClient()
41      {
42          this(DEFAULT_PROTOCOL, false);
43      }
44  
45      /**
46       * Constructor for AuthenticatingIMAPClient that delegates to IMAPSClient.
47       * @param implicit The security mode (Implicit/Explicit).
48       */
49      public AuthenticatingIMAPClient(boolean implicit)
50      {
51          this(DEFAULT_PROTOCOL, implicit);
52      }
53  
54      /**
55       * Constructor for AuthenticatingIMAPClient that delegates to IMAPSClient.
56       * @param proto the protocol.
57       */
58      public AuthenticatingIMAPClient(String proto)
59      {
60          this(proto, false);
61      }
62  
63      /**
64       * Constructor for AuthenticatingIMAPClient that delegates to IMAPSClient.
65       * @param proto the protocol.
66       * @param implicit The security mode(Implicit/Explicit).
67       */
68      public AuthenticatingIMAPClient(String proto, boolean implicit)
69      {
70          this(proto, implicit, null);
71      }
72  
73      /**
74       * Constructor for AuthenticatingIMAPClient that delegates to IMAPSClient.
75       * @param proto the protocol.
76       * @param implicit The security mode(Implicit/Explicit).
77       * @param ctx the context
78       */
79      public AuthenticatingIMAPClient(String proto, boolean implicit, SSLContext ctx)
80      {
81          super(proto, implicit, ctx);
82      }
83  
84      /**
85       * Constructor for AuthenticatingIMAPClient that delegates to IMAPSClient.
86       * @param implicit The security mode(Implicit/Explicit).
87       * @param ctx A pre-configured SSL Context.
88       */
89      public AuthenticatingIMAPClient(boolean implicit, SSLContext ctx)
90      {
91          this(DEFAULT_PROTOCOL, implicit, ctx);
92      }
93  
94      /**
95       * Constructor for AuthenticatingIMAPClient that delegates to IMAPSClient.
96       * @param context A pre-configured SSL Context.
97       */
98      public AuthenticatingIMAPClient(SSLContext context)
99      {
100         this(false, context);
101     }
102 
103     /**
104      * Authenticate to the IMAP server by sending the AUTHENTICATE command with the
105      * selected mechanism, using the given username and the given password.
106      *
107      * @param method the method name
108      * @param username user
109      * @param password password
110      * @return True if successfully completed, false if not.
111      * @exception IOException  If an I/O error occurs while either sending a
112      *      command to the server or receiving a reply from the server.
113      * @exception NoSuchAlgorithmException If the CRAM hash algorithm
114      *      cannot be instantiated by the Java runtime system.
115      * @exception InvalidKeyException If the CRAM hash algorithm
116      *      failed to use the given password.
117      * @exception InvalidKeySpecException If the CRAM hash algorithm
118      *      failed to use the given password.
119      */
120     public boolean authenticate(AuthenticatingIMAPClient.AUTH_METHOD method,
121                         String username, String password)
122                         throws IOException, NoSuchAlgorithmException,
123                         InvalidKeyException, InvalidKeySpecException
124     {
125         return auth(method, username, password);
126     }
127 
128     /**
129      * Authenticate to the IMAP server by sending the AUTHENTICATE command with the
130      * selected mechanism, using the given username and the given password.
131      *
132      * @param method the method name
133      * @param username user
134      * @param password password
135      * @return True if successfully completed, false if not.
136      * @exception IOException  If an I/O error occurs while either sending a
137      *      command to the server or receiving a reply from the server.
138      * @exception NoSuchAlgorithmException If the CRAM hash algorithm
139      *      cannot be instantiated by the Java runtime system.
140      * @exception InvalidKeyException If the CRAM hash algorithm
141      *      failed to use the given password.
142      * @exception InvalidKeySpecException If the CRAM hash algorithm
143      *      failed to use the given password.
144      */
145     public boolean auth(AuthenticatingIMAPClient.AUTH_METHOD method,
146                         String username, String password)
147                         throws IOException, NoSuchAlgorithmException,
148                         InvalidKeyException, InvalidKeySpecException
149     {
150         if (!IMAPReply.isContinuation(sendCommand(IMAPCommand.AUTHENTICATE, method.getAuthName())))
151         {
152             return false;
153         }
154 
155         switch (method) {
156             case PLAIN:
157             {
158                 // the server sends an empty response ("+ "), so we don't have to read it.
159                 int result = sendData(
160                     Base64.encodeBase64StringUnChunked(("\000" + username + "\000" + password)
161                             .getBytes(getCharsetName())));  // Java 1.6 can use getCharset()
162                 if (result == IMAPReply.OK)
163                 {
164                     setState(IMAP.IMAPState.AUTH_STATE);
165                 }
166                 return result == IMAPReply.OK;
167             }
168             case CRAM_MD5:
169             {
170                 // get the CRAM challenge (after "+ ")
171                 byte[] serverChallenge = Base64.decodeBase64(getReplyString().substring(2).trim());
172                 // get the Mac instance
173                 Mac hmac_md5 = Mac.getInstance("HmacMD5");
174                 hmac_md5.init(new SecretKeySpec(password.getBytes(getCharsetName()), "HmacMD5")); // Java 1.6 can use getCharset()
175                 // compute the result:
176                 // Java 1.6 can use getCharset()
177                 byte[] hmacResult = _convertToHexString(hmac_md5.doFinal(serverChallenge)).getBytes(getCharsetName());
178                 // join the byte arrays to form the reply
179                 byte[] usernameBytes = username.getBytes(getCharsetName()); // Java 1.6 can use getCharset()
180                 byte[] toEncode = new byte[usernameBytes.length + 1 /* the space */ + hmacResult.length];
181                 System.arraycopy(usernameBytes, 0, toEncode, 0, usernameBytes.length);
182                 toEncode[usernameBytes.length] = ' ';
183                 System.arraycopy(hmacResult, 0, toEncode, usernameBytes.length + 1, hmacResult.length);
184                 // send the reply and read the server code:
185                 int result = sendData(Base64.encodeBase64StringUnChunked(toEncode));
186                 if (result == IMAPReply.OK)
187                 {
188                     setState(IMAP.IMAPState.AUTH_STATE);
189                 }
190                 return result == IMAPReply.OK;
191             }
192             case LOGIN:
193             {
194                 // the server sends fixed responses (base64("Username") and
195                 // base64("Password")), so we don't have to read them.
196                 if (sendData(
197                         // Java 1.6 can use getCharset()
198                     Base64.encodeBase64StringUnChunked(username.getBytes(getCharsetName()))) != IMAPReply.CONT)
199                 {
200                     return false;
201                 }
202                 // Java 1.6 can use getCharset()
203                 int result = sendData(Base64.encodeBase64StringUnChunked(password.getBytes(getCharsetName())));
204                 if (result == IMAPReply.OK)
205                 {
206                     setState(IMAP.IMAPState.AUTH_STATE);
207                 }
208                 return result == IMAPReply.OK;
209             }
210             case XOAUTH:
211             {
212                 int result = sendData(username);
213                 if (result == IMAPReply.OK)
214                 {
215                     setState(IMAP.IMAPState.AUTH_STATE);
216                 }
217                 return result == IMAPReply.OK;
218             }
219         }
220         return false; // safety check
221     }
222 
223     /**
224      * Converts the given byte array to a String containing the hex values of the bytes.
225      * For example, the byte 'A' will be converted to '41', because this is the ASCII code
226      * (and the byte value) of the capital letter 'A'.
227      * @param a The byte array to convert.
228      * @return The resulting String of hex codes.
229      */
230     private String _convertToHexString(byte[] a)
231     {
232         StringBuilder result = new StringBuilder(a.length*2);
233         for (byte element : a)
234         {
235             if ( (element & 0x0FF) <= 15 ) {
236                 result.append("0");
237             }
238             result.append(Integer.toHexString(element & 0x0FF));
239         }
240         return result.toString();
241     }
242 
243     /**
244      * The enumeration of currently-supported authentication methods.
245      */
246     public static enum AUTH_METHOD
247     {
248         /** The standarised (RFC4616) PLAIN method, which sends the password unencrypted (insecure). */
249         PLAIN("PLAIN"),
250         /** The standarised (RFC2195) CRAM-MD5 method, which doesn't send the password (secure). */
251         CRAM_MD5("CRAM-MD5"),
252         /** The unstandarised Microsoft LOGIN method, which sends the password unencrypted (insecure). */
253         LOGIN("LOGIN"),
254         /** XOAUTH */
255         XOAUTH("XOAUTH");
256 
257         private final String authName;
258 
259         private AUTH_METHOD(String name){
260             this.authName=name;
261         }
262         /**
263          * Gets the name of the given authentication method suitable for the server.
264          * @return The name of the given authentication method suitable for the server.
265          */
266         public final String getAuthName()
267         {
268             return authName;
269         }
270     }
271 }
272 /* kate: indent-width 4; replace-tabs on; */