Skip to content

Commit

Permalink
Add support for AndroidSafetyNet
Browse files Browse the repository at this point in the history
Add support for assertion responses that include
AndroidSafetyNet parameters.

Add UI elements to index.jsp.
  • Loading branch information
cpiper authored and Casey Piper committed May 25, 2017
1 parent 6272229 commit daafab0
Show file tree
Hide file tree
Showing 34 changed files with 1,352 additions and 75 deletions.
26 changes: 26 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@
<version>${appengine.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.codec</artifactId>
<version>1.8</version>
</dependency>

<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-stubs</artifactId>
Expand All @@ -90,6 +96,26 @@
<artifactId>bcprov-jdk15on</artifactId>
<version>1.56</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.22.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
</dependencies>
<build>
<!-- for hot reload of the web application -->
Expand Down
14 changes: 13 additions & 1 deletion src/main/java/com/google/webauthn/gaedemo/crypto/Crypto.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,26 @@
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import org.bouncycastle.asn1.sec.SECNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;
import org.bouncycastle.math.ec.ECPoint;

public class Crypto {

static {
Security.addProvider(new BouncyCastleProvider());
}

public static byte[] sha256Digest(byte[] input) {
SHA256Digest digest = new SHA256Digest();
Expand All @@ -25,6 +32,11 @@ public static byte[] sha256Digest(byte[] input) {
digest.doFinal(result, 0);
return result;
}

public static byte[] digest(byte[] input, String alg) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance(alg);
return digest.digest(input);
}

public static boolean verifySignature(PublicKey publicKey, byte[] signedBytes,
byte[] signature) throws WebAuthnException {
Expand All @@ -51,7 +63,7 @@ public static PublicKey decodePublicKey(byte[] x, byte[] y) throws WebAuthnExcep
} catch (RuntimeException e) {
throw new WebAuthnException("Couldn't parse user public key", e);
}

return KeyFactory.getInstance("ECDSA").generatePublic(
new ECPublicKeySpec(point,
new ECParameterSpec(
Expand Down
168 changes: 168 additions & 0 deletions src/main/java/com/google/webauthn/gaedemo/crypto/OfflineVerify.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

package com.google.webauthn.gaedemo.crypto;

import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.webtoken.JsonWebSignature;
import com.google.api.client.util.Base64;
import com.google.api.client.util.Key;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;

import javax.net.ssl.SSLException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import java.util.Arrays;

/**
* Sample code to verify the device attestation statement offline.
*/
public class OfflineVerify {

private static final DefaultHostnameVerifier HOSTNAME_VERIFIER = new DefaultHostnameVerifier();

/**
* Class for parsing the JSON data.
*/
public static class AttestationStatement extends JsonWebSignature.Payload {
@Key
private String nonce;

@Key
private long timestampMs;

@Key
private String apkPackageName;

@Key
private String apkDigestSha256;

@Key
private boolean ctsProfileMatch;

public byte[] getNonce() {
return Base64.decodeBase64(nonce);
}

public long getTimestampMs() {
return timestampMs;
}

public String getApkPackageName() {
return apkPackageName;
}

public byte[] getApkDigestSha256() {
return Base64.decodeBase64(apkDigestSha256);
}

public boolean isCtsProfileMatch() {
return ctsProfileMatch;
}
}

public static AttestationStatement parseAndVerify(String signedAttestationStatment) {
// Parse JSON Web Signature format.
JsonWebSignature jws;
try {
jws = JsonWebSignature.parser(JacksonFactory.getDefaultInstance())
.setPayloadClass(AttestationStatement.class).parse(signedAttestationStatment);
} catch (IOException e) {
System.err.println("Failure: " + signedAttestationStatment + " is not valid JWS " +
"format.");
return null;
}

// Verify the signature of the JWS and retrieve the signature certificate.
X509Certificate cert;
try {
cert = jws.verifySignature();
if (cert == null) {
System.err.println("Failure: Signature verification failed.");
return null;
}
} catch (GeneralSecurityException e) {
System.err.println(
"Failure: Error during cryptographic verification of the JWS signature.");
return null;
}

// Verify the hostname of the certificate.
if (!verifyHostname("attest.android.com", cert)) {
System.err.println("Failure: Certificate isn't issued for the hostname attest.android" +
".com.");
return null;
}

// Extract and use the payload data.
AttestationStatement stmt = (AttestationStatement) jws.getPayload();
return stmt;
}

/**
* Verifies that the certificate matches the specified hostname.
* Uses the {@link DefaultHostnameVerifier} from the Apache HttpClient library
* to confirm that the hostname matches the certificate.
*
* @param hostname
* @param leafCert
* @return
*/
private static boolean verifyHostname(String hostname, X509Certificate leafCert) {
try {
// Check that the hostname matches the certificate. This method throws an exception if
// the cert could not be verified.
HOSTNAME_VERIFIER.verify(hostname, leafCert);
return true;
} catch (SSLException e) {
e.printStackTrace();
}

return false;
}


private static void process(String signedAttestationStatement) {
AttestationStatement stmt = parseAndVerify(signedAttestationStatement);
if (stmt == null) {
System.err.println("Failure: Failed to parse and verify the attestation statement.");
return;
}

System.out.println("Successfully verified the attestation statement. The content is:");

System.out.println("Nonce: " + Arrays.toString(stmt.getNonce()));
System.out.println("Timestamp: " + stmt.getTimestampMs() + " ms");
System.out.println("APK package name: " + stmt.getApkPackageName());
System.out.println("APK digest SHA256: " + Arrays.toString(stmt.getApkDigestSha256()));
System.out.println("CTS profile match: " + stmt.isCtsProfileMatch());

System.out.println("\n** This sample only shows how to verify the authenticity of an "
+ "attestation response. Next, you must check that the server response matches the "
+ "request by comparing the nonce, package name, timestamp and digest.");
}

public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: OfflineVerify <signed attestation statement>");
return;
}
process(args[0]);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package com.google.webauthn.gaedemo.objects;

import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.model.ByteString;
import co.nstant.in.cbor.model.DataItem;
import co.nstant.in.cbor.model.Map;
import co.nstant.in.cbor.model.UnicodeString;
import com.google.webauthn.gaedemo.exceptions.ResponseException;
import com.googlecode.objectify.annotation.Subclass;
import java.util.Arrays;

@Subclass
public class AndroidSafetyNetAttestationStatement extends AttestationStatement {

public String ver;
public byte[] response;

/**
* @param ver
* @param response
*/
public AndroidSafetyNetAttestationStatement() {
this.ver = null;
this.response = null;
}

/**
* @param attStmt
* @return
* @throws ResponseException
*/
public static AndroidSafetyNetAttestationStatement decode(DataItem attStmt)
throws ResponseException {
AndroidSafetyNetAttestationStatement result = new AndroidSafetyNetAttestationStatement();
Map given = (Map) attStmt;
for (DataItem data : given.getKeys()) {
if (data instanceof UnicodeString) {
if (((UnicodeString) data).getString().equals("ver")) {
UnicodeString version = (UnicodeString) given.get(data);
result.ver = version.getString();
} else if (((UnicodeString) data).getString().equals("response")) {
result.response = ((ByteString) (given.get(data))).getBytes();
}
}
}
if (result.response == null || result.ver == null)
throw new ResponseException("Invalid JWT Cbor");
return result;
}

@Override
DataItem encode() throws CborException {
Map map = new Map();
map.put(new UnicodeString("ver"), new UnicodeString(ver));
map.put(new UnicodeString("response"), new ByteString(response));
return map;
}

@Override
public boolean equals(Object obj) {
if (obj instanceof AndroidSafetyNetAttestationStatement) {
AndroidSafetyNetAttestationStatement other = (AndroidSafetyNetAttestationStatement) obj;
if (ver == other.ver || ((ver != null && other.ver != null) && ver.equals(other.ver))) {
if (Arrays.equals(response, other.response)) {
return true;
}
}
}
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,18 @@ public AttestationData() {
publicKey = new EccKey();
}

/**
* @param aaguid
* @param credentialId
* @param publicKey
*/
public AttestationData(byte[] aaguid, byte[] credentialId, CredentialPublicKey publicKey) {
super();
this.aaguid = aaguid;
this.credentialId = credentialId;
this.publicKey = publicKey;
}

/**
* @param data
* @return AttestationData object created from the byte sequence
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,24 @@ public class AttestationObject {
String fmt;
AttestationStatement attStmt;

/**
*
*/
public AttestationObject() {

}

/**
* @param authData
* @param fmt
* @param attStmt
*/
public AttestationObject(AuthenticatorData authData, String fmt, AttestationStatement attStmt) {
this.authData = authData;
this.fmt = fmt;
this.attStmt = attStmt;
}

/**
* @param attestationObject
* @return AttestationObject created from the provided byte array
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.model.DataItem;
import com.google.webauthn.gaedemo.exceptions.ResponseException;

public abstract class AttestationStatement {

Expand All @@ -14,6 +15,14 @@ public static AttestationStatement decode(String fmt, DataItem attStmt) {
if (fmt.equals("fido-u2f")) {
FidoU2fAttestationStatement stmt = FidoU2fAttestationStatement.decode(attStmt);
return stmt;
} else if (fmt.equals("android-safetynet")) {
AndroidSafetyNetAttestationStatement stmt;
try {
stmt = AndroidSafetyNetAttestationStatement.decode(attStmt);
} catch (ResponseException e) {
return null;
}
return stmt;
}

return null;
Expand Down
Loading

0 comments on commit daafab0

Please sign in to comment.