1package eu.siacs.conversations.crypto.sasl;
2
3import android.util.Base64;
4
5import org.bouncycastle.crypto.Digest;
6import org.bouncycastle.crypto.digests.SHA1Digest;
7import org.bouncycastle.crypto.macs.HMac;
8import org.bouncycastle.crypto.params.KeyParameter;
9
10import java.math.BigInteger;
11import java.nio.charset.Charset;
12import java.security.InvalidKeyException;
13import java.security.SecureRandom;
14
15import eu.siacs.conversations.entities.Account;
16import eu.siacs.conversations.utils.CryptoHelper;
17import eu.siacs.conversations.xml.TagWriter;
18
19public class ScramSha1 extends SaslMechanism {
20 // TODO: When channel binding (SCRAM-SHA1-PLUS) is supported in future, generalize this to indicate support and/or usage.
21 final private static String GS2_HEADER = "n,,";
22 private String clientFirstMessageBare;
23 private byte[] serverFirstMessage;
24 final private String clientNonce;
25 private byte[] serverSignature = null;
26 private static HMac HMAC;
27 private static Digest DIGEST;
28 private static final byte[] CLIENT_KEY_BYTES = "Client Key".getBytes();
29 private static final byte[] SERVER_KEY_BYTES = "Server Key".getBytes();
30
31 static {
32 DIGEST = new SHA1Digest();
33 HMAC = new HMac(new SHA1Digest());
34 }
35
36 private State state = State.INITIAL;
37
38 public ScramSha1(final TagWriter tagWriter, final Account account, final SecureRandom rng) {
39 super(tagWriter, account, rng);
40
41 // This nonce should be different for each authentication attempt.
42 clientNonce = new BigInteger(100, this.rng).toString(32);
43 clientFirstMessageBare = "";
44 }
45
46 @Override
47 public int getPriority() {
48 return 20;
49 }
50
51 @Override
52 public String getMechanism() {
53 return "SCRAM-SHA-1";
54 }
55
56 @Override
57 public String getClientFirstMessage() {
58 if (clientFirstMessageBare.isEmpty() && state == State.INITIAL) {
59 clientFirstMessageBare = "n=" + CryptoHelper.saslPrep(account.getUsername()) +
60 ",r=" + this.clientNonce;
61 state = State.AUTH_TEXT_SENT;
62 }
63 return Base64.encodeToString(
64 (GS2_HEADER + clientFirstMessageBare).getBytes(Charset.defaultCharset()),
65 Base64.NO_WRAP);
66 }
67
68 @Override
69 public String getResponse(final String challenge) throws AuthenticationException {
70 switch (state) {
71 case AUTH_TEXT_SENT:
72 serverFirstMessage = Base64.decode(challenge, Base64.DEFAULT);
73 final Tokenizer tokenizer = new Tokenizer(serverFirstMessage);
74 String nonce = "";
75 int iterationCount = -1;
76 String salt = "";
77 for (final String token : tokenizer) {
78 if (token.charAt(1) == '=') {
79 switch (token.charAt(0)) {
80 case 'i':
81 try {
82 iterationCount = Integer.parseInt(token.substring(2));
83 } catch (final NumberFormatException e) {
84 throw new AuthenticationException(e);
85 }
86 break;
87 case 's':
88 salt = token.substring(2);
89 break;
90 case 'r':
91 nonce = token.substring(2);
92 break;
93 case 'm':
94 /*
95 * RFC 5802:
96 * m: This attribute is reserved for future extensibility. In this
97 * version of SCRAM, its presence in a client or a server message
98 * MUST cause authentication failure when the attribute is parsed by
99 * the other end.
100 */
101 throw new AuthenticationException("Server sent reserved token: `m'");
102 }
103 }
104 }
105
106 if (iterationCount < 0) {
107 throw new AuthenticationException("Server did not send iteration count");
108 }
109 if (nonce.isEmpty() || !nonce.startsWith(clientNonce)) {
110 throw new AuthenticationException("Server nonce does not contain client nonce: " + nonce);
111 }
112 if (salt.isEmpty()) {
113 throw new AuthenticationException("Server sent empty salt");
114 }
115
116 final String clientFinalMessageWithoutProof = "c=" + Base64.encodeToString(
117 GS2_HEADER.getBytes(), Base64.NO_WRAP) + ",r=" + nonce;
118 final byte[] authMessage = (clientFirstMessageBare + ',' + new String(serverFirstMessage) + ','
119 + clientFinalMessageWithoutProof).getBytes();
120
121 // TODO: In future, cache the clientKey and serverKey and re-use them on re-auth.
122 final byte[] saltedPassword, clientSignature, serverKey, clientKey;
123 try {
124 saltedPassword = hi(CryptoHelper.saslPrep(account.getPassword()).getBytes(),
125 Base64.decode(salt, Base64.DEFAULT), iterationCount);
126 serverKey = hmac(saltedPassword, SERVER_KEY_BYTES);
127 serverSignature = hmac(serverKey, authMessage);
128 clientKey = hmac(saltedPassword, CLIENT_KEY_BYTES);
129 final byte[] storedKey = digest(clientKey);
130
131 clientSignature = hmac(storedKey, authMessage);
132
133 } catch (final InvalidKeyException e) {
134 throw new AuthenticationException(e);
135 }
136
137 final byte[] clientProof = new byte[clientKey.length];
138
139 for (int i = 0; i < clientProof.length; i++) {
140 clientProof[i] = (byte) (clientKey[i] ^ clientSignature[i]);
141 }
142
143
144 final String clientFinalMessage = clientFinalMessageWithoutProof + ",p=" +
145 Base64.encodeToString(clientProof, Base64.NO_WRAP);
146 state = State.RESPONSE_SENT;
147 return Base64.encodeToString(clientFinalMessage.getBytes(), Base64.NO_WRAP);
148 case RESPONSE_SENT:
149 final String clientCalculatedServerFinalMessage = "v=" +
150 Base64.encodeToString(serverSignature, Base64.NO_WRAP);
151 if (!clientCalculatedServerFinalMessage.equals(new String(Base64.decode(challenge, Base64.DEFAULT)))) {
152 throw new AuthenticationException("Server final message does not match calculated final message");
153 }
154 state = State.VALID_SERVER_RESPONSE;
155 return "";
156 default:
157 throw new InvalidStateException(state);
158 }
159 }
160
161 public static synchronized byte[] hmac(final byte[] key, final byte[] input)
162 throws InvalidKeyException {
163 HMAC.init(new KeyParameter(key));
164 HMAC.update(input, 0, input.length);
165 final byte[] out = new byte[HMAC.getMacSize()];
166 HMAC.doFinal(out, 0);
167 return out;
168 }
169
170 public static synchronized byte[] digest(byte[] bytes) {
171 DIGEST.reset();
172 DIGEST.update(bytes, 0, bytes.length);
173 final byte[] out = new byte[DIGEST.getDigestSize()];
174 DIGEST.doFinal(out, 0);
175 return out;
176 }
177
178 /*
179 * Hi() is, essentially, PBKDF2 [RFC2898] with HMAC() as the
180 * pseudorandom function (PRF) and with dkLen == output length of
181 * HMAC() == output length of H().
182 */
183 private static synchronized byte[] hi(final byte[] key, final byte[] salt, final int iterations)
184 throws InvalidKeyException {
185 byte[] u = hmac(key, CryptoHelper.concatenateByteArrays(salt, CryptoHelper.ONE));
186 byte[] out = u.clone();
187 for (int i = 1; i < iterations; i++) {
188 u = hmac(key, u);
189 for (int j = 0; j < u.length; j++) {
190 out[j] ^= u[j];
191 }
192 }
193 return out;
194 }
195}