-
-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathAttestationServer.java
1735 lines (1577 loc) · 74.4 KB
/
AttestationServer.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package app.attestation.server;
import app.attestation.server.AttestationProtocol.DeviceInfo;
import app.attestation.server.attestation.ParsedAttestationRecord;
import com.almworks.sqlite4java.SQLiteConnection;
import com.almworks.sqlite4java.SQLiteException;
import com.almworks.sqlite4java.SQLiteStatement;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.google.common.io.BaseEncoding;
import com.google.common.primitives.Bytes;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import jakarta.json.JsonArrayBuilder;
import jakarta.json.JsonException;
import jakarta.json.JsonObject;
import jakarta.json.JsonObjectBuilder;
import jakarta.json.JsonReader;
import jakarta.json.JsonWriter;
import jakarta.mail.internet.AddressException;
import jakarta.mail.internet.InternetAddress;
import org.bouncycastle.crypto.generators.SCrypt;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.cert.Certificate;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.DataFormatException;
import static app.attestation.server.AttestationProtocol.fingerprintsCustomOS;
import static app.attestation.server.AttestationProtocol.fingerprintsStock;
import static app.attestation.server.AttestationProtocol.fingerprintsStrongBoxCustomOS;
import static app.attestation.server.AttestationProtocol.fingerprintsStrongBoxStock;
import static app.attestation.server.SyslogLevel.ALERT;
import static com.almworks.sqlite4java.SQLiteConstants.SQLITE_CONSTRAINT_UNIQUE;
class AttestationServer {
static final File ATTESTATION_DATABASE = new File("attestation.db");
static final File SAMPLES_DATABASE = new File("samples.db");
private static final int MAX_SAMPLE_SIZE = 64 * 1024;
private static final int DEFAULT_VERIFY_INTERVAL = 6 * 60 * 60;
private static final int MIN_VERIFY_INTERVAL = 60 * 60;
private static final int MAX_VERIFY_INTERVAL = 7 * 24 * 70 * 60;
private static final int DEFAULT_ALERT_DELAY = 48 * 60 * 60;
private static final int MIN_ALERT_DELAY = 32 * 60 * 60;
private static final int MAX_ALERT_DELAY = 2 * 7 * 24 * 60 * 60;
private static final int BUSY_TIMEOUT = 10 * 1000;
private static final int QR_CODE_PIXEL_SIZE = 300;
private static final long SESSION_LENGTH = 48 * 60 * 60 * 1000;
private static final int HISTORY_PER_PAGE = 20;
private static final long MMAP_SIZE = 1024 * 1024 * 1024;
static final String DOMAIN = "attestation.app";
private static final String ORIGIN = "https://" + DOMAIN;
private static final long POST_START_DELAY_MS = 1000;
private static final Logger logger = Logger.getLogger(AttestationServer.class.getName());
// This should be moved to a table in the database so that it can be modified dynamically
// without modifying the source code.
private static final String[] emailBlacklistPatterns = {
"(contact|security|webmaster)@(attestation.app|grapheneos.org|seamlessupdate.app)"
};
private static final Cache<ByteBuffer, Boolean> pendingChallenges = Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.MINUTES)
.maximumSize(1000000)
.build();
static SQLiteConnection open(final File db) throws SQLiteException {
final SQLiteConnection conn = new SQLiteConnection(db);
conn.open();
try {
conn.setBusyTimeout(BUSY_TIMEOUT);
conn.exec("PRAGMA foreign_keys = ON");
conn.exec("PRAGMA journal_mode = WAL");
conn.exec("PRAGMA trusted_schema = OFF");
conn.exec("PRAGMA mmap_size = " + MMAP_SIZE);
} catch (final Exception e) {
conn.dispose();
throw e;
}
return conn;
}
private static final ThreadLocal<SQLiteConnection> localAttestationConn = new ThreadLocal<>();
static SQLiteConnection getLocalAttestationConn() throws SQLiteException {
SQLiteConnection conn = localAttestationConn.get();
if (conn != null) {
return conn;
}
conn = open(ATTESTATION_DATABASE);
localAttestationConn.set(conn);
return conn;
}
static void rollbackIfNeeded(final SQLiteConnection conn) throws SQLiteException {
if (!conn.getAutoCommit()) {
conn.exec("ROLLBACK");
}
}
private static int getUserVersion(final SQLiteConnection conn) throws SQLiteException {
final SQLiteStatement pragmaUserVersion = conn.prepare("PRAGMA user_version");
try {
pragmaUserVersion.step();
int userVersion = pragmaUserVersion.columnInt(0);
logger.info("Existing schema version: " + userVersion);
return userVersion;
} finally {
pragmaUserVersion.dispose();
}
}
private static final String CREATE_SAMPLES_TABLE = """
CREATE TABLE IF NOT EXISTS Samples (
sample BLOB NOT NULL,
time INTEGER NOT NULL
) STRICT""";
private static void setupSamplesDatabase() throws SQLiteException {
final SQLiteConnection conn = open(SAMPLES_DATABASE);
try {
final SQLiteStatement selectCreated = conn.prepare(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='Samples'");
if (!selectCreated.step()) {
conn.exec("PRAGMA user_version = 1");
}
selectCreated.dispose();
int userVersion = getUserVersion(conn);
conn.exec(CREATE_SAMPLES_TABLE);
if (userVersion < 1) {
logger.log(ALERT, SAMPLES_DATABASE + " database schemas older than version 1 are no longer " +
"supported. Use an older AttestationServer revision to upgrade.");
System.exit(1);
}
logger.info("Finished database setup for " + SAMPLES_DATABASE);
} finally {
conn.dispose();
}
}
private static final String CREATE_ATTESTATION_TABLES = """
CREATE TABLE IF NOT EXISTS Configuration (
key TEXT PRIMARY KEY NOT NULL,
value ANY NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS Accounts (
userId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL COLLATE NOCASE UNIQUE,
passwordHash BLOB NOT NULL,
passwordSalt BLOB NOT NULL,
subscribeKey BLOB NOT NULL,
creationTime INTEGER NOT NULL,
loginTime INTEGER NOT NULL,
verifyInterval INTEGER NOT NULL,
alertDelay INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS EmailAddresses (
userId INTEGER NOT NULL REFERENCES Accounts (userId) ON DELETE CASCADE,
address TEXT NOT NULL,
PRIMARY KEY (userId, address)
) STRICT;
CREATE TABLE IF NOT EXISTS Sessions (
sessionId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
userId INTEGER NOT NULL REFERENCES Accounts (userId) ON DELETE CASCADE,
token BLOB NOT NULL,
expiryTime INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS Devices (
fingerprint BLOB NOT NULL PRIMARY KEY,
pinnedCertificates BLOB NOT NULL,
attestKey INTEGER NOT NULL CHECK (attestKey in (0, 1)),
pinnedVerifiedBootKey BLOB NOT NULL,
verifiedBootHash BLOB,
pinnedOsVersion INTEGER NOT NULL,
pinnedOsPatchLevel INTEGER NOT NULL,
pinnedVendorPatchLevel INTEGER,
pinnedBootPatchLevel INTEGER,
pinnedAppVersion INTEGER NOT NULL,
pinnedAppVariant INTEGER NOT NULL CHECK (pinnedAppVariant in (0, 1, 2)),
pinnedSecurityLevel INTEGER NOT NULL,
userProfileSecure INTEGER NOT NULL CHECK (userProfileSecure in (0, 1)),
enrolledBiometrics INTEGER NOT NULL CHECK (enrolledBiometrics in (0, 1)),
accessibility INTEGER NOT NULL CHECK (accessibility in (0, 1)),
deviceAdmin INTEGER NOT NULL CHECK (deviceAdmin in (0, 1, 2)),
adbEnabled INTEGER NOT NULL CHECK (adbEnabled in (0, 1)),
addUsersWhenLocked INTEGER NOT NULL CHECK (addUsersWhenLocked in (0, 1)),
oemUnlockAllowed INTEGER NOT NULL CHECK (oemUnlockAllowed in (0, 1)),
systemUser INTEGER NOT NULL CHECK (systemUser in (0, 1)),
verifiedTimeFirst INTEGER NOT NULL,
verifiedTimeLast INTEGER NOT NULL,
expiredTimeLast INTEGER,
failureTimeLast INTEGER,
failureAlertTime INTEGER,
userId INTEGER NOT NULL REFERENCES Accounts (userId) ON DELETE CASCADE,
deletionTime INTEGER
) STRICT;
CREATE TABLE IF NOT EXISTS Attestations (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
fingerprint BLOB NOT NULL REFERENCES Devices (fingerprint) ON DELETE CASCADE,
time INTEGER NOT NULL,
strong INTEGER NOT NULL CHECK (strong in (0, 1)),
osVersion INTEGER NOT NULL,
osPatchLevel INTEGER NOT NULL,
vendorPatchLevel INTEGER,
bootPatchLevel INTEGER,
verifiedBootHash BLOB,
appVersion INTEGER NOT NULL,
userProfileSecure INTEGER NOT NULL CHECK (userProfileSecure in (0, 1)),
enrolledBiometrics INTEGER NOT NULL CHECK (enrolledBiometrics in (0, 1)),
accessibility INTEGER NOT NULL CHECK (accessibility in (0, 1)),
deviceAdmin INTEGER NOT NULL CHECK (deviceAdmin in (0, 1, 2)),
adbEnabled INTEGER NOT NULL CHECK (adbEnabled in (0, 1)),
addUsersWhenLocked INTEGER NOT NULL CHECK (addUsersWhenLocked in (0, 1)),
oemUnlockAllowed INTEGER NOT NULL CHECK (oemUnlockAllowed in (0, 1)),
systemUser INTEGER NOT NULL CHECK (systemUser in (0, 1))
) STRICT""";
private static final String CREATE_ATTESTATION_INDICES = """
CREATE INDEX IF NOT EXISTS Accounts_loginTime
ON Accounts (loginTime);
CREATE INDEX IF NOT EXISTS Sessions_expiryTime
ON Sessions (expiryTime);
CREATE INDEX IF NOT EXISTS Sessions_userId
ON Sessions (userId);
CREATE INDEX IF NOT EXISTS Devices_userId_verifiedTimeFirst
ON Devices (userId, verifiedTimeFirst);
CREATE INDEX IF NOT EXISTS Devices_userId_verifiedTimeLast_deletionTimeNull
ON Devices (userId, verifiedTimeLast) WHERE deletionTime IS NULL;
CREATE INDEX IF NOT EXISTS Devices_deletionTime
ON Devices (deletionTime) WHERE deletionTime IS NOT NULL;
CREATE INDEX IF NOT EXISTS Devices_verifiedTimeLast_deletionTimeNull
ON Devices (verifiedTimeLast) WHERE deletionTime IS NULL;
CREATE INDEX IF NOT EXISTS Attestations_fingerprint_id
ON Attestations (fingerprint, id)""";
private static void setupAttestationDatabase() throws DataFormatException, GeneralSecurityException, IOException, SQLiteException {
final SQLiteConnection conn = open(ATTESTATION_DATABASE);
try {
final SQLiteStatement selectCreated = conn.prepare(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='Configuration'");
if (!selectCreated.step()) {
conn.exec("PRAGMA user_version = 13");
}
selectCreated.dispose();
int userVersion = getUserVersion(conn);
conn.exec(CREATE_ATTESTATION_TABLES);
conn.exec(CREATE_ATTESTATION_INDICES);
if (userVersion < 11) {
logger.log(ALERT, ATTESTATION_DATABASE + " database schemas older than version 11 are no longer " +
"supported. Use an older AttestationServer revision to upgrade.");
System.exit(1);
}
int targetUserVersion;
// remove denyNewUsb column from Devices
targetUserVersion = 12;
if (userVersion < targetUserVersion) {
conn.exec("PRAGMA foreign_keys = OFF");
conn.exec("BEGIN IMMEDIATE TRANSACTION");
conn.exec("ALTER TABLE Devices RENAME TO OldDevices");
conn.exec("ALTER TABLE Attestations RENAME TO OldAttestations");
conn.exec(CREATE_ATTESTATION_TABLES);
conn.exec("""
INSERT INTO Devices (
fingerprint,
pinnedCertificates,
attestKey,
pinnedVerifiedBootKey,
verifiedBootHash,
pinnedOsVersion,
pinnedOsPatchLevel,
pinnedVendorPatchLevel,
pinnedBootPatchLevel,
pinnedAppVersion,
pinnedAppVariant,
pinnedSecurityLevel,
userProfileSecure,
enrolledBiometrics,
accessibility,
deviceAdmin,
adbEnabled,
addUsersWhenLocked,
oemUnlockAllowed,
systemUser,
verifiedTimeFirst,
verifiedTimeLast,
expiredTimeLast,
failureTimeLast,
userId,
deletionTime)
SELECT
fingerprint,
pinnedCertificates,
attestKey,
pinnedVerifiedBootKey,
verifiedBootHash,
pinnedOsVersion,
pinnedOsPatchLevel,
pinnedVendorPatchLevel,
pinnedBootPatchLevel,
pinnedAppVersion,
pinnedAppVariant,
pinnedSecurityLevel,
userProfileSecure,
enrolledBiometrics,
accessibility,
deviceAdmin,
adbEnabled,
addUsersWhenLocked,
oemUnlockAllowed,
systemUser,
verifiedTimeFirst,
verifiedTimeLast,
expiredTimeLast,
failureTimeLast,
userId,
deletionTime
FROM OldDevices""");
conn.exec("""
INSERT INTO Attestations (
id,
fingerprint,
time,
strong,
osVersion,
osPatchLevel,
vendorPatchLevel,
bootPatchLevel,
verifiedBootHash,
appVersion,
userProfileSecure,
enrolledBiometrics,
accessibility,
deviceAdmin,
adbEnabled,
addUsersWhenLocked,
oemUnlockAllowed,
systemUser
) SELECT
id,
fingerprint,
time,
strong,
osVersion,
osPatchLevel,
vendorPatchLevel,
bootPatchLevel,
verifiedBootHash,
appVersion,
userProfileSecure,
enrolledBiometrics,
accessibility,
deviceAdmin,
adbEnabled,
addUsersWhenLocked,
oemUnlockAllowed,
systemUser
FROM OldAttestations""");
conn.exec("DROP TABLE OldDevices");
conn.exec("DROP TABLE OldAttestations");
conn.exec(CREATE_ATTESTATION_INDICES);
conn.exec("PRAGMA user_version = " + targetUserVersion);
conn.exec("COMMIT TRANSACTION");
userVersion = targetUserVersion;
conn.exec("PRAGMA foreign_keys = ON");
logger.info("Migrated to schema version: " + userVersion);
}
// update DEFLATE dictionary from 2 to 4
targetUserVersion = 13;
if (userVersion < targetUserVersion) {
conn.exec("BEGIN IMMEDIATE TRANSACTION");
final SQLiteStatement select = conn.prepare(
"SELECT pinnedCertificates, fingerprint FROM Devices");
final SQLiteStatement update = conn.prepare(
"UPDATE Devices SET pinnedCertificates = ? where fingerprint = ?");
while (select.step()) {
final Certificate[] chain = AttestationProtocol.decodeChain(AttestationProtocol.DEFLATE_DICTIONARY_2, select.columnBlob(0));
update.bind(1, AttestationProtocol.encodeChain(AttestationProtocol.DEFLATE_DICTIONARY_4, chain));
update.bind(2, select.columnBlob(1));
update.step();
update.reset();
}
select.dispose();
update.dispose();
conn.exec("PRAGMA user_version = " + targetUserVersion);
conn.exec("COMMIT TRANSACTION");
userVersion = targetUserVersion;
logger.info("Migrated to schema version: " + userVersion);
}
// add failureAlertTime column to Devices
targetUserVersion = 14;
if (userVersion < targetUserVersion) {
conn.exec("PRAGMA foreign_keys = OFF");
conn.exec("BEGIN IMMEDIATE TRANSACTION");
conn.exec("ALTER TABLE Devices RENAME TO OldDevices");
conn.exec("ALTER TABLE Attestations RENAME TO OldAttestations");
conn.exec(CREATE_ATTESTATION_TABLES);
conn.exec("""
INSERT INTO Devices (
fingerprint,
pinnedCertificates,
attestKey,
pinnedVerifiedBootKey,
verifiedBootHash,
pinnedOsVersion,
pinnedOsPatchLevel,
pinnedVendorPatchLevel,
pinnedBootPatchLevel,
pinnedAppVersion,
pinnedAppVariant,
pinnedSecurityLevel,
userProfileSecure,
enrolledBiometrics,
accessibility,
deviceAdmin,
adbEnabled,
addUsersWhenLocked,
oemUnlockAllowed,
systemUser,
verifiedTimeFirst,
verifiedTimeLast,
expiredTimeLast,
failureTimeLast,
failureAlertTime,
userId,
deletionTime)
SELECT
fingerprint,
pinnedCertificates,
attestKey,
pinnedVerifiedBootKey,
verifiedBootHash,
pinnedOsVersion,
pinnedOsPatchLevel,
pinnedVendorPatchLevel,
pinnedBootPatchLevel,
pinnedAppVersion,
pinnedAppVariant,
pinnedSecurityLevel,
userProfileSecure,
enrolledBiometrics,
accessibility,
deviceAdmin,
adbEnabled,
addUsersWhenLocked,
oemUnlockAllowed,
systemUser,
verifiedTimeFirst,
verifiedTimeLast,
expiredTimeLast,
failureTimeLast,
NULL,
userId,
deletionTime
FROM OldDevices""");
conn.exec("""
INSERT INTO Attestations (
id,
fingerprint,
time,
strong,
osVersion,
osPatchLevel,
vendorPatchLevel,
bootPatchLevel,
verifiedBootHash,
appVersion,
userProfileSecure,
enrolledBiometrics,
accessibility,
deviceAdmin,
adbEnabled,
addUsersWhenLocked,
oemUnlockAllowed,
systemUser
) SELECT
id,
fingerprint,
time,
strong,
osVersion,
osPatchLevel,
vendorPatchLevel,
bootPatchLevel,
verifiedBootHash,
appVersion,
userProfileSecure,
enrolledBiometrics,
accessibility,
deviceAdmin,
adbEnabled,
addUsersWhenLocked,
oemUnlockAllowed,
systemUser
FROM OldAttestations""");
conn.exec("DROP TABLE OldDevices");
conn.exec("DROP TABLE OldAttestations");
conn.exec(CREATE_ATTESTATION_INDICES);
conn.exec("PRAGMA user_version = " + targetUserVersion);
conn.exec("COMMIT TRANSACTION");
userVersion = targetUserVersion;
conn.exec("PRAGMA foreign_keys = ON");
logger.info("Migrated to schema version: " + userVersion);
}
logger.info("Finished database setup for " + ATTESTATION_DATABASE);
} finally {
conn.dispose();
}
}
public static void main(final String[] args) {
Thread.currentThread().setName("Main");
Logger.getLogger("com.almworks.sqlite4java").setLevel(Level.OFF);
Logger.getLogger("app.attestation").setUseParentHandlers(false);
final ConsoleHandler handler = new ConsoleHandler();
handler.setFormatter(new JournaldFormatter());
Logger.getLogger("app.attestation").addHandler(handler);
try {
setupSamplesDatabase();
setupAttestationDatabase();
} catch (final DataFormatException | GeneralSecurityException | IOException | SQLiteException e) {
logger.log(ALERT, "failed to setup databases", e);
System.exit(1);
}
final ThreadPoolExecutor executor = new ThreadPoolExecutor(32, 32, 0, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(1024),
new ThreadFactoryBuilder().setNameFormat("HTTP %d").build());
System.setProperty("sun.net.httpserver.nodelay", "true");
try {
final HttpServer server = HttpServer.create(new InetSocketAddress("::1", 8080), 4096);
server.createContext("/api/status", new StatusHandler());
server.createContext("/api/create-account", new CreateAccountHandler());
server.createContext("/api/change-password", new ChangePasswordHandler());
server.createContext("/api/login", new LoginHandler());
server.createContext("/api/logout", new LogoutHandler());
server.createContext("/api/logout-everywhere", new LogoutEverywhereHandler());
server.createContext("/api/rotate", new RotateHandler());
server.createContext("/api/account", new AccountHandler());
server.createContext("/api/account.png", new AccountQrHandler());
server.createContext("/api/configuration", new ConfigurationHandler());
server.createContext("/api/delete-device", new DeleteDeviceHandler());
server.createContext("/api/devices.json", new DevicesHandler());
server.createContext("/api/attestation-history.json", new AttestationHistoryHandler());
server.createContext("/auditor/challenge", new ChallengeHandler());
server.createContext("/auditor/verify", new VerifyHandler());
server.createContext("/auditor/submit", new SubmitHandler());
server.createContext("/challenge", new ChallengeHandler());
server.createContext("/verify", new VerifyHandler());
server.createContext("/submit", new SubmitHandler());
server.setExecutor(executor);
server.start();
} catch (final IOException e) {
logger.log(ALERT, "failed to start HTTP server", e);
System.exit(1);
}
try {
Thread.sleep(POST_START_DELAY_MS);
} catch (final InterruptedException e) {
return;
}
executor.prestartAllCoreThreads();
new Thread(new AlertDispatcher(), "AlertDispatcher").start();
new Thread(new Maintenance(), "Maintenance").start();
}
private static String getRequestHeaderValue(final HttpExchange exchange, final String header)
throws GeneralSecurityException {
final List<String> values = exchange.getRequestHeaders().get(header);
if (values == null) {
return null;
}
if (values.size() > 1) {
throw new GeneralSecurityException("multiple values for '" + header + "' header");
}
return values.get(0);
}
private abstract static class PostHandler implements HttpHandler {
protected abstract void handlePost(final HttpExchange exchange) throws IOException, SQLiteException;
public void checkRequestHeaders(final HttpExchange exchange) throws GeneralSecurityException {
if (!ORIGIN.equals(getRequestHeaderValue(exchange, "Origin"))) {
throw new GeneralSecurityException("missing or invalid Origin header");
}
if (!"application/json".equals(getRequestHeaderValue(exchange, "Content-Type"))) {
throw new GeneralSecurityException("missing or invalid Content-Type header");
}
if (!"same-origin".equals(getRequestHeaderValue(exchange, "Sec-Fetch-Mode"))) {
throw new GeneralSecurityException("missing or invalid Sec-Fetch-Mode header");
}
if (!"same-origin".equals(getRequestHeaderValue(exchange, "Sec-Fetch-Site"))) {
throw new GeneralSecurityException("missing or invalid Sec-Fetch-Site header");
}
if (!"empty".equals(getRequestHeaderValue(exchange, "Sec-Fetch-Dest"))) {
throw new GeneralSecurityException("missing or invalid Sec-Fetch-Dest header");
}
}
@Override
public final void handle(final HttpExchange exchange) throws IOException {
try {
if (!exchange.getRequestMethod().equals("POST")) {
exchange.getResponseHeaders().set("Allow", "POST");
exchange.sendResponseHeaders(405, -1);
return;
}
try {
checkRequestHeaders(exchange);
} catch (final GeneralSecurityException e) {
logger.info(e.getMessage());
exchange.sendResponseHeaders(403, -1);
return;
}
handlePost(exchange);
} catch (final IOException e) {
if ("Broken pipe".equals(e.getMessage())) {
logger.info("client abort");
} else {
logger.log(Level.SEVERE, "unhandled error handling request", e);
}
exchange.sendResponseHeaders(500, -1);
} catch (final Exception e) {
logger.log(Level.SEVERE, "unhandled error handling request", e);
exchange.sendResponseHeaders(500, -1);
} finally {
exchange.close();
}
}
}
private abstract static class AppPostHandler extends PostHandler {
@Override
public void checkRequestHeaders(final HttpExchange exchange) throws GeneralSecurityException {
if (getRequestHeaderValue(exchange, "Origin") != null) {
throw new GeneralSecurityException("expected no Origin header");
}
}
}
private static class StatusHandler extends AppPostHandler {
@Override
public final void handlePost(final HttpExchange exchange) throws IOException {
final JsonObjectBuilder status = Json.createObjectBuilder();
status.add("health", true);
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(200, 0);
try (final OutputStream output = exchange.getResponseBody();
final JsonWriter writer = Json.createWriter(output)) {
writer.write(status.build());
}
}
}
private static byte[] hash(final byte[] password, final byte[] salt) {
return SCrypt.generate(password, salt, 32768, 8, 1, 32);
}
private static class UsernameUnavailableException extends GeneralSecurityException {
public UsernameUnavailableException() {}
}
private static void validateUsername(final String username) throws GeneralSecurityException {
if (username.length() > 32 || !username.matches("[a-zA-Z0-9]+")) {
throw new GeneralSecurityException("invalid username");
}
}
private static void validateUnicode(final String s) throws CharacterCodingException {
StandardCharsets.UTF_16LE.newEncoder().encode(CharBuffer.wrap(s));
}
private static void validatePassword(final String password) throws GeneralSecurityException {
if (password.length() < 8 || password.length() > 256) {
throw new GeneralSecurityException("invalid password length");
}
try {
validateUnicode(password);
} catch (final CharacterCodingException e) {
throw new GeneralSecurityException("invalid Unicode for password", e);
}
}
private static void createAccount(final String username, final String password)
throws GeneralSecurityException, SQLiteException {
validateUsername(username);
validatePassword(password);
final byte[] passwordSalt = AttestationProtocol.generateRandomToken();
final byte[] passwordHash = hash(password.getBytes(), passwordSalt);
final byte[] subscribeKey = AttestationProtocol.generateRandomToken();
final SQLiteConnection conn = getLocalAttestationConn();
try {
final SQLiteStatement insert = conn.prepare("""
INSERT INTO Accounts (
username,
passwordHash,
passwordSalt,
subscribeKey,
creationTime,
loginTime,
verifyInterval,
alertDelay
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)""");
try {
insert.bind(1, username);
insert.bind(2, passwordHash);
insert.bind(3, passwordSalt);
insert.bind(4, subscribeKey);
final long now = System.currentTimeMillis();
insert.bind(5, now);
insert.bind(6, now);
insert.bind(7, DEFAULT_VERIFY_INTERVAL);
insert.bind(8, DEFAULT_ALERT_DELAY);
insert.step();
logger.info("created account " + conn.getLastInsertId() + " with username '" + username + "'");
} finally {
insert.dispose();
}
} catch (final SQLiteException e) {
if (e.getErrorCode() == SQLITE_CONSTRAINT_UNIQUE) {
throw new UsernameUnavailableException();
}
throw e;
}
}
private static void changePassword(final long userId, final String currentPassword, final String newPassword)
throws GeneralSecurityException, SQLiteException {
validatePassword(currentPassword);
validatePassword(newPassword);
final SQLiteConnection conn = getLocalAttestationConn();
try {
conn.exec("BEGIN IMMEDIATE TRANSACTION");
final SQLiteStatement select = conn.prepare(
"SELECT passwordHash, passwordSalt FROM Accounts WHERE userId = ?");
final byte[] currentPasswordHash;
final byte[] currentPasswordSalt;
try {
select.bind(1, userId);
select.step();
currentPasswordHash = select.columnBlob(0);
currentPasswordSalt = select.columnBlob(1);
} finally {
select.dispose();
}
if (!MessageDigest.isEqual(hash(currentPassword.getBytes(), currentPasswordSalt), currentPasswordHash)) {
throw new GeneralSecurityException("incorrect password for account " + userId);
}
final byte[] newPasswordSalt = AttestationProtocol.generateRandomToken();
final byte[] newPasswordHash = hash(newPassword.getBytes(), newPasswordSalt);
final SQLiteStatement update = conn.prepare(
"UPDATE Accounts SET passwordHash = ?, passwordSalt = ? WHERE userId = ?");
try {
update.bind(1, newPasswordHash);
update.bind(2, newPasswordSalt);
update.bind(3, userId);
update.step();
} finally {
update.dispose();
}
conn.exec("COMMIT TRANSACTION");
logger.info("changed password for account " + userId);
} finally {
rollbackIfNeeded(conn);
}
}
private record Session(long sessionId, byte[] token) {}
private static Session login(final String username, final String password)
throws GeneralSecurityException, SQLiteException {
validatePassword(password);
final SQLiteConnection conn = getLocalAttestationConn();
try {
conn.exec("BEGIN IMMEDIATE TRANSACTION");
final SQLiteStatement select = conn.prepare(
"SELECT userId, passwordHash, passwordSalt FROM Accounts WHERE username = ?");
final long userId;
final byte[] passwordHash;
final byte[] passwordSalt;
try {
select.bind(1, username);
if (!select.step()) {
throw new UsernameUnavailableException();
}
userId = select.columnLong(0);
passwordHash = select.columnBlob(1);
passwordSalt = select.columnBlob(2);
} finally {
select.dispose();
}
if (!MessageDigest.isEqual(hash(password.getBytes(), passwordSalt), passwordHash)) {
throw new GeneralSecurityException("incorrect password for account " + userId);
}
final long now = System.currentTimeMillis();
final SQLiteStatement deleteExpiredSessions = conn.prepare(
"DELETE FROM Sessions WHERE expiryTime < ?");
try {
deleteExpiredSessions.bind(1, now);
deleteExpiredSessions.step();
} finally {
deleteExpiredSessions.dispose();
}
final byte[] token = AttestationProtocol.generateRandomToken();
final SQLiteStatement insert = conn.prepare(
"INSERT INTO Sessions (userId, token, expiryTime) VALUES (?, ?, ?)");
try {
insert.bind(1, userId);
insert.bind(2, token);
insert.bind(3, now + SESSION_LENGTH);
insert.step();
} finally {
insert.dispose();
}
final SQLiteStatement updateLoginTime = conn.prepare(
"UPDATE Accounts SET loginTime = ? WHERE userId = ?");
try {
updateLoginTime.bind(1, now);
updateLoginTime.bind(2, userId);
updateLoginTime.step();
} finally {
updateLoginTime.dispose();
}
conn.exec("COMMIT TRANSACTION");
logger.info("login for account " + userId);
return new Session(conn.getLastInsertId(), token);
} finally {
rollbackIfNeeded(conn);
}
}
private static class CreateAccountHandler extends PostHandler {
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
final String username;
final String password;
try (final JsonReader reader = Json.createReader(exchange.getRequestBody())) {
final JsonObject object = reader.readObject();
username = object.getString("username");
password = object.getString("password");
} catch (final ClassCastException | JsonException | NullPointerException e) {
logger.log(Level.WARNING, "invalid request", e);
exchange.sendResponseHeaders(400, -1);
return;
}
try {
createAccount(username, password);
} catch (final UsernameUnavailableException e) {
exchange.sendResponseHeaders(409, -1);
return;
} catch (final GeneralSecurityException e) {
logger.log(Level.WARNING, "invalid request", e);
exchange.sendResponseHeaders(400, -1);
return;
}
exchange.sendResponseHeaders(200, -1);
}
}
private static class ChangePasswordHandler extends PostHandler {
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
final String currentPassword;
final String newPassword;
try (final JsonReader reader = Json.createReader(exchange.getRequestBody())) {
final JsonObject object = reader.readObject();
currentPassword = object.getString("currentPassword");
newPassword = object.getString("newPassword");
} catch (final ClassCastException | JsonException | NullPointerException e) {
logger.log(Level.WARNING, "invalid request", e);
exchange.sendResponseHeaders(400, -1);
return;
}
final Account account = verifySession(exchange, false);
if (account == null) {
return;
}
try {
changePassword(account.userId, currentPassword, newPassword);
} catch (final GeneralSecurityException e) {
logger.log(Level.WARNING, "invalid request", e);
exchange.sendResponseHeaders(400, -1);
return;
}
exchange.sendResponseHeaders(200, -1);
}
}
private static class LoginHandler extends PostHandler {
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
final String username;
final String password;
try (final JsonReader reader = Json.createReader(exchange.getRequestBody())) {
final JsonObject object = reader.readObject();
username = object.getString("username");
password = object.getString("password");
} catch (final ClassCastException | JsonException | NullPointerException e) {
logger.log(Level.WARNING, "invalid request", e);
exchange.sendResponseHeaders(400, -1);
return;