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