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.imap;
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.SSLException;
29 import javax.net.ssl.SSLHandshakeException;
30 import javax.net.ssl.SSLSocket;
31 import javax.net.ssl.SSLSocketFactory;
32 import javax.net.ssl.TrustManager;
33
34 import org.apache.commons.net.io.CRLFLineReader;
35 import org.apache.commons.net.util.SSLContextUtils;
36 import org.apache.commons.net.util.SSLSocketUtils;
37
38 /**
39 * The IMAPSClient class provides SSL/TLS connection encryption to IMAPClient. Copied from
40 * <a href="https://commons.apache.org/proper/commons-net/apidocs/index.html?org/apache/commons/net/ftp/FTPSClient.html"> FTPSClient</a> and modified to suit
41 * IMAP. If implicit mode is selected (NOT the default), SSL/TLS negotiation starts right after the connection has been established. In explicit mode (the
42 * default), SSL/TLS negotiation starts when the user calls execTLS() and the server accepts the command.
43 *
44 * <pre>
45 * {@code
46 * //Implicit usage:
47 *
48 * IMAPSClient c = new IMAPSClient(true);
49 * c.connect("127.0.0.1", 993);
50 *
51 * //Explicit usage:
52 *
53 * IMAPSClient c = new IMAPSClient();
54 * c.connect("127.0.0.1", 143);
55 * if (c.execTLS()) { /rest of the commands here/ }
56 * }
57 * </pre>
58 *
59 * <strong>Warning</strong>: the hostname is not verified against the certificate by default, use {@link #setHostnameVerifier(HostnameVerifier)} or
60 * {@link #setEndpointCheckingEnabled(boolean)} (on Java 1.7+) to enable verification.
61 */
62 public class IMAPSClient extends IMAPClient {
63
64 /** The default IMAP over SSL port. */
65 public static final int DEFAULT_IMAPS_PORT = 993;
66
67 /** Default secure socket protocol name. */
68 public static final String DEFAULT_PROTOCOL = "TLS";
69
70 /** The security mode. True - Implicit Mode / False - Explicit Mode. */
71 private final boolean isImplicit;
72
73 /** The secure socket protocol to be used, like SSL/TLS. */
74 private final String protocol;
75
76 /** The context object. */
77 private SSLContext context;
78
79 /**
80 * The cipher suites. SSLSockets have a default set of these anyway, so no initialization required.
81 */
82 private String[] suites;
83
84 /** The protocol versions. */
85 private String[] protocols // null;
86 ; // {"SSLv2", "SSLv3", "TLSv1", "TLSv1.1", "SSLv2Hello"};
87
88 /** The IMAPS {@link TrustManager} implementation, default null. */
89 private TrustManager trustManager;
90
91 /** The {@link KeyManager}, default null. */
92 private KeyManager keyManager;
93
94 /** The {@link HostnameVerifier} to use post-TLS, default null (i.e. no verification). */
95 private HostnameVerifier hostnameVerifier;
96
97 /** Use Java 1.7+ HTTPS Endpoint Identification Algorithm. */
98 private boolean tlsEndpointChecking;
99
100 /**
101 * Constructor for IMAPSClient. Sets security mode to explicit (isImplicit = false).
102 */
103 public IMAPSClient() {
104 this(DEFAULT_PROTOCOL, false);
105 }
106
107 /**
108 * Constructor for IMAPSClient.
109 *
110 * @param implicit The security mode (Implicit/Explicit).
111 */
112 public IMAPSClient(final boolean implicit) {
113 this(DEFAULT_PROTOCOL, implicit);
114 }
115
116 /**
117 * Constructor for IMAPSClient.
118 *
119 * @param implicit The security mode(Implicit/Explicit).
120 * @param ctx A pre-configured SSL Context.
121 */
122 public IMAPSClient(final boolean implicit, final SSLContext ctx) {
123 this(DEFAULT_PROTOCOL, implicit, ctx);
124 }
125
126 /**
127 * Constructor for IMAPSClient.
128 *
129 * @param context A pre-configured SSL Context.
130 */
131 public IMAPSClient(final SSLContext context) {
132 this(false, context);
133 }
134
135 /**
136 * Constructor for IMAPSClient.
137 *
138 * @param proto the protocol.
139 */
140 public IMAPSClient(final String proto) {
141 this(proto, false);
142 }
143
144 /**
145 * Constructor for IMAPSClient.
146 *
147 * @param proto the protocol.
148 * @param implicit The security mode(Implicit/Explicit).
149 */
150 public IMAPSClient(final String proto, final boolean implicit) {
151 this(proto, implicit, null);
152 }
153
154 /**
155 * Constructor for IMAPSClient.
156 *
157 * @param proto the protocol.
158 * @param implicit The security mode(Implicit/Explicit).
159 * @param ctx the SSL context
160 */
161 public IMAPSClient(final String proto, final boolean implicit, final SSLContext ctx) {
162 setDefaultPort(DEFAULT_IMAPS_PORT);
163 protocol = proto;
164 isImplicit = implicit;
165 context = ctx;
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 performSSLNegotiation();
180 }
181 super._connectAction_();
182 // Explicit mode - don't do anything. The user calls execTLS()
183 }
184
185 /**
186 * The TLS command execution.
187 *
188 * @throws SSLException If the server reply code is not positive.
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 SSLException, IOException {
193 if (sendCommand(IMAPCommand.getCommand(IMAPCommand.STARTTLS)) != IMAPReply.OK) {
194 return false;
195 // throw new SSLException(getReplyString());
196 }
197 performSSLNegotiation();
198 return true;
199 }
200
201 /**
202 * Gets 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}.
206 */
207 public String[] getEnabledCipherSuites() {
208 if (_socket_ instanceof SSLSocket) {
209 return ((SSLSocket) _socket_).getEnabledCipherSuites();
210 }
211 return null;
212 }
213
214 /**
215 * Gets 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}.
219 */
220 public String[] getEnabledProtocols() {
221 if (_socket_ instanceof SSLSocket) {
222 return ((SSLSocket) _socket_).getEnabledProtocols();
223 }
224 return null;
225 }
226
227 /**
228 * Gets 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 * Gets the {@link KeyManager} instance.
239 *
240 * @return The current {@link KeyManager} instance.
241 */
242 private KeyManager getKeyManager() {
243 return keyManager;
244 }
245
246 /**
247 * Gets 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 * Tests 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
295 if (protocols != null) {
296 socket.setEnabledProtocols(protocols);
297 }
298 if (suites != null) {
299 socket.setEnabledCipherSuites(suites);
300 }
301 socket.startHandshake();
302
303 // TODO the following setup appears to duplicate that in the super class methods
304 _socket_ = socket;
305 _input_ = socket.getInputStream();
306 _output_ = socket.getOutputStream();
307 _reader = new CRLFLineReader(new InputStreamReader(_input_, __DEFAULT_ENCODING));
308 __writer = new BufferedWriter(new OutputStreamWriter(_output_, __DEFAULT_ENCODING));
309
310 if (hostnameVerifier != null && !hostnameVerifier.verify(host, socket.getSession())) {
311 throw new SSLHandshakeException("Hostname doesn't match certificate");
312 }
313 }
314
315 /**
316 * Sets which particular cipher suites are enabled for use on this connection. Called before server negotiation.
317 *
318 * @param cipherSuites The cipher suites.
319 */
320 public void setEnabledCipherSuites(final String[] cipherSuites) {
321 suites = cipherSuites.clone();
322 }
323
324 /**
325 * Sets which particular protocol versions are enabled for use on this connection. I perform setting before a server negotiation.
326 *
327 * @param protocolVersions The protocol versions.
328 */
329 public void setEnabledProtocols(final String[] protocolVersions) {
330 protocols = protocolVersions.clone();
331 }
332
333 /**
334 * Sets automatic endpoint identification checking using the HTTPS algorithm is supported on Java 1.7+. The default behavior is for this to be disabled.
335 *
336 * @param enable Enable automatic endpoint identification checking using the HTTPS algorithm on Java 1.7+.
337 * @since 3.4
338 */
339 public void setEndpointCheckingEnabled(final boolean enable) {
340 tlsEndpointChecking = enable;
341 }
342
343 /**
344 * Sets to override the default {@link HostnameVerifier} to use.
345 *
346 * @param newHostnameVerifier The HostnameVerifier implementation to set or {@code null} to disable.
347 * @since 3.4
348 */
349 public void setHostnameVerifier(final HostnameVerifier newHostnameVerifier) {
350 hostnameVerifier = newHostnameVerifier;
351 }
352
353 /**
354 * Sets a {@link KeyManager} to use.
355 *
356 * @param newKeyManager The KeyManager implementation to set.
357 * @see org.apache.commons.net.util.KeyManagerUtils
358 */
359 public void setKeyManager(final KeyManager newKeyManager) {
360 keyManager = newKeyManager;
361 }
362
363 /**
364 * Sets to override the default {@link TrustManager} to use.
365 *
366 * @param newTrustManager The TrustManager implementation to set.
367 * @see org.apache.commons.net.util.TrustManagerUtils
368 */
369 public void setTrustManager(final TrustManager newTrustManager) {
370 trustManager = newTrustManager;
371 }
372 }
373