-
-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy pathverifyAttestationAndroidSafetyNet.ts
173 lines (151 loc) · 4.78 KB
/
verifyAttestationAndroidSafetyNet.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import type { AttestationFormatVerifierOpts } from '../verifyRegistrationResponse.ts';
import { toHash } from '../../helpers/toHash.ts';
import { verifySignature } from '../../helpers/verifySignature.ts';
import { getCertificateInfo } from '../../helpers/getCertificateInfo.ts';
import { validateCertificatePath } from '../../helpers/validateCertificatePath.ts';
import { convertCertBufferToPEM } from '../../helpers/convertCertBufferToPEM.ts';
import { isoBase64URL, isoUint8Array } from '../../helpers/iso/index.ts';
import { MetadataService } from '../../services/metadataService.ts';
import { verifyAttestationWithMetadata } from '../../metadata/verifyAttestationWithMetadata.ts';
/**
* Verify an attestation response with fmt 'android-safetynet'
*/
export async function verifyAttestationAndroidSafetyNet(
options: AttestationFormatVerifierOpts,
): Promise<boolean> {
const {
attStmt,
clientDataHash,
authData,
aaguid,
rootCertificates,
verifyTimestampMS = true,
credentialPublicKey,
} = options;
const alg = attStmt.get('alg');
const response = attStmt.get('response');
const ver = attStmt.get('ver');
if (!ver) {
throw new Error('No ver value in attestation (SafetyNet)');
}
if (!response) {
throw new Error(
'No response was included in attStmt by authenticator (SafetyNet)',
);
}
// Prepare to verify a JWT
const jwt = isoUint8Array.toUTF8String(response);
const jwtParts = jwt.split('.');
const HEADER: SafetyNetJWTHeader = JSON.parse(
isoBase64URL.toUTF8String(jwtParts[0]),
);
const PAYLOAD: SafetyNetJWTPayload = JSON.parse(
isoBase64URL.toUTF8String(jwtParts[1]),
);
const SIGNATURE: SafetyNetJWTSignature = jwtParts[2];
/**
* START Verify PAYLOAD
*/
const { nonce, ctsProfileMatch, timestampMs } = PAYLOAD;
if (verifyTimestampMS) {
// Make sure timestamp is in the past
let now = Date.now();
if (timestampMs > Date.now()) {
throw new Error(
`Payload timestamp "${timestampMs}" was later than "${now}" (SafetyNet)`,
);
}
// Consider a SafetyNet attestation valid within a minute of it being performed
const timestampPlusDelay = timestampMs + 60 * 1000;
now = Date.now();
if (timestampPlusDelay < now) {
throw new Error(
`Payload timestamp "${timestampPlusDelay}" has expired (SafetyNet)`,
);
}
}
const nonceBase = isoUint8Array.concat([authData, clientDataHash]);
const nonceBuffer = await toHash(nonceBase);
const expectedNonce = isoBase64URL.fromBuffer(nonceBuffer, 'base64');
if (nonce !== expectedNonce) {
throw new Error('Could not verify payload nonce (SafetyNet)');
}
if (!ctsProfileMatch) {
throw new Error('Could not verify device integrity (SafetyNet)');
}
/**
* END Verify PAYLOAD
*/
/**
* START Verify Header
*/
// `HEADER.x5c[0]` is definitely a base64 string
const leafCertBuffer = isoBase64URL.toBuffer(HEADER.x5c[0], 'base64');
const leafCertInfo = getCertificateInfo(leafCertBuffer);
const { subject } = leafCertInfo;
// Ensure the certificate was issued to this hostname
// See https://developer.android.com/training/safetynet/attestation#verify-attestation-response
if (subject.CN !== 'attest.android.com') {
throw new Error(
'Certificate common name was not "attest.android.com" (SafetyNet)',
);
}
const statement = await MetadataService.getStatement(aaguid);
if (statement) {
try {
await verifyAttestationWithMetadata({
statement,
credentialPublicKey,
x5c: HEADER.x5c,
attestationStatementAlg: alg,
});
} catch (err) {
const _err = err as Error;
throw new Error(`${_err.message} (SafetyNet)`);
}
} else {
try {
// Try validating the certificate path using the root certificates set via SettingsService
await validateCertificatePath(
HEADER.x5c.map(convertCertBufferToPEM),
rootCertificates,
);
} catch (err) {
const _err = err as Error;
throw new Error(`${_err.message} (SafetyNet)`);
}
}
/**
* END Verify Header
*/
/**
* START Verify Signature
*/
const signatureBaseBuffer = isoUint8Array.fromUTF8String(
`${jwtParts[0]}.${jwtParts[1]}`,
);
const signatureBuffer = isoBase64URL.toBuffer(SIGNATURE);
const verified = await verifySignature({
signature: signatureBuffer,
data: signatureBaseBuffer,
x509Certificate: leafCertBuffer,
});
/**
* END Verify Signature
*/
return verified;
}
type SafetyNetJWTHeader = {
alg: string;
x5c: string[];
};
type SafetyNetJWTPayload = {
nonce: string;
timestampMs: number;
apkPackageName: string;
apkDigestSha256: string;
ctsProfileMatch: boolean;
apkCertificateDigestSha256: string[];
basicIntegrity: boolean;
};
type SafetyNetJWTSignature = string;