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    *      https://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.smtp;
19  
20  import java.io.IOException;
21  import java.net.InetAddress;
22  import java.security.InvalidKeyException;
23  import java.security.NoSuchAlgorithmException;
24  import java.util.Arrays;
25  import java.util.Base64;
26  
27  import javax.crypto.Mac;
28  import javax.crypto.spec.SecretKeySpec;
29  import javax.net.ssl.SSLContext;
30  
31  /**
32   * An SMTP Client class with authentication support (RFC4954).
33   *
34   * @see SMTPClient
35   * @since 3.0
36   */
37  public class AuthenticatingSMTPClient extends SMTPSClient {
38  
39      /**
40       * The enumeration of currently-supported authentication methods.
41       */
42      public enum AUTH_METHOD {
43  
44          /** The standardized (RFC4616) PLAIN method, which sends the password unencrypted (insecure). */
45          PLAIN,
46  
47          /** The standardized (RFC2195) CRAM-MD5 method, which doesn't send the password (secure). */
48          CRAM_MD5,
49  
50          /** The non-standarized Microsoft LOGIN method, which sends the password unencrypted (insecure). */
51          LOGIN,
52  
53          /** XOAuth method which accepts a signed and base64ed OAuth URL. */
54          XOAUTH,
55  
56          /** XOAuth 2 method which accepts a signed and base64ed OAuth JSON. */
57          XOAUTH2;
58  
59          /**
60           * Gets the name of the given authentication method suitable for the server.
61           *
62           * @param method The authentication method to get the name for.
63           * @return The name of the given authentication method suitable for the server.
64           */
65          public static String getAuthName(final AUTH_METHOD method) {
66              if (method.equals(PLAIN)) {
67                  return "PLAIN";
68              }
69              if (method.equals(CRAM_MD5)) {
70                  return "CRAM-MD5";
71              }
72              if (method.equals(LOGIN)) {
73                  return "LOGIN";
74              }
75              if (method.equals(XOAUTH)) {
76                  return "XOAUTH";
77              }
78              if (method.equals(XOAUTH2)) {
79                  return "XOAUTH2";
80              }
81              return null;
82          }
83      }
84  
85      /** {@link Mac} algorithm. */
86      private static final String MAC_ALGORITHM = "HmacMD5";
87  
88      /**
89       * The default AuthenticatingSMTPClient constructor. Creates a new Authenticating SMTP Client.
90       */
91      public AuthenticatingSMTPClient() {
92      }
93  
94      /**
95       * Overloaded constructor that takes the implicit argument, and using {@link #DEFAULT_PROTOCOL} i.e. TLS
96       *
97       * @param implicit The security mode, {@code true} for implicit, {@code false} for explicit
98       * @param ctx      A pre-configured SSL Context.
99       * @since 3.3
100      */
101     public AuthenticatingSMTPClient(final boolean implicit, final SSLContext ctx) {
102         super(implicit, ctx);
103     }
104 
105     /**
106      * Overloaded constructor that takes a protocol specification
107      *
108      * @param protocol The protocol to use
109      */
110     public AuthenticatingSMTPClient(final String protocol) {
111         super(protocol);
112     }
113 
114     /**
115      * Overloaded constructor that takes a protocol specification and the implicit argument
116      *
117      * @param proto    the protocol.
118      * @param implicit The security mode, {@code true} for implicit, {@code false} for explicit
119      * @since 3.3
120      */
121     public AuthenticatingSMTPClient(final String proto, final boolean implicit) {
122         super(proto, implicit);
123     }
124 
125     /**
126      * Overloaded constructor that takes the protocol specification, the implicit argument and encoding
127      *
128      * @param proto    the protocol.
129      * @param implicit The security mode, {@code true} for implicit, {@code false} for explicit
130      * @param encoding the encoding
131      * @since 3.3
132      */
133     public AuthenticatingSMTPClient(final String proto, final boolean implicit, final String encoding) {
134         super(proto, implicit, encoding);
135     }
136 
137     /**
138      * Overloaded constructor that takes a protocol specification and encoding
139      *
140      * @param protocol The protocol to use
141      * @param encoding The encoding to use
142      * @since 3.3
143      */
144     public AuthenticatingSMTPClient(final String protocol, final String encoding) {
145         super(protocol, false, encoding);
146     }
147 
148     /**
149      * Authenticate to the SMTP server by sending the AUTH command with the selected mechanism, using the given user and the given password.
150      *
151      * @param method   the method to use, one of the {@link AuthenticatingSMTPClient.AUTH_METHOD} enum values
152      * @param user the user name. If the method is XOAUTH/XOAUTH2, then this is used as the plain text oauth protocol parameter string which is
153      *                 Base64-encoded for transmission.
154      * @param password the password for the username. Ignored for XOAUTH/XOAUTH2.
155      * @return True if successfully completed, false if not.
156      * @throws SMTPConnectionClosedException If the SMTP server prematurely closes the connection as a result of the client being idle or some other reason
157      *                                       causing the server to send SMTP reply code 421. This exception may be caught either as an IOException or
158      *                                       independently as itself.
159      * @throws IOException                   If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
160      * @throws NoSuchAlgorithmException      If the CRAM hash algorithm cannot be instantiated by the Java runtime system.
161      * @throws InvalidKeyException           If the CRAM hash algorithm failed to use the given password.
162      */
163     public boolean auth(final AuthenticatingSMTPClient.AUTH_METHOD method, final String user, final String password)
164             throws IOException, NoSuchAlgorithmException, InvalidKeyException {
165         if (!SMTPReply.isPositiveIntermediate(sendCommand(SMTPCommand.AUTH, AUTH_METHOD.getAuthName(method)))) {
166             return false;
167         }
168 
169         if (method.equals(AUTH_METHOD.PLAIN)) {
170             // the server sends an empty response ("334 "), so we don't have to read it.
171             return SMTPReply
172                     .isPositiveCompletion(sendCommand(Base64.getEncoder().encodeToString(("\000" + user + "\000" + password).getBytes(getCharset()))));
173         }
174         if (method.equals(AUTH_METHOD.CRAM_MD5)) {
175             // get the CRAM challenge
176             final byte[] serverChallenge = Base64.getDecoder().decode(getReplyString().substring(4).trim());
177             // get the Mac instance
178             final Mac hmacMd5 = Mac.getInstance(MAC_ALGORITHM);
179             hmacMd5.init(new SecretKeySpec(password.getBytes(getCharset()), MAC_ALGORITHM));
180             // compute the result:
181             final byte[] hmacResult = convertToHexString(hmacMd5.doFinal(serverChallenge)).getBytes(getCharset());
182             // join the byte arrays to form the reply
183             final byte[] userNameBytes = user.getBytes(getCharset());
184             final byte[] toEncode = new byte[userNameBytes.length + 1 /* the space */ + hmacResult.length];
185             System.arraycopy(userNameBytes, 0, toEncode, 0, userNameBytes.length);
186             toEncode[userNameBytes.length] = ' ';
187             System.arraycopy(hmacResult, 0, toEncode, userNameBytes.length + 1, hmacResult.length);
188             // send the reply and read the server code:
189             return SMTPReply.isPositiveCompletion(sendCommand(Base64.getEncoder().encodeToString(toEncode)));
190         }
191         if (method.equals(AUTH_METHOD.LOGIN)) {
192             // the server sends fixed responses (base64("UserName") and
193             // base64("Password")), so we don't have to read them.
194             if (!SMTPReply.isPositiveIntermediate(sendCommand(Base64.getEncoder().encodeToString(user.getBytes(getCharset()))))) {
195                 return false;
196             }
197             return SMTPReply.isPositiveCompletion(sendCommand(Base64.getEncoder().encodeToString(password.getBytes(getCharset()))));
198         }
199         if (method.equals(AUTH_METHOD.XOAUTH) || method.equals(AUTH_METHOD.XOAUTH2)) {
200             return SMTPReply.isPositiveIntermediate(sendCommand(Base64.getEncoder().encodeToString(user.getBytes(getCharset()))));
201         }
202         return false; // safety check
203     }
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 
223     /**
224      * A convenience method to send the ESMTP EHLO command to the server, receive the reply, and return the reply code.
225      *
226      * @param hostname The hostname of the sender.
227      * @return The reply code received from the server.
228      * @throws SMTPConnectionClosedException If the SMTP server prematurely closes the connection as a result of the client being idle or some other reason
229      *                                       causing the server to send SMTP reply code 421. This exception may be caught either as an IOException or
230      *                                       independently as itself.
231      * @throws IOException                   If an I/O error occurs while either sending the command or receiving the server reply.
232      */
233     public int ehlo(final String hostname) throws IOException {
234         return sendCommand(SMTPCommand.EHLO, hostname);
235     }
236 
237     /**
238      * Login to the ESMTP server by sending the EHLO command with the client hostname as an argument. Before performing any mail commands, you must first login.
239      *
240      * @return True if successfully completed, false if not.
241      * @throws SMTPConnectionClosedException If the SMTP server prematurely closes the connection as a result of the client being idle or some other reason
242      *                                       causing the server to send SMTP reply code 421. This exception may be caught either as an IOException or
243      *                                       independently as itself.
244      * @throws IOException                   If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
245      */
246     public boolean elogin() throws IOException {
247         final String name;
248         final InetAddress host;
249 
250         host = getLocalAddress();
251         name = host.getHostName();
252 
253         if (name == null) {
254             return false;
255         }
256 
257         return SMTPReply.isPositiveCompletion(ehlo(name));
258     }
259 
260     /**
261      * Login to the ESMTP server by sending the EHLO command with the given hostname as an argument. Before performing any mail commands, you must first login.
262      *
263      * @param hostname The hostname with which to greet the SMTP server.
264      * @return True if successfully completed, false if not.
265      * @throws SMTPConnectionClosedException If the SMTP server prematurely closes the connection as a result of the client being idle or some other reason
266      *                                       causing the server to send SMTP reply code 421. This exception may be caught either as an IOException or
267      *                                       independently as itself.
268      * @throws IOException                   If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
269      */
270     public boolean elogin(final String hostname) throws IOException {
271         return SMTPReply.isPositiveCompletion(ehlo(hostname));
272     }
273 
274     /**
275      * Gets the integer values of the enhanced reply code of the last SMTP reply.
276      *
277      * @return The integer values of the enhanced reply code of the last SMTP reply. First digit is in the first array element.
278      */
279     public int[] getEnhancedReplyCode() {
280         final String reply = getReplyString().substring(4);
281         final String[] parts = reply.substring(0, reply.indexOf(' ')).split("\\.");
282         final int[] res = new int[parts.length];
283         Arrays.setAll(res, i -> Integer.parseInt(parts[i]));
284         return res;
285     }
286 }