    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.smtp;
    019
    020import java.io.IOException;
    021import java.net.InetAddress;
    022import java.security.InvalidKeyException;
    023import java.security.NoSuchAlgorithmException;
    024import java.util.Arrays;
    025import java.util.Base64;
    026
    027import javax.crypto.Mac;
    028import javax.crypto.spec.SecretKeySpec;
    029import javax.net.ssl.SSLContext;
    030
    031/**
    032 * An SMTP Client class with authentication support (RFC4954).
    033 *
    034 * @see SMTPClient
    035 * @since 3.0
    036 */
    037public class AuthenticatingSMTPClient extends SMTPSClient {
    038
    039    /**
    040     * The enumeration of currently-supported authentication methods.
    041     */
    042    public enum AUTH_METHOD {
    043
    044        /** The standardized (RFC4616) PLAIN method, which sends the password unencrypted (insecure). */
    045        PLAIN,
    046
    047        /** The standardized (RFC2195) CRAM-MD5 method, which doesn't send the password (secure). */
    048        CRAM_MD5,
    049
    050        /** The non-standarized Microsoft LOGIN method, which sends the password unencrypted (insecure). */
    051        LOGIN,
    052
    053        /** XOAuth method which accepts a signed and base64ed OAuth URL. */
    054        XOAUTH,
    055
    056        /** XOAuth 2 method which accepts a signed and base64ed OAuth JSON. */
    057        XOAUTH2;
    058
    059        /**
    060         * Gets the name of the given authentication method suitable for the server.
    061         *
    062         * @param method The authentication method to get the name for.
    063         * @return The name of the given authentication method suitable for the server.
    064         */
    065        public static String getAuthName(final AUTH_METHOD method) {
    066            if (method.equals(PLAIN)) {
    067                return "PLAIN";
    068            }
    069            if (method.equals(CRAM_MD5)) {
    070                return "CRAM-MD5";
    071            }
    072            if (method.equals(LOGIN)) {
    073                return "LOGIN";
    074            }
    075            if (method.equals(XOAUTH)) {
    076                return "XOAUTH";
    077            }
    078            if (method.equals(XOAUTH2)) {
    079                return "XOAUTH2";
    080            }
    081            return null;
    082        }
    083    }
    084
    085    /** {@link Mac} algorithm. */
    086    private static final String MAC_ALGORITHM = "HmacMD5";
    087
    088    /**
    089     * The default AuthenticatingSMTPClient constructor. Creates a new Authenticating SMTP Client.
    090     */
    091    public AuthenticatingSMTPClient() {
    092    }
    093
    094    /**
    095     * Overloaded constructor that takes the implicit argument, and using {@link #DEFAULT_PROTOCOL} i.e. TLS
    096     *
    097     * @param implicit The security mode, {@code true} for implicit, {@code false} for explicit
    098     * @param ctx      A pre-configured SSL Context.
    099     * @since 3.3
    100     */
    101    public AuthenticatingSMTPClient(final boolean implicit, final SSLContext ctx) {
    102        super(implicit, ctx);
    103    }
    104
    105    /**
    106     * Overloaded constructor that takes a protocol specification
    107     *
    108     * @param protocol The protocol to use
    109     */
    110    public AuthenticatingSMTPClient(final String protocol) {
    111        super(protocol);
    112    }
    113
    114    /**
    115     * Overloaded constructor that takes a protocol specification and the implicit argument
    116     *
    117     * @param proto    the protocol.
    118     * @param implicit The security mode, {@code true} for implicit, {@code false} for explicit
    119     * @since 3.3
    120     */
    121    public AuthenticatingSMTPClient(final String proto, final boolean implicit) {
    122        super(proto, implicit);
    123    }
    124
    125    /**
    126     * Overloaded constructor that takes the protocol specification, the implicit argument and encoding
    127     *
    128     * @param proto    the protocol.
    129     * @param implicit The security mode, {@code true} for implicit, {@code false} for explicit
    130     * @param encoding the encoding
    131     * @since 3.3
    132     */
    133    public AuthenticatingSMTPClient(final String proto, final boolean implicit, final String encoding) {
    134        super(proto, implicit, encoding);
    135    }
    136
    137    /**
    138     * Overloaded constructor that takes a protocol specification and encoding
    139     *
    140     * @param protocol The protocol to use
    141     * @param encoding The encoding to use
    142     * @since 3.3
    143     */
    144    public AuthenticatingSMTPClient(final String protocol, final String encoding) {
    145        super(protocol, false, encoding);
    146    }
    147
    148    /**
    149     * Authenticate to the SMTP server by sending the AUTH command with the selected mechanism, using the given user and the given password.
    150     *
    151     * @param method   the method to use, one of the {@link AuthenticatingSMTPClient.AUTH_METHOD} enum values
    152     * @param user the user name. If the method is XOAUTH/XOAUTH2, then this is used as the plain text oauth protocol parameter string which is
    153     *                 Base64-encoded for transmission.
    154     * @param password the password for the username. Ignored for XOAUTH/XOAUTH2.
    155     * @return True if successfully completed, false if not.
    156     * @throws SMTPConnectionClosedException If the SMTP server prematurely closes the connection as a result of the client being idle or some other reason
    157     *                                       causing the server to send SMTP reply code 421. This exception may be caught either as an IOException or
    158     *                                       independently as itself.
    159     * @throws IOException                   If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    160     * @throws NoSuchAlgorithmException      If the CRAM hash algorithm cannot be instantiated by the Java runtime system.
    161     * @throws InvalidKeyException           If the CRAM hash algorithm failed to use the given password.
    162     */
    163    public boolean auth(final AuthenticatingSMTPClient.AUTH_METHOD method, final String user, final String password)
    164            throws IOException, NoSuchAlgorithmException, InvalidKeyException {
    165        if (!SMTPReply.isPositiveIntermediate(sendCommand(SMTPCommand.AUTH, AUTH_METHOD.getAuthName(method)))) {
    166            return false;
    167        }
    168
    169        if (method.equals(AUTH_METHOD.PLAIN)) {
    170            // the server sends an empty response ("334 "), so we don't have to read it.
    171            return SMTPReply
    172                    .isPositiveCompletion(sendCommand(Base64.getEncoder().encodeToString(("\000" + user + "\000" + password).getBytes(getCharset()))));
    173        }
    174        if (method.equals(AUTH_METHOD.CRAM_MD5)) {
    175            // get the CRAM challenge
    176            final byte[] serverChallenge = Base64.getDecoder().decode(getReplyString().substring(4).trim());
    177            // get the Mac instance
    178            final Mac hmacMd5 = Mac.getInstance(MAC_ALGORITHM);
    179            hmacMd5.init(new SecretKeySpec(password.getBytes(getCharset()), MAC_ALGORITHM));
    180            // compute the result:
    181            final byte[] hmacResult = convertToHexString(hmacMd5.doFinal(serverChallenge)).getBytes(getCharset());
    182            // join the byte arrays to form the reply
    183            final byte[] userNameBytes = user.getBytes(getCharset());
    184            final byte[] toEncode = new byte[userNameBytes.length + 1 /* the space */ + hmacResult.length];
    185            System.arraycopy(userNameBytes, 0, toEncode, 0, userNameBytes.length);
    186            toEncode[userNameBytes.length] = ' ';
    187            System.arraycopy(hmacResult, 0, toEncode, userNameBytes.length + 1, hmacResult.length);
    188            // send the reply and read the server code:
    189            return SMTPReply.isPositiveCompletion(sendCommand(Base64.getEncoder().encodeToString(toEncode)));
    190        }
    191        if (method.equals(AUTH_METHOD.LOGIN)) {
    192            // the server sends fixed responses (base64("UserName") and
    193            // base64("Password")), so we don't have to read them.
    194            if (!SMTPReply.isPositiveIntermediate(sendCommand(Base64.getEncoder().encodeToString(user.getBytes(getCharset()))))) {
    195                return false;
    196            }
    197            return SMTPReply.isPositiveCompletion(sendCommand(Base64.getEncoder().encodeToString(password.getBytes(getCharset()))));
    198        }
    199        if (method.equals(AUTH_METHOD.XOAUTH) || method.equals(AUTH_METHOD.XOAUTH2)) {
    200            return SMTPReply.isPositiveIntermediate(sendCommand(Base64.getEncoder().encodeToString(user.getBytes(getCharset()))));
    201        }
    202        return false; // safety check
    203    }
    204
    205    /**
    206     * Converts the given byte array to a String containing the hexadecimal values of the bytes. For example, the byte 'A' will be converted to '41', because
    207     * this is the ASCII code (and the byte value) of the capital letter 'A'.
    208     *
    209     * @param a The byte array to convert.
    210     * @return The resulting String of hexadecimal codes.
    211     */
    212    private String convertToHexString(final byte[] a) {
    213        final StringBuilder result = new StringBuilder(a.length * 2);
    214        for (final byte element : a) {
    215            if ((element & 0x0FF) <= 15) {
    216                result.append("0");
    217            }
    218            result.append(Integer.toHexString(element & 0x0FF));
    219        }
    220        return result.toString();
    221    }
    222
    223    /**
    224     * A convenience method to send the ESMTP EHLO command to the server, receive the reply, and return the reply code.
    225     *
    226     * @param hostname The hostname of the sender.
    227     * @return The reply code received from the server.
    228     * @throws SMTPConnectionClosedException If the SMTP server prematurely closes the connection as a result of the client being idle or some other reason
    229     *                                       causing the server to send SMTP reply code 421. This exception may be caught either as an IOException or
    230     *                                       independently as itself.
    231     * @throws IOException                   If an I/O error occurs while either sending the command or receiving the server reply.
    232     */
    233    public int ehlo(final String hostname) throws IOException {
    234        return sendCommand(SMTPCommand.EHLO, hostname);
    235    }
    236
    237    /**
    238     * Login to the ESMTP server by sending the EHLO command with the client hostname as an argument. Before performing any mail commands, you must first login.
    239     *
    240     * @return True if successfully completed, false if not.
    241     * @throws SMTPConnectionClosedException If the SMTP server prematurely closes the connection as a result of the client being idle or some other reason
    242     *                                       causing the server to send SMTP reply code 421. This exception may be caught either as an IOException or
    243     *                                       independently as itself.
    244     * @throws IOException                   If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    245     */
    246    public boolean elogin() throws IOException {
    247        final String name;
    248        final InetAddress host;
    249
    250        host = getLocalAddress();
    251        name = host.getHostName();
    252
    253        if (name == null) {
    254            return false;
    255        }
    256
    257        return SMTPReply.isPositiveCompletion(ehlo(name));
    258    }
    259
    260    /**
    261     * Login to the ESMTP server by sending the EHLO command with the given hostname as an argument. Before performing any mail commands, you must first login.
    262     *
    263     * @param hostname The hostname with which to greet the SMTP server.
    264     * @return True if successfully completed, false if not.
    265     * @throws SMTPConnectionClosedException If the SMTP server prematurely closes the connection as a result of the client being idle or some other reason
    266     *                                       causing the server to send SMTP reply code 421. This exception may be caught either as an IOException or
    267     *                                       independently as itself.
    268     * @throws IOException                   If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
    269     */
    270    public boolean elogin(final String hostname) throws IOException {
    271        return SMTPReply.isPositiveCompletion(ehlo(hostname));
    272    }
    273
    274    /**
    275     * Gets the integer values of the enhanced reply code of the last SMTP reply.
    276     *
    277     * @return The integer values of the enhanced reply code of the last SMTP reply. First digit is in the first array element.
    278     */
    279    public int[] getEnhancedReplyCode() {
    280        final String reply = getReplyString().substring(4);
    281        final String[] parts = reply.substring(0, reply.indexOf(' ')).split("\\.");
    282        final int[] res = new int[parts.length];
    283        Arrays.setAll(res, i -> Integer.parseInt(parts[i]));
    284        return res;
    285    }
    286}