    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 *      http://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.smtp;
    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.SSLHandshakeException;
    029import javax.net.ssl.SSLSocket;
    030import javax.net.ssl.SSLSocketFactory;
    031import javax.net.ssl.TrustManager;
    032
    033import org.apache.commons.net.io.CRLFLineReader;
    034import org.apache.commons.net.util.SSLContextUtils;
    035import org.apache.commons.net.util.SSLSocketUtils;
    036
    037/**
    038 * 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
    039 * right after the connection has been established. In explicit mode (the default), SSL/TLS negotiation starts when the user calls execTLS() and the server
    040 * accepts the command. Implicit usage:
    041 *
    042 * <pre>
    043 * SMTPSClient c = new SMTPSClient(true);
    044 * c.connect("127.0.0.1", 465);
    045 * </pre>
    046 *
    047 * Explicit usage:
    048 *
    049 * <pre>
    050 * SMTPSClient c = new SMTPSClient();
    051 * c.connect("127.0.0.1", 25);
    052 * if (c.execTLS()) {
    053 *     // Rest of the commands here
    054 * }
    055 * </pre>
    056 *
    057 * <em>Warning</em>: the hostname is not verified against the certificate by default, use {@link #setHostnameVerifier(HostnameVerifier)} or
    058 * {@link #setEndpointCheckingEnabled(boolean)} (on Java 1.7+) to enable verification.
    059 *
    060 * @since 3.0
    061 */
    062public class SMTPSClient extends SMTPClient {
    063    /** Default secure socket protocol name, like TLS */
    064    private static final String DEFAULT_PROTOCOL = "TLS";
    065
    066    /** The security mode. True - Implicit Mode / False - Explicit Mode. */
    067
    068    private final boolean isImplicit;
    069    /** The secure socket protocol to be used, like SSL/TLS. */
    070
    071    private final String protocol;
    072    /** The context object. */
    073
    074    private SSLContext context;
    075    /**
    076     * The cipher suites. SSLSockets have a default set of these anyway, so no initialization required.
    077     */
    078
    079    private String[] suites;
    080    /** The protocol versions. */
    081
    082    private String[] protocols;
    083
    084    /** The {@link TrustManager} implementation, default null (i.e. use system managers). */
    085    private TrustManager trustManager;
    086
    087    /** The {@link KeyManager}, default null (i.e. use system managers). */
    088    private KeyManager keyManager; // seems not to be required
    089
    090    /** The {@link HostnameVerifier} to use post-TLS, default null (i.e. no verification). */
    091    private HostnameVerifier hostnameVerifier;
    092
    093    /** Use Java 1.7+ HTTPS Endpoint Identification Algorithm. */
    094    private boolean tlsEndpointChecking;
    095
    096    /**
    097     * Constructor for SMTPSClient, using {@link #DEFAULT_PROTOCOL} i.e. TLS Sets security mode to explicit (isImplicit = false).
    098     */
    099    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