Modern Apps git

MAOS.git

Public
git clone https://git.maproj.org/MAOS.git
main ▾

MAOS.git / patches / packages_apps_Settings_maos_attestation.patch

packages_apps_Settings_maos_attestation.patch703 lines · 28.6 KiBRaw
1diff --git a/res/values/strings_ext.xml b/res/values/strings_ext.xml
2index 0ac5bf5656d..52caca80bf5 100644
3--- a/res/values/strings_ext.xml
4+++ b/res/values/strings_ext.xml
5@@ -371,4 +371,26 @@ For compatibility, this app can still see clipboard metadata, such as whether an
6 <string name="app_clipboard_read_shared_uid_warning">"The clipboard access setting, blocked access message setting, and temporary Paste access are shared among these apps:
7 %1$s"</string>
8
9+ <string name="maos_attestation_title">Device attestation</string>
10+ <string name="maos_attestation_status_title">Last server verdict</string>
11+ <string name="maos_attestation_never">Not verified yet. Tap Verify.</string>
12+ <string name="maos_attestation_last">%1$s (%2$s) at %3$s</string>
13+ <string name="maos_attestation_verify_title">Verify</string>
14+ <string name="maos_attestation_verify_summary">Ask the MAOS server for a fresh challenge for your session and answer it with a one-time hardware attestation. The verdict shown here is the server's, not this device's.</string>
15+ <string name="maos_attestation_session_title">Session code</string>
16+ <string name="maos_attestation_session_summary">Start at maproj.org/attest, then enter the session code it shows here. Long-press the field to paste.</string>
17+ <string name="maos_attestation_scan_title">Scan QR code</string>
18+ <string name="maos_attestation_scan_summary">Scan the code shown at maproj.org/attest, or enter the session code below instead.</string>
19+ <string name="maos_attestation_scan_invalid">That is not an attestation code. Try again.</string>
20+ <string name="maos_attestation_session_required">Enter the session code from maproj.org/attest first.</string>
21+ <string name="maos_attestation_verifying">Verifying...</string>
22+ <string name="maos_attestation_passed">Server verdict: verified</string>
23+ <string name="maos_attestation_failed">Server verdict: failed (%1$s)</string>
24+ <string name="maos_attestation_result_title">Your verification</string>
25+ <string name="maos_attestation_result_summary">See your verification: maproj.org/attest — code %1$s\n%2$s</string>
26+ <string name="maos_attestation_about_title">How this works</string>
27+ <string name="maos_attestation_about_summary">A hardware-backed key (StrongBox where available, otherwise the trusted execution environment) is generated with a one-time server challenge. Its certificate chain is sent to api.maproj.org, which verifies it up to Google's hardware attestation root and checks that verified boot is Verified and the device is locked. No approval is needed: any device with valid hardware evidence gets a verdict. After verifying, see the result on the page that gave you the session code; this screen also shows a receipt code for reopening it. This page never grades itself.</string>
28+ <string name="maos_attestation_entry_title">Device attestation</string>
29+ <string name="maos_attestation_entry_summary">Server-verified hardware attestation</string>
30+
31 </resources>
32diff --git a/res/xml/maos_attestation_settings.xml b/res/xml/maos_attestation_settings.xml
33new file mode 100644
34index 00000000000..622c3177b5f
35--- /dev/null
36+++ b/res/xml/maos_attestation_settings.xml
37@@ -0,0 +1,45 @@
38+<?xml version="1.0" encoding="utf-8"?>
39+<!--
40+ MAOS device attestation (Auditor, shape 3): server-verified status and a
41+ single user-triggered "Verify" action. No periodic verification.
42+ -->
43+<PreferenceScreen
44+ xmlns:android="http://schemas.android.com/apk/res/android"
45+ android:key="maos_attestation_settings"
46+ android:title="@string/maos_attestation_title">
47+
48+ <Preference
49+ android:key="maos_attestation_status"
50+ android:title="@string/maos_attestation_status_title"
51+ android:summary="@string/maos_attestation_never"
52+ android:selectable="false" />
53+
54+ <Preference
55+ android:key="maos_attestation_scan"
56+ android:title="@string/maos_attestation_scan_title"
57+ android:summary="@string/maos_attestation_scan_summary"
58+ android:fragment="com.android.settings.security.MaosAttestationScannerFragment" />
59+
60+ <EditTextPreference
61+ android:key="maos_attestation_session_code"
62+ android:title="@string/maos_attestation_session_title"
63+ android:summary="@string/maos_attestation_session_summary"
64+ android:persistent="true"
65+ android:dialogTitle="@string/maos_attestation_session_title" />
66+
67+ <Preference
68+ android:key="maos_attestation_verify"
69+ android:title="@string/maos_attestation_verify_title"
70+ android:summary="@string/maos_attestation_verify_summary" />
71+
72+ <Preference
73+ android:key="maos_attestation_result"
74+ android:title="@string/maos_attestation_result_title" />
75+
76+ <Preference
77+ android:key="maos_attestation_about"
78+ android:title="@string/maos_attestation_about_title"
79+ android:summary="@string/maos_attestation_about_summary"
80+ android:selectable="false" />
81+
82+</PreferenceScreen>
83diff --git a/res/xml/security_dashboard_settings.xml b/res/xml/security_dashboard_settings.xml
84index 3bb7d69bf0d..7f29614bcfc 100644
85--- a/res/xml/security_dashboard_settings.xml
86+++ b/res/xml/security_dashboard_settings.xml
87@@ -62,6 +62,18 @@
88 settings:keywords="@string/keywords_biometric_settings" />
89 </PreferenceCategory>
90
91+ <!-- MAOS: server-verified device attestation, directly on the
92+ SecuritySettings dashboard (Settings > Security & privacy),
93+ above More security settings. Following the surrounding entries
94+ in this screen, no icon is set. -->
95+ <Preference
96+ android:order="90"
97+ android:key="maos_attestation"
98+ android:title="@string/maos_attestation_entry_title"
99+ android:summary="@string/maos_attestation_entry_summary"
100+ android:fragment="com.android.settings.security.MaosAttestationFragment"
101+ settings:keywords="@string/maos_attestation_entry_title" />
102+
103 <Preference
104 android:order="100"
105 android:key="security_advanced_settings"
106diff --git a/src/com/android/settings/security/MaosAttestationClient.java b/src/com/android/settings/security/MaosAttestationClient.java
107new file mode 100644
108index 00000000000..41c3e961edf
109--- /dev/null
110+++ b/src/com/android/settings/security/MaosAttestationClient.java
111@@ -0,0 +1,205 @@
112+/*
113+ * MAOS device attestation client (one-time, the Auditor model).
114+ *
115+ * One-off, user-triggered only: nothing here runs on a schedule, at boot,
116+ * or in the background. When the user taps "Verify" this client asks the
117+ * server for a fresh single-use challenge, generates a hardware-backed
118+ * key with that challenge (StrongBox where available, TEE otherwise), and
119+ * sends the resulting certificate chain to the server in a single submit.
120+ * There is no enrollment and no device identity: every Verify is a fresh
121+ * one-shot attestation. The server verifies the chain up to Google's
122+ * hardware attestation root, checks the challenge is fresh, and checks
123+ * the RootOfTrust says Verified with the device locked. Any device with
124+ * valid hardware evidence gets a verdict — no approval is needed or
125+ * involved.
126+ *
127+ * The verdict, code and URL shown in Settings are the server's response,
128+ * never a local self-assessment. All attestation claims come from the
129+ * certificate chain, not from Build properties or any other OS-reported
130+ * value (a compromised OS could lie about those).
131+ */
132+package com.android.settings.security;
133+
134+import android.content.Context;
135+import android.content.SharedPreferences;
136+import android.security.keystore.KeyGenParameterSpec;
137+import android.security.keystore.KeyProperties;
138+import android.util.Base64;
139+
140+import org.json.JSONArray;
141+import org.json.JSONObject;
142+
143+import java.io.BufferedReader;
144+import java.io.InputStream;
145+import java.io.InputStreamReader;
146+import java.io.OutputStream;
147+import java.net.HttpURLConnection;
148+import java.net.URL;
149+import java.nio.charset.StandardCharsets;
150+import java.security.KeyPairGenerator;
151+import java.security.KeyStore;
152+import java.security.cert.Certificate;
153+import java.security.spec.ECGenParameterSpec;
154+
155+final class MaosAttestationClient {
156+
157+ static final String PREFS = "maos_attestation";
158+ static final String KEY_LAST_RESULT = "last_result";
159+ static final String KEY_LAST_AT = "last_at";
160+ static final String KEY_LAST_LEVEL = "last_level";
161+ static final String KEY_LAST_CODE = "last_code";
162+ static final String KEY_LAST_URL = "last_url";
163+
164+ private static final String BASE = "https://api.maproj.org/attest/v1";
165+ private static final String FRESH_ALIAS = "maos_attestation_fresh";
166+
167+ private final SharedPreferences mPrefs;
168+
169+ MaosAttestationClient(Context context) {
170+ mPrefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
171+ }
172+
173+ static final class Result {
174+ final boolean pass;
175+ final String reason;
176+ final String securityLevel;
177+ final String userCode;
178+ final String verifyUrl;
179+
180+ Result(boolean pass, String reason, String securityLevel, String userCode,
181+ String verifyUrl) {
182+ this.pass = pass;
183+ this.reason = reason;
184+ this.securityLevel = securityLevel;
185+ this.userCode = userCode;
186+ this.verifyUrl = verifyUrl;
187+ }
188+ }
189+
190+ /** Run one one-shot verification round-trip. Blocking; call off the main thread. */
191+ Result verifyNow(String sessionCode) throws Exception {
192+ String code = sessionCode == null ? "" : sessionCode.trim();
193+ if (code.isEmpty()) {
194+ throw new IllegalStateException("missing session code");
195+ }
196+ JSONObject challenge = post("/challenge",
197+ new JSONObject().put("sessionCode", code));
198+ byte[] nonce = hexToBytes(challenge.getString("nonce"));
199+ boolean strongBox = generateKey(FRESH_ALIAS, nonce, true);
200+ JSONObject resp = post("/submit", new JSONObject()
201+ .put("chain", chainJson(FRESH_ALIAS))
202+ .put("sessionCode", code));
203+ return record(resp, strongBox);
204+ }
205+
206+ private Result record(JSONObject resp, boolean strongBoxRequested) throws Exception {
207+ boolean pass = resp.optBoolean("pass", false);
208+ String reason = resp.optString("reason", pass ? "ok" : "unknown");
209+ // The security level that counts is the one the server read from
210+ // the verified chain; the local StrongBox label is only a hint for
211+ // the (pre-verdict) case where the server did not answer.
212+ String level = resp.optString("security_level",
213+ strongBoxRequested ? "StrongBox" : "TrustedEnvironment");
214+ String userCode = resp.optString("userCode", "");
215+ String verifyUrl = resp.optString("verifyUrl", "");
216+ mPrefs.edit()
217+ .putString(KEY_LAST_RESULT, pass ? "pass" : "fail: " + reason)
218+ .putLong(KEY_LAST_AT, System.currentTimeMillis())
219+ .putString(KEY_LAST_LEVEL, level)
220+ .putString(KEY_LAST_CODE, userCode)
221+ .putString(KEY_LAST_URL, verifyUrl)
222+ .apply();
223+ return new Result(pass, reason, level, userCode, verifyUrl);
224+ }
225+
226+ /**
227+ * Generate (or replace) a hardware EC P-256 signing key attested with
228+ * {@code challenge}. Tries StrongBox first; on failure retries with the
229+ * TEE and returns false so the UI can label the level honestly (the
230+ * server's verdict still carries the authoritative level from the
231+ * chain).
232+ */
233+ private boolean generateKey(String alias, byte[] challenge, boolean tryStrongBox)
234+ throws Exception {
235+ try {
236+ buildKey(alias, challenge, tryStrongBox);
237+ return tryStrongBox;
238+ } catch (Exception e) {
239+ if (!tryStrongBox) {
240+ throw e;
241+ }
242+ buildKey(alias, challenge, false);
243+ return false;
244+ }
245+ }
246+
247+ private void buildKey(String alias, byte[] challenge, boolean strongBox)
248+ throws Exception {
249+ KeyPairGenerator gen = KeyPairGenerator.getInstance(
250+ KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
251+ KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(
252+ alias, KeyProperties.PURPOSE_SIGN)
253+ .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
254+ .setDigests(KeyProperties.DIGEST_SHA256)
255+ .setAttestationChallenge(challenge);
256+ if (strongBox) {
257+ builder.setIsStrongBoxBacked(true);
258+ }
259+ gen.initialize(builder.build());
260+ gen.generateKeyPair();
261+ }
262+
263+ private JSONArray chainJson(String alias) throws Exception {
264+ KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
265+ ks.load(null);
266+ Certificate[] chain = ks.getCertificateChain(alias);
267+ if (chain == null || chain.length == 0) {
268+ throw new IllegalStateException("no certificate chain for " + alias);
269+ }
270+ JSONArray out = new JSONArray();
271+ for (Certificate cert : chain) {
272+ out.put(Base64.encodeToString(cert.getEncoded(), Base64.NO_WRAP));
273+ }
274+ return out;
275+ }
276+
277+ private JSONObject post(String path, JSONObject body) throws Exception {
278+ HttpURLConnection conn = (HttpURLConnection) new URL(BASE + path).openConnection();
279+ conn.setRequestMethod("POST");
280+ conn.setRequestProperty("Content-Type", "application/json");
281+ conn.setConnectTimeout(15_000);
282+ conn.setReadTimeout(15_000);
283+ conn.setDoOutput(true);
284+ try (OutputStream os = conn.getOutputStream()) {
285+ os.write(body.toString().getBytes(StandardCharsets.UTF_8));
286+ }
287+ int code = conn.getResponseCode();
288+ InputStream in = code >= 400 ? conn.getErrorStream() : conn.getInputStream();
289+ String text = readAll(in);
290+ if (code >= 400) {
291+ String reason = new JSONObject(text).optString("reason", "http_" + code);
292+ throw new IllegalStateException(reason);
293+ }
294+ return new JSONObject(text);
295+ }
296+
297+ private static String readAll(InputStream in) throws Exception {
298+ StringBuilder sb = new StringBuilder();
299+ try (BufferedReader reader = new BufferedReader(
300+ new InputStreamReader(in, StandardCharsets.UTF_8))) {
301+ String line;
302+ while ((line = reader.readLine()) != null) {
303+ sb.append(line);
304+ }
305+ }
306+ return sb.toString();
307+ }
308+
309+ private static byte[] hexToBytes(String hex) {
310+ byte[] out = new byte[hex.length() / 2];
311+ for (int i = 0; i < out.length; i++) {
312+ out[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
313+ }
314+ return out;
315+ }
316+}
317diff --git a/src/com/android/settings/security/MaosAttestationFragment.java b/src/com/android/settings/security/MaosAttestationFragment.java
318new file mode 100644
319index 00000000000..0eefb3e8939
320--- /dev/null
321+++ b/src/com/android/settings/security/MaosAttestationFragment.java
322@@ -0,0 +1,202 @@
323+/*
324+ * MAOS "Device attestation" settings page (one-time, the Auditor model).
325+ *
326+ * Deliberately minimal: a status line (the last server verdict, stored
327+ * from the server's response), a single "Verify" action, and — once a
328+ * verification has completed — the code and URL for viewing that one
329+ * result at maproj.org/attest. There is no periodic or on-boot
330+ * verification, no enrollment, and no background work of any kind.
331+ */
332+package com.android.settings.security;
333+
334+import android.app.settings.SettingsEnums;
335+import android.content.Context;
336+import android.content.Intent;
337+import android.content.SharedPreferences;
338+import android.net.Uri;
339+import android.os.Bundle;
340+
341+import androidx.preference.EditTextPreference;
342+import androidx.preference.Preference;
343+
344+import com.android.settings.R;
345+import com.android.settings.dashboard.DashboardFragment;
346+import com.android.settings.search.BaseSearchIndexProvider;
347+import com.android.settingslib.search.SearchIndexable;
348+
349+import java.text.DateFormat;
350+import java.util.Date;
351+import java.util.concurrent.Executors;
352+
353+@SearchIndexable
354+public class MaosAttestationFragment extends DashboardFragment {
355+
356+ private static final String TAG = "MaosAttestation";
357+ private static final String KEY_STATUS = "maos_attestation_status";
358+ private static final String KEY_SESSION = "maos_attestation_session_code";
359+ private static final String KEY_VERIFY = "maos_attestation_verify";
360+ private static final String KEY_RESULT = "maos_attestation_result";
361+
362+ @Override
363+ public int getMetricsCategory() {
364+ return SettingsEnums.SECURITY;
365+ }
366+
367+ @Override
368+ protected String getLogTag() {
369+ return TAG;
370+ }
371+
372+ @Override
373+ protected int getPreferenceScreenResId() {
374+ return R.xml.maos_attestation_settings;
375+ }
376+
377+ @Override
378+ public void onResume() {
379+ super.onResume();
380+ updateStatus();
381+ }
382+
383+ @Override
384+ public boolean onPreferenceTreeClick(Preference preference) {
385+ if (KEY_VERIFY.equals(preference.getKey())) {
386+ runVerify(preference);
387+ return true;
388+ }
389+ if (KEY_RESULT.equals(preference.getKey())) {
390+ openVerification();
391+ return true;
392+ }
393+ return super.onPreferenceTreeClick(preference);
394+ }
395+
396+ private void openVerification() {
397+ Context context = getContext();
398+ if (context == null) {
399+ return;
400+ }
401+ SharedPreferences prefs = context.getSharedPreferences(
402+ MaosAttestationClient.PREFS, Context.MODE_PRIVATE);
403+ String url = prefs.getString(MaosAttestationClient.KEY_LAST_URL, null);
404+ if (url == null || url.isEmpty()) {
405+ return;
406+ }
407+ Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
408+ try {
409+ startActivity(intent);
410+ } catch (Exception e) {
411+ // No browser to open it with: the code and URL stay readable
412+ // on this screen, which is the point of showing them.
413+ }
414+ }
415+
416+ private void runVerify(Preference verifyPref) {
417+ Context context = getContext();
418+ if (context == null) {
419+ return;
420+ }
421+ String sessionCode = sessionCode();
422+ if (sessionCode.isEmpty()) {
423+ verifyPref.setSummary(R.string.maos_attestation_session_required);
424+ return;
425+ }
426+ verifyPref.setEnabled(false);
427+ verifyPref.setSummary(R.string.maos_attestation_verifying);
428+ Executors.newSingleThreadExecutor().execute(() -> {
429+ String message;
430+ try {
431+ MaosAttestationClient.Result result =
432+ new MaosAttestationClient(context).verifyNow(sessionCode);
433+ message = result.pass
434+ ? getString(R.string.maos_attestation_passed)
435+ : getString(R.string.maos_attestation_failed, result.reason);
436+ } catch (Exception e) {
437+ message = getString(R.string.maos_attestation_failed,
438+ String.valueOf(e.getMessage()));
439+ }
440+ String done = message;
441+ if (getActivity() != null) {
442+ getActivity().runOnUiThread(() -> {
443+ verifyPref.setEnabled(true);
444+ verifyPref.setSummary(done);
445+ updateStatus();
446+ });
447+ }
448+ });
449+ }
450+
451+ private void updateStatus() {
452+ Preference status = findPreference(KEY_STATUS);
453+ Context context = getContext();
454+ if (status == null || context == null) {
455+ return;
456+ }
457+ SharedPreferences prefs = context.getSharedPreferences(
458+ MaosAttestationClient.PREFS, Context.MODE_PRIVATE);
459+ String result = prefs.getString(MaosAttestationClient.KEY_LAST_RESULT, null);
460+ if (result == null) {
461+ status.setSummary(R.string.maos_attestation_never);
462+ } else {
463+ long at = prefs.getLong(MaosAttestationClient.KEY_LAST_AT, 0);
464+ String level = prefs.getString(MaosAttestationClient.KEY_LAST_LEVEL, "");
465+ String when = at == 0 ? "" : DateFormat.getDateTimeInstance().format(new Date(at));
466+ status.setSummary(getString(R.string.maos_attestation_last, result, level, when));
467+ }
468+ Preference verification = findPreference(KEY_RESULT);
469+ if (verification != null) {
470+ String code = prefs.getString(MaosAttestationClient.KEY_LAST_CODE, null);
471+ String url = prefs.getString(MaosAttestationClient.KEY_LAST_URL, null);
472+ if (code == null || code.isEmpty() || url == null || url.isEmpty()) {
473+ verification.setVisible(false);
474+ } else {
475+ verification.setVisible(true);
476+ verification.setSummary(
477+ getString(R.string.maos_attestation_result_summary, code, url));
478+ }
479+ }
480+ }
481+
482+ private String sessionCode() {
483+ Preference pref = findPreference(KEY_SESSION);
484+ if (pref instanceof EditTextPreference) {
485+ String text = ((EditTextPreference) pref).getText();
486+ return text == null ? "" : text.trim();
487+ }
488+ return "";
489+ }
490+
491+ @Override
492+ public void onCreate(Bundle icicle) {
493+ super.onCreate(icicle);
494+ // Scanned session code: fill the field and verify right away.
495+ getParentFragmentManager().setFragmentResultListener(
496+ MaosAttestationScannerFragment.RESULT_KEY, this, (requestKey, result) -> {
497+ String code = result.getString(MaosAttestationScannerFragment.RESULT_CODE, "");
498+ Preference session = findPreference(KEY_SESSION);
499+ if (session instanceof EditTextPreference) {
500+ ((EditTextPreference) session).setText(code);
501+ }
502+ Preference verify = findPreference(KEY_VERIFY);
503+ if (verify != null) {
504+ runVerify(verify);
505+ }
506+ });
507+ }
508+
509+ @Override
510+ public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
511+ super.onCreatePreferences(savedInstanceState, rootKey);
512+ Preference pref = findPreference(KEY_SESSION);
513+ if (pref instanceof EditTextPreference) {
514+ ((EditTextPreference) pref).setOnBindEditTextListener(editText -> {
515+ editText.setSingleLine(true);
516+ editText.setHint("XXXX-XXXX");
517+ editText.setSelection(editText.getText().length());
518+ });
519+ }
520+ }
521+
522+ public static final BaseSearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
523+ new BaseSearchIndexProvider(R.xml.maos_attestation_settings);
524+}
525diff --git a/src/com/android/settings/security/MaosAttestationScannerFragment.java b/src/com/android/settings/security/MaosAttestationScannerFragment.java
526new file mode 100644
527index 00000000000..7f1ceb0c385
528--- /dev/null
529+++ b/src/com/android/settings/security/MaosAttestationScannerFragment.java
530@@ -0,0 +1,173 @@
531+/*
532+ * MAOS attestation QR scanner: scans the session code shown at
533+ * maproj.org/attest using SettingsLib's QrCamera (the same scanner path
534+ * as Wi-Fi DPP and ADB pairing), then hands the code back to
535+ * MaosAttestationFragment, which runs Verify against that session.
536+ * Manual code entry on the attestation screen is the fallback.
537+ */
538+package com.android.settings.security;
539+
540+import android.app.settings.SettingsEnums;
541+import android.graphics.Matrix;
542+import android.graphics.Rect;
543+import android.graphics.SurfaceTexture;
544+import android.os.Bundle;
545+import android.util.Size;
546+import android.view.LayoutInflater;
547+import android.view.TextureView;
548+import android.view.View;
549+import android.view.ViewGroup;
550+import android.widget.TextView;
551+
552+import com.android.settings.R;
553+import com.android.settings.wifi.dpp.WifiDppQrCodeBaseFragment;
554+import com.android.settingslib.qrcode.QrCamera;
555+
556+public class MaosAttestationScannerFragment extends WifiDppQrCodeBaseFragment
557+ implements TextureView.SurfaceTextureListener, QrCamera.ScannerCallback {
558+
559+ static final String RESULT_KEY = "maos_attestation_scan";
560+ static final String RESULT_CODE = "session_code";
561+
562+ private QrCamera mCamera;
563+ private TextureView mTextureView;
564+ private TextView mErrorMessage;
565+
566+ @Override
567+ public int getMetricsCategory() {
568+ return SettingsEnums.SECURITY;
569+ }
570+
571+ @Override
572+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
573+ Bundle savedInstanceState) {
574+ return inflater.inflate(R.layout.adb_qrcode_scanner_fragment, container, false);
575+ }
576+
577+ @Override
578+ public void onViewCreated(View view, Bundle savedInstanceState) {
579+ super.onViewCreated(view, savedInstanceState);
580+ mTextureView = view.findViewById(R.id.preview_view);
581+ mTextureView.setSurfaceTextureListener(this);
582+ mErrorMessage = view.findViewById(R.id.error_message);
583+ setHeaderTitle(R.string.maos_attestation_scan_title);
584+ mSummary.setText(R.string.maos_attestation_scan_summary);
585+ }
586+
587+ @Override
588+ public void onResume() {
589+ super.onResume();
590+ if (mCamera != null && mTextureView.getSurfaceTexture() != null) {
591+ mCamera.start(mTextureView.getSurfaceTexture());
592+ }
593+ }
594+
595+ @Override
596+ public void onPause() {
597+ if (mCamera != null) {
598+ mCamera.stop();
599+ }
600+ super.onPause();
601+ }
602+
603+ @Override
604+ public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
605+ if (mCamera == null) {
606+ mCamera = new QrCamera(getContext(), this);
607+ mCamera.start(surface);
608+ }
609+ }
610+
611+ @Override
612+ public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {}
613+
614+ @Override
615+ public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
616+ if (mCamera != null) {
617+ mCamera.stop();
618+ mCamera = null;
619+ }
620+ return true;
621+ }
622+
623+ @Override
624+ public void onSurfaceTextureUpdated(SurfaceTexture surface) {}
625+
626+ @Override
627+ public Size getViewSize() {
628+ return new Size(mTextureView.getWidth(), mTextureView.getHeight());
629+ }
630+
631+ @Override
632+ public void setTransform(Matrix transform) {
633+ if (getActivity() != null) {
634+ getActivity().runOnUiThread(() -> mTextureView.setTransform(transform));
635+ }
636+ }
637+
638+ @Override
639+ public Rect getFramePosition(Size previewSize, int cameraOrientation) {
640+ return new Rect(0, 0, previewSize.getHeight(), previewSize.getHeight());
641+ }
642+
643+ /** Session code from `maos-attest://verify?code=XXXX-XXXX`, a bare
644+ * code, or any URL carrying `code=` / `sessionCode=`. */
645+ static String parseSessionCode(String qr) {
646+ if (qr == null) {
647+ return null;
648+ }
649+ String s = qr.trim();
650+ for (String key : new String[]{"code=", "sessionCode="}) {
651+ int at = s.indexOf(key);
652+ if (at >= 0) {
653+ String rest = s.substring(at + key.length());
654+ StringBuilder out = new StringBuilder();
655+ for (int i = 0; i < rest.length(); i++) {
656+ char c = rest.charAt(i);
657+ if (c == '&' || Character.isWhitespace(c) || c == '"' || c == '\'') {
658+ break;
659+ }
660+ out.append(c);
661+ }
662+ return out.toString();
663+ }
664+ }
665+ return s;
666+ }
667+
668+ @Override
669+ public boolean isValid(String qrCode) {
670+ String code = parseSessionCode(qrCode);
671+ if (code == null || code.replace("-", "").length() != 8) {
672+ mErrorMessage.setText(R.string.maos_attestation_scan_invalid);
673+ mErrorMessage.setVisibility(View.VISIBLE);
674+ return false;
675+ }
676+ return true;
677+ }
678+
679+ @Override
680+ public void handleSuccessfulResult(String qrCode) {
681+ if (mCamera != null) {
682+ mCamera.stop();
683+ mCamera = null;
684+ }
685+ Bundle result = new Bundle();
686+ result.putString(RESULT_CODE, parseSessionCode(qrCode));
687+ getParentFragmentManager().setFragmentResult(RESULT_KEY, result);
688+ getParentFragmentManager().popBackStack();
689+ }
690+
691+ @Override
692+ public void handleCameraFailure() {
693+ if (mCamera != null) {
694+ mCamera.stop();
695+ mCamera = null;
696+ }
697+ }
698+
699+ @Override
700+ protected boolean isFooterAvailable() {
701+ return false;
702+ }
703+}