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.pop3;
019
020import java.io.IOException;
021import java.security.InvalidKeyException;
022import java.security.NoSuchAlgorithmException;
023import java.util.Base64;
024
025import javax.crypto.Mac;
026import javax.crypto.spec.SecretKeySpec;
027
028/**
029 * A POP3 Client class with protocol and authentication extensions support (RFC2449 and RFC2195).
030 *
031 * @see POP3Client
032 * @since 3.0
033 */
034public class ExtendedPOP3Client extends POP3SClient {
035
036    /**
037     * The enumeration of currently-supported authentication methods.
038     */
039    public enum AUTH_METHOD {
040
041        /** The standardized (RFC4616) PLAIN method, which sends the password unencrypted (insecure). */
042        PLAIN("PLAIN"),
043
044        /** The standardized (RFC2195) CRAM-MD5 method, which doesn't send the password (secure). */
045        CRAM_MD5("CRAM-MD5");
046
047        private final String methodName;
048
049        AUTH_METHOD(final String methodName) {
050            this.methodName = methodName;
051        }
052
053        /**
054         * Gets the name of the given authentication method suitable for the server.
055         *
056         * @return The name of the given authentication method suitable for the server.
057         */
058        public String getAuthName() {
059            return methodName;
060        }
061    }
062
063    /** {@link Mac} algorithm. */
064    private static final String MAC_ALGORITHM = "HmacMD5";
065
066    /**
067     * The default ExtendedPOP3Client constructor. Creates a new Extended POP3 Client.
068     *
069     * @throws NoSuchAlgorithmException Never thrown here.
070     */
071    public ExtendedPOP3Client() throws NoSuchAlgorithmException {
072    }
073
074    /**
075     * Authenticate to the POP3 server by sending the AUTH command with the selected mechanism, using the given user and the given password.
076     *
077     * @param method   the {@link AUTH_METHOD} to use
078     * @param user the user name
079     * @param password the password
080     * @return True if successfully completed, false if not.
081     * @throws IOException              If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
082     * @throws NoSuchAlgorithmException If the CRAM hash algorithm cannot be instantiated by the Java runtime system.
083     * @throws InvalidKeyException      If the CRAM hash algorithm failed to use the given password.
084     */
085    public boolean auth(final AUTH_METHOD method, final String user, final String password)
086            throws IOException, NoSuchAlgorithmException, InvalidKeyException {
087        if (sendCommand(POP3Command.AUTH, method.getAuthName()) != POP3Reply.OK_INT) {
088            return false;
089        }
090
091        switch (method) {
092        case PLAIN:
093            // the server sends an empty response ("+ "), so we don't have to read it.
094            return sendCommand(
095                    new String(Base64.getEncoder().encode(("\000" + user + "\000" + password).getBytes(getCharset())), getCharset())) == POP3Reply.OK;
096        case CRAM_MD5:
097            // get the CRAM challenge
098            final byte[] serverChallenge = Base64.getDecoder().decode(getReplyString().substring(2).trim());
099            // get the Mac instance
100            final Mac hmacMd5 = Mac.getInstance(MAC_ALGORITHM);
101            hmacMd5.init(new SecretKeySpec(password.getBytes(getCharset()), MAC_ALGORITHM));
102            // compute the result:
103            final byte[] hmacResult = convertToHexString(hmacMd5.doFinal(serverChallenge)).getBytes(getCharset());
104            // join the byte arrays to form the reply
105            final byte[] userNameBytes = user.getBytes(getCharset());
106            final byte[] toEncode = new byte[userNameBytes.length + 1 /* the space */ + hmacResult.length];
107            System.arraycopy(userNameBytes, 0, toEncode, 0, userNameBytes.length);
108            toEncode[userNameBytes.length] = ' ';
109            System.arraycopy(hmacResult, 0, toEncode, userNameBytes.length + 1, hmacResult.length);
110            // send the reply and read the server code:
111            return sendCommand(Base64.getEncoder().encodeToString(toEncode)) == POP3Reply.OK;
112        default:
113            return false;
114        }
115    }
116
117    /**
118     * 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
119     * this is the ASCII code (and the byte value) of the capital letter 'A'.
120     *
121     * @param a The byte array to convert.
122     * @return The resulting String of hexadecimal codes.
123     */
124    private String convertToHexString(final byte[] a) {
125        final StringBuilder result = new StringBuilder(a.length * 2);
126        for (final byte element : a) {
127            if ((element & 0x0FF) <= 15) {
128                result.append("0");
129            }
130            result.append(Integer.toHexString(element & 0x0FF));
131        }
132        return result.toString();
133    }
134}