-
Notifications
You must be signed in to change notification settings - Fork 370
Expand file tree
/
Copy pathDefaultValidator.java
More file actions
1262 lines (1134 loc) · 46.6 KB
/
DefaultValidator.java
File metadata and controls
1262 lines (1134 loc) · 46.6 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
/**
* OWASP Enterprise Security API (ESAPI)
*
* This file is part of the Open Web Application Security Project (OWASP)
* Enterprise Security API (ESAPI) project. For details, please see
* <a href="http://www.owasp.org/index.php/ESAPI">http://www.owasp.org/index.php/ESAPI</a>.
*
* Copyright (c) 2007 - The OWASP Foundation
*
* The ESAPI is published by OWASP under the BSD license. You should read and accept the
* LICENSE before you use, modify, and/or redistribute this software.
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @author Jim Manico (jim@manico.net) <a href="http://www.manico.net">Manico.net</a>
*
* @created 2007
*/
package org.owasp.esapi.reference;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.Encoder;
import org.owasp.esapi.Logger;
import org.owasp.esapi.SecurityConfiguration;
import org.owasp.esapi.ValidationErrorList;
import org.owasp.esapi.ValidationRule;
import org.owasp.esapi.Validator;
import org.owasp.esapi.errors.IntrusionException;
import org.owasp.esapi.errors.ValidationAvailabilityException;
import org.owasp.esapi.errors.ValidationException;
import org.owasp.esapi.reference.validation.CreditCardValidationRule;
import org.owasp.esapi.reference.validation.DateValidationRule;
import org.owasp.esapi.reference.validation.HTMLValidationRule;
import org.owasp.esapi.reference.validation.IntegerValidationRule;
import org.owasp.esapi.reference.validation.NumberValidationRule;
import org.owasp.esapi.reference.validation.StringValidationRule;
/**
* Reference implementation of the Validator interface. This implementation
* relies on the ESAPI Encoder, Java Pattern (regex), Date,
* and several other classes to provide basic validation functions. This library
* has a heavy emphasis on whitelist validation and canonicalization.
*
* @author Jeff Williams (jeff.williams .at. aspectsecurity.com) <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @author Jim Manico (jim@manico.net) <a href="http://www.manico.net">Manico.net</a>
* @author Matt Seil (mseil .at. acm.org)
*
* @since June 1, 2007
* @see org.owasp.esapi.Validator
*/
public class DefaultValidator implements org.owasp.esapi.Validator {
private static Logger logger = ESAPI.log();
private static volatile Validator instance = null;
public static Validator getInstance() {
if ( instance == null ) {
synchronized ( Validator.class ) {
if ( instance == null ) {
instance = new DefaultValidator();
}
}
}
return instance;
}
/** A map of validation rules */
private Map<String, ValidationRule> rules = new HashMap<String, ValidationRule>();
/** The encoder to use for canonicalization */
private Encoder encoder = null;
/** The encoder to use for file system */
private static Validator fileValidator = null;
/** Initialize file validator with an appropriate set of codecs */
static {
List<String> list = new ArrayList<String>();
list.add( "HTMLEntityCodec" );
list.add( "PercentCodec" );
Encoder fileEncoder = new DefaultEncoder( list );
fileValidator = new DefaultValidator( fileEncoder );
}
/**
* Default constructor uses the ESAPI standard encoder for canonicalization.
*/
public DefaultValidator() {
this.encoder = ESAPI.encoder();
}
/**
* Construct a new DefaultValidator that will use the specified
* Encoder for canonicalization.
*
* @param encoder
*/
public DefaultValidator( Encoder encoder ) {
this.encoder = encoder;
}
/**
* Add a validation rule to the registry using the "type name" of the rule as the key.
*/
public void addRule( ValidationRule rule ) {
rules.put( rule.getTypeName(), rule );
}
/**
* Get a validation rule from the registry with the "type name" of the rule as the key.
*/
public ValidationRule getRule( String name ) {
return rules.get( name );
}
/**
* Returns true if data received from browser is valid. Double encoding is treated as an attack. The
* default encoder supports html encoding, URL encoding, and javascript escaping. Input is canonicalized
* by default before validation.
*
* @param context A descriptive name for the field to validate. This is used for error facing validation messages and element identification.
* @param input The actual user input data to validate.
* @param type The regular expression name while maps to the actual regular expression from "ESAPI.properties".
* @param maxLength The maximum post-canonicalized String length allowed.
* @param allowNull If allowNull is true then a input that is NULL or an empty string will be legal. If allowNull is false then NULL or an empty String will throw a ValidationException.
* @return The canonicalized user input.
* @throws IntrusionException
*/
public boolean isValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws IntrusionException {
return isValidInput(context, input, type, maxLength, allowNull, true);
}
public boolean isValidInput(String context, String input, String type, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
return isValidInput(context, input, type, maxLength, allowNull, true, errors);
}
public boolean isValidInput(String context, String input, String type, int maxLength, boolean allowNull, boolean canonicalize) throws IntrusionException {
try {
getValidInput( context, input, type, maxLength, allowNull, canonicalize);
return true;
} catch( Exception e ) {
return false;
}
}
public boolean isValidInput(String context, String input, String type, int maxLength, boolean allowNull, boolean canonicalize, ValidationErrorList errors) throws IntrusionException {
try {
getValidInput( context, input, type, maxLength, allowNull, canonicalize);
return true;
} catch( ValidationException e ) {
errors.addError( context, e );
return false;
}
}
/**
* Validates data received from the browser and returns a safe version.
* Double encoding is treated as an attack. The default encoder supports
* html encoding, URL encoding, and javascript escaping. Input is
* canonicalized by default before validation.
*
* @param context A descriptive name for the field to validate. This is used for error facing validation messages and element identification.
* @param input The actual user input data to validate.
* @param type The regular expression name which maps to the actual regular expression from "ESAPI.properties".
* @param maxLength The maximum post-canonicalized String length allowed.
* @param allowNull If allowNull is true then a input that is NULL or an empty string will be legal. If allowNull is false then NULL or an empty String will throw a ValidationException.
* @return The canonicalized user input.
* @throws ValidationException
* @throws IntrusionException
*/
public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws ValidationException {
return getValidInput(context, input, type, maxLength, allowNull, true);
}
/**
* Validates data received from the browser and returns a safe version. Only
* URL encoding is supported. Double encoding is treated as an attack.
*
* @param context A descriptive name for the field to validate. This is used for error facing validation messages and element identification.
* @param input The actual user input data to validate.
* @param type The regular expression name which maps to the actual regular expression in the ESAPI validation configuration file
* @param maxLength The maximum String length allowed. If input is canonicalized per the canonicalize argument, then maxLength must be verified after canonicalization
* @param allowNull If allowNull is true then a input that is NULL or an empty string will be legal. If allowNull is false then NULL or an empty String will throw a ValidationException.
* @param canonicalize If canonicalize is true then input will be canonicalized before validation
* @return The user input, may be canonicalized if canonicalize argument is true
* @throws ValidationException
* @throws IntrusionException
*/
public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull, boolean canonicalize) throws ValidationException {
StringValidationRule rvr = new StringValidationRule( type, encoder );
Pattern p = ESAPI.securityConfiguration().getValidationPattern( type );
if ( p != null ) {
rvr.addWhitelistPattern( p );
} else {
// Issue 232 - Specify requested type in exception message - CS
throw new IllegalArgumentException("The selected type [" + type + "] was not set via the ESAPI validation configuration");
}
rvr.setMaximumLength(maxLength);
rvr.setAllowNull(allowNull);
rvr.setCanonicalize(canonicalize);
return rvr.getValid(context, input);
}
/**
* Validates data received from the browser and returns a safe version. Only
* URL encoding is supported. Double encoding is treated as an attack. Input
* is canonicalized by default before validation.
*
* @param context A descriptive name for the field to validate. This is used for error facing validation messages and element identification.
* @param input The actual user input data to validate.
* @param type The regular expression name while maps to the actual regular expression from "ESAPI.properties".
* @param maxLength The maximum String length allowed. If input is canonicalized per the canonicalize argument, then maxLength must be verified after canonicalization
* @param allowNull If allowNull is true then a input that is NULL or an empty string will be legal. If allowNull is false then NULL or an empty String will throw a ValidationException.
* @param errors If ValidationException is thrown, then add to error list instead of throwing out to caller
* @return The canonicalized user input.
* @throws IntrusionException
*/
public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
return getValidInput(context, input, type, maxLength, allowNull, true, errors);
}
/**
* Validates data received from the browser and returns a safe version. Only
* URL encoding is supported. Double encoding is treated as an attack.
*
* @param context A descriptive name for the field to validate. This is used for error facing validation messages and element identification.
* @param input The actual user input data to validate.
* @param type The regular expression name while maps to the actual regular expression from "ESAPI.properties".
* @param maxLength The maximum post-canonicalized String length allowed
* @param allowNull If allowNull is true then a input that is NULL or an empty string will be legal. If allowNull is false then NULL or an empty String will throw a ValidationException.
* @param canonicalize If canonicalize is true then input will be canonicalized before validation
* @param errors If ValidationException is thrown, then add to error list instead of throwing out to caller
* @return The user input, may be canonicalized if canonicalize argument is true
* @throws IntrusionException
*/
public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull, boolean canonicalize, ValidationErrorList errors) throws IntrusionException {
try {
return getValidInput(context, input, type, maxLength, allowNull, canonicalize);
} catch (ValidationException e) {
errors.addError(context, e);
}
return "";
}
/**
* {@inheritDoc}
*/
public boolean isValidDate(String context, String input, DateFormat format, boolean allowNull) throws IntrusionException {
try {
getValidDate( context, input, format, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean isValidDate(String context, String input, DateFormat format, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
getValidDate( context, input, format, allowNull, errors);
return errors.isEmpty();
}
/**
* {@inheritDoc}
*/
public Date getValidDate(String context, String input, DateFormat format, boolean allowNull) throws ValidationException, IntrusionException {
ValidationErrorList vel = new ValidationErrorList();
Date validDate = getValidDate(context, input, format, allowNull, vel);
if (vel.isEmpty()) {
return validDate;
}
throw vel.errors().get(0);
}
/**
* {@inheritDoc}
*/
public Date getValidDate(String context, String input, DateFormat format, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
Date safeDate = null;
DateValidationRule dvr = new DateValidationRule( "SimpleDate", encoder, format);
dvr.setAllowNull(allowNull);
safeDate = dvr.sanitize(context, input, errors);
if (!errors.isEmpty()) {
safeDate = null;
}
// error has been added to list, so return null
return safeDate;
}
/**
* {@inheritDoc}
*/
public boolean isValidSafeHTML(String context, String input, int maxLength, boolean allowNull) throws IntrusionException {
try {
getValidSafeHTML( context, input, maxLength, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean isValidSafeHTML(String context, String input, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
getValidSafeHTML( context, input, maxLength, allowNull);
return true;
} catch( ValidationException e ) {
errors.addError(context, e);
return false;
}
}
/**
* {@inheritDoc}
*
* This implementation relies on the OWASP AntiSamy project.
*/
public String getValidSafeHTML( String context, String input, int maxLength, boolean allowNull ) throws ValidationException, IntrusionException {
HTMLValidationRule hvr = new HTMLValidationRule( "safehtml", encoder );
hvr.setMaximumLength(maxLength);
hvr.setAllowNull(allowNull);
return hvr.getValid(context, input);
}
/**
* {@inheritDoc}
*/
public String getValidSafeHTML(String context, String input, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidSafeHTML(context, input, maxLength, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
return "";
}
/**
* {@inheritDoc}
*/
public boolean isValidCreditCard(String context, String input, boolean allowNull) throws IntrusionException {
try {
getValidCreditCard( context, input, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean isValidCreditCard(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
getValidCreditCard( context, input, allowNull);
return true;
} catch( ValidationException e ) {
errors.addError(context, e);
return false;
}
}
/**
* {@inheritDoc}
*/
public String getValidCreditCard(String context, String input, boolean allowNull) throws ValidationException, IntrusionException {
CreditCardValidationRule ccvr = new CreditCardValidationRule( "creditcard", encoder );
ccvr.setAllowNull(allowNull);
return ccvr.getValid(context, input);
}
/**
* {@inheritDoc}
*/
public String getValidCreditCard(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidCreditCard(context, input, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
return "";
}
/**
* {@inheritDoc}
*
* <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath
* is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real
* path (/private/etc), not the symlink (/etc).</p>
*/
public boolean isValidDirectoryPath(String context, String input, File parent, boolean allowNull) throws IntrusionException {
try {
getValidDirectoryPath( context, input, parent, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*
* <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath
* is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real
* path (/private/etc), not the symlink (/etc).</p>
*/
public boolean isValidDirectoryPath(String context, String input, File parent, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
getValidDirectoryPath( context, input, parent, allowNull);
return true;
} catch( ValidationException e ) {
errors.addError(context, e);
return false;
}
}
/**
* {@inheritDoc}
*/
public String getValidDirectoryPath(String context, String input, File parent, boolean allowNull) throws ValidationException, IntrusionException {
try {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input directory path required", "Input directory path required: context=" + context + ", input=" + input, context );
}
File dir = new File( input );
// check dir exists and parent exists and dir is inside parent
if ( !dir.exists() ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory, does not exist: context=" + context + ", input=" + input );
}
if ( !dir.isDirectory() ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory, not a directory: context=" + context + ", input=" + input );
}
if ( !parent.exists() ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory, specified parent does not exist: context=" + context + ", input=" + input + ", parent=" + parent );
}
if ( !parent.isDirectory() ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory, specified parent is not a directory: context=" + context + ", input=" + input + ", parent=" + parent );
}
if ( !dir.getCanonicalPath().startsWith(parent.getCanonicalPath() ) ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory, not inside specified parent: context=" + context + ", input=" + input + ", parent=" + parent );
}
// check canonical form matches input
String canonicalPath = dir.getCanonicalPath();
String canonical = fileValidator.getValidInput( context, canonicalPath, "DirectoryName", 255, false);
if ( !canonical.equals( input ) ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context );
}
return canonical;
} catch (Exception e) {
throw new ValidationException( context + ": Invalid directory name", "Failure to validate directory path: context=" + context + ", input=" + input, e, context );
}
}
/**
* {@inheritDoc}
*/
public String getValidDirectoryPath(String context, String input, File parent, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidDirectoryPath(context, input, parent, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
return "";
}
/**
* {@inheritDoc}
*/
public boolean isValidFileName(String context, String input, boolean allowNull) throws IntrusionException {
return isValidFileName( context, input, ESAPI.securityConfiguration().getAllowedFileExtensions(), allowNull );
}
/**
* {@inheritDoc}
*/
public boolean isValidFileName(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
return isValidFileName( context, input, ESAPI.securityConfiguration().getAllowedFileExtensions(), allowNull, errors );
}
/**
* {@inheritDoc}
*/
public boolean isValidFileName(String context, String input, List<String> allowedExtensions, boolean allowNull) throws IntrusionException {
try {
getValidFileName( context, input, allowedExtensions, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean isValidFileName(String context, String input, List<String> allowedExtensions, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
getValidFileName( context, input, allowedExtensions, allowNull);
return true;
} catch( ValidationException e ) {
errors.addError(context, e);
return false;
}
}
/**
* {@inheritDoc}
*/
public String getValidFileName(String context, String input, List<String> allowedExtensions, boolean allowNull) throws ValidationException, IntrusionException {
if ((allowedExtensions == null) || (allowedExtensions.isEmpty())) {
throw new ValidationException( "Internal Error", "getValidFileName called with an empty or null list of allowed Extensions, therefore no files can be uploaded" );
}
String canonical = "";
// detect path manipulation
try {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input file name required", "Input required: context=" + context + ", input=" + input, context );
}
// do basic validation
canonical = new File(input).getCanonicalFile().getName();
getValidInput( context, input, "FileName", 255, true );
File f = new File(canonical);
String c = f.getCanonicalPath();
String cpath = c.substring(c.lastIndexOf(File.separator) + 1);
// the path is valid if the input matches the canonical path
if (!input.equals(cpath)) {
throw new ValidationException( context + ": Invalid file name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context );
}
} catch (IOException e) {
throw new ValidationException( context + ": Invalid file name", "Invalid file name does not exist: context=" + context + ", canonical=" + canonical, e, context );
}
// verify extensions
Iterator<String> i = allowedExtensions.iterator();
while (i.hasNext()) {
String ext = i.next();
if (input.toLowerCase().endsWith(ext.toLowerCase())) {
return canonical;
}
}
throw new ValidationException( context + ": Invalid file name does not have valid extension ( "+allowedExtensions+")", "Invalid file name does not have valid extension ( "+allowedExtensions+"): context=" + context+", input=" + input, context );
}
/**
* {@inheritDoc}
*/
public String getValidFileName(String context, String input, List<String> allowedParameters, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidFileName(context, input, allowedParameters, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
return "";
}
/**
* {@inheritDoc}
*/
public boolean isValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws IntrusionException {
try {
getValidNumber(context, input, minValue, maxValue, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean isValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
getValidNumber(context, input, minValue, maxValue, allowNull);
return true;
} catch( ValidationException e ) {
errors.addError(context, e);
return false;
}
}
/**
* {@inheritDoc}
*/
public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws ValidationException, IntrusionException {
Double minDoubleValue = new Double(minValue);
Double maxDoubleValue = new Double(maxValue);
return getValidDouble(context, input, minDoubleValue.doubleValue(), maxDoubleValue.doubleValue(), allowNull);
}
/**
* {@inheritDoc}
*/
public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidNumber(context, input, minValue, maxValue, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
return null;
}
/**
* {@inheritDoc}
*/
public boolean isValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws IntrusionException {
try {
getValidDouble( context, input, minValue, maxValue, allowNull );
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean isValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
getValidDouble( context, input, minValue, maxValue, allowNull );
return true;
} catch( ValidationException e ) {
errors.addError(context, e);
return false;
}
}
/**
* {@inheritDoc}
*/
public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws ValidationException, IntrusionException {
NumberValidationRule nvr = new NumberValidationRule( "number", encoder, minValue, maxValue );
nvr.setAllowNull(allowNull);
return nvr.getValid(context, input);
}
/**
* {@inheritDoc}
*/
public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidDouble(context, input, minValue, maxValue, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
return new Double(Double.NaN);
}
/**
* {@inheritDoc}
*/
public boolean isValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws IntrusionException {
try {
getValidInteger( context, input, minValue, maxValue, allowNull);
return true;
} catch( ValidationException e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean isValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
getValidInteger( context, input, minValue, maxValue, allowNull);
return true;
} catch( ValidationException e ) {
errors.addError(context, e);
return false;
}
}
/**
* {@inheritDoc}
*/
public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws ValidationException, IntrusionException {
IntegerValidationRule ivr = new IntegerValidationRule( "number", encoder, minValue, maxValue );
ivr.setAllowNull(allowNull);
return ivr.getValid(context, input);
}
/**
* {@inheritDoc}
*/
public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidInteger(context, input, minValue, maxValue, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return null;
}
/**
* {@inheritDoc}
*/
public boolean isValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws IntrusionException {
try {
getValidFileContent( context, input, maxBytes, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean isValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
getValidFileContent( context, input, maxBytes, allowNull);
return true;
} catch( ValidationException e ) {
errors.addError(context, e);
return false;
}
}
/**
* {@inheritDoc}
*/
public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws ValidationException, IntrusionException {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input required", "Input required: context=" + context + ", input=" + Arrays.toString(input), context );
}
long esapiMaxBytes = ESAPI.securityConfiguration().getAllowedFileUploadSize();
if (input.length > esapiMaxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + esapiMaxBytes + " bytes", "Exceeded ESAPI max length", context );
if (input.length > maxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + maxBytes + " bytes", "Exceeded maxBytes ( " + input.length + ")", context );
return input;
}
/**
* {@inheritDoc}
*/
public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidFileContent(context, input, maxBytes, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// return empty byte array on error
return new byte[0];
}
/**
* {@inheritDoc}
*
* <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath
* is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real
* path (/private/etc), not the symlink (/etc).</p>
*/
public boolean isValidFileUpload(String context, String directorypath, String filename, File parent, byte[] content, int maxBytes, boolean allowNull) throws IntrusionException {
return( isValidFileName( context, filename, allowNull ) &&
isValidDirectoryPath( context, directorypath, parent, allowNull ) &&
isValidFileContent( context, content, maxBytes, allowNull ) );
}
/**
* {@inheritDoc}
*
* <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath
* is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real
* path (/private/etc), not the symlink (/etc).</p>
*/
public boolean isValidFileUpload(String context, String directorypath, String filename, File parent, byte[] content, int maxBytes, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
return( isValidFileName( context, filename, allowNull, errors ) &&
isValidDirectoryPath( context, directorypath, parent, allowNull, errors ) &&
isValidFileContent( context, content, maxBytes, allowNull, errors ) );
}
/**
* {@inheritDoc}
*/
public void assertValidFileUpload(String context, String directorypath, String filename, File parent, byte[] content, int maxBytes, List<String> allowedExtensions, boolean allowNull) throws ValidationException, IntrusionException {
getValidFileName( context, filename, allowedExtensions, allowNull );
getValidDirectoryPath( context, directorypath, parent, allowNull );
getValidFileContent( context, content, maxBytes, allowNull );
}
/**
* {@inheritDoc}
*/
public void assertValidFileUpload(String context, String filepath, String filename, File parent, byte[] content, int maxBytes, List<String> allowedExtensions, boolean allowNull, ValidationErrorList errors)
throws IntrusionException {
try {
assertValidFileUpload(context, filepath, filename, parent, content, maxBytes, allowedExtensions, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
}
/**
* {@inheritDoc}
*
* Returns true if input is a valid list item.
*/
public boolean isValidListItem(String context, String input, List<String> list) {
try {
getValidListItem( context, input, list);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*
* Returns true if input is a valid list item.
*/
public boolean isValidListItem(String context, String input, List<String> list, ValidationErrorList errors) {
try {
getValidListItem( context, input, list);
return true;
} catch( ValidationException e ) {
errors.addError(context, e);
return false;
}
}
/**
* Returns the list item that exactly matches the canonicalized input. Invalid or non-matching input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public String getValidListItem(String context, String input, List<String> list) throws ValidationException, IntrusionException {
if (list.contains(input)) return input;
throw new ValidationException( context + ": Invalid list item", "Invalid list item: context=" + context + ", input=" + input, context );
}
/**
* ValidationErrorList variant of getValidListItem
*
* @param errors
*/
public String getValidListItem(String context, String input, List<String> list, ValidationErrorList errors) throws IntrusionException {
try {
return getValidListItem(context, input, list);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return input;
}
/**
* {@inheritDoc}
*/
public boolean isValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> requiredNames, Set<String> optionalNames) {
try {
assertValidHTTPRequestParameterSet( context, request, requiredNames, optionalNames);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public boolean isValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> requiredNames, Set<String> optionalNames, ValidationErrorList errors) {
try {
assertValidHTTPRequestParameterSet( context, request, requiredNames, optionalNames);
return true;
} catch( ValidationException e ) {
errors.addError(context, e);
return false;
}
}
/**
* Validates that the parameters in the current request contain all required parameters and only optional ones in
* addition. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*
* Uses current HTTPRequest
*/
public void assertValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> required, Set<String> optional) throws ValidationException, IntrusionException {
Set<String> actualNames = request.getParameterMap().keySet();
// verify ALL required parameters are present
Set<String> missing = new HashSet<String>(required);
missing.removeAll(actualNames);
if (missing.size() > 0) {
throw new ValidationException( context + ": Invalid HTTP request missing parameters", "Invalid HTTP request missing parameters " + missing + ": context=" + context, context );
}
// verify ONLY optional + required parameters are present
Set<String> extra = new HashSet<String>(actualNames);
extra.removeAll(required);
extra.removeAll(optional);
if (extra.size() > 0) {
throw new ValidationException( context + ": Invalid HTTP request extra parameters " + extra, "Invalid HTTP request extra parameters " + extra + ": context=" + context, context );
}
}
/**
* ValidationErrorList variant of assertIsValidHTTPRequestParameterSet
*
* Uses current HTTPRequest saved in ESAPI Authenticator
* @param errors
*/
public void assertValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> required, Set<String> optional, ValidationErrorList errors) throws IntrusionException {
try {
assertValidHTTPRequestParameterSet(context, request, required, optional);
} catch (ValidationException e) {
errors.addError(context, e);
}
}
/**
* {@inheritDoc}
*
* Checks that all bytes are valid ASCII characters (between 33 and 126
* inclusive). This implementation does no decoding. http://en.wikipedia.org/wiki/ASCII.
*/
public boolean isValidPrintable(String context, char[] input, int maxLength, boolean allowNull) throws IntrusionException {
try {
getValidPrintable( context, input, maxLength, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*
* Checks that all bytes are valid ASCII characters (between 33 and 126
* inclusive). This implementation does no decoding. http://en.wikipedia.org/wiki/ASCII.
*/
public boolean isValidPrintable(String context, char[] input, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
getValidPrintable( context, input, maxLength, allowNull);
return true;
} catch( ValidationException e ) {
errors.addError(context, e);
return false;
}
}
/**
* Returns canonicalized and validated printable characters as a byte array. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*
* @throws IntrusionException
*/
public char[] getValidPrintable(String context, char[] input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException(context + ": Input bytes required", "Input bytes required: HTTP request is null", context );
}