Repository navigation
Expand file tree
/
Copy pathGetter.java
More file actions
2646 lines (2402 loc) · 103 KB
/
Copy pathGetter.java
File metadata and controls
2646 lines (2402 loc) · 103 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.IOException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.owasp.encoder.Encode;
import servlets.Register;
import utils.ModulePlan;
import utils.ScoreboardStatus;
/**
* Used to retrieve information from 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 Getter {
private static final Logger log = LogManager.getLogger(Getter.class);
/** Used for scoreboards / progress bars */
private static final int widthOfUnitBar = 11; // px
private static final int fieldTrainingCap = 45;
private static final int privateCap = 80;
private static final int corporalCap = 105;
private static final int sergeantCap = 130;
private static final int lieutenantCap = 145;
private static final int majorCap = 175;
private static final int admiralCap = 999; // everything above Major is Admiral
/**
* Safety cap on the number of rows materialized by {@link #getClassInfo}, {@link
* #getPlayersByClass}, and {@link #getAdmins}. These methods return a {@link
* javax.sql.rowset.CachedRowSet}, which holds every row in memory. Realistic workloads are well
* under this limit (tens to a few hundred per call); the cap exists to fail fast on a runaway
* query rather than OOM the JVM. Tracked for proper bounded-collection conversion in #839.
*/
private static final int MAX_ROWSET_ROWS = 10_000;
/**
* This method hashes the user submitted password and sends it to the database. The database does
* the rest of the work, including Brute Force prevention.
*
* @param userName The submitted user name to be used in authentication process
* @param password The submitted password in plain text to be used in authentication
* @return A string array made up of nothing or information to be consumed by the initiating
* authentication process.
*/
public static String[] authUser(String ApplicationRoot, String userName, String password) {
log.debug("$$$ Getter.authUser $$$");
log.debug("userName = " + userName);
// Phase 1: Fetch user record (short DB hold, ~1-5ms)
String userId;
String dbUserName;
String dbHash;
String userRole;
int badLoginCount;
boolean tempPassword;
String classId;
Timestamp suspendedUntil;
String loginType;
boolean tempUsername;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
PreparedStatement prestmt =
conn.prepareStatement(
"SELECT userId, userName, userPass, userRole, badLoginCount, tempPassword, classId,"
+ " suspendedUntil, loginType, tempUsername FROM `users` WHERE userName = ?")) {
prestmt.setString(1, userName);
try (ResultSet userResult = prestmt.executeQuery()) {
if (userResult.next()) {
log.debug("User Found");
userId = userResult.getString(1);
dbUserName = userResult.getString(2);
dbHash = userResult.getString(3);
userRole = userResult.getString(4);
badLoginCount = userResult.getInt(5);
tempPassword = userResult.getBoolean(6);
classId = userResult.getString(7);
suspendedUntil = userResult.getTimestamp(8);
loginType = userResult.getString(9);
tempUsername = userResult.getBoolean(10);
} else {
log.debug("User did not exist");
log.debug("$$$ End authUser $$$");
return null;
}
}
} catch (SQLException e) {
log.fatal("authUser failed: " + e.toString());
throw new RuntimeException(e);
}
// Connection released — all user data extracted into local variables
// Fail-fast: reject suspended and SSO users before expensive Argon2 work
if (!"login".equals(loginType)) {
log.debug("User is SSO user, can't login with password!");
return null;
}
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
if (suspendedUntil != null && suspendedUntil.after(currentTime)) {
return null;
}
// Phase 2: Verify password (CPU-bound Argon2, no DB connection held)
log.debug("Verifying hash");
Argon2 argon2 = Argon2Factory.create();
boolean userVerified = argon2.verify(dbHash, password.toCharArray());
if (!userVerified) {
log.debug("Hash did not match, authentication failed");
log.debug("$$$ End authUser $$$");
return null;
}
// Phase 3: Post-verification DB updates (short DB hold if needed)
log.debug("Hash matches");
if (!dbUserName.equalsIgnoreCase(userName)) {
log.fatal(
"User Name used ("
+ userName
+ ") and User Name retrieved ("
+ dbUserName
+ ") were not the Same. Nulling Result");
return null;
}
log.debug("User '" + userName + "' has logged in");
if (badLoginCount > 0) {
log.debug("Clearing Bad Login History");
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmt = conn.prepareCall("call userBadLoginReset(?)")) {
callstmt.setString(1, userId);
callstmt.execute();
log.debug("userBadLoginReset executed!");
} catch (SQLException e) {
log.fatal("Could not reset bad login count: " + e.toString());
throw new RuntimeException(e);
}
}
String[] result = new String[6];
result[0] = userId;
result[1] = dbUserName;
result[2] = userRole;
result[3] = Boolean.toString(tempPassword);
result[4] = classId;
result[5] = Boolean.toString(tempUsername);
log.debug("$$$ End authUser $$$");
return result;
}
/**
* This method hashes the user submitted password and sends it to the database. The database does
* the rest of the work, including Brute Force prevention.
*
* @param ApplicationRoot The current running context of an application
* @param userName The submitted user name to be used in authentication process
* @param ssoName
* @param password The submitted password in plain text to be used in authentication
* @return A string array made up of nothing or information to be consumed by the initiating
* authentication process.
*/
public static String[] authUserSSO(
String ApplicationRoot, String classId, String userName, String ssoName, String userRole) {
log.debug("$$$ Getter.authUserSSO $$$");
log.debug("ssoName = " + ssoName);
log.debug("userName = " + userName);
String[] result = new String[6];
String userID = new String();
String newUsername = null;
String defaultClass = Register.getDefaultClass();
boolean userFound = false;
boolean isTempUsername = false;
try {
// Phase 1: See if the user already exists, and capture suspension data if so.
// Each phase opens its own pooled connection in try-with-resources so the
// connection is never held across the Setter.userCreateSSO call (Phase 2).
Timestamp suspendedUntil = null;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
PreparedStatement prestmt =
conn.prepareStatement(
"SELECT suspendedUntil FROM `users` WHERE ssoName = ? AND loginType='saml'")) {
prestmt.setString(1, ssoName);
log.debug("Gathering userFind ResultSet");
try (ResultSet userResult = prestmt.executeQuery()) {
log.debug("Opening Result Set from userResult");
if (userResult.next()) {
// User found if a row is in the database
userFound = true;
log.debug("User Found");
suspendedUntil = userResult.getTimestamp(1);
} else {
userFound = false;
}
}
}
if (!userFound) {
// Phase 2: User wasn't found, enroll them in database. No pooled
// connection is held here; Setter.userCreateSSO borrows its own.
boolean userCreated = false;
log.debug("User did not exist, create it from SSO data");
try {
if (defaultClass.isEmpty()) {
log.debug("Adding player to database, with null classId");
newUsername = Setter.userCreateSSO(ApplicationRoot, null, userName, ssoName, userRole);
} else // defaultClass is not empty, so It must be set to a class!
{
log.debug("Adding player to database, to class " + defaultClass);
newUsername =
Setter.userCreateSSO(ApplicationRoot, defaultClass, userName, ssoName, userRole);
}
if (newUsername == null) {
userCreated = false;
} else {
userCreated = true;
}
userName = newUsername;
} catch (SQLException e) {
String message =
"Could not create user "
+ userName
+ " with ssoName "
+ ssoName
+ " via SSO: "
+ e.toString();
log.fatal(message);
throw new RuntimeException(message);
}
if (!userCreated) {
String message =
"Could not create user " + userName + " with ssoName " + ssoName + " via SSO";
log.fatal(message);
throw new RuntimeException(message);
}
log.debug("User created");
} else {
log.debug("Getting suspension data");
// Get current system time
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
if (suspendedUntil.after(currentTime)) {
// User is suspended
log.debug("User is suspended");
result = null;
return result;
}
}
// Phase 3: Find the generated userID and username by asking the database.
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
PreparedStatement prestmt =
conn.prepareStatement(
"SELECT userId, userName, classID, tempUsername FROM `users` WHERE ssoName = ?"
+ " AND loginType='saml'")) {
prestmt.setString(1, ssoName);
log.debug("Gathering userResult ResultSet");
try (ResultSet userResult = prestmt.executeQuery()) {
log.debug("Opening user list result set");
if (userResult.next()) {
userFound = true;
log.debug("User Found");
} else {
userFound = false;
}
if (!userFound) {
// If user wasn't found at this stage something is quite wrong, so exit
// forcefully
String message = "User wasn't found after being added!";
log.fatal(message);
throw new RuntimeException(message);
}
userID = userResult.getString(1);
userName = userResult.getString(2);
classId = userResult.getString(3); // classId
isTempUsername = userResult.getBoolean(4);
}
}
log.debug("User '" + userName + "' has logged in via SSO" + " with role " + userRole);
result[0] = userID;
result[1] = userName; // userName
result[2] = userRole; // role
result[5] = "false"; // sso logins can't change password
result[4] = classId; // classId
result[5] = Boolean.toString(isTempUsername);
log.debug("$$$ End authUser $$$");
return result;
} catch (SQLException e) {
log.fatal("authUserSSO failed: " + e.toString());
throw new RuntimeException(e);
}
}
/**
* Used to determine if a user has completed a module already
*
* @param ApplicationRoot The current running context of an application
* @param moduleId The module identifier
* @param userId The user identifier
* @return The module name of the module IF the user has not completed AND the user has previously
* opened the challenge.
*/
public static String checkPlayerResult(String ApplicationRoot, String moduleId, String userId) {
log.debug("*** Getter.checkPlayerResult ***");
String result = null;
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmnt = conn.prepareCall("call userCheckResult(?, ?)")) {
log.debug("Preparing userCheckResult call");
callstmnt.setString(1, moduleId);
callstmnt.setString(2, userId);
log.debug("Executing userCheckResult");
try (ResultSet resultSet = callstmnt.executeQuery()) {
resultSet.next();
result = resultSet.getString(1);
}
} catch (SQLException e) {
log.debug("userCheckResult Failure: " + e.toString());
result = null;
}
log.debug("*** END checkPlayerResult ***");
return result;
}
/**
* Used to decipher whether or not a user exists as a player
*
* @param userId The user identifier of the player to be found
* @return A boolean reflecting the state of existence of the player
*/
public static boolean findPlayerById(String ApplicationRoot, String userId) {
log.debug("*** Getter.findPlayerById ***");
boolean userFound = false;
// Get connection
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmt = conn.prepareCall("call playerFindById(?)")) {
log.debug("Gathering playerFindById ResultSet");
callstmt.setString(1, userId);
try (ResultSet userFind = callstmt.executeQuery()) {
log.debug("Opening Result Set from playerFindById");
userFind.next(); // This will throw an exception if player not found
log.debug(
"Player Found: "
+ userFind.getString(1)); // This line will not execute if player not found
userFound = true;
}
} catch (SQLException e) {
log.error("Player did not exist: " + e.toString());
userFound = false;
}
log.debug("*** END findPlayerById ***");
return userFound;
}
/**
* Used to gather all module information for internal functionality. This method is used in
* creating View's or in control class operations
*
* @param ApplicationRoot The current runing context of the application
* @return An ArrayList of String arrays that contain the module identifier, module name, module
* type and module category of each module in the core database.
*/
public static ArrayList<String[]> getAllModuleInfo(String ApplicationRoot) {
log.debug("*** Getter.getAllModuleInfo ***");
ArrayList<String[]> modules = new ArrayList<String[]>();
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmt = conn.prepareCall("call moduleGetAll()")) {
log.debug("Gathering moduleGetAll ResultSet");
try (ResultSet resultSet = callstmt.executeQuery()) {
log.debug("Opening Result Set from moduleGetAll");
int i = 0;
while (resultSet.next()) {
String[] result = new String[4];
i++;
result[0] = resultSet.getString(1); // moduleId
result[1] = resultSet.getString(2); // moduleName
result[2] = resultSet.getString(3); // moduleType
result[3] = resultSet.getString(4); // mdouleCategory
modules.add(result);
}
log.debug("Returning Array list with " + i + " entries.");
}
} catch (SQLException e) {
log.error("Could not execute query: " + e.toString());
}
log.debug("*** END getAllModuleInfo ***");
return modules;
}
/**
* Returns HTML menu for challenges. Challenges are only referenced by their id, The user will
* have to go through another servlet to get the module's View address
*
* @param ApplicationRoot The current running context of the application
* @param userId The user identifier of the player
* @param lang The Locale the user has enabled
* @return HTML menu for challenges
* @throws SQLException
*/
public static String getChallenges(String ApplicationRoot, String userId, Locale lang)
throws SQLException {
log.debug("*** Getter.getChallenges ***");
String output = new String();
// Getting Translated Level Names
ResourceBundle bundle = ResourceBundle.getBundle("i18n.moduleGenerics.moduleNames", lang);
// Encoder to prevent XSS
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmt = conn.prepareCall("call moduleAllInfo(?, ?)")) {
callstmt.setString(1, "challenge");
callstmt.setString(2, userId);
log.debug("Gathering moduleAllInfo ResultSet");
try (ResultSet challenges = callstmt.executeQuery()) {
log.debug("Opening Result Set from moduleAllInfo");
String challengeCategory = new String();
int rowNumber = 0; // Identifies the first row, ie the start of the list. This is slightly
// different output to every other row
while (challenges.next()) {
if (!challengeCategory.equalsIgnoreCase(challenges.getString(2))) {
challengeCategory = challenges.getString(2);
// log.debug("New Category Detected: " + challengeCategory);
if (rowNumber > 0) // output prepared for Every row after row 1
{
output +=
"</ul></li><li><a href='javascript:;' class='challengeHeader' >"
+ Encode.forHtml(bundle.getString("category." + challengeCategory))
+ "</a><ul class='challengeList' style='display: none;'>";
} else // output prepared for First row in entire challenge
{
output +=
"<li><a href='javascript:;' class='challengeHeader'>"
+ Encode.forHtml(bundle.getString("category." + challengeCategory))
+ "</a><ul class='challengeList' style='display: none;'>";
}
// log.debug("Compiling Challenge Category - " + challengeCategory);
}
output += "<li>"; // Starts next LI element
if (challenges.getString(4) != null) {
output += "<img src='css/images/completed.png'/>"; // Completed marker
} else {
output += "<img src='css/images/uncompleted.png'/>"; // Incomplete marker
}
// Final out put compilation
output +=
"<a class='lesson' id='"
+ Encode.forHtmlAttribute(challenges.getString(3))
+ "' href='javascript:;'>"
+ Encode.forHtml(bundle.getString(challenges.getString(1)))
+ "</a>";
output += "</li>";
rowNumber++;
}
// Check if output is empty
if (output.isEmpty()) {
output = "<li>No challenges found</li>";
} else {
log.debug("Appending End tags");
output += "</ul></li>";
}
}
log.debug("*** END getChallenges() ***");
return output;
}
}
/**
* @param ApplicationRoot The current running context of the application
* @return The amount of classes currently existing in the database
*/
public static int getClassCount(String ApplicationRoot) {
int result = 0;
log.debug("*** Getter.getClassCount ***");
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmt = conn.prepareCall("call classCount()")) {
log.debug("Gathering classCount ResultSet");
try (ResultSet resultSet = callstmt.executeQuery()) {
log.debug("Opening Result Set from classCount");
resultSet.next();
result = resultSet.getInt(1);
}
} catch (SQLException e) {
log.error("Could not execute query: " + e.toString());
result = 0;
}
log.debug("*** END getClassCount");
return result;
}
/**
* @param ApplicationRoot The current running context of the application
* @return Result set containing class info in the order classId, className and then classYear
*/
public static ResultSet getClassInfo(String ApplicationRoot) {
ResultSet result = null;
log.debug("*** Getter.getClassInfo (All Classes) ***");
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmt = conn.prepareCall("call classesGetData()")) {
callstmt.setMaxRows(MAX_ROWSET_ROWS);
try (ResultSet resultSet = callstmt.executeQuery()) {
log.debug("Gathering classesGetData ResultSet");
CachedRowSet rowSet = RowSetProvider.newFactory().createCachedRowSet();
rowSet.populate(resultSet);
rowSet.beforeFirst(); // populate() leaves the cursor after the last row
result = rowSet;
}
log.debug("Returning Result Set from classesGetData");
} catch (SQLException e) {
log.error("Could not execute query: " + e.toString());
result = null;
}
log.debug("*** END getClassInfo");
return result;
}
/**
* @param ApplicationRoot The current running context of the application
* @param classId The identifier of the class
* @return String Array with Class information with the format of {name, year}
*/
public static String[] getClassInfo(String ApplicationRoot, String classId) {
String[] result = new String[2];
log.debug("*** Getter.getClassInfo (Single Class) ***");
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmt = conn.prepareCall("call classFind(?)")) {
callstmt.setString(1, classId);
log.debug("Gathering classFind ResultSet");
try (ResultSet resultSet = callstmt.executeQuery()) {
log.debug("Opening Result Set from classFind");
resultSet.next();
result[0] = resultSet.getString(1); // Name
result[1] = resultSet.getString(2); // Year
}
} catch (SQLException e) {
log.error("Could not execute query: " + e.toString());
result = null;
}
log.debug("*** END getClassInfo");
return result;
}
/**
* The CSRF forum is used in CSRF levels for users to deliver CSRF attacks against each other.
* URLs are contained in IFRAME tags
*
* @param ApplicationRoot The current running context of the application
* @param classId Identifier of the class to populate the forum with
* @param moduleId The module in which to return the forum for
* @param bundle Strings Package for the Language Local of the user making the request
* @return A HTML table of a Class's CSRF Submissions for a specific module
*/
public static String getCsrfForumWithIframe(
String ApplicationRoot, String classId, String moduleId, ResourceBundle bundle) {
log.debug("*** Getter.getCsrfForum ***");
log.debug("Getting stored messages from class: " + classId);
String htmlOutput = new String();
try (Connection conn = Database.getCoreConnection(ApplicationRoot)) {
if (classId != null) {
try (CallableStatement callstmt = conn.prepareCall("call resultMessageByClass(?, ?)")) {
log.debug("Gathering resultMessageByClass ResultSet");
callstmt.setString(1, classId);
callstmt.setString(2, moduleId);
try (ResultSet resultSet = callstmt.executeQuery()) {
log.debug("resultMessageByClass executed");
// Table Header
htmlOutput =
"<table><tr><th>"
+ bundle.getString("forum.userName")
+ "</th><th>"
+ bundle.getString("forum.message")
+ "</th></tr>";
log.debug("Opening Result Set from resultMessageByClass");
int counter = 0;
while (resultSet.next()) {
counter++;
// Table content
htmlOutput +=
"<tr><td>"
+ Encode.forHtml(resultSet.getString(1))
+ "</td><td><iframe sandbox=\"allow-scripts allow-forms\" src=\""
+ Encode.forHtmlAttribute(resultSet.getString(2))
+ "\"></iframe></td></tr>";
}
if (counter > 0) {
log.debug("Added a " + counter + " row table");
} else {
log.debug("No results from query");
}
// Table end
htmlOutput += "</table>";
}
}
} else {
log.error("User with Null Class detected");
htmlOutput = "<p><font color='red'>" + bundle.getString("error.noClass") + "</font></p>";
}
} catch (SQLException e) {
log.error("Could not execute query: " + e.toString());
htmlOutput = "<p>" + bundle.getString("error.occurred ") + "</p>";
} catch (Exception e) {
log.fatal("Could not return CSRF Forum: " + e.toString());
}
log.debug("*** END getCsrfForum ***");
return htmlOutput;
}
/**
* The CSRF forum is used in CSRF levels for users to deliver CSRF attacks against each other.
* URLs are contained in IMG tags
*
* @param ApplicationRoot The current running context of the application
* @param classId Identifier of the class to populate the forum with
* @param moduleId The module in which to return the forum for
* @param bundle The strings package for the language of the user
* @return A HTML table of a Class's CSRF Submissions for a specific module
*/
public static String getCsrfForumWithImg(
String ApplicationRoot, String classId, String moduleId, ResourceBundle bundle) {
log.debug("*** Getter.getCsrfForum ***");
log.debug("Getting stored messages from class: " + classId);
String htmlOutput = new String();
try (Connection conn = Database.getCoreConnection(ApplicationRoot)) {
if (classId != null) {
try (CallableStatement callstmt = conn.prepareCall("call resultMessageByClass(?, ?)")) {
log.debug("Gathering resultMessageByClass ResultSet");
callstmt.setString(1, classId);
callstmt.setString(2, moduleId);
try (ResultSet resultSet = callstmt.executeQuery()) {
log.debug("resultMessageByClass executed");
// Table Header
htmlOutput =
"<table><tr><th>"
+ bundle.getString("forum.userName")
+ "</th><th>"
+ bundle.getString("forum.image")
+ "</th></tr>";
log.debug("Opening Result Set from resultMessageByClass");
int counter = 0;
while (resultSet.next()) {
counter++;
// Table content
htmlOutput +=
"<tr><td>"
+ Encode.forHtml(resultSet.getString(1))
+ "</td><td><img src=\""
+ Encode.forHtmlAttribute(resultSet.getString(2))
+ "\"/></td></tr>";
}
if (counter > 0) {
log.debug("Added a " + counter + " row table");
} else {
log.debug("No results from query");
}
// Table end
htmlOutput += "</table>";
}
}
} else {
log.error("User with Null Class detected");
htmlOutput = "<p><font color='red'>" + bundle.getString("error.noClass") + "</font></p>";
}
} catch (SQLException e) {
log.error("Could not execute query: " + e.toString());
htmlOutput = "<p>" + bundle.getString("error.occurred") + "</p>";
} catch (Exception e) {
log.fatal("Could not return CSRF Forum: " + e.toString());
}
log.debug("*** END getCsrfForum ***");
return htmlOutput;
}
/**
* Used to present a modules feedback, including averages and raw results.
*
* @param applicationRoot The current running context of the application.
* @param moduleId The module identifier
* @return A HTML table of the feedback for a specific module
*/
public static String getFeedback(String applicationRoot, String moduleId) {
log.debug("*** Getter.getFeedback ***");
String result = new String();
try (Connection conn = Database.getCoreConnection(applicationRoot);
CallableStatement callstmnt = conn.prepareCall("call moduleFeedback(?)")) {
log.debug("Preparing moduleFeedback call");
callstmnt.setString(1, moduleId);
log.debug("Executing moduleFeedback");
try (ResultSet resultSet = callstmnt.executeQuery()) {
int resultAmount = 0;
int before = 0;
int after = 0;
int difficulty = 0;
boolean color = true;
while (resultSet.next()) {
if (resultSet.getString(1) != null) {
resultAmount++;
difficulty += resultSet.getInt(3);
before += resultSet.getInt(4);
after += resultSet.getInt(5);
result += "<tr ";
if (color) // Alternate row color
{
color = !color;
result += "BGCOLOR='A878EF'";
} else {
color = !color;
result += "BGCOLOR='D4BCF7'";
}
// A row off information
result +=
"><td>"
+ Encode.forHtml(resultSet.getString(1))
+ "</td><td>"
+ Encode.forHtml(resultSet.getString(2))
+ "</td><td>"
+ resultSet.getInt(3)
+ "</td><td>"
+ resultSet.getInt(4)
+ "</td><td>"
+ resultSet.getInt(5)
+ "</td><td>"
+ Encode.forHtml(resultSet.getString(6))
+ "</td></tr>";
}
}
if (resultAmount > 0) // Table header
{
result =
"<table><tr><th>Player</th><th>Time</th><th>Difficulty</th><th>Before</th><th>After</th><th>Comments</th></tr>"
+ "<tr><td>Average</td><td></td><td>"
+ difficulty / resultAmount
+ "</td><td>"
+ before / resultAmount
+ "</td><td>"
+ after / resultAmount
+ "</td><td></td></tr>"
+ result
+ "<table>";
} else // If empty, Blank output
{
result = new String();
}
}
} catch (SQLException e) {
log.error("moduleFeedback Failure: " + e.toString());
result = null;
}
log.debug("*** END getFeedback ***");
return result;
}
/**
* This method prepares the incremental module menu. This is when Security Shepherd is in "Game
* Mode". Users are presented with one uncompleted module at a time. This method also returns a
* script to be executed every time the menu is chanegd. This is script defines the animation and
* operations to be carried out when the menu is interacted with
*
* @param ApplicationRoot The running context of the application.
* @param userId The user identifier of the user.
* @param lang The name of the Locale the user
* @param csrfToken The cross site request forgery token
* @return A HTML menu of a users current module progress and a script for interaction with this
* menu
*/
public static String getIncrementalModules(
String ApplicationRoot, String userId, String lang, String csrfToken) {
log.debug("*** Getter.getIncrementalChallenges ***");
String output = new String();
Locale.setDefault(new Locale("en"));
Locale locale = new Locale(lang);
ResourceBundle bundle = ResourceBundle.getBundle("i18n.text", locale);
ResourceBundle levelNames = ResourceBundle.getBundle("i18n.moduleGenerics.moduleNames", locale);
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmt = conn.prepareCall("call moduleIncrementalInfo(?)")) {
callstmt.setString(1, userId);
log.debug("Gathering moduleIncrementalInfo ResultSet");
try (ResultSet modules = callstmt.executeQuery()) {
log.debug("Opening Result Set from moduleIncrementalInfo");
boolean lastRow = false;
boolean completedModules = false;
// Preparing first Category header; "Completed"
output =
"<li><a id='completedList' href='javascript:;'><div class='menuButton'>"
+ bundle.getString("getter.button.completed")
+ "</div></a>\n"
+ "<ul id='theCompletedList' style='display: none;' class='levelList'>";
while (modules.next() && !lastRow) {
// For each row, prepair the modules the users can select
if (modules.getString(4) != null) // If not Last Row
{
completedModules = true;
output += "<li>";
output +=
"<a class='lesson' id='"
+ Encode.forHtmlAttribute(modules.getString(3))
+ "' href='javascript:;'>"
+ Encode.forHtml(levelNames.getString(modules.getString(1)))
+ "</a>";
output += "</li>";
} else {
lastRow = true;
// Last Row - Highlighed Next Challenge
if (completedModules) {
output += "</ul></li><li>";
} else {
// NO completed modules, so dont show any...
output = new String();
}
// Second category - Uncompleted
output +=
"<a class='lesson' id='"
+ Encode.forHtmlAttribute(modules.getString(3))
+ "' href='javascript:;'>"
+ "<div class='menuButton'>"
+ bundle.getString("getter.button.nextChallenge")
+ "</div>"
+ "</a>";
output += "</li>";
}
}
if (!lastRow) // If true, then the user has completed all challenges
{
output +=
"<h2 id='uncompletedList'><a href='javascript:;'>"
+ bundle.getString("getter.button.finished")
+ "</a></h2>\n"
+ "</li>";
}
if (output
.isEmpty()) // If this method has gone so far without any output, create a error message
{
output =
"<li><a href='javascript:;'>"
+ bundle.getString("getter.button.noModulesFound")
+ "</a></li>";
} else // final tags to ensure valid HTML
{
log.debug("Appending End tags");
// output += "</ul></li>"; //Commented Out to prevent Search Box being pushed
// into Footer
}
// This is the script for menu interaction
output +=
"<script>applyMenuButtonActionsCtfMode('"
+ Encode.forHtml(csrfToken)
+ "', \""
+ Encode.forHtml(bundle.getString("generic.text.sorryError"))
+ "\");</script>";
}
} catch (Exception e) {
log.error("Challenge Retrieval: " + e.toString());
}
log.debug("*** END getIncrementalChallenges() ***");
return output;
}
/**
* This method prepares the incremental module menu. This is when Security Shepherd is in "Game
* Mode". Users are presented with one uncompleted module at a time. This method does not return
* the JS script describing how the menu used should work
*
* @param ApplicationRoot The running context of the application.
* @param userId The user identifier of the user.
* @param lang The name of the Locale the user
* @param csrfToken The cross site request forgery token
* @return A HTML menu of a users current module progress and a script for interaction with this
* menu
*/
public static String getIncrementalModulesWithoutScript(
String ApplicationRoot, String userId, String lang, String csrfToken) {
log.debug("*** Getter.getIncrementalChallengesWithoutScript ***");
String output = new String();
Locale.setDefault(new Locale("en"));
Locale locale = new Locale(lang);
ResourceBundle bundle = ResourceBundle.getBundle("i18n.text", locale);
ResourceBundle levelNames = ResourceBundle.getBundle("i18n.moduleGenerics.moduleNames", locale);
try (Connection conn = Database.getCoreConnection(ApplicationRoot);
CallableStatement callstmt = conn.prepareCall("call moduleIncrementalInfo(?)")) {
callstmt.setString(1, userId);
log.debug("Gathering moduleIncrementalInfo ResultSet");
try (ResultSet modules = callstmt.executeQuery()) {
log.debug("Opening Result Set from moduleIncrementalInfo");
boolean lastRow = false;
boolean completedModules = false;
// Preparing first Category header; "Completed"
output =
"<li><a id='completedList' href='javascript:;'><div class='menuButton'>"
+ bundle.getString("getter.button.completed")
+ "</div></a>\n"
+ "<ul id='theCompletedList' style='display: none;' class='levelList'>";
while (modules.next() && !lastRow) {
// For each row, prepair the modules the users can select
if (modules.getString(4) != null) // If not Last Row
{
completedModules = true;
output += "<li>";
output +=
"<a class='lesson' id='"
+ Encode.forHtmlAttribute(modules.getString(3))
+ "' href='javascript:;'>"
+ Encode.forHtml(levelNames.getString(modules.getString(1)))
+ "</a>";
output += "</li>";
} else {