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