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.smtp;
19  
20  import java.io.BufferedWriter;
21  import java.io.IOException;
22  import java.io.InputStreamReader;
23  import java.io.OutputStreamWriter;
24  
25  import javax.net.ssl.HostnameVerifier;
26  import javax.net.ssl.KeyManager;
27  import javax.net.ssl.SSLContext;
28  import javax.net.ssl.SSLHandshakeException;
29  import javax.net.ssl.SSLSocket;
30  import javax.net.ssl.SSLSocketFactory;
31  import javax.net.ssl.TrustManager;
32  
33  import org.apache.commons.net.io.CRLFLineReader;
34  import org.apache.commons.net.util.SSLContextUtils;
35  import org.apache.commons.net.util.SSLSocketUtils;
36  
37  /**
38   * SMTP over SSL processing. Copied from FTPSClient.java and modified to suit SMTP. If implicit mode is selected (NOT the default), SSL/TLS negotiation starts
39   * right after the connection has been established. In explicit mode (the default), SSL/TLS negotiation starts when the user calls execTLS() and the server
40   * accepts the command. Implicit usage:
41   *
42   * <pre>
43   * SMTPSClient c = new SMTPSClient(true);
44   * c.connect("127.0.0.1", 465);
45   * </pre>
46   *
47   * Explicit usage:
48   *
49   * <pre>
50   * SMTPSClient c = new SMTPSClient();
51   * c.connect("127.0.0.1", 25);
52   * if (c.execTLS()) {
53   *     // Rest of the commands here
54   * }
55   * </pre>
56   *
57   * <em>Warning</em>: the hostname is not verified against the certificate by default, use {@link #setHostnameVerifier(HostnameVerifier)} or
58   * {@link #setEndpointCheckingEnabled(boolean)} (on Java 1.7+) to enable verification.
59   *
60   * @since 3.0
61   */
62  public class SMTPSClient extends SMTPClient {
63      /** Default secure socket protocol name, like TLS */
64      private static final String DEFAULT_PROTOCOL = "TLS";
65  
66      /** The security mode. True - Implicit Mode / False - Explicit Mode. */
67  
68      private final boolean isImplicit;
69      /** The secure socket protocol to be used, like SSL/TLS. */
70  
71      private final String protocol;
72      /** The context object. */
73  
74      private SSLContext context;
75      /**
76       * The cipher suites. SSLSockets have a default set of these anyway, so no initialization required.
77       */
78  
79      private String[] suites;
80      /** The protocol versions. */
81  
82      private String[] protocols;
83  
84      /** The {@link TrustManager} implementation, default null (i.e. use system managers). */
85      private TrustManager trustManager;
86  
87      /** The {@link KeyManager}, default null (i.e. use system managers). */
88      private KeyManager keyManager; // seems not to be required
89  
90      /** The {@link HostnameVerifier} to use post-TLS, default null (i.e. no verification). */
91      private HostnameVerifier hostnameVerifier;
92  
93      /** Use Java 1.7+ HTTPS Endpoint Identification Algorithm. */
94      private boolean tlsEndpointChecking;
95  
96      /**
97       * Constructor for SMTPSClient, using {@link #DEFAULT_PROTOCOL} i.e. TLS Sets security mode to explicit (isImplicit = false).
98       */
99      public SMTPSClient() {
100         this(DEFAULT_PROTOCOL, false);
101     }
102 
103     /**
104      * Constructor for SMTPSClient, using {@link #DEFAULT_PROTOCOL} i.e. TLS
105      *
106      * @param implicit The security mode, {@code true} for implicit, {@code false} for explicit
107      */
108     public SMTPSClient(final boolean implicit) {
109         this(DEFAULT_PROTOCOL, implicit);
110     }
111 
112     /**
113      * Constructor for SMTPSClient, using {@link #DEFAULT_PROTOCOL} i.e. TLS
114      *
115      * @param implicit The security mode, {@code true} for implicit, {@code false} for explicit
116      * @param ctx      A pre-configured SSL Context.
117      */
118     public SMTPSClient(final boolean implicit, final SSLContext ctx) {
119         isImplicit = implicit;
120         context = ctx;
121         protocol = DEFAULT_PROTOCOL;
122     }
123 
124     /**
125      * Constructor for SMTPSClient.
126      *
127      * @param context A pre-configured SSL Context.
128      * @see #SMTPSClient(boolean, SSLContext)
129      */
130     public SMTPSClient(final SSLContext context) {
131         this(false, context);
132     }
133 
134     /**
135      * Constructor for SMTPSClient, using explicit security mode.
136      *
137      * @param proto the protocol.
138      */
139     public SMTPSClient(final String proto) {
140         this(proto, false);
141     }
142 
143     /**
144      * Constructor for SMTPSClient.
145      *
146      * @param proto    the protocol.
147      * @param implicit The security mode, {@code true} for implicit, {@code false} for explicit
148      */
149     public SMTPSClient(final String proto, final boolean implicit) {
150         protocol = proto;
151         isImplicit = implicit;
152     }
153 
154     /**
155      * Constructor for SMTPSClient.
156      *
157      * @param proto    the protocol.
158      * @param implicit The security mode, {@code true} for implicit, {@code false} for explicit
159      * @param encoding the encoding
160      * @since 3.3
161      */
162     public SMTPSClient(final String proto, final boolean implicit, final String encoding) {
163         super(encoding);
164         protocol = proto;
165         isImplicit = implicit;
166     }
167 
168     /**
169      * Because there are so many connect() methods, the _connectAction_() method is provided as a means of performing some action immediately after establishing
170      * a connection, rather than reimplementing all the connect() methods.
171      *
172      * @throws IOException If it is thrown by _connectAction_().
173      * @see org.apache.commons.net.SocketClient#_connectAction_()
174      */
175     @Override
176     protected void _connectAction_() throws IOException {
177         // Implicit mode.
178         if (isImplicit) {
179             applySocketAttributes();
180             performSSLNegotiation();
181         }
182         super._connectAction_();
183         // Explicit mode - don't do anything. The user calls execTLS()
184     }
185 
186     /**
187      * The TLS command execution.
188      *
189      * @throws IOException If an I/O error occurs while sending the command or performing the negotiation.
190      * @return TRUE if the command and negotiation succeeded.
191      */
192     public boolean execTLS() throws IOException {
193         if (!SMTPReply.isPositiveCompletion(sendCommand("STARTTLS"))) {
194             return false;
195             // throw new SSLException(getReplyString());
196         }
197         performSSLNegotiation();
198         return true;
199     }
200 
201     /**
202      * Returns the names of the cipher suites which could be enabled for use on this connection. When the underlying {@link java.net.Socket Socket} is not an
203      * {@link SSLSocket} instance, returns null.
204      *
205      * @return An array of cipher suite names, or <code>null</code>.
206      */
207     public String[] getEnabledCipherSuites() {
208         if (_socket_ instanceof SSLSocket) {
209             return ((SSLSocket) _socket_).getEnabledCipherSuites();
210         }
211         return null;
212     }
213 
214     /**
215      * Returns the names of the protocol versions which are currently enabled for use on this connection. When the underlying {@link java.net.Socket Socket} is
216      * not an {@link SSLSocket} instance, returns null.
217      *
218      * @return An array of protocols, or <code>null</code>.
219      */
220     public String[] getEnabledProtocols() {
221         if (_socket_ instanceof SSLSocket) {
222             return ((SSLSocket) _socket_).getEnabledProtocols();
223         }
224         return null;
225     }
226 
227     /**
228      * Get the currently configured {@link HostnameVerifier}.
229      *
230      * @return A HostnameVerifier instance.
231      * @since 3.4
232      */
233     public HostnameVerifier getHostnameVerifier() {
234         return hostnameVerifier;
235     }
236 
237     /**
238      * Get the {@link KeyManager} instance.
239      *
240      * @return The current {@link KeyManager} instance.
241      */
242     public KeyManager getKeyManager() {
243         return keyManager;
244     }
245 
246     /**
247      * Get the currently configured {@link TrustManager}.
248      *
249      * @return A TrustManager instance.
250      */
251     public TrustManager getTrustManager() {
252         return trustManager;
253     }
254 
255     /**
256      * Performs a lazy init of the SSL context.
257      *
258      * @throws IOException When could not initialize the SSL context.
259      */
260     private void initSSLContext() throws IOException {
261         if (context == null) {
262             context = SSLContextUtils.createSSLContext(protocol, getKeyManager(), getTrustManager());
263         }
264     }
265 
266     /**
267      * Return whether or not endpoint identification using the HTTPS algorithm on Java 1.7+ is enabled. The default behavior is for this to be disabled.
268      *
269      * @return True if enabled, false if not.
270      * @since 3.4
271      */
272     public boolean isEndpointCheckingEnabled() {
273         return tlsEndpointChecking;
274     }
275 
276     /**
277      * SSL/TLS negotiation. Acquires an SSL socket of a connection and carries out handshake processing.
278      *
279      * @throws IOException If server negotiation fails.
280      */
281     private void performSSLNegotiation() throws IOException {
282         initSSLContext();
283 
284         final SSLSocketFactory ssf = context.getSocketFactory();
285         final String host = _hostname_ != null ? _hostname_ : getRemoteAddress().getHostAddress();
286         final int port = getRemotePort();
287         final SSLSocket socket = (SSLSocket) ssf.createSocket(_socket_, host, port, true);
288         socket.setEnableSessionCreation(true);
289         socket.setUseClientMode(true);
290 
291         if (tlsEndpointChecking) {
292             SSLSocketUtils.enableEndpointNameVerification(socket);
293         }
294         if (protocols != null) {
295             socket.setEnabledProtocols(protocols);
296         }
297         if (suites != null) {
298             socket.setEnabledCipherSuites(suites);
299         }
300         socket.startHandshake();
301 
302         // TODO the following setup appears to duplicate that in the super class methods
303         _socket_ = socket;
304         _input_ = socket.getInputStream();
305         _output_ = socket.getOutputStream();
306         reader = new CRLFLineReader(new InputStreamReader(_input_, encoding));
307         writer = new BufferedWriter(new OutputStreamWriter(_output_, encoding));
308 
309         if (hostnameVerifier != null && !hostnameVerifier.verify(host, socket.getSession())) {
310             throw new SSLHandshakeException("Hostname doesn't match certificate");
311         }
312     }
313 
314     /**
315      * Controls which particular cipher suites are enabled for use on this connection. Called before server negotiation.
316      *
317      * @param cipherSuites The cipher suites.
318      */
319     public void setEnabledCipherSuites(final String[] cipherSuites) {
320         suites = cipherSuites.clone();
321     }
322 
323     /**
324      * Controls which particular protocol versions are enabled for use on this connection. I perform setting before a server negotiation.
325      *
326      * @param protocolVersions The protocol versions.
327      */
328     public void setEnabledProtocols(final String[] protocolVersions) {
329         protocols = protocolVersions.clone();
330     }
331 
332     /**
333      * Automatic endpoint identification checking using the HTTPS algorithm is supported on Java 1.7+. The default behavior is for this to be disabled.
334      *
335      * @param enable Enable automatic endpoint identification checking using the HTTPS algorithm on Java 1.7+.
336      * @since 3.4
337      */
338     public void setEndpointCheckingEnabled(final boolean enable) {
339         tlsEndpointChecking = enable;
340     }
341 
342     /**
343      * Override the default {@link HostnameVerifier} to use.
344      *
345      * @param newHostnameVerifier The HostnameVerifier implementation to set or <code>null</code> to disable.
346      * @since 3.4
347      */
348     public void setHostnameVerifier(final HostnameVerifier newHostnameVerifier) {
349         hostnameVerifier = newHostnameVerifier;
350     }
351 
352     /**
353      * Set a {@link KeyManager} to use.
354      *
355      * @param newKeyManager The KeyManager implementation to set.
356      * @see org.apache.commons.net.util.KeyManagerUtils
357      */
358     public void setKeyManager(final KeyManager newKeyManager) {
359         keyManager = newKeyManager;
360     }
361 
362     /**
363      * Override the default {@link TrustManager} to use.
364      *
365      * @param newTrustManager The TrustManager implementation to set.
366      * @see org.apache.commons.net.util.TrustManagerUtils
367      */
368     public void setTrustManager(final TrustManager newTrustManager) {
369         trustManager = newTrustManager;
370     }
371 }
372 
373