-
Notifications
You must be signed in to change notification settings - Fork 364
/
DefaultHTTPUtilities.java
1179 lines (1038 loc) · 45.2 KB
/
DefaultHTTPUtilities.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 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>
* @created 2007
*/
package org.owasp.esapi.reference;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.HTTPUtilities;
import org.owasp.esapi.Logger;
import org.owasp.esapi.PropNames;
import org.owasp.esapi.SecurityConfiguration;
import org.owasp.esapi.StringUtilities;
import org.owasp.esapi.User;
import org.owasp.esapi.ValidationErrorList;
import org.owasp.esapi.codecs.Hex;
import org.owasp.esapi.crypto.CipherText;
import org.owasp.esapi.crypto.PlainText;
import org.owasp.esapi.errors.AccessControlException;
import org.owasp.esapi.errors.AuthenticationException;
import org.owasp.esapi.errors.ConfigurationException;
import org.owasp.esapi.errors.EncodingException;
import org.owasp.esapi.errors.EncryptionException;
import org.owasp.esapi.errors.IntegrityException;
import org.owasp.esapi.errors.IntrusionException;
import org.owasp.esapi.errors.ValidationException;
import org.owasp.esapi.errors.ValidationUploadException;
/**
* Reference implementation of the HTTPUtilities interface. This implementation
* uses the Apache Commons FileUploader library, which in turn uses the Apache
* Commons IO library.
* <P>
* To simplify the interface, some methods use the current request and response that
* are tracked by ThreadLocal variables in the Authenticator. This means that you
* must have called ESAPI.authenticator().setCurrentHTTP(request, response) before
* calling these methods.
* <P>
* Typically, this is done by calling the Authenticator.login() method, which
* calls setCurrentHTTP() automatically. However if you want to use these methods
* in another application, you should explicitly call setCurrentHTTP() in your
* own code. In either case, you *must* call ESAPI.clearCurrent() to clear threadlocal
* variables before the thread is reused. The advantages of having identity everywhere
* outweigh the disadvantages of this approach.
*
* @author Jeff Williams (jeff.williams .at. aspectsecurity.com) <a
* href="http://www.aspectsecurity.com">Aspect Security</a>
* @since June 1, 2007
* @see org.owasp.esapi.HTTPUtilities
*/
public class DefaultHTTPUtilities implements org.owasp.esapi.HTTPUtilities {
private static volatile HTTPUtilities instance = null;
// Apache Commons FileUpload property for enabling / disabling Java deserialization via file uploads.
// ESAPI will save current value, set it to "false", and then restore value before returning. GitHub issue #417.
private static String DISKFILEITEM_SERIALIZABLE = "org.apache.commons.fileupload.disk.DiskFileItem.serializable";
public static HTTPUtilities getInstance() {
if ( instance == null ) {
synchronized ( DefaultHTTPUtilities.class ) {
if ( instance == null ) {
instance = new DefaultHTTPUtilities();
}
}
}
return instance;
}
/**
* Defines the ThreadLocalRequest to store the current request for this thread.
*/
private class ThreadLocalRequest extends InheritableThreadLocal<HttpServletRequest> {
public HttpServletRequest getRequest() {
return super.get();
}
public HttpServletRequest initialValue() {
return null;
}
public void setRequest(HttpServletRequest newRequest) {
super.set(newRequest);
}
}
/**
* Defines the ThreadLocalResponse to store the current response for this thread.
*/
private class ThreadLocalResponse extends InheritableThreadLocal<HttpServletResponse> {
public HttpServletResponse getResponse() {
return super.get();
}
public HttpServletResponse initialValue() {
return null;
}
public void setResponse(HttpServletResponse newResponse) {
super.set(newResponse);
}
}
/** The logger. */
private final Logger logger = ESAPI.getLogger("HTTPUtilities");
/** The max bytes. */
static final int maxBytes = ESAPI.securityConfiguration().getAllowedFileUploadSize();
/** The max # of files per request. */
static int maxFiles = 20; // Same as default in configuration/esapi/ESAPI.properties
static boolean fileUploadAllowAnonymousUsers = true;
static {
// OPENISSUE - Not sure if we should log this. I can throw because the
// property is not set in ESAPI.properties, but it can also throw
// because ESAPI.properties can't be found. If the latter is the case,
// then trying to log it would cause another ConfigurationException to
// be thrown while trying do the logging making the exception stack
// traces even more obtuse. And I don't want to spend then next 5 years
// answering Stack Overflow questions about that.
try {
maxFiles = ESAPI.securityConfiguration().getIntProp( PropNames.MAX_UPLOAD_FILE_COUNT );
} catch ( ConfigurationException ex ) {
// TODO: Figure out what we want to do log this. See OPENISSUE, above.
System.err.println("WARNING: Caught exception looking for property " + PropNames.MAX_UPLOAD_FILE_COUNT +
" in ESAPI.properties. Using hard-coded default of " + maxFiles +
"; exception was: " + ex);
}
try {
fileUploadAllowAnonymousUsers = ESAPI.securityConfiguration().getBooleanProp( PropNames.FILEUPLOAD_ALLOW_ANONYMOUS_USERS );
} catch ( ConfigurationException ex ) {
// This likely will be the normal case (because ESAPI clients seldom update
// their ESAPI.properties file from release to release. Therefore, I am
// going to ignore it, and we silently go with the default of 'false'.
; // Intentionally ignore!
}
}
/*
* The currentRequest ThreadLocal variable is used to make the currentRequest available to any call in any part of an
* application. This enables API's for actions that require the request to be much simpler. For example, the logout()
* method in the Authenticator class requires the currentRequest to get the session in order to invalidate it.
*/
private ThreadLocalRequest currentRequest = new ThreadLocalRequest();
/*
* The currentResponse ThreadLocal variable is used to make the currentResponse available to any call in any part of an
* application. This enables API's for actions that require the response to be much simpler. For example, the logout()
* method in the Authenticator class requires the currentResponse to kill the Session ID cookie.
*/
private ThreadLocalResponse currentResponse = new ThreadLocalResponse();
/**
* No arg constructor.
*/
public DefaultHTTPUtilities() { // Public CTOR for singletons. SMH. Sigh.
}
/**
* {@inheritDoc}
* This implementation uses a custom "set-cookie" header rather than Java's
* cookie interface which doesn't allow the use of HttpOnly. Configure the
* HttpOnly and Secure settings in ESAPI.properties.
*/
public void addCookie( Cookie cookie ) {
addCookie( getCurrentResponse(), cookie );
}
/**
* {@inheritDoc}
* This implementation uses a custom "set-cookie" header rather than Java's
* cookie interface which doesn't allow the use of HttpOnly. Configure the
* HttpOnly and Secure settings in ESAPI.properties.
*/
public void addCookie(HttpServletResponse response, Cookie cookie) {
String name = cookie.getName();
String value = cookie.getValue();
int maxAge = cookie.getMaxAge();
String domain = cookie.getDomain();
String path = cookie.getPath();
boolean secure = cookie.getSecure();
// validate the name and value
ValidationErrorList errors = new ValidationErrorList();
SecurityConfiguration sc = ESAPI.securityConfiguration();
String cookieName = ESAPI.validator().getValidInput("cookie name", name, "HTTPCookieName", sc.getIntProp("HttpUtilities.MaxHeaderNameSize"), false, errors);
String cookieValue = ESAPI.validator().getValidInput("cookie value", value, "HTTPCookieValue", sc.getIntProp("HttpUtilities.MaxHeaderValueSize"), false, errors);
// if there are no errors, then set the cookie either with a header or normally
if (errors.size() == 0) {
if ( ESAPI.securityConfiguration().getForceHttpOnlyCookies() ) {
String header = createCookieHeader(cookieName, cookieValue, maxAge, domain, path, secure);
addHeader(response, "Set-Cookie", header);
} else {
// Issue 23 - If the ESAPI Configuration is set to force secure cookies, force the secure flag on the cookie before setting it
cookie.setSecure( secure || ESAPI.securityConfiguration().getForceSecureCookies() );
response.addCookie(cookie);
}
return;
}
logger.warning(Logger.SECURITY_FAILURE, "Attempt to add unsafe data to cookie (skip mode). Skipping cookie and continuing.");
}
/**
* {@inheritDoc}
*/
public String addCSRFToken(String href) {
User user = ESAPI.authenticator().getCurrentUser();
if (user.isAnonymous()) {
return href;
}
// if there are already parameters append with &, otherwise append with ?
String token = CSRF_TOKEN_NAME + "=" + user.getCSRFToken();
return href.indexOf( '?') != -1 ? href + "&" + token : href + "?" + token;
}
/**
* {@inheritDoc}
*/
public void addHeader(String name, String value) {
addHeader( getCurrentResponse(), name, value );
}
/**
* {@inheritDoc}
*/
public void addHeader(HttpServletResponse response, String name, String value) {
SecurityConfiguration sc = ESAPI.securityConfiguration();
try {
String strippedName = StringUtilities.replaceLinearWhiteSpace(name);
String strippedValue = StringUtilities.replaceLinearWhiteSpace(value);
String safeName = ESAPI.validator().getValidInput("addHeader", strippedName, "HTTPHeaderName", sc.getIntProp("HttpUtilities.MaxHeaderNameSize"), false);
String safeValue = ESAPI.validator().getValidInput("addHeader", strippedValue, "HTTPHeaderValue", sc.getIntProp("HttpUtilities.MaxHeaderValueSize"), false);
response.addHeader(safeName, safeValue);
} catch (ValidationException e) {
logger.warning(Logger.SECURITY_FAILURE, "Attempt to add invalid header denied", e);
}
}
/**
* {@inheritDoc}
*/
public void assertSecureChannel() throws AccessControlException {
assertSecureChannel( getCurrentRequest() );
}
/**
* {@inheritDoc}
*
* This implementation ignores the built-in isSecure() method
* and uses the URL to determine if the request was transmitted over SSL.
* This is because SSL may have been terminated somewhere outside the
* container.
*/
public void assertSecureChannel(HttpServletRequest request) throws AccessControlException {
if ( request == null ) {
throw new AccessControlException( "Insecure request received", "HTTP request was null" );
}
StringBuffer sb = request.getRequestURL();
if ( sb == null ) {
throw new AccessControlException( "Insecure request received", "HTTP request URL was null" );
}
String url = sb.toString();
if ( !url.startsWith( "https" ) ) {
throw new AccessControlException( "Insecure request received", "HTTP request did not use SSL" );
}
}
/**
* {@inheritDoc}
*/
public void assertSecureRequest() throws AccessControlException {
assertSecureRequest( getCurrentRequest() );
}
/**
* {@inheritDoc}
*/
public void assertSecureRequest(HttpServletRequest request) throws AccessControlException {
assertSecureChannel( request );
String receivedMethod = request.getMethod();
String requiredMethod = "POST";
if ( !receivedMethod.equals( requiredMethod ) ) {
throw new AccessControlException( "Insecure request received", "Received request using " + receivedMethod + " when only " + requiredMethod + " is allowed" );
}
}
/**
* {@inheritDoc}
*/
public HttpSession changeSessionIdentifier() throws AuthenticationException {
return changeSessionIdentifier( getCurrentRequest() );
}
/**
* {@inheritDoc}
*/
public HttpSession changeSessionIdentifier(HttpServletRequest request) throws AuthenticationException {
// get the current session
HttpSession oldSession = request.getSession();
// make a copy of the session content
Map<String,Object> temp = new ConcurrentHashMap<String,Object>();
Enumeration e = oldSession.getAttributeNames();
while (e != null && e.hasMoreElements()) {
String name = (String) e.nextElement();
Object value = oldSession.getAttribute(name);
temp.put(name, value);
}
// kill the old session and create a new one
oldSession.invalidate();
HttpSession newSession = request.getSession();
User user = ESAPI.authenticator().getCurrentUser();
user.addSession( newSession );
user.removeSession( oldSession );
// copy back the session content
for (Map.Entry<String, Object> stringObjectEntry : temp.entrySet())
{
newSession.setAttribute(stringObjectEntry.getKey(), stringObjectEntry.getValue());
}
return newSession;
}
/**
* {@inheritDoc}
*/
public void clearCurrent() {
currentRequest.set(null);
currentResponse.set(null);
}
private String createCookieHeader(String name, String value, int maxAge, String domain, String path, boolean secure) {
// create the special cookie header instead of creating a Java cookie
// Set-Cookie:<name>=<value>[; <name>=<value>][; expires=<date>][;
// domain=<domain_name>][; path=<some_path>][; secure][;HttpOnly]
String header = name + "=" + value;
if (maxAge >= 0) {
header += "; Max-Age=" + maxAge;
}
if (domain != null) {
header += "; Domain=" + domain;
}
if (path != null) {
header += "; Path=" + path;
}
if ( secure || ESAPI.securityConfiguration().getForceSecureCookies() ) {
header += "; Secure";
}
if ( ESAPI.securityConfiguration().getForceHttpOnlyCookies() ) {
header += "; HttpOnly";
}
return header;
}
/**
* {@inheritDoc}
*/
public String decryptHiddenField(String encrypted) {
try {
return decryptString(encrypted);
} catch( EncryptionException e ) {
throw new IntrusionException("Invalid request","Tampering detected. Hidden field data did not decrypt properly.", e);
}
}
/**
* {@inheritDoc}
*/
public Map<String,String> decryptQueryString(String encrypted) throws EncryptionException {
String plaintext = decryptString(encrypted);
return queryToMap(plaintext);
}
/**
* {@inheritDoc}
*/
public Map<String,String> decryptStateFromCookie() throws EncryptionException {
return decryptStateFromCookie( getCurrentRequest() );
}
/**
* {@inheritDoc}
*
* @param request
*/
public Map<String,String> decryptStateFromCookie(HttpServletRequest request) throws EncryptionException {
try {
String encrypted = getCookie( request, ESAPI_STATE );
if ( encrypted == null ) return new HashMap<String,String>();
String plaintext = decryptString(encrypted);
return queryToMap( plaintext );
} catch( ValidationException e ) {
return null;
}
}
/**
* {@inheritDoc}
*/
public String encryptHiddenField(String value) throws EncryptionException {
return encryptString(value);
}
/**
* {@inheritDoc}
*/
public String encryptQueryString(String query) throws EncryptionException {
return encryptString(query);
}
/**
* {@inheritDoc}
*/
public void encryptStateInCookie(HttpServletResponse response, Map<String,String> cleartext) throws EncryptionException {
StringBuilder sb = new StringBuilder();
Iterator i = cleartext.entrySet().iterator();
while ( i.hasNext() ) {
try {
Map.Entry entry = (Map.Entry)i.next();
// What do these need to be URL encoded? They are encrypted!
String name = ESAPI.encoder().encodeForURL( entry.getKey().toString() );
String value = ESAPI.encoder().encodeForURL( entry.getValue().toString() );
sb.append(name).append("=").append(value);
if ( i.hasNext() ) sb.append( "&" );
} catch( EncodingException e ) {
logger.error(Logger.SECURITY_FAILURE, "Problem encrypting state in cookie - skipping entry", e );
}
}
String encrypted = encryptString(sb.toString());
if ( encrypted.length() > (MAX_COOKIE_LEN ) ) {
logger.error(Logger.SECURITY_FAILURE, "Problem encrypting state in cookie - skipping entry");
throw new EncryptionException("Encryption failure", "Encrypted cookie state of " + encrypted.length() + " longer than allowed " + MAX_COOKIE_LEN );
}
Cookie cookie = new Cookie( ESAPI_STATE, encrypted );
addCookie( response, cookie );
}
/**
* {@inheritDoc}
*/
public void encryptStateInCookie( Map<String,String> cleartext ) throws EncryptionException {
encryptStateInCookie( getCurrentResponse(), cleartext );
}
/**
* {@inheritDoc}
*/
public String getCookie( HttpServletRequest request, String name ) throws ValidationException {
Cookie c = getFirstCookie( request, name );
SecurityConfiguration sc = ESAPI.securityConfiguration();
if ( c == null ) return null;
String value = c.getValue();
return ESAPI.validator().getValidInput("HTTP cookie value: " + value, value, "HTTPCookieValue", sc.getIntProp("HttpUtilities.MaxHeaderValueSize"), false);
}
/**
* {@inheritDoc}
*/
public String getCookie( String name ) throws ValidationException {
return getCookie( getCurrentRequest(), name );
}
/**
* {@inheritDoc}
*/
public String getCSRFToken() {
User user = ESAPI.authenticator().getCurrentUser();
if (user == null) return null;
return user.getCSRFToken();
}
/**
* {@inheritDoc}
*/
public HttpServletRequest getCurrentRequest() {
return currentRequest.getRequest();
}
/**
* {@inheritDoc}
*/
public HttpServletResponse getCurrentResponse() {
return currentResponse.getResponse();
}
/**
* {@inheritDoc}
*/
public List<File> getFileUploads() throws ValidationException {
return getFileUploads( getCurrentRequest(), ESAPI.securityConfiguration().getUploadDirectory(), ESAPI.securityConfiguration().getAllowedFileExtensions() );
}
/**
* {@inheritDoc}
*/
public List<File> getFileUploads(HttpServletRequest request) throws ValidationException {
return getFileUploads(request, ESAPI.securityConfiguration().getUploadDirectory(), ESAPI.securityConfiguration().getAllowedFileExtensions());
}
/**
* {@inheritDoc}
*/
public List<File> getFileUploads(HttpServletRequest request, File finalDir ) throws ValidationException {
return getFileUploads(request, finalDir, ESAPI.securityConfiguration().getAllowedFileExtensions());
}
/**
* {@inheritDoc}
*/
public List<File> getFileUploads(HttpServletRequest request, File finalDir, List allowedExtensions) throws ValidationException {
File tempDir = ESAPI.securityConfiguration().getUploadTempDirectory();
if ( !tempDir.exists() ) {
if ( !tempDir.mkdirs() ) throw new ValidationUploadException( "Upload failed", "Could not create temp directory: " + tempDir.getAbsolutePath() );
}
if( finalDir != null){
if ( !finalDir.exists() ) {
if ( !finalDir.mkdirs() ) throw new ValidationUploadException( "Upload failed", "Could not create final upload directory: " + finalDir.getAbsolutePath() );
}
}
else {
if ( !ESAPI.securityConfiguration().getUploadDirectory().exists()) {
if ( !ESAPI.securityConfiguration().getUploadDirectory().mkdirs() ) throw new ValidationUploadException( "Upload failed", "Could not create final upload directory: " + ESAPI.securityConfiguration().getUploadDirectory().getAbsolutePath() );
}
finalDir = ESAPI.securityConfiguration().getUploadDirectory();
}
// Check if this user should be blocked from file upload access. See allowUserFileUploadAccess() and comments
// around 'HttpUtilities.FileUploadAllowAnonymousUser' in ESAPI.properties file for details.
if ( ! allowUserFileUploadAccess() ) {
final String authZErrorMsg = "Upload failed. Anonymous user disallowed by ESAPI property " +
"'HttpUtilities.FileUploadAllowAnonymousUser'; attempted file upload blocked.";
logger.warning(Logger.SECURITY_FAILURE, authZErrorMsg);
throw new java.security.AccessControlException( authZErrorMsg );
}
List<File> newFiles = new ArrayList<File>();
String dfiPrevValue = "false"; // Fail safely in case of Java Security Manager & weird security policy
try {
dfiPrevValue = System.getProperty(DISKFILEITEM_SERIALIZABLE);
System.setProperty(DISKFILEITEM_SERIALIZABLE, "false");
final HttpSession session = request.getSession(false);
if (!ServletFileUpload.isMultipartContent(request)) {
throw new ValidationUploadException("Upload failed", "Not a multipart request");
}
// this factory will store ALL files in the temp directory, regardless of size
DiskFileItemFactory factory = new DiskFileItemFactory(0, tempDir);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxBytes);
upload.setFileCountMax(maxFiles); // Required to address CVE-2023-24998.
// Create a progress listener
ProgressListener progressListener = new ProgressListener() {
private long megaBytes = -1;
private long progress = 0;
public void update(long pBytesRead, long pContentLength, int pItems) {
if (pItems == 0)
return;
long mBytes = pBytesRead / 1000000;
if (megaBytes == mBytes)
return;
megaBytes = mBytes;
progress = (long) (((double) pBytesRead / (double) pContentLength) * 100);
if ( session != null ) {
session.setAttribute("progress", Long.toString(progress));
}
// logger.logSuccess(Logger.SECURITY, " Item " + pItems + " (" + progress + "% of " + pContentLength + " bytes]");
}
};
upload.setProgressListener(progressListener);
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items)
{
if (!item.isFormField() && item.getName() != null && !(item.getName().equals("")))
{
String[] fparts = item.getName().split("[\\/\\\\]");
String filename = fparts[fparts.length - 1];
if (!ESAPI.validator().isValidFileName("upload", filename, allowedExtensions, false))
{
throw new ValidationUploadException("Upload only simple filenames with the following extensions " + allowedExtensions, "Upload failed isValidFileName check");
}
logger.info(Logger.SECURITY_SUCCESS, "File upload requested: " + filename);
File f = new File(finalDir, filename);
if (f.exists())
{
String[] parts = filename.split("\\/.");
String extension = "";
if (parts.length > 1)
{
extension = parts[parts.length - 1];
}
String filenm = filename.substring(0, filename.length() - extension.length());
f = File.createTempFile(filenm, "." + extension, finalDir);
}
item.write(f);
newFiles.add(f);
// delete temporary file
item.delete();
logger.fatal(Logger.SECURITY_SUCCESS, "File successfully uploaded: " + f);
if (session != null)
{
session.setAttribute("progress", Long.toString(0));
}
}
}
} catch (Exception e) {
if (e instanceof ValidationUploadException) {
throw (ValidationException)e;
}
throw new ValidationUploadException("Upload failure", "Problem during upload:" + e.getMessage(), e);
}
finally {
if ( dfiPrevValue != null ) {
System.setProperty(DISKFILEITEM_SERIALIZABLE, dfiPrevValue);
}
}
return Collections.synchronizedList(newFiles);
}
/**
* Utility to return the first cookie matching the provided name.
* @param request
* @param name
*/
private Cookie getFirstCookie(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies)
{
if (cookie.getName().equals(name))
{
return cookie;
}
}
}
return null;
}
/**
* {@inheritDoc}
*/
public String getHeader( HttpServletRequest request, String name ) throws ValidationException {
SecurityConfiguration sc = ESAPI.securityConfiguration();
String value = request.getHeader(name);
return ESAPI.validator().getValidInput("HTTP header value: " + value, value, "HTTPHeaderValue", sc.getIntProp("HttpUtilities.MaxHeaderValueSize"), false);
}
/**
* {@inheritDoc}
*/
public String getHeader( String name ) throws ValidationException {
return getHeader( getCurrentRequest(), name );
}
/**
* {@inheritDoc}
*/
public String getParameter( HttpServletRequest request, String name ) throws ValidationException {
String value = request.getParameter(name);
return ESAPI.validator().getValidInput("HTTP parameter value: " + value, value, "HTTPParameterValue", 2000, true);
}
/**
* {@inheritDoc}
*/
public String getParameter( String name ) throws ValidationException {
return getParameter( getCurrentRequest(), name );
}
/**
* {@inheritDoc}
*/
public void killAllCookies() {
killAllCookies( getCurrentRequest(), getCurrentResponse() );
}
/**
* {@inheritDoc}
*
* @param request
* @param response
*/
public void killAllCookies(HttpServletRequest request, HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies)
{
killCookie(request, response, cookie.getName());
}
}
}
/**
* {@inheritDoc}
*
* @param request
* @param response
* @param name
*/
public void killCookie(HttpServletRequest request, HttpServletResponse response, String name) {
String path = "/";
String domain="";
Cookie cookie = getFirstCookie(request, name);
if ( cookie != null ) {
path = cookie.getPath();
domain = cookie.getDomain();
}
Cookie deleter = new Cookie( name, "deleted" );
deleter.setMaxAge( 0 );
if ( domain != null ) deleter.setDomain( domain );
if ( path != null ) deleter.setPath( path );
response.addCookie( deleter );
}
/**
* {@inheritDoc}
*/
public void killCookie( String name ) {
killCookie( getCurrentRequest(), getCurrentResponse(), name );
}
/**
* {@inheritDoc}
*/
public void logHTTPRequest() {
logHTTPRequest( getCurrentRequest(), logger, null );
}
/**
* {@inheritDoc}
*/
public void logHTTPRequest(HttpServletRequest request, Logger logger) {
logHTTPRequest( request, logger, null );
}
/**
* Formats an HTTP request into a log suitable string. This implementation logs the remote host IP address (or
* hostname if available), the request method (GET/POST), the URL, and all the querystring and form parameters. All
* the parameters are presented as though they were in the URL even if they were in a form. Any parameters that
* match items in the parameterNamesToObfuscate are shown as eight asterisks.
*
*
* @param request
*/
public void logHTTPRequest(HttpServletRequest request, Logger logger, List parameterNamesToObfuscate) {
StringBuilder params = new StringBuilder();
Iterator i = request.getParameterMap().keySet().iterator();
while (i.hasNext()) {
String key = (String) i.next();
String[] value = request.getParameterMap().get(key);
for (int j = 0; j < value.length; j++) {
params.append(key).append("=");
if (parameterNamesToObfuscate != null && parameterNamesToObfuscate.contains(key)) {
params.append("********");
} else {
params.append(value[j]);
}
if (j < value.length - 1) {
params.append("&");
}
}
if (i.hasNext())
params.append("&");
}
Cookie[] cookies = request.getCookies();
if ( cookies != null ) {
for (Cookie cooky : cookies)
{
if (!cooky.getName().equals(ESAPI.securityConfiguration().getHttpSessionIdName()))
{
params.append("+").append(cooky.getName()).append("=").append(cooky.getValue());
}
}
}
String msg = request.getMethod() + " " + request.getRequestURL() + (params.length() > 0 ? "?" + params : "");
logger.info(Logger.SECURITY_SUCCESS, msg);
}
private Map<String,String> queryToMap(String query) {
TreeMap<String,String> map = new TreeMap<String,String>();
String[] parts = query.split("&");
for (String part : parts)
{
try
{
String[] nvpair = part.split("=");
String name = ESAPI.encoder().decodeFromURL(nvpair[0]);
String value = ESAPI.encoder().decodeFromURL(nvpair[1]);
map.put(name, value);
}
catch (EncodingException e)
{
// skip the nvpair with the encoding problem - note this is already logged.
}
}
return map;
}
/**
* {@inheritDoc}
*
* This implementation simply checks to make sure that the forward location starts with "WEB-INF" and
* is intended for use in frameworks that forward to JSP files inside the WEB-INF folder.
*/
public void sendForward(HttpServletRequest request, HttpServletResponse response, String location) throws AccessControlException,ServletException,IOException {
if (!location.startsWith("WEB-INF")) {
throw new AccessControlException("Forward failed", "Bad forward location: " + location);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(location);
dispatcher.forward( request, response );
}
/**
* {@inheritDoc}
*/
public void sendForward( String location ) throws AccessControlException,ServletException,IOException {
sendForward( getCurrentRequest(), getCurrentResponse(), location);
}
/**
* {@inheritDoc}
*
* This implementation checks against the list of safe redirect locations defined in ESAPI.properties.
*/
public void sendRedirect(HttpServletResponse response, String location) throws AccessControlException, IOException {
if (!ESAPI.validator().isValidRedirectLocation("Redirect", location, false)) {
logger.fatal(Logger.SECURITY_FAILURE, "Bad redirect location: " + location);
throw new AccessControlException("Redirect failed", "Bad redirect location: " + location);
}
response.sendRedirect(location);
}
/**
* {@inheritDoc}
*/
public void sendRedirect( String location ) throws AccessControlException,IOException {
sendRedirect( getCurrentResponse(), location);
}
/**
* {@inheritDoc}
*/
public void setContentType() {
setContentType( getCurrentResponse() );
}
/**
* {@inheritDoc}
*/
public void setContentType(HttpServletResponse response) {
response.setContentType((ESAPI.securityConfiguration()).getResponseContentType());
}
/**
* {@inheritDoc}
*/
public void setCurrentHTTP(HttpServletRequest request, HttpServletResponse response) {
currentRequest.setRequest(request);
currentResponse.setResponse(response);
}
/**
* {@inheritDoc}
*/
public void setHeader(HttpServletResponse response, String name, String value) {
try {
SecurityConfiguration sc = ESAPI.securityConfiguration();
String strippedName = StringUtilities.replaceLinearWhiteSpace(name);
String strippedValue = StringUtilities.replaceLinearWhiteSpace(value);
String safeName = ESAPI.validator().getValidInput("setHeader", strippedName, "HTTPHeaderName", sc.getIntProp("HttpUtilities.MaxHeaderNameSize"), false);
String safeValue = ESAPI.validator().getValidInput("setHeader", strippedValue, "HTTPHeaderValue", sc.getIntProp("HttpUtilities.MaxHeaderValueSize"), false);
response.setHeader(safeName, safeValue);
} catch (ValidationException e) {
logger.warning(Logger.SECURITY_FAILURE, "Attempt to set invalid header denied", e);
}
}
/**
* {@inheritDoc}
*/
public void setHeader( String name, String value ) {
setHeader( getCurrentResponse(), name, value );
}
/**
* {@inheritDoc}
*/
public void setNoCacheHeaders() {
setNoCacheHeaders( getCurrentResponse() );
}
/**
* {@inheritDoc}
*
* @param response
*/
public void setNoCacheHeaders(HttpServletResponse response) {
// HTTP 1.1
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// HTTP 1.0
response.setHeader("Pragma","no-cache");
response.setDateHeader("Expires", -1);
}
/**
* {@inheritDoc}
*
* Save the user's remember me data in an encrypted cookie and send it to the user.
* Any old remember me cookie is destroyed first. Setting this cookie will keep the user
* logged in until the maxAge passes, the password is changed, or the cookie is deleted.
* If the cookie exists for the current user, it will automatically be used by ESAPI to
* log the user in, if the data is valid and not expired.
*
* @param request
* @param response
*/
public String setRememberToken( HttpServletRequest request, HttpServletResponse response, String password, int maxAge, String domain, String path ) {
User user = ESAPI.authenticator().getCurrentUser();
try {
killCookie(request, response, REMEMBER_TOKEN_COOKIE_NAME );
// seal already contains random data
String clearToken = user.getAccountName() + "|" + password;
long expiry = ESAPI.encryptor().getRelativeTimeStamp(maxAge * 1000);
String cryptToken = ESAPI.encryptor().seal(clearToken, expiry);
SecurityConfiguration sg = ESAPI.securityConfiguration();
boolean forceSecureCookies = sg.getBooleanProp("HttpUtilities.ForceSecureCookies");
boolean forceHttpOnly = sg.getBooleanProp("HttpUtilities.ForceHttpOnlyCookies");
// Do NOT URLEncode cryptToken before creating cookie. See Google Issue # 144,
// which was marked as "WontFix".