Repository navigation
Expand file tree
/
Copy pathSetter.java
More file actions
1507 lines (1304 loc) · 54.1 KB
/
Copy pathSetter.java
File metadata and controls
1507 lines (1304 loc) · 54.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 dbProcs;
import de.mkammerer.argon2.Argon2;
import de.mkammerer.argon2.Argon2Factory;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import utils.CountdownHandler;
import utils.InvalidCountdownStateException;
/**
* Used to add information to the Database <br>
* <br>
* This file is part of the Security Shepherd Project.
*
* <p>The Security Shepherd project is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.<br>
*
* <p>The Security Shepherd project is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.<br>
*
* <p>You should have received a copy of the GNU General Public License along with the Security
* Shepherd project. If not, see <http://www.gnu.org/licenses/>.
*
* @author Mark
*/
public class Setter {
private static final Logger log = LogManager.getLogger(Setter.class);
// TODO - Replace this with a new mobile/web/etc attribute in the modules table
public static final String webModuleCategoryHardcodedWhereClause =
new String(
"moduleCategory = 'CSRF'"
+ " OR moduleCategory = 'Failure to Restrict URL Access'"
+ " OR moduleCategory = 'Injection'"
+ " OR moduleCategory = 'Insecure Cryptographic Storage'"
+ " OR moduleCategory = 'Insecure Direct Object References'"
+ " OR moduleCategory = 'Poor Data Validation'"
+ " OR moduleCategory = 'Security Misconfigurations'"
+ " OR moduleCategory = 'Session Management'"
+ " OR moduleCategory = 'Unvalidated Redirects and Forwards'"
+ " OR moduleCategory = 'XSS'");
public static final String mobileModuleCategoryHardcodedWhereClause =
new String(
""
+ "moduleCategory = 'Mobile Broken Crypto'"
+ " OR moduleCategory = 'Mobile Content Provider'"
+ " OR moduleCategory = 'Mobile Data Leakage'"
+ " OR moduleCategory = 'Mobile Injection'"
+ " OR moduleCategory = 'Mobile Insecure Data Storage'"
+ " OR moduleCategory = 'Mobile Poor Authentication'"
+ " OR moduleCategory = 'Mobile Reverse Engineering'"
+ " OR moduleCategory = 'Mobile Security Decisions via Untrusted Input'");
/**
* Database procedure just adds this. So this method just prepares the statement
*
* @param ApplicationRoot
* @param className Class name
* @param classYear Year of the class in YY/YY. eg 11/12
* @return
*/
public static boolean classCreate(String ApplicationRoot, String className, String classYear) {
log.debug("*** Setter.classCreate ***");
boolean result = false;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmnt = conn.prepareCall("call classCreate(?, ?)")) {
log.debug("Preparing classCreate call");
callstmnt.setString(1, className);
callstmnt.setString(2, classYear);
log.debug("Executing classCreate");
callstmnt.execute();
result = true;
} catch (SQLException e) {
log.error("classCreate Failure: " + e.toString());
}
log.debug("*** END classCreate ***");
return result;
}
/**
* This method sets every module status to Closed.
*
* @param ApplicationRoot Current running director of the application
* @return Boolean result depicting success of statement
*/
public static boolean closeAllModules(String ApplicationRoot) {
log.debug("*** Setter.closeAllModules ***");
boolean result = false;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
PreparedStatement callstmt =
conn.prepareStatement("UPDATE modules SET moduleStatus = 'closed'")) {
callstmt.execute();
log.debug("All modules Set to closed");
result = true;
} catch (SQLException e) {
log.error("Could not close all modules: " + e.toString());
}
log.debug("*** END closeAllModules ***");
return result;
}
/**
* Used to increment bad submission counter in DB. DB will handle point deductions once the
* counter hits 40
*
* @param ApplicationRoot application running context
* @param userId user identifier to increment
* @return False if the statement fails to execute
*/
public static boolean incrementBadSubmission(String ApplicationRoot, String userId) {
log.debug("*** Setter.incrementBadSubmission ***");
boolean result = false;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
PreparedStatement callstmnt = conn.prepareCall("CALL userBadSubmission(?)")) {
log.debug("Prepairing bad Submission call");
callstmnt.setString(1, userId);
log.debug("Executing userBadSubmission statement on id '" + userId + "'");
callstmnt.execute();
result = true;
} catch (SQLException e) {
log.error("userBadSubmission Failure: " + e.toString());
result = false;
}
log.debug("*** END userBadSubmisison ***");
return result;
}
/**
* This method sets every module status to Open.
*
* @param ApplicationRoot Current running director of the application
* @param unsafe set whether to open all safe modules or all modules that are unsafe
* @return Boolean result depicting success of statement
*/
public static boolean openAllModules(String ApplicationRoot, boolean unsafe) {
log.debug("*** Setter.openAllModules ***");
boolean result = false;
String updateSql =
unsafe
? "UPDATE modules SET moduleStatus = 'open' WHERE isUnsafe = 1"
: "UPDATE modules SET moduleStatus = 'open' WHERE isUnsafe = 0";
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
PreparedStatement callstmt = conn.prepareStatement(updateSql)) {
callstmt.execute();
log.debug(unsafe ? "All unsafe modules set to open" : "All safe modules set to open");
result = true;
} catch (SQLException e) {
log.error("Could not open all modules: " + e.toString());
}
log.debug("*** END setModuleStatusOpen ***");
return result;
}
/**
* This is used to only open Mobile category levels
*
* @param ApplicationRoot Used to locate database properties file
* @return
*/
public static boolean openOnlyMobileCategories(String ApplicationRoot) {
log.debug("*** Setter.openOnlyMobileCategories ***");
boolean result = false;
try (Connection conn = Database.getCoreConnection(ApplicationRoot)) {
try (PreparedStatement prepstmt =
conn.prepareStatement(
"UPDATE modules SET moduleStatus = 'closed' WHERE "
+ webModuleCategoryHardcodedWhereClause)) {
prepstmt.execute();
log.debug("Web Levels have been closed");
}
try (PreparedStatement prepstmt =
conn.prepareStatement(
"UPDATE modules SET moduleStatus = 'open' WHERE "
+ mobileModuleCategoryHardcodedWhereClause)) {
prepstmt.execute();
log.debug("Mobile Levels have been opened");
}
result = true;
} catch (SQLException e) {
log.error("Could not only open Mobile Levels: " + e.toString());
}
log.debug("*** END openOnlyMobileCategories ***");
return result;
}
/**
* This is used to only open Mobile category levels
*
* @param ApplicationRoot Used to locate database properties file
* @param unsafe Used to track if the level is deemed unsafe or safe
* @return
*/
public static boolean openOnlyWebCategories(String ApplicationRoot, int unsafe) {
log.debug("*** Setter.openOnlyWebCategories ***");
boolean result = false;
try (Connection conn = Database.getCoreConnection(ApplicationRoot)) {
PreparedStatement prepstmt =
conn.prepareStatement(
"UPDATE modules SET moduleStatus = 'open' WHERE "
+ "("
+ webModuleCategoryHardcodedWhereClause
+ ")"
+ " AND isUnsafe = "
+ unsafe);
prepstmt.execute();
log.debug("Web Levels have been opened");
prepstmt =
conn.prepareStatement(
"UPDATE modules SET moduleStatus = 'closed' WHERE "
+ mobileModuleCategoryHardcodedWhereClause);
prepstmt.execute();
log.debug("Mobile Levels have been closed");
result = true;
} catch (SQLException e) {
log.error("Could not only open Web levels: " + e.toString());
}
log.debug("*** END openOnlyWebCategories ***");
return result;
}
/**
* Resets user bad submission counter to 0
*
* @param ApplicationRoot Application's running context
* @param userId User Identifier to reset
* @return
*/
public static boolean resetBadSubmission(String ApplicationRoot, String userId) {
log.debug("*** Setter.resetBadSubmission ***");
boolean result = false;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
PreparedStatement callstmnt = conn.prepareCall("CALL resetUserBadSubmission(?)")) {
log.debug("Prepairing resetUserBadSubmission call");
callstmnt.setString(1, userId);
log.debug("Executing resetUserBadSubmission statement on id '" + userId + "'");
callstmnt.execute();
result = true;
} catch (SQLException e) {
log.error("resetUserBadSubmission Failure: " + e.toString());
result = false;
}
log.debug("*** END resetBadSubmission ***");
return result;
}
/**
* This method converts the default database properties file at
* applicationRoot/WEB-INF/site.properties
*
* @param applicationRoot The directory that the server is actually in
* @param url The Url of the core Database
* @param userName The user name of the database user
* @param password The password of the database user
* @return Boolean value depicting the success of the method
*/
public static boolean setCoreDatabaseInfo(
String applicationRoot, String url, String userName, String password) {
userName = userName.toLowerCase();
try {
// Update Database Settings
File siteProperties = new File(applicationRoot + "/WEB-INF/database.properties");
DataOutputStream writer = new DataOutputStream(new FileOutputStream(siteProperties, false));
String theProperties =
new String("databaseConnectionURL=" + url + "\nDriverType=org.mariadb.jdbc.Driver");
writer.write(theProperties.getBytes());
writer.close();
// Update Core Schema Settings
siteProperties = new File(applicationRoot + "/WEB-INF/coreDatabase.properties");
writer = new DataOutputStream(new FileOutputStream(siteProperties, false));
theProperties =
new String(
"databaseConnectionURL=core"
+ "\ndatabaseUsername="
+ userName
+ "\ndatabasePassword="
+ password);
writer.write(theProperties.getBytes());
writer.close();
return true;
} catch (IOException e) {
log.error("Could not update Core Database Info: " + e.toString());
return false;
}
}
/**
* This method is used to store a CSRF Token for a specific user in the csrfChallengeSeven DB
* Schema. May not necessarily be a new CSRF token after running
*
* @param userId User Identifier
* @param csrfToken CSRF Token to add to the csrfChallengeFour DB Schema
* @param ApplicationRoot Running context of the application
* @return Returns current CSRF token for user for CSRF Ch4
*/
public static String setCsrfChallengeFourCsrfToken(
String userId, String csrfToken, String ApplicationRoot) {
log.debug("*** setCsrfChallengeFourToken ***");
try (Connection conn = Database.getChallengeConnection(ApplicationRoot, "csrfChallengeFour")) {
boolean tokenExists = false;
log.debug("Preparing setSsrfChallengeFourToken call");
try (PreparedStatement callstmnt =
conn.prepareStatement("SELECT csrfTokenscol FROM csrfTokens WHERE userId = ?")) {
callstmnt.setString(1, userId);
log.debug("Executing setCsrfChallengeFourToken");
try (ResultSet rs = callstmnt.executeQuery()) {
if (rs.next()) {
// Need to Update CSRF token rather than Insert
log.debug("CSRF for Challenge 4 already is set");
csrfToken = rs.getString(1); // overwrite token with DB Stored Entry
tokenExists = true;
} else {
log.debug("No CSRF token Found for Challenge 4... Creating");
}
}
}
String whatToDo = new String();
if (!tokenExists) {
whatToDo =
"INSERT INTO `csrfChallengeFour`.`csrfTokens` (`csrfTokenscol`, `userId`) VALUES (?,"
+ " ?)";
}
try (PreparedStatement callstmnt = conn.prepareStatement(whatToDo)) {
callstmnt.setString(1, csrfToken);
callstmnt.setString(2, userId);
callstmnt.execute();
}
} catch (SQLException e) {
log.error("CsrfChallenge4 TokenUpdate Failure: " + e.toString());
}
return csrfToken;
}
/**
* This method is used to store a CSRF Token for a specific user in the csrfChallengeSix DB Schema
*
* @param userId User Identifier
* @param csrfToken CSRF Token to add to the csrfChallengeSix DB Schema
* @param ApplicationRoot Running context of the application
* @return
*/
public static boolean setCsrfChallengeSevenCsrfToken(
String userId, String csrfToken, String ApplicationRoot) {
log.debug("*** setCsrfChallengeSevenToken ***");
boolean result = false;
try (Connection conn =
Database.getChallengeConnection(ApplicationRoot, "csrfChallengeEnumerateTokens")) {
boolean updateToken = false;
log.debug("Preparing setCsrfChallengeSevenToken call");
try (PreparedStatement prestmnt =
conn.prepareStatement("SELECT csrfTokenscol FROM csrfTokens WHERE userId = ?")) {
prestmnt.setString(1, userId);
log.debug("Executing setCsrfChallengeSevenToken");
try (ResultSet rs = prestmnt.executeQuery()) {
if (rs.next()) {
// Need to Update CSRF token rather than Insert
log.debug("CSRF token Found for Challenge 7... Updating");
updateToken = true;
} else {
log.debug("No CSRF token Found for Challenge 7... Creating");
}
}
}
String whatToDo;
if (updateToken) {
whatToDo =
"UPDATE `csrfChallengeEnumTokens`.`csrfTokens` SET csrfTokenscol = ? WHERE userId = ?";
} else {
whatToDo =
"INSERT INTO `csrfChallengeEnumTokens`.`csrfTokens` (`csrfTokenscol`, `userId`) VALUES"
+ " (?, ?)";
}
try (PreparedStatement prestmnt = conn.prepareStatement(whatToDo)) {
prestmnt.setString(1, csrfToken);
prestmnt.setString(2, userId);
log.debug("Executing: " + whatToDo);
prestmnt.execute();
result = true;
}
} catch (SQLException e) {
log.error("csrfChallenge7EnumTokens TokenUpdate Failure: " + e.toString());
}
return result;
}
/**
* This method is used to set the status of all modules in a category to open or closed.
*
* @param ApplicationRoot Used to locate database properties file
* @param moduleCategory The module category to open or closed
* @param openOrClosed What to set the module status to. Can only be "open" or "closed"
* @return True if method executes without failure
*/
public static boolean setModuleCategoryStatusOpen(
String ApplicationRoot, String moduleCategory, String openOrClosed) {
log.debug("*** Setter.setModuleCategoryStatusOpen ***");
boolean result = false;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
PreparedStatement prepstmt =
conn.prepareStatement("UPDATE modules SET moduleStatus = ? WHERE moduleCategory = ?")) {
prepstmt.setString(1, openOrClosed);
prepstmt.setString(2, moduleCategory);
prepstmt.execute();
log.debug("Set " + moduleCategory + " to " + openOrClosed);
result = true;
} catch (SQLException e) {
log.error("Could not open/close category: " + e.toString());
}
log.debug("*** END setModuleCategoryStatusOpen ***");
return result;
}
/**
* This method sets the module status to Closed. This information is absorbed by the Tournament
* Floor Plan
*
* @param ApplicationRoot Current running director of the application
* @param moduleId The identifier of the module that is been set to closed status
* @return Boolean result depicting success of statement
*/
public static boolean setModuleStatusClosed(String ApplicationRoot, String moduleId) {
log.debug("*** Setter.setModuleStatusClosed ***");
boolean result = false;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmt = conn.prepareCall("call moduleSetStatus(?, ?)")) {
log.debug("Preparing moduleSetStatus procedure");
callstmt.setString(1, moduleId);
callstmt.setString(2, "closed");
callstmt.execute();
log.debug("Executed moduleSetStatus");
result = true;
} catch (SQLException e) {
log.error("Could not execute moduleSetStatus: " + e.toString());
}
log.debug("*** END setModuleStatusClosed ***");
return result;
}
/**
* This method sets the module status to Open. This information is absorbed by the Tournament
* Floor Plan
*
* @param ApplicationRoot Current running director of the application
* @param moduleId The identifier of the module that is been set to open status
* @return Boolean result depicting success of statement
*/
public static boolean setModuleStatusOpen(String ApplicationRoot, String moduleId) {
log.debug("*** Setter.setModuleStatusOpen ***");
boolean result = false;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmt = conn.prepareCall("call moduleSetStatus(?, ?)")) {
log.debug("Preparing moduleSetStatus procedure");
callstmt.setString(1, moduleId);
callstmt.setString(2, "open");
callstmt.execute();
log.debug("Executed moduleSetStatus");
result = true;
} catch (SQLException e) {
log.error("Could not execute moduleSetStatus: " + e.toString());
}
log.debug("*** END setModuleStatusOpen ***");
return result;
}
/**
* Used by CSRF levels to store their CSRF attack string, that will be displayed in a CSRF forum
* for the class the user is in
*
* @param ApplicationRoot The current running context of the application
* @param message The String they want to store
* @param userId The identifier of the user in which to store the attack under
* @param moduleId The module identifier of which to store the message under
* @return A boolean value reflecting the success of the function
*/
public static boolean setStoredMessage(
String ApplicationRoot, String message, String userId, String moduleId) {
log.debug("*** Setter.setStoredMessage ***");
boolean result = false;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmt = conn.prepareCall("call resultMessageSet(?, ?, ?)")) {
log.debug("Preparing resultMessageSet procedure");
callstmt.setString(1, message);
callstmt.setString(2, userId);
callstmt.setString(3, moduleId);
callstmt.execute();
log.debug("Executed resultMessageSet");
result = true;
} catch (SQLException e) {
log.error("Could not execute resultMessageSet: " + e.toString());
}
log.debug("*** END setStoredMessage ***");
return result;
}
/**
* Sets user to suspended in the database for a specific amount of time. This prevents them from
* signing into the application
*
* @param ApplicationRoot Running context of application
* @param userId User Identifier of the to be suspended user
* @param numberOfMinutes Amount of minutes to suspend user
* @return Returns true if statement succeeds without fatal error
*/
public static boolean suspendUser(String ApplicationRoot, String userId, int numberOfMinutes) {
log.debug("*** Setter.suspendUser ***");
boolean result = false;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
PreparedStatement callstmnt = conn.prepareCall("CALL suspendUser(?, ?)")) {
log.debug("Prepairing suspendUser call");
callstmnt.setString(1, userId);
callstmnt.setInt(2, numberOfMinutes);
log.debug("Executing suspendUser statement on id '" + userId + "'");
callstmnt.execute();
result = true;
} catch (SQLException e) {
log.error("suspendUser Failure: " + e.toString());
result = false;
}
log.debug("*** END suspendUser ***");
return result;
}
/**
* Revokes a suspension that may have been applied to a user
*
* @param ApplicationRoot Running context of application
* @param userId The Identifier of the user that will be released from suspension
* @return
*/
public static boolean unSuspendUser(String ApplicationRoot, String userId) {
log.debug("*** Setter.unSuspendUser ***");
boolean result = false;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
PreparedStatement callstmnt = conn.prepareCall("CALL unSuspendUser(?)")) {
log.debug("Prepairing suspendUser call");
callstmnt.setString(1, userId);
log.debug("Executing unSuspendUser statement on id '" + userId + "'");
callstmnt.execute();
result = true;
} catch (SQLException e) {
log.error("unSuspendUser Failure: " + e.toString());
result = false;
}
log.debug("*** END unSuspendUser ***");
return result;
}
/**
* Used to increment a users CSRF counter for CSRF levels.
*
* @param ApplicationRoot The current running context of the application.
* @param moduleId The identifier of the module to increment the counter of
* @param userId The user to be incremented
* @return Boolean reflecting the success of the operation
*/
public static boolean updateCsrfCounter(String ApplicationRoot, String moduleId, String userId) {
log.debug("*** Setter.updateCsrfCounter ***");
boolean result = false;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmt = conn.prepareCall("call resultMessagePlus(?, ?)")) {
log.debug("Preparing resultMessagePlus procedure");
callstmt.setString(1, moduleId);
callstmt.setString(2, userId);
callstmt.execute();
result = true;
} catch (SQLException e) {
log.error("Could not execute resultMessagePlus: " + e.toString());
}
log.debug("*** END updateCsrfCounter ***");
return result;
}
/**
* @param ApplicationRoot The current running context of the application
* @param userName User name of the user
* @param currentPassword User's current password
* @param newPassword New password to use in update
* @return true if the password was updated, false if the current password did not verify
*/
public static boolean updatePassword(
String ApplicationRoot, String userName, String currentPassword, String newPassword) {
log.debug("*** Setter.updatePassword ***");
boolean result = false;
// Phase 1: Verify current password (Getter.authUser manages its own connection)
log.debug("Checking current password");
String user[] = Getter.authUser(ApplicationRoot, userName, currentPassword);
if (user == null || user[0].isEmpty()) {
// Wrong password
log.debug("Current password incorrect!");
return false;
}
// Phase 2: Hash new password (CPU-bound, ~100-200ms — do not hold a DB connection)
log.debug("Hashing password");
Argon2 argon2 = Argon2Factory.create();
String newHash = argon2.hash(10, 65536, 1, newPassword.toCharArray());
// TODO: wipe password from memory after hashing
// Phase 3: Persist the new hash (short DB hold)
log.debug("Preparing userPasswordChange call");
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmnt = conn.prepareCall("call userPasswordChange(?, ?)")) {
callstmnt.setString(1, userName);
callstmnt.setString(2, newHash);
log.debug("Executing userPasswordChange");
callstmnt.execute();
result = true;
} catch (SQLException e) {
log.debug("Could not update password: " + e.toString());
throw new RuntimeException(e);
}
log.debug("*** END updatePassword ***");
return result;
}
/**
* @param ApplicationRoot The current running context of the application
* @param userName Existing user name to rename
* @param newUsername The new user name to assign
* @return true if the username was updated successfully
*/
public static boolean updateUsername(
String ApplicationRoot, String userName, String newUsername) {
log.debug("*** Setter.updateUsername ***");
boolean result = false;
log.debug("Preparing username change call from username " + userName + " to " + newUsername);
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
PreparedStatement prestmnt =
conn.prepareStatement(
"UPDATE users SET userName = ?, tempUsername = FALSE WHERE userName = ?;")) {
prestmnt.setString(1, newUsername);
prestmnt.setString(2, userName);
log.debug("Executing name change query");
prestmnt.execute();
result = true;
} catch (SQLException e) {
log.debug("Could not update username: " + e.toString());
throw new RuntimeException(e);
}
log.debug("*** END updateUsername ***");
return result;
}
/**
* Updates a player's password without needing the current password
*
* @param ApplicationRoot Running context of the applicaiton
* @param userId The user id of the user to update
* @param newPassword The new password to assign to the user
* @return
*/
public static boolean updatePasswordAdmin(
String ApplicationRoot, String userId, String newPassword) {
log.debug("*** Setter.updatePasswordAdmin ***");
boolean result = false;
// Hash before opening a DB connection (Argon2 is CPU-bound, ~100-200ms)
log.debug("Hashing password");
Argon2 argon2 = Argon2Factory.create();
String newHash = argon2.hash(10, 65536, 1, newPassword.toCharArray());
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmnt = conn.prepareCall("call userPasswordChangeAdmin(?, ?)")) {
log.debug("Preparing userPasswordChangeAdmin call");
callstmnt.setString(1, userId);
callstmnt.setString(2, newHash);
log.debug("Executing userPasswordChangeAdmin");
callstmnt.execute();
result = true;
} catch (SQLException e) {
log.error("updatePasswordAdmin Failure: " + e.toString());
}
log.debug("*** END updatePasswordAdmin ***");
return result;
}
/**
* Updates a PLAYER's class identifier
*
* @param ApplicationRoot The current running context of the application
* @param classId New class to be assigned to
* @param playerId Player to be assigned to new class
* @return The userName that was updated
*/
public static String updatePlayerClass(String ApplicationRoot, String classId, String playerId) {
log.debug("*** Setter.updatePlayerClass ***");
String result = null;
try (Connection conn = Database.getCoreConnection(ApplicationRoot)) {
log.debug("Preparing playerUpdateClass call");
try (CallableStatement callstmnt = conn.prepareCall("call playerUpdateClass(?, ?)")) {
callstmnt.setString(1, playerId);
callstmnt.setString(2, classId);
log.debug("Executing playerUpdateClass");
try (ResultSet resultSet = callstmnt.executeQuery()) {
resultSet.next();
result = resultSet.getString(1);
}
}
} catch (SQLException e) {
log.error("playerUpdateClass Failure: " + e.toString());
result = null;
}
log.debug("*** END updatePlayerClass ***");
return result;
}
/**
* Updates a PLAYER's class identifier to null
*
* @param ApplicationRoot The current running context of the application
* @param playerId The identifier of the player to be assigned to class NULL
* @return The userName that was updated
*/
public static String updatePlayerClassToNull(String ApplicationRoot, String playerId) {
log.debug("*** Setter.updatePlayerClassToNull ***");
String result = null;
try (Connection conn = Database.getCoreConnection(ApplicationRoot)) {
log.debug("Preparing playerUpdateClassToNull call");
try (CallableStatement callstmnt = conn.prepareCall("call playerUpdateClassToNull(?)")) {
callstmnt.setString(1, playerId);
log.debug("Executing playerUpdateClassToNull");
try (ResultSet resultSet = callstmnt.executeQuery()) {
resultSet.next();
result = resultSet.getString(1);
}
}
} catch (SQLException e) {
log.error("updatePlayerClassToNull Failure: " + e.toString());
result = null;
}
log.debug("*** END updatePlayerClassToNull ***");
return result;
}
/**
* Updates a users result of a specific module
*
* @param ApplicationRoot The current running context of the application
* @param moduleId Identifier of the module the user is completing
* @param userId Identifier of the user completing the module
* @param extra The additional comments submitted in feedback by the user, or if CSRF, the attack
* string they used
* @param before The knowledge the user felt before they completed the level
* @param after The knowledge the user felt after they completed the level
* @param difficulty The difficulty the user felt they encountered
* @return The module name of the module completed by the user
*/
public static String updatePlayerResult(
String ApplicationRoot,
String moduleId,
String userId,
String extra,
int before,
int after,
int difficulty) {
log.debug("*** Setter.updatePlayerResult ***");
String result = null;
boolean isOpen;
Boolean isRunning;
try {
isOpen = CountdownHandler.isOpen();
isRunning = CountdownHandler.isRunning();
} catch (InvalidCountdownStateException e1) {
String message = "Countdown handler is in an invalid state.";
log.error(message);
throw new RuntimeException(message);
}
if (isRunning) {
boolean updated = false;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmnt =
conn.prepareCall("call userUpdateResult(?, ?, ?, ?, ?, ?, ?)")) {
log.debug("Preparing userUpdateResult call");
callstmnt.setString(1, moduleId);
callstmnt.setString(2, userId);
callstmnt.setInt(3, before);
callstmnt.setInt(4, after);
callstmnt.setInt(5, difficulty);
callstmnt.setBoolean(6, isOpen); // Only give points if CTF is open
callstmnt.setString(7, extra);
log.debug("Executing userUpdateResult");
callstmnt.execute();
updated = true;
} catch (SQLException e) {
log.error("userUpdateResult Failure: " + e.toString());
}
// Release the core connection before calling back into Getter, which opens its own.
// Holding two pooled connections per call doubles pool pressure under concurrency.
if (updated) {
result = Getter.getModuleNameLocaleKey(ApplicationRoot, moduleId);
}
} else {
log.error("Error: Can't allow results to be stored when CTF isn't running");
result = null;
}
log.debug("*** END updatePlayerResult ***");
return result;
}
/**
* Adds or Subtracts points from a user.
*
* @param ApplicationRoot Running context of application
* @param userId Identifier of user to update
* @param points Positive or Negative number of points to update by
* @return Returns true if statement executes without fatal error
*/
public static boolean updateUserPoints(String ApplicationRoot, String userId, int points) {
log.debug("*** Setter.updateUserPoints ***");
boolean result = false;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
PreparedStatement prestmnt =
conn.prepareStatement("UPDATE users SET userScore = userScore + ? WHERE userId = ?")) {
log.debug("Preparing updateUserPoints call");
prestmnt.setInt(1, points);
prestmnt.setString(2, userId);
log.debug("Executing updateUserPoints");
prestmnt.execute();
result = true;
} catch (SQLException e) {
log.error("updateUserPoints Failure: " + e.toString());
}
log.debug("*** END updateUserPoints ***");
return result;
}
/**
* Updates a USER's role
*
* @param ApplicationRoot The current running context of the application
* @param playerId The identifier of the player to update
* @param newRole Must be "player" or "admin"
* @return The user name of the user updated
*/
public static String updateUserRole(String ApplicationRoot, String playerId, String newRole) {
log.debug("*** Setter.updateUserRole ***");
String result = null;
try (Connection conn = Database.getCoreConnection(ApplicationRoot)) {
log.debug("Preparing userUpdateRole call");
try (CallableStatement callstmnt = conn.prepareCall("call userUpdateRole(?, ?)")) {
callstmnt.setString(1, playerId);
callstmnt.setString(2, newRole);
log.debug("Executing userUpdateRole");
try (ResultSet resultSet = callstmnt.executeQuery()) {
resultSet.next();
result = resultSet.getString(1);
}
}
} catch (SQLException e) {
log.error("userUpdateRole Failure: " + e.toString());
result = null;
}
log.debug("*** END updateUserRole ***");
return result;
}
/**
* Used by many functions to create players or admins
*
* @param ApplicationRoot
* @param classId Cannot be null, relationship depending
* @param userName Cannot be null
* @param userPass Cannot be null
* @param userRole Cannot be null, must be "player" or "admin"
* @param userAddress Must be unique
* @param tempPass Whether or not to set the user with a temporary pass flag
* @return A boolean value determining the result of the creation
* @throws SQLException If the creation fails, a Exception is thrown
*/
public static boolean userCreate(
String ApplicationRoot,
String classId,
String userName,
String userPass,
String userRole,
String userAddress,
boolean tempPass)
throws SQLException {
boolean result = false;
log.debug("*** Setter.userCreate ***");
log.debug("classId = " + classId);
log.debug("userName = " + userName);
// We don't log passwords
log.debug("userRole = " + userRole);
log.debug("userAddress = " + userAddress);
// Hash before opening a DB connection (Argon2 is CPU-bound, ~100-200ms)
log.debug("Hashing password");
Argon2 argon2 = Argon2Factory.create();
String hash = argon2.hash(10, 65536, 1, userPass.toCharArray());
// TODO: wipe password from memory after hashing
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmt =
conn.prepareCall("call userCreate(?, ?, ?, ?, ?, ?, ?, ?, ?)")) {
log.debug("Executing userCreate procedure on Database");
callstmt.setString(1, classId);
callstmt.setString(2, userName);
callstmt.setString(3, hash);
callstmt.setString(4, userRole);
callstmt.setString(5, null); // ssoName
callstmt.setString(6, userAddress);
callstmt.setString(7, "login"); // login type
callstmt.setBoolean(8, tempPass);
callstmt.setBoolean(9, false); // Tempname
try (ResultSet registerAttempt = callstmt.executeQuery()) {
log.debug("Opening result set");
registerAttempt.next(); // Procedure Ran correctly
if (registerAttempt.getString(1) == null) {
// Registration success