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 public static String getMechanism() {
47 return "SCRAM-SHA-1";
48 }
49
50 @Override
51 public String getClientFirstMessage() {
52 if (clientFirstMessageBare.isEmpty() && state == State.INITIAL) {
53 clientFirstMessageBare = "n=" + CryptoHelper.saslPrep(account.getUsername()) +
54 ",r=" + this.clientNonce;
55 state = State.AUTH_TEXT_SENT;
56 }
57 return Base64.encodeToString(
58 (GS2_HEADER + clientFirstMessageBare).getBytes(Charset.defaultCharset()),
59 Base64.NO_WRAP);
60 }
61
62 @Override
63 public String getResponse(final String challenge) throws AuthenticationException {
64 switch (state) {
65 case AUTH_TEXT_SENT:
66 serverFirstMessage = Base64.decode(challenge, Base64.DEFAULT);
67 final Tokenizer tokenizer = new Tokenizer(serverFirstMessage);
68 String nonce = "";
69 int iterationCount = -1;
70 String salt = "";
71 for (final String token : tokenizer) {
72 if (token.charAt(1) == '=') {
73 switch (token.charAt(0)) {
74 case 'i':
75 try {
76 iterationCount = Integer.parseInt(token.substring(2));
77 } catch (final NumberFormatException e) {
78 throw new AuthenticationException(e);
79 }
80 break;
81 case 's':
82 salt = token.substring(2);
83 break;
84 case 'r':
85 nonce = token.substring(2);
86 break;
87 case 'm':
88 /*
89 * RFC 5802:
90 * m: This attribute is reserved for future extensibility. In this
91 * version of SCRAM, its presence in a client or a server message
92 * MUST cause authentication failure when the attribute is parsed by
93 * the other end.
94 */
95 throw new AuthenticationException("Server sent reserved token: `m'");
96 }
97 }
98 }
99
100 if (iterationCount < 0) {
101 throw new AuthenticationException("Server did not send iteration count");
102 }
103 if (nonce.isEmpty() || !nonce.startsWith(clientNonce)) {
104 throw new AuthenticationException("Server nonce does not contain client nonce: " + nonce);
105 }
106 if (salt.isEmpty()) {
107 throw new AuthenticationException("Server sent empty salt");
108 }
109
110 final String clientFinalMessageWithoutProof = "c=" + Base64.encodeToString(
111 GS2_HEADER.getBytes(), Base64.NO_WRAP) + ",r=" + nonce;
112 final byte[] authMessage = (clientFirstMessageBare + ',' + new String(serverFirstMessage) + ','
113 + clientFinalMessageWithoutProof).getBytes();
114
115 // TODO: In future, cache the clientKey and serverKey and re-use them on re-auth.
116 final byte[] saltedPassword, clientSignature, serverKey, clientKey;
117 try {
118 saltedPassword = hi(CryptoHelper.saslPrep(account.getPassword()).getBytes(),
119 Base64.decode(salt, Base64.DEFAULT), iterationCount);
120 serverKey = hmac(saltedPassword, SERVER_KEY_BYTES);
121 serverSignature = hmac(serverKey, authMessage);
122 clientKey = hmac(saltedPassword, CLIENT_KEY_BYTES);
123 final byte[] storedKey = digest(clientKey);
124
125 clientSignature = hmac(storedKey, authMessage);
126
127 } catch (final InvalidKeyException e) {
128 throw new AuthenticationException(e);
129 }
130
131 final byte[] clientProof = new byte[clientKey.length];
132
133 for (int i = 0; i < clientProof.length; i++) {
134 clientProof[i] = (byte) (clientKey[i] ^ clientSignature[i]);
135 }
136
137
138 final String clientFinalMessage = clientFinalMessageWithoutProof + ",p=" +
139 Base64.encodeToString(clientProof, Base64.NO_WRAP);
140 state = State.RESPONSE_SENT;
141 return Base64.encodeToString(clientFinalMessage.getBytes(), Base64.NO_WRAP);
142 case RESPONSE_SENT:
143 final String clientCalculatedServerFinalMessage = "v=" +
144 Base64.encodeToString(serverSignature, Base64.NO_WRAP);
145 if (!clientCalculatedServerFinalMessage.equals(new String(Base64.decode(challenge, Base64.DEFAULT)))) {
146 throw new AuthenticationException("Server final message does not match calculated final message");
147 }
148 state = State.VALID_SERVER_RESPONSE;
149 return "";
150 default:
151 throw new InvalidStateException(state);
152 }
153 }
154
155 public static synchronized byte[] hmac(final byte[] key, final byte[] input)
156 throws InvalidKeyException {
157 HMAC.init(new KeyParameter(key));
158 HMAC.update(input, 0, input.length);
159 final byte[] out = new byte[HMAC.getMacSize()];
160 HMAC.doFinal(out, 0);
161 return out;
162 }
163
164 public static synchronized byte[] digest(byte[] bytes) {
165 DIGEST.reset();
166 DIGEST.update(bytes, 0, bytes.length);
167 final byte[] out = new byte[DIGEST.getDigestSize()];
168 DIGEST.doFinal(out, 0);
169 return out;
170 }
171
172 /*
173 * Hi() is, essentially, PBKDF2 [RFC2898] with HMAC() as the
174 * pseudorandom function (PRF) and with dkLen == output length of
175 * HMAC() == output length of H().
176 */
177 private static synchronized byte[] hi(final byte[] key, final byte[] salt, final int iterations)
178 throws InvalidKeyException {
179 byte[] u = hmac(key, CryptoHelper.concatenateByteArrays(salt, CryptoHelper.ONE));
180 byte[] out = u.clone();
181 for (int i = 1; i < iterations; i++) {
182 u = hmac(key, u);
183 for (int j = 0; j < u.length; j++) {
184 out[j] ^= u[j];
185 }
186 }
187 return out;
188 }
189}