-
Notifications
You must be signed in to change notification settings - Fork 6
/
SafetyNetUtils.java
219 lines (188 loc) · 10 KB
/
SafetyNetUtils.java
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package com.catherine.securitysample.safety_net;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.Nullable;
import android.util.Base64;
import android.util.Log;
import com.catherine.securitysample.MyApplication;
import com.catherine.securitysample.Utils;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.safetynet.HarmfulAppsData;
import com.google.android.gms.safetynet.SafetyNet;
import com.google.android.gms.safetynet.SafetyNetApi;
import org.json.JSONException;
import java.security.SecureRandom;
import java.util.List;
/**
* Created by Catherine on 2017/6/29.
*/
public class SafetyNetUtils {
private final static String TAG = "SafetyNetUtils";
private Context ctx;
private Callback callback;
private final SecureRandom secureRandom;
private GoogleApiClient googleApiClient;
public SafetyNetUtils(Context ctx, Callback callback) {
this.ctx = ctx;
this.callback = callback;
GoogleApiClient.OnConnectionFailedListener googleApiConnectionFailedListener = connectionResult -> Log.e(TAG, "onConnectionFailed:" + connectionResult.toString());
GoogleApiClient.ConnectionCallbacks googleApiConnectionCallbacks = new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(@Nullable Bundle bundle) {
String logs = bundle == null ? "" : bundle.toString();
callback.onResponse("GoogleApiClient onConnected " + logs);
}
@Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "onConnectionSuspended" + i);
}
};
Handler handler = new Handler(MyApplication.INSTANCE.safetyNetLooper.getLooper());
googleApiClient = new GoogleApiClient.Builder(ctx)
.addApi(SafetyNet.API)
.addConnectionCallbacks(googleApiConnectionCallbacks)
.addOnConnectionFailedListener(googleApiConnectionFailedListener)
.setHandler(handler) //Run on a new thread
.build();
googleApiClient.connect();
secureRandom = new SecureRandom();
}
public interface Callback {
void onResponse(String message);
void onFail(ErrorMessage code, String message);
}
public void verifyApps() {
if (!isGooglePlayServicesAvailable()) return;
final StringBuilder sb = new StringBuilder();
SafetyNet.getClient(ctx)
.isVerifyAppsEnabled()
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
SafetyNetApi.VerifyAppsUserResponse result = task.getResult();
if (result.isVerifyAppsEnabled()) {
sb.append("The Verify Apps feature is enabled.\n");
} else {
sb.append("The Verify Apps feature is disabled.\n");
}
} else {
sb.append("A general error occurred.\n");
Log.e(TAG, "A general error occurred.");
}
callback.onResponse(sb.toString());
});
SafetyNet.getClient(ctx)
.enableVerifyApps()
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
SafetyNetApi.VerifyAppsUserResponse result = task.getResult();
if (result.isVerifyAppsEnabled()) {
sb.append("The user gave consent to enable the Verify Apps feature.\n");
} else {
sb.append("The user didn't give consent to enable the Verify Apps feature.\n");
}
} else {
sb.append("A general error occurred.\n");
Log.e(TAG, "A general error occurred.");
}
callback.onResponse(sb.toString());
});
SafetyNet.getClient(ctx)
.listHarmfulApps()
.addOnCompleteListener(task -> {
sb.append("Received listHarmfulApps() result\n");
if (task.isSuccessful()) {
SafetyNetApi.HarmfulAppsResponse result = task.getResult();
List<HarmfulAppsData> appList = result.getHarmfulAppsList();
if (appList.isEmpty()) {
sb.append("There are no known potentially harmful apps installed.\n");
} else {
sb.append("Potentially harmful apps are installed!\n");
for (HarmfulAppsData harmfulApp : appList) {
Log.e(TAG, "Information about a harmful app:");
sb.append("Information about a harmful app:\n");
Log.e(TAG,
" APK: " + harmfulApp.apkPackageName);
sb.append(" APK: " + harmfulApp.apkPackageName + "\n");
Log.e(TAG,
" SHA-256: " + harmfulApp.apkSha256);
sb.append(" SHA-256: " + harmfulApp.apkSha256 + "\n");
// Categories are defined in VerifyAppsConstants.
Log.e(TAG,
" Category: " + harmfulApp.apkCategory);
sb.append(" Category: " + harmfulApp.apkCategory + "\n");
}
}
} else {
sb.append("An error occurred. Call isVerifyAppsEnabled() to ensure that the user has consented.\n");
Log.d(TAG, "An error occurred. Call isVerifyAppsEnabled() to ensure that the user has consented.");
}
callback.onResponse(sb.toString());
});
}
public void requestAttestation(final boolean verifyJWSResponse) {
if (!isGooglePlayServicesAvailable()) return;
Log.v(TAG, "running SafetyNet.API Test");
byte[] requestNonce = generateOneTimeRequestNonce();
Log.d(TAG, "Nonce:" + Base64.encodeToString(requestNonce, Base64.DEFAULT));
SafetyNet.SafetyNetApi.attest(googleApiClient, requestNonce)
.setResultCallback(attestationResult -> {
Status status = attestationResult.getStatus();
boolean isSuccess = status.isSuccess();
if (!isSuccess)
callback.onFail(ErrorMessage.SAFETY_NET_API_NOT_WORK, ErrorMessage.SAFETY_NET_API_NOT_WORK.name());
else {
try {
final String jwsResult = attestationResult.getJwsResult();
final JwsHelper jwsHelper = new JwsHelper(jwsResult);
final AttestationResult response = new AttestationResult(jwsHelper.getDecodedPayload());
if (!verifyJWSResponse) {
callback.onResponse(response.getFormattedString());
//release SafetyNet HandlerThread
MyApplication.INSTANCE.safetyNetLooper.quit();
} else {
AndroidDeviceVerifier androidDeviceVerifier = new AndroidDeviceVerifier(ctx, jwsResult);
androidDeviceVerifier.verify(new AttestationTaskCallback() {
@Override
public void error(String errorMsg) {
callback.onFail(ErrorMessage.FAILED_TO_CALL_GOOGLE_API_SERVICES, errorMsg);
//release SafetyNet HandlerThread
MyApplication.INSTANCE.safetyNetLooper.quit();
}
@Override
public void success(boolean isValidSignature) {
if (isValidSignature)
callback.onResponse("isValidSignature true\n\n" + response.getFormattedString());
else
callback.onFail(ErrorMessage.ERROR_VALID_SIGNATURE, ErrorMessage.ERROR_VALID_SIGNATURE.name());
//release SafetyNet HandlerThread
MyApplication.INSTANCE.safetyNetLooper.quit();
}
});
}
} catch (JSONException e) {
callback.onFail(ErrorMessage.EXCEPTION, e.getMessage());
//release SafetyNet HandlerThread
MyApplication.INSTANCE.safetyNetLooper.quit();
}
}
});
}
private boolean isGooglePlayServicesAvailable() {
if (ConnectionResult.SUCCESS != GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(ctx)) {
Log.e(TAG, "GooglePlayServices is not available on this device.\n\nAttestation is not available.");
callback.onFail(ErrorMessage.GOOGLE_PLAY_SERVICES_UNAVAILABLE, "GooglePlayServices is not available on this device.\n\nAttestation is not available.");
return false;
} else
return true;
}
private byte[] generateOneTimeRequestNonce() {
byte[] nonce = new byte[32];
secureRandom.nextBytes(nonce);
return nonce;
}
}