ScramSha1.java

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