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