001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * https://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018package org.apache.commons.net.imap; 019 020import java.io.BufferedWriter; 021import java.io.IOException; 022import java.io.InputStreamReader; 023import java.io.OutputStreamWriter; 024 025import javax.net.ssl.HostnameVerifier; 026import javax.net.ssl.KeyManager; 027import javax.net.ssl.SSLContext; 028import javax.net.ssl.SSLException; 029import javax.net.ssl.SSLHandshakeException; 030import javax.net.ssl.SSLSocket; 031import javax.net.ssl.SSLSocketFactory; 032import javax.net.ssl.TrustManager; 033 034import org.apache.commons.net.io.CRLFLineReader; 035import org.apache.commons.net.util.SSLContextUtils; 036import org.apache.commons.net.util.SSLSocketUtils; 037 038/** 039 * The IMAPSClient class provides SSL/TLS connection encryption to IMAPClient. Copied from 040 * <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 041 * IMAP. If implicit mode is selected (NOT the default), SSL/TLS negotiation starts right after the connection has been established. In explicit mode (the 042 * default), SSL/TLS negotiation starts when the user calls execTLS() and the server accepts the command. 043 * 044 * <pre> 045 * {@code 046 * //Implicit usage: 047 * 048 * IMAPSClient c = new IMAPSClient(true); 049 * c.connect("127.0.0.1", 993); 050 * 051 * //Explicit usage: 052 * 053 * IMAPSClient c = new IMAPSClient(); 054 * c.connect("127.0.0.1", 143); 055 * if (c.execTLS()) { /rest of the commands here/ } 056 * } 057 * </pre> 058 * 059 * <strong>Warning</strong>: the hostname is not verified against the certificate by default, use {@link #setHostnameVerifier(HostnameVerifier)} or 060 * {@link #setEndpointCheckingEnabled(boolean)} (on Java 1.7+) to enable verification. 061 */ 062public class IMAPSClient extends IMAPClient { 063 064 /** The default IMAP over SSL port. */ 065 public static final int DEFAULT_IMAPS_PORT = 993; 066 067 /** Default secure socket protocol name. */ 068 public static final String DEFAULT_PROTOCOL = "TLS"; 069 070 /** The security mode. True - Implicit Mode / False - Explicit Mode. */ 071 private final boolean isImplicit; 072 073 /** The secure socket protocol to be used, like SSL/TLS. */ 074 private final String protocol; 075 076 /** The context object. */ 077 private SSLContext context; 078 079 /** 080 * The cipher suites. SSLSockets have a default set of these anyway, so no initialization required. 081 */ 082 private String[] suites; 083 084 /** The protocol versions. */ 085 private String[] protocols // null; 086 ; // {"SSLv2", "SSLv3", "TLSv1", "TLSv1.1", "SSLv2Hello"}; 087 088 /** The IMAPS {@link TrustManager} implementation, default null. */ 089 private TrustManager trustManager; 090 091 /** The {@link KeyManager}, default null. */ 092 private KeyManager keyManager; 093 094 /** The {@link HostnameVerifier} to use post-TLS, default null (i.e. no verification). */ 095 private HostnameVerifier hostnameVerifier; 096 097 /** Use Java 1.7+ HTTPS Endpoint Identification Algorithm. */ 098 private boolean tlsEndpointChecking; 099 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