-
-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathAttestationServer.java
More file actions
1400 lines (1263 loc) · 61.1 KB
/
AttestationServer.java
File metadata and controls
1400 lines (1263 loc) · 61.1 KB
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.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.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 com.almworks.sqlite4java.SQLiteConstants.SQLITE_CONSTRAINT_UNIQUE;
public 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 = 4 * 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 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 void createAttestationTables(final SQLiteConnection conn) throws SQLiteException {
conn.exec(
"CREATE TABLE IF NOT EXISTS Configuration (\n" +
"key TEXT PRIMARY KEY NOT NULL,\n" +
"value ANY NOT NULL\n" +
") STRICT");
conn.exec(
"CREATE TABLE IF NOT EXISTS Accounts (\n" +
"userId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" +
"username TEXT NOT NULL COLLATE NOCASE UNIQUE,\n" +
"passwordHash BLOB NOT NULL,\n" +
"passwordSalt BLOB NOT NULL,\n" +
"subscribeKey BLOB NOT NULL,\n" +
"creationTime INTEGER NOT NULL,\n" +
"loginTime INTEGER NOT NULL,\n" +
"verifyInterval INTEGER NOT NULL,\n" +
"alertDelay INTEGER NOT NULL\n" +
") STRICT");
conn.exec(
"CREATE TABLE IF NOT EXISTS EmailAddresses (\n" +
"userId INTEGER NOT NULL REFERENCES Accounts (userId) ON DELETE CASCADE,\n" +
"address TEXT NOT NULL,\n" +
"PRIMARY KEY (userId, address)\n" +
") STRICT");
conn.exec(
"CREATE TABLE IF NOT EXISTS Sessions (\n" +
"sessionId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" +
"userId INTEGER NOT NULL REFERENCES Accounts (userId) ON DELETE CASCADE,\n" +
"token BLOB NOT NULL,\n" +
"expiryTime INTEGER NOT NULL\n" +
") STRICT");
conn.exec(
"CREATE TABLE IF NOT EXISTS Devices (\n" +
"fingerprint BLOB NOT NULL PRIMARY KEY,\n" +
"pinnedCertificates BLOB NOT NULL,\n" +
"attestKey INTEGER NOT NULL CHECK (attestKey in (0, 1)),\n" +
"pinnedVerifiedBootKey BLOB NOT NULL,\n" +
"verifiedBootHash BLOB,\n" +
"pinnedOsVersion INTEGER NOT NULL,\n" +
"pinnedOsPatchLevel INTEGER NOT NULL,\n" +
"pinnedVendorPatchLevel INTEGER,\n" +
"pinnedBootPatchLevel INTEGER,\n" +
"pinnedAppVersion INTEGER NOT NULL,\n" +
"pinnedAppVariant INTEGER NOT NULL CHECK (pinnedAppVariant in (0, 1, 2)),\n" +
"pinnedSecurityLevel INTEGER NOT NULL,\n" +
"userProfileSecure INTEGER NOT NULL CHECK (userProfileSecure in (0, 1)),\n" +
"enrolledBiometrics INTEGER NOT NULL CHECK (enrolledBiometrics in (0, 1)),\n" +
"accessibility INTEGER NOT NULL CHECK (accessibility in (0, 1)),\n" +
"deviceAdmin INTEGER NOT NULL CHECK (deviceAdmin in (0, 1, 2)),\n" +
"adbEnabled INTEGER NOT NULL CHECK (adbEnabled in (0, 1)),\n" +
"addUsersWhenLocked INTEGER NOT NULL CHECK (addUsersWhenLocked in (0, 1)),\n" +
"denyNewUsb INTEGER NOT NULL CHECK (denyNewUsb in (0, 1)),\n" +
"oemUnlockAllowed INTEGER NOT NULL CHECK (oemUnlockAllowed in (0, 1)),\n" +
"systemUser INTEGER NOT NULL CHECK (systemUser in (0, 1)),\n" +
"verifiedTimeFirst INTEGER NOT NULL,\n" +
"verifiedTimeLast INTEGER NOT NULL,\n" +
"expiredTimeLast INTEGER,\n" +
"failureTimeLast INTEGER,\n" +
"userId INTEGER NOT NULL REFERENCES Accounts (userId) ON DELETE CASCADE,\n" +
"deletionTime INTEGER\n" +
") STRICT");
conn.exec(
"CREATE TABLE IF NOT EXISTS Attestations (\n" +
"id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" +
"fingerprint BLOB NOT NULL REFERENCES Devices (fingerprint) ON DELETE CASCADE,\n" +
"time INTEGER NOT NULL,\n" +
"strong INTEGER NOT NULL CHECK (strong in (0, 1)),\n" +
"osVersion INTEGER NOT NULL,\n" +
"osPatchLevel INTEGER NOT NULL,\n" +
"vendorPatchLevel INTEGER,\n" +
"bootPatchLevel INTEGER,\n" +
"verifiedBootHash BLOB,\n" +
"appVersion INTEGER NOT NULL,\n" +
"userProfileSecure INTEGER NOT NULL CHECK (userProfileSecure in (0, 1)),\n" +
"enrolledBiometrics INTEGER NOT NULL CHECK (enrolledBiometrics in (0, 1)),\n" +
"accessibility INTEGER NOT NULL CHECK (accessibility in (0, 1)),\n" +
"deviceAdmin INTEGER NOT NULL CHECK (deviceAdmin in (0, 1, 2)),\n" +
"adbEnabled INTEGER NOT NULL CHECK (adbEnabled in (0, 1)),\n" +
"addUsersWhenLocked INTEGER NOT NULL CHECK (addUsersWhenLocked in (0, 1)),\n" +
"denyNewUsb INTEGER NOT NULL CHECK (denyNewUsb in (0, 1)),\n" +
"oemUnlockAllowed INTEGER NOT NULL CHECK (oemUnlockAllowed in (0, 1)),\n" +
"systemUser INTEGER NOT NULL CHECK (systemUser in (0, 1))\n" +
") STRICT");
}
private static void createAttestationIndices(final SQLiteConnection conn) throws SQLiteException {
conn.exec("CREATE INDEX IF NOT EXISTS Accounts_loginTime " +
"ON Accounts (loginTime)");
conn.exec("CREATE INDEX IF NOT EXISTS Sessions_expiryTime " +
"ON Sessions (expiryTime)");
conn.exec("CREATE INDEX IF NOT EXISTS Sessions_userId " +
"ON Sessions (userId)");
conn.exec("CREATE INDEX IF NOT EXISTS Devices_userId_verifiedTimeFirst " +
"ON Devices (userId, verifiedTimeFirst)");
conn.exec("CREATE INDEX IF NOT EXISTS Devices_userId_verifiedTimeLast_deletionTimeNull " +
"ON Devices (userId, verifiedTimeLast) WHERE deletionTime IS NULL");
conn.exec("CREATE INDEX IF NOT EXISTS Devices_deletionTime " +
"ON Devices (deletionTime) WHERE deletionTime IS NOT NULL");
conn.exec("CREATE INDEX IF NOT EXISTS Devices_verifiedTimeLast_deletionTimeNull " +
"ON Devices (verifiedTimeLast) WHERE deletionTime IS NULL");
conn.exec("CREATE INDEX IF NOT EXISTS Attestations_fingerprint_id " +
"ON Attestations (fingerprint, id)");
}
private static void createSamplesTable(final SQLiteConnection conn) throws SQLiteException {
conn.exec(
"CREATE TABLE IF NOT EXISTS Samples (\n" +
"sample BLOB NOT NULL,\n" +
"time INTEGER NOT NULL\n" +
") STRICT");
}
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();
}
}
public static void main(final String[] args) throws Exception {
final SQLiteConnection samplesConn = open(SAMPLES_DATABASE);
try {
final SQLiteStatement selectCreated = samplesConn.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Samples'");
if (!selectCreated.step()) {
samplesConn.exec("PRAGMA user_version = 1");
}
selectCreated.dispose();
int userVersion = getUserVersion(samplesConn);
createSamplesTable(samplesConn);
if (userVersion < 1) {
throw new RuntimeException(SAMPLES_DATABASE + " database schemas older than version 1 are no longer " +
"supported. Use an older AttestationServer revision to upgrade.");
}
logger.info("Finished database setup for " + SAMPLES_DATABASE);
} finally {
samplesConn.dispose();
}
final SQLiteConnection attestationConn = open(ATTESTATION_DATABASE);
try {
final SQLiteStatement selectCreated = attestationConn.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Configuration'");
if (!selectCreated.step()) {
attestationConn.exec("PRAGMA user_version = 11");
}
selectCreated.dispose();
int userVersion = getUserVersion(attestationConn);
createAttestationTables(attestationConn);
createAttestationIndices(attestationConn);
if (userVersion < 11) {
throw new RuntimeException(ATTESTATION_DATABASE + " database schemas older than version 10 are no longer " +
"supported. Use an older AttestationServer revision to upgrade.");
}
logger.info("Finished database setup for " + ATTESTATION_DATABASE);
} finally {
attestationConn.dispose();
}
new Thread(new AlertDispatcher()).start();
new Thread(new Maintenance()).start();
final ThreadPoolExecutor executor = new ThreadPoolExecutor(32, 32, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(1024));
executor.prestartAllCoreThreads();
System.setProperty("sun.net.httpserver.nodelay", "true");
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("/challenge", new ChallengeHandler());
server.createContext("/verify", new VerifyHandler());
server.createContext("/submit", new SubmitHandler());
server.setExecutor(executor);
server.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();
}
if (!"application/json".equals(getRequestHeaderValue(exchange, "Content-Type"))) {
throw new GeneralSecurityException();
}
if (!"same-origin".equals(getRequestHeaderValue(exchange, "Sec-Fetch-Mode"))) {
throw new GeneralSecurityException();
}
if (!"same-origin".equals(getRequestHeaderValue(exchange, "Sec-Fetch-Site"))) {
throw new GeneralSecurityException();
}
if (!"empty".equals(getRequestHeaderValue(exchange, "Sec-Fetch-Dest"))) {
throw new GeneralSecurityException();
}
}
@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.log(Level.INFO, "invalid request headers", e);
exchange.sendResponseHeaders(403, -1);
return;
}
handlePost(exchange);
} 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();
}
}
}
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 final SecureRandom random = new SecureRandom();
private static byte[] generateRandomToken() {
final byte[] token = new byte[32];
random.nextBytes(token);
return token;
}
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");
}
try {
validateUnicode(password);
} catch (final CharacterCodingException e) {
throw new GeneralSecurityException(e);
}
}
private static void createAccount(final String username, final String password)
throws GeneralSecurityException, SQLiteException {
validateUsername(username);
validatePassword(password);
final byte[] passwordSalt = generateRandomToken();
final byte[] passwordHash = hash(password.getBytes(), passwordSalt);
final byte[] subscribeKey = 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("invalid password");
}
final byte[] newPasswordSalt = 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 static class Session {
final long sessionId;
final byte[] token;
Session(final long sessionId, final byte[] token) {
this.sessionId = sessionId;
this.token = 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("invalid password");
}
final long now = System.currentTimeMillis();
final SQLiteStatement delete = conn.prepare("DELETE FROM Sessions WHERE expiryTime < ?");
try {
delete.bind(1, now);
delete.step();
} finally {
delete.dispose();
}
final byte[] token = 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.INFO, "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.INFO, "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.INFO, "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.INFO, "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.INFO, "invalid request", e);
exchange.sendResponseHeaders(400, -1);
return;
}
final Session session;
try {
session = login(username, password);
} catch (final UsernameUnavailableException e) {
exchange.sendResponseHeaders(400, -1);
return;
} catch (final GeneralSecurityException e) {
logger.log(Level.INFO, "invalid login information", e);
exchange.sendResponseHeaders(403, -1);
return;
}
final Base64.Encoder encoder = Base64.getEncoder();
exchange.getResponseHeaders().set("Set-Cookie",
String.format("__Host-session=%d|%s; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=%d",
session.sessionId, new String(encoder.encode(session.token)),
SESSION_LENGTH / 1000));
exchange.sendResponseHeaders(200, -1);
}
}
private static class LogoutHandler extends PostHandler {
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
final Account account = verifySession(exchange, true);
if (account == null) {
return;
}
purgeSessionCookie(exchange);
exchange.sendResponseHeaders(200, -1);
}
}
private static class LogoutEverywhereHandler extends PostHandler {
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
final Account account = verifySession(exchange, false);
if (account == null) {
return;
}
final SQLiteConnection conn = getLocalAttestationConn();
final SQLiteStatement select = conn.prepare("DELETE FROM Sessions WHERE userId = ?");
try {
select.bind(1, account.userId);
select.step();
} finally {
select.dispose();
}
purgeSessionCookie(exchange);
exchange.sendResponseHeaders(200, -1);
}
}
private static class RotateHandler extends PostHandler {
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
final Account account = verifySession(exchange, false);
if (account == null) {
return;
}
final SQLiteConnection conn = getLocalAttestationConn();
final byte[] subscribeKey = generateRandomToken();
final SQLiteStatement select = conn.prepare("UPDATE Accounts SET " +
"subscribeKey = ? WHERE userId = ?");
try {
select.bind(1, subscribeKey);
select.bind(2, account.userId);
select.step();
logger.info("rotated subscribe key for account " + account.userId);
} finally {
select.dispose();
}
exchange.sendResponseHeaders(200, -1);
}
}
private static String getCookie(final HttpExchange exchange, final String key) {
final List<String> cookieHeaders = exchange.getRequestHeaders().get("Cookie");
if (cookieHeaders == null) {
return null;
}
for (final String cookieHeader : cookieHeaders) {
final String[] cookies = cookieHeader.split(";");
for (final String cookie : cookies) {
final String[] keyValue = cookie.trim().split("=", 2);
if (keyValue.length == 2) {
if (keyValue[0].equals(key)) {
return keyValue[1];
}
}
}
}
return null;
}
private static void purgeSessionCookie(final HttpExchange exchange) {
exchange.getResponseHeaders().set("Set-Cookie",
"__Host-session=; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=0");
}
private static class Account {
final long userId;
final String username;
final byte[] subscribeKey;
final int verifyInterval;
final int alertDelay;
Account(final long userId, final String username, final byte[] subscribeKey,
final int verifyInterval, final int alertDelay) {
this.userId = userId;
this.username = username;
this.subscribeKey = subscribeKey;
this.verifyInterval = verifyInterval;
this.alertDelay = alertDelay;
}
}
private static Account verifySession(final HttpExchange exchange, final boolean end)
throws IOException, SQLiteException {
final String cookie = getCookie(exchange, "__Host-session");
if (cookie == null) {
exchange.sendResponseHeaders(403, -1);
return null;
}
final String[] session = cookie.split("\\|", 2);
if (session.length != 2) {
purgeSessionCookie(exchange);
exchange.sendResponseHeaders(403, -1);
return null;
}
final long sessionId = Long.parseLong(session[0]);
final byte[] token = Base64.getDecoder().decode(session[1]);
final SQLiteConnection conn = getLocalAttestationConn();
final SQLiteStatement select = conn.prepare("SELECT token, expiryTime, " +
"username, subscribeKey, Accounts.userId, verifyInterval, alertDelay " +
"FROM Sessions " +
"INNER JOIN Accounts on Accounts.userId = Sessions.userId " +
"WHERE sessionId = ?");
try {
select.bind(1, sessionId);
if (!select.step() || !MessageDigest.isEqual(token, select.columnBlob(0))) {
purgeSessionCookie(exchange);
exchange.sendResponseHeaders(403, -1);
return null;
}
if (select.columnLong(1) < System.currentTimeMillis()) {
purgeSessionCookie(exchange);
exchange.sendResponseHeaders(403, -1);
return null;
}
if (end) {
final SQLiteStatement delete = conn.prepare("DELETE FROM Sessions " +
"WHERE sessionId = ?");
try {
delete.bind(1, sessionId);
delete.step();
} finally {
delete.dispose();
}
}
return new Account(select.columnLong(4), select.columnString(2), select.columnBlob(3),
select.columnInt(5), select.columnInt(6));
} finally {
select.dispose();
}
}
private static class AccountHandler extends PostHandler {
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
final Account account = verifySession(exchange, false);
if (account == null) {
return;
}
final JsonObjectBuilder accountJson = Json.createObjectBuilder();
accountJson.add("username", account.username);
accountJson.add("verifyInterval", account.verifyInterval);
accountJson.add("alertDelay", account.alertDelay);
final SQLiteConnection conn = getLocalAttestationConn();
final SQLiteStatement select = conn.prepare("SELECT address FROM EmailAddresses " +
"WHERE userId = ?");
try {
select.bind(1, account.userId);
if (select.step()) {
accountJson.add("email", select.columnString(0));
}
} finally {
select.dispose();
}
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(accountJson.build());
}
}
}
private static void writeQrCode(final byte[] contents, final OutputStream output) throws IOException {
try {
final QRCodeWriter writer = new QRCodeWriter();
final Map<EncodeHintType,Object> hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.ISO_8859_1);
final BitMatrix result = writer.encode(new String(contents, StandardCharsets.ISO_8859_1),
BarcodeFormat.QR_CODE, QR_CODE_PIXEL_SIZE, QR_CODE_PIXEL_SIZE, hints);
MatrixToImageWriter.writeToStream(result, "png", output);
} catch (WriterException e) {
throw new RuntimeException(e);
}
}
private static class AccountQrHandler extends PostHandler {
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
final Account account = verifySession(exchange, false);
if (account == null) {
return;
}
exchange.getResponseHeaders().set("Content-Type", "image/png");
exchange.sendResponseHeaders(200, 0);
try (final OutputStream output = exchange.getResponseBody()) {
final String contents = DOMAIN + " " +
account.userId + " " +
BaseEncoding.base64().encode(account.subscribeKey) + " " +
account.verifyInterval;
writeQrCode(contents.getBytes(), output);
}
}
}
private static class ConfigurationHandler extends PostHandler {
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
final int verifyInterval;
final int alertDelay;
final String email;
try (final JsonReader reader = Json.createReader(exchange.getRequestBody())) {
final JsonObject object = reader.readObject();
verifyInterval = object.getInt("verifyInterval");
alertDelay = object.getInt("alertDelay");
email = object.getString("email").trim();
} catch (final ClassCastException | JsonException | NullPointerException e) {
logger.log(Level.INFO, "invalid request", e);
exchange.sendResponseHeaders(400, -1);
return;
}
final Account account = verifySession(exchange, false);
if (account == null) {
return;
}
if (verifyInterval < MIN_VERIFY_INTERVAL || verifyInterval > MAX_VERIFY_INTERVAL) {
exchange.sendResponseHeaders(400, -1);
return;
}
if (alertDelay < MIN_ALERT_DELAY || alertDelay > MAX_ALERT_DELAY || alertDelay <= verifyInterval) {
exchange.sendResponseHeaders(400, -1);
return;
}
if (!email.isEmpty()) {
try {
new InternetAddress(email).validate();
for (final String emailBlacklistPattern : emailBlacklistPatterns) {
if (email.matches(emailBlacklistPattern)) {
exchange.sendResponseHeaders(400, -1);
return;
}
}
} catch (final AddressException e) {
exchange.sendResponseHeaders(400, -1);
return;
}
}
final SQLiteConnection conn = getLocalAttestationConn();
try {
conn.exec("BEGIN IMMEDIATE TRANSACTION");
final SQLiteStatement update = conn.prepare("UPDATE Accounts SET " +
"verifyInterval = ?, alertDelay = ? WHERE userId = ?");
try {
update.bind(1, verifyInterval);
update.bind(2, alertDelay);
update.bind(3, account.userId);
update.step();
} finally {
update.dispose();
}
final SQLiteStatement delete = conn.prepare("DELETE FROM EmailAddresses " +
"WHERE userId = ?");
try {
delete.bind(1, account.userId);