POP3SClient.java

  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. package org.apache.commons.net.pop3;

  18. import java.io.BufferedWriter;
  19. import java.io.IOException;
  20. import java.io.InputStreamReader;
  21. import java.io.OutputStreamWriter;

  22. import javax.net.ssl.HostnameVerifier;
  23. import javax.net.ssl.KeyManager;
  24. import javax.net.ssl.SSLContext;
  25. import javax.net.ssl.SSLException;
  26. import javax.net.ssl.SSLHandshakeException;
  27. import javax.net.ssl.SSLSocket;
  28. import javax.net.ssl.SSLSocketFactory;
  29. import javax.net.ssl.TrustManager;

  30. import org.apache.commons.net.io.CRLFLineReader;
  31. import org.apache.commons.net.util.SSLContextUtils;
  32. import org.apache.commons.net.util.SSLSocketUtils;

  33. /**
  34.  * POP3 over SSL processing. Copied from FTPSClient.java and modified to suit POP3. If implicit mode is selected (NOT the default), SSL/TLS negotiation starts
  35.  * right after the connection has been established. In explicit mode (the default), SSL/TLS negotiation starts when the user calls execTLS() and the server
  36.  * accepts the command. Implicit usage: POP3SClient c = new POP3SClient(true); c.connect("127.0.0.1", 995); Explicit usage: POP3SClient c = new POP3SClient();
  37.  * c.connect("127.0.0.1", 110); if (c.execTLS()) { /rest of the commands here/ }
  38.  *
  39.  * Warning: the hostname is not verified against the certificate by default, use {@link #setHostnameVerifier(HostnameVerifier)} or
  40.  * {@link #setEndpointCheckingEnabled(boolean)} (on Java 1.7+) to enable verification.
  41.  *
  42.  * @since 3.0
  43.  */
  44. public class POP3SClient extends POP3Client {
  45.     // from http://www.iana.org/assignments/port-numbers

  46.     // pop3s 995/tcp pop3 protocol over TLS/SSL (was spop3)
  47.     // pop3s 995/udp pop3 protocol over TLS/SSL (was spop3)

  48.     private static final int DEFAULT_POP3S_PORT = 995;

  49.     /** Default secure socket protocol name, like TLS */
  50.     private static final String DEFAULT_PROTOCOL = "TLS";

  51.     /** The security mode. True - Implicit Mode / False - Explicit Mode. */
  52.     private final boolean isImplicit;
  53.     /** The secure socket protocol to be used, like SSL/TLS. */
  54.     private final String protocol;
  55.     /** The context object. */
  56.     private SSLContext context;
  57.     /**
  58.      * The cipher suites. SSLSockets have a default set of these anyway, so no initialization required.
  59.      */
  60.     private String[] suites;
  61.     /** The protocol versions. */
  62.     private String[] protocols // null;
  63.     ; // {"SSLv2", "SSLv3", "TLSv1", "TLSv1.1", "SSLv2Hello"};

  64.     /** The FTPS {@link TrustManager} implementation, default null. */
  65.     private TrustManager trustManager;

  66.     /** The {@link KeyManager}, default null. */
  67.     private KeyManager keyManager;

  68.     /** The {@link HostnameVerifier} to use post-TLS, default null (i.e. no verification). */
  69.     private HostnameVerifier hostnameVerifier;

  70.     /** Use Java 1.7+ HTTPS Endpoint Identification Algorithm. */
  71.     private boolean tlsEndpointChecking;

  72.     /**
  73.      * Constructor for POP3SClient, using {@link #DEFAULT_PROTOCOL} i.e. TLS Sets security mode to explicit.
  74.      */
  75.     public POP3SClient() {
  76.         this(DEFAULT_PROTOCOL, false);
  77.     }

  78.     /**
  79.      * Constructor for POP3SClient, using {@link #DEFAULT_PROTOCOL} i.e. TLS
  80.      *
  81.      * @param implicit The security mode, {@code true} for implicit, {@code false} for explicit
  82.      */
  83.     public POP3SClient(final boolean implicit) {
  84.         this(DEFAULT_PROTOCOL, implicit);
  85.     }

  86.     /**
  87.      * Constructor for POP3SClient, using {@link #DEFAULT_PROTOCOL} i.e. TLS
  88.      *
  89.      * @param implicit The security mode, {@code true} for implicit, {@code false} for explicit
  90.      * @param ctx      A pre-configured SSL Context.
  91.      */
  92.     public POP3SClient(final boolean implicit, final SSLContext ctx) {
  93.         this(DEFAULT_PROTOCOL, implicit, ctx);
  94.     }

  95.     /**
  96.      * Constructor for POP3SClient, using {@link #DEFAULT_PROTOCOL} - TLS - and isImplicit = false
  97.      *
  98.      * @param context A pre-configured SSL Context.
  99.      * @see #POP3SClient(boolean, SSLContext)
  100.      */
  101.     public POP3SClient(final SSLContext context) {
  102.         this(false, context);
  103.     }

  104.     /**
  105.      * Constructor for POP3SClient. Sets security mode to explicit.
  106.      *
  107.      * @param proto the protocol.
  108.      */
  109.     public POP3SClient(final String proto) {
  110.         this(proto, false);
  111.     }

  112.     /**
  113.      * Constructor for POP3SClient.
  114.      *
  115.      * @param proto    the protocol.
  116.      * @param implicit The security mode, {@code true} for implicit, {@code false} for explicit
  117.      */
  118.     public POP3SClient(final String proto, final boolean implicit) {
  119.         this(proto, implicit, null);
  120.     }

  121.     /**
  122.      * Constructor for POP3SClient. Sets the default port to {@link #DEFAULT_POP3S_PORT} - 995 - if using implicit mode
  123.      *
  124.      * @param proto    the protocol.
  125.      * @param implicit The security mode, {@code true} for implicit, {@code false} for explicit
  126.      * @param ctx      the context to be used
  127.      */
  128.     public POP3SClient(final String proto, final boolean implicit, final SSLContext ctx) {
  129.         protocol = proto;
  130.         isImplicit = implicit;
  131.         context = ctx;
  132.         if (isImplicit) {
  133.             setDefaultPort(DEFAULT_POP3S_PORT);
  134.         }
  135.     }

  136.     /**
  137.      * Because there are so many connect() methods, the _connectAction_() method is provided as a means of performing some action immediately after establishing
  138.      * a connection, rather than reimplementing all the connect() methods.
  139.      *
  140.      * @throws IOException If it is thrown by _connectAction_().
  141.      * @see org.apache.commons.net.SocketClient#_connectAction_()
  142.      */
  143.     @Override
  144.     protected void _connectAction_() throws IOException {
  145.         // Implicit mode.
  146.         if (isImplicit) {
  147.             applySocketAttributes();
  148.             performSSLNegotiation();
  149.         }
  150.         super._connectAction_();
  151.         // Explicit mode - don't do anything. The user calls execTLS()
  152.     }

  153.     /**
  154.      * The TLS command execution.
  155.      *
  156.      * @throws SSLException If the server reply code is not positive.
  157.      * @throws IOException  If an I/O error occurs while sending the command or performing the negotiation.
  158.      * @return TRUE if the command and negotiation succeeded.
  159.      */
  160.     public boolean execTLS() throws SSLException, IOException {
  161.         if (sendCommand("STLS") != POP3Reply.OK) {
  162.             return false;
  163.             // throw new SSLException(getReplyString());
  164.         }
  165.         performSSLNegotiation();
  166.         return true;
  167.     }

  168.     /**
  169.      * 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
  170.      * {@link SSLSocket} instance, returns null.
  171.      *
  172.      * @return An array of cipher suite names, or {@code null}.
  173.      */
  174.     public String[] getEnabledCipherSuites() {
  175.         if (_socket_ instanceof SSLSocket) {
  176.             return ((SSLSocket) _socket_).getEnabledCipherSuites();
  177.         }
  178.         return null;
  179.     }

  180.     /**
  181.      * 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
  182.      * not an {@link SSLSocket} instance, returns null.
  183.      *
  184.      * @return An array of protocols, or {@code null}.
  185.      */
  186.     public String[] getEnabledProtocols() {
  187.         if (_socket_ instanceof SSLSocket) {
  188.             return ((SSLSocket) _socket_).getEnabledProtocols();
  189.         }
  190.         return null;
  191.     }

  192.     /**
  193.      * Gets the currently configured {@link HostnameVerifier}.
  194.      *
  195.      * @return A HostnameVerifier instance.
  196.      * @since 3.4
  197.      */
  198.     public HostnameVerifier getHostnameVerifier() {
  199.         return hostnameVerifier;
  200.     }

  201.     /**
  202.      * Gets the {@link KeyManager} instance.
  203.      *
  204.      * @return The current {@link KeyManager} instance.
  205.      */
  206.     private KeyManager getKeyManager() {
  207.         return keyManager;
  208.     }

  209.     /**
  210.      * Gets the currently configured {@link TrustManager}.
  211.      *
  212.      * @return A TrustManager instance.
  213.      */
  214.     public TrustManager getTrustManager() {
  215.         return trustManager;
  216.     }

  217.     /**
  218.      * Performs a lazy init of the SSL context.
  219.      *
  220.      * @throws IOException When could not initialize the SSL context.
  221.      */
  222.     private void initSSLContext() throws IOException {
  223.         if (context == null) {
  224.             context = SSLContextUtils.createSSLContext(protocol, getKeyManager(), getTrustManager());
  225.         }
  226.     }

  227.     /**
  228.      * 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.
  229.      *
  230.      * @return True if enabled, false if not.
  231.      * @since 3.4
  232.      */
  233.     public boolean isEndpointCheckingEnabled() {
  234.         return tlsEndpointChecking;
  235.     }

  236.     /**
  237.      * SSL/TLS negotiation. Acquires an SSL socket of a connection and carries out handshake processing.
  238.      *
  239.      * @throws IOException If server negotiation fails.
  240.      */
  241.     private void performSSLNegotiation() throws IOException {
  242.         initSSLContext();

  243.         final SSLSocketFactory ssf = context.getSocketFactory();
  244.         final String host = _hostname_ != null ? _hostname_ : getRemoteAddress().getHostAddress();
  245.         final int port = getRemotePort();
  246.         final SSLSocket socket = (SSLSocket) ssf.createSocket(_socket_, host, port, true);
  247.         socket.setEnableSessionCreation(true);
  248.         socket.setUseClientMode(true);

  249.         if (tlsEndpointChecking) {
  250.             SSLSocketUtils.enableEndpointNameVerification(socket);
  251.         }

  252.         if (protocols != null) {
  253.             socket.setEnabledProtocols(protocols);
  254.         }
  255.         if (suites != null) {
  256.             socket.setEnabledCipherSuites(suites);
  257.         }
  258.         socket.startHandshake();

  259.         // TODO the following setup appears to duplicate that in the super class methods
  260.         _socket_ = socket;
  261.         _input_ = socket.getInputStream();
  262.         _output_ = socket.getOutputStream();
  263.         reader = new CRLFLineReader(new InputStreamReader(_input_, DEFAULT_ENCODING));
  264.         writer = new BufferedWriter(new OutputStreamWriter(_output_, DEFAULT_ENCODING));

  265.         if (hostnameVerifier != null && !hostnameVerifier.verify(host, socket.getSession())) {
  266.             throw new SSLHandshakeException("Hostname doesn't match certificate");
  267.         }
  268.     }

  269.     /**
  270.      * Controls which particular cipher suites are enabled for use on this connection. Called before server negotiation.
  271.      *
  272.      * @param cipherSuites The cipher suites.
  273.      */
  274.     public void setEnabledCipherSuites(final String[] cipherSuites) {
  275.         suites = cipherSuites.clone();
  276.     }

  277.     /**
  278.      * Controls which particular protocol versions are enabled for use on this connection. I perform setting before a server negotiation.
  279.      *
  280.      * @param protocolVersions The protocol versions.
  281.      */
  282.     public void setEnabledProtocols(final String[] protocolVersions) {
  283.         protocols = protocolVersions.clone();
  284.     }

  285.     /**
  286.      * Automatic endpoint identification checking using the HTTPS algorithm is supported on Java 1.7+. The default behavior is for this to be disabled.
  287.      *
  288.      * @param enable Enable automatic endpoint identification checking using the HTTPS algorithm on Java 1.7+.
  289.      * @since 3.4
  290.      */
  291.     public void setEndpointCheckingEnabled(final boolean enable) {
  292.         tlsEndpointChecking = enable;
  293.     }

  294.     /**
  295.      * Override the default {@link HostnameVerifier} to use.
  296.      *
  297.      * @param newHostnameVerifier The HostnameVerifier implementation to set or {@code null} to disable.
  298.      * @since 3.4
  299.      */
  300.     public void setHostnameVerifier(final HostnameVerifier newHostnameVerifier) {
  301.         hostnameVerifier = newHostnameVerifier;
  302.     }

  303.     /**
  304.      * Sets a {@link KeyManager} to use.
  305.      *
  306.      * @param newKeyManager The KeyManager implementation to set.
  307.      * @see org.apache.commons.net.util.KeyManagerUtils
  308.      */
  309.     public void setKeyManager(final KeyManager newKeyManager) {
  310.         keyManager = newKeyManager;
  311.     }

  312.     /**
  313.      * Override the default {@link TrustManager} to use.
  314.      *
  315.      * @param newTrustManager The TrustManager implementation to set.
  316.      * @see org.apache.commons.net.util.TrustManagerUtils
  317.      */
  318.     public void setTrustManager(final TrustManager newTrustManager) {
  319.         trustManager = newTrustManager;
  320.     }
  321. }