blob: 85e4dbfd716f8662d6dd0194718075c541c07e0e [file] [log] [blame]
Shawn O. Pearce44671f52009-11-07 12:55:26 -08001// Copyright (C) 2009 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package org.apache.commons.net.smtp;
16
David Pursehouse19c63fa2015-10-08 15:46:47 +090017import static java.nio.charset.StandardCharsets.UTF_8;
18
David Pursehousea6270b92019-10-12 15:02:27 +090019import com.google.common.io.BaseEncoding;
Shawn O. Pearce44671f52009-11-07 12:55:26 -080020import com.google.gerrit.util.ssl.BlindSSLSocketFactory;
Liu Yubao34d4d192012-05-24 11:28:45 +080021import java.io.BufferedReader;
22import java.io.BufferedWriter;
Shawn O. Pearce44671f52009-11-07 12:55:26 -080023import java.io.IOException;
Liu Yubao34d4d192012-05-24 11:28:45 +080024import java.io.InputStreamReader;
25import java.io.OutputStreamWriter;
Shawn O. Pearce44671f52009-11-07 12:55:26 -080026import java.io.UnsupportedEncodingException;
27import java.net.SocketException;
28import java.security.InvalidKeyException;
29import java.security.NoSuchAlgorithmException;
30import java.util.Arrays;
Shawn O. Pearce44671f52009-11-07 12:55:26 -080031import java.util.List;
Shawn O. Pearce44671f52009-11-07 12:55:26 -080032import javax.crypto.Mac;
33import javax.crypto.spec.SecretKeySpec;
Edwin Kempind1e2c2f2016-03-13 10:24:17 +010034import javax.net.ssl.SSLParameters;
35import javax.net.ssl.SSLSocket;
Shawn O. Pearce44671f52009-11-07 12:55:26 -080036import javax.net.ssl.SSLSocketFactory;
37
38public class AuthSMTPClient extends SMTPClient {
Shawn O. Pearce44671f52009-11-07 12:55:26 -080039 private String authTypes;
Shawn O. Pearce44671f52009-11-07 12:55:26 -080040
Han-Wen Nienhuysb0fb0a72017-06-13 18:10:03 +020041 public AuthSMTPClient(String charset) {
Shawn O. Pearce44671f52009-11-07 12:55:26 -080042 super(charset);
43 }
44
Han-Wen Nienhuysb0fb0a72017-06-13 18:10:03 +020045 public void enableSSL(boolean verify) {
Shawn O. Pearce44671f52009-11-07 12:55:26 -080046 _socketFactory_ = sslFactory(verify);
47 }
48
Han-Wen Nienhuysb0fb0a72017-06-13 18:10:03 +020049 public boolean startTLS(String hostname, int port, boolean verify)
Shawn O. Pearce44671f52009-11-07 12:55:26 -080050 throws SocketException, IOException {
51 if (sendCommand("STARTTLS") != 220) {
52 return false;
53 }
54
55 _socket_ = sslFactory(verify).createSocket(_socket_, hostname, port, true);
Liu Yubao34d4d192012-05-24 11:28:45 +080056
John Viklund7dfc4dd2016-08-11 16:09:09 +020057 if (verify) {
58 SSLParameters sslParams = new SSLParameters();
59 sslParams.setEndpointIdentificationAlgorithm("HTTPS");
Dave Borowitz292fa152016-11-13 09:56:32 -080060 ((SSLSocket) _socket_).setSSLParameters(sslParams);
John Viklund7dfc4dd2016-08-11 16:09:09 +020061 }
Edwin Kempind1e2c2f2016-03-13 10:24:17 +010062
Liu Yubao34d4d192012-05-24 11:28:45 +080063 // XXX: Can't call _connectAction_() because SMTP server doesn't
64 // give banner information again after STARTTLS, thus SMTP._connectAction_()
65 // will wait on __getReply() forever, see source code of commons-net-2.2.
66 //
67 // The lines below are copied from SocketClient._connectAction_() and
68 // SMTP._connectAction_() in commons-net-2.2.
69 _socket_.setSoTimeout(_timeout_);
70 _input_ = _socket_.getInputStream();
71 _output_ = _socket_.getOutputStream();
Dave Borowitz292fa152016-11-13 09:56:32 -080072 _reader = new BufferedReader(new InputStreamReader(_input_, UTF_8));
73 _writer = new BufferedWriter(new OutputStreamWriter(_output_, UTF_8));
Shawn O. Pearce44671f52009-11-07 12:55:26 -080074 return true;
75 }
76
Han-Wen Nienhuysb0fb0a72017-06-13 18:10:03 +020077 private static SSLSocketFactory sslFactory(boolean verify) {
Shawn O. Pearce44671f52009-11-07 12:55:26 -080078 if (verify) {
79 return (SSLSocketFactory) SSLSocketFactory.getDefault();
Shawn O. Pearce44671f52009-11-07 12:55:26 -080080 }
David Pursehouse32324722016-06-01 21:20:02 +090081 return (SSLSocketFactory) BlindSSLSocketFactory.getDefault();
Shawn O. Pearce44671f52009-11-07 12:55:26 -080082 }
83
Shawn O. Pearce44671f52009-11-07 12:55:26 -080084 @Override
Shawn O. Pearce44671f52009-11-07 12:55:26 -080085 public boolean login() throws IOException {
86 final String name = getLocalAddress().getHostName();
87 if (name == null) {
88 return false;
89 }
90
91 boolean ok = SMTPReply.isPositiveCompletion(sendCommand("EHLO", name));
92 authTypes = "";
93 for (String line : getReplyStrings()) {
94 if (line != null && (line.startsWith("250 AUTH ") || line.startsWith("250-AUTH "))) {
95 authTypes = line;
96 break;
97 }
98 }
99
100 return ok;
101 }
102
103 public boolean auth(String smtpUser, String smtpPass) throws IOException {
104 List<String> types = Arrays.asList(authTypes.split(" "));
105 if ("".equals(authTypes)) {
106 // Server didn't advertise authentication support.
107 //
108 return true;
109 }
110
111 if (smtpPass == null) {
112 smtpPass = "";
113 }
114 if (types.contains("CRAM-SHA1")) {
115 return authCram(smtpUser, smtpPass, "SHA1");
116 }
117 if (types.contains("CRAM-MD5")) {
118 return authCram(smtpUser, smtpPass, "MD5");
119 }
Bob Foerstera1b2d452011-03-10 11:55:11 -0500120 if (types.contains("LOGIN")) {
121 return authLogin(smtpUser, smtpPass);
122 }
Shawn O. Pearce44671f52009-11-07 12:55:26 -0800123 if (types.contains("PLAIN")) {
124 return authPlain(smtpUser, smtpPass);
125 }
Shawn O. Pearce44671f52009-11-07 12:55:26 -0800126 throw new IOException("Unsupported AUTH: " + authTypes);
127 }
128
129 private boolean authCram(String smtpUser, String smtpPass, String alg)
130 throws UnsupportedEncodingException, IOException {
131 final String macName = "Hmac" + alg;
132 if (sendCommand("AUTH", "CRAM-" + alg) != 334) {
133 return false;
134 }
135
136 final String enc = getReplyStrings()[0].split(" ", 2)[1];
David Pursehousea6270b92019-10-12 15:02:27 +0900137 final byte[] nonce = BaseEncoding.base64().decode(enc);
Shawn O. Pearce44671f52009-11-07 12:55:26 -0800138 final String sec;
139 try {
140 Mac mac = Mac.getInstance(macName);
141 mac.init(new SecretKeySpec(smtpPass.getBytes(UTF_8), macName));
142 sec = toHex(mac.doFinal(nonce));
Urs Wolfer64cfaf22015-06-24 20:06:25 +0200143 } catch (NoSuchAlgorithmException | InvalidKeyException e) {
Shawn O. Pearce44671f52009-11-07 12:55:26 -0800144 throw new IOException("Cannot use CRAM-" + alg, e);
145 }
146
147 String token = smtpUser + ' ' + sec;
148 String cmd = encodeBase64(token.getBytes(UTF_8));
149 return SMTPReply.isPositiveCompletion(sendCommand(cmd));
150 }
151
Dave Borowitz292fa152016-11-13 09:56:32 -0800152 private boolean authLogin(String smtpUser, String smtpPass)
153 throws UnsupportedEncodingException, IOException {
Bob Foerstera1b2d452011-03-10 11:55:11 -0500154 if (sendCommand("AUTH", "LOGIN") != 334) {
155 return false;
156 }
157
158 String cmd = encodeBase64(smtpUser.getBytes(UTF_8));
David Pursehousec5ccbf12016-04-11 19:43:20 +0900159 if (sendCommand(cmd) != 334) {
Bob Foerstera1b2d452011-03-10 11:55:11 -0500160 return false;
161 }
162
163 cmd = encodeBase64(smtpPass.getBytes(UTF_8));
164 return SMTPReply.isPositiveCompletion(sendCommand(cmd));
165 }
166
Dave Borowitz292fa152016-11-13 09:56:32 -0800167 private static final char[] hexchar = {
168 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
169 };
Shawn O. Pearce44671f52009-11-07 12:55:26 -0800170
Han-Wen Nienhuysb0fb0a72017-06-13 18:10:03 +0200171 private String toHex(byte[] b) {
Shawn O. Pearce44671f52009-11-07 12:55:26 -0800172 final StringBuilder sec = new StringBuilder();
alex.ryazantsev05872ef2013-12-04 01:02:53 +0400173 for (byte c : b) {
174 final int u = (c >> 4) & 0xf;
175 final int l = c & 0xf;
Shawn O. Pearce44671f52009-11-07 12:55:26 -0800176 sec.append(hexchar[u]);
177 sec.append(hexchar[l]);
178 }
179 return sec.toString();
180 }
181
Dave Borowitz292fa152016-11-13 09:56:32 -0800182 private boolean authPlain(String smtpUser, String smtpPass)
183 throws UnsupportedEncodingException, IOException {
Shawn O. Pearce44671f52009-11-07 12:55:26 -0800184 String token = '\0' + smtpUser + '\0' + smtpPass;
185 String cmd = "PLAIN " + encodeBase64(token.getBytes(UTF_8));
186 return SMTPReply.isPositiveCompletion(sendCommand("AUTH", cmd));
187 }
188
Han-Wen Nienhuysb0fb0a72017-06-13 18:10:03 +0200189 private static String encodeBase64(byte[] data) {
David Pursehousea6270b92019-10-12 15:02:27 +0900190 return BaseEncoding.base64().encode(data);
Shawn O. Pearce44671f52009-11-07 12:55:26 -0800191 }
192}