File tree 2 files changed +34
-3
lines changed
2 files changed +34
-3
lines changed Original file line number Diff line number Diff line change 6
6
module . exports = isUrl ;
7
7
8
8
/**
9
- * Matcher.
9
+ * RegExps.
10
+ * A URL must match #1 and then at least one of #2/#3.
11
+ * Use two levels of REs to avoid REDOS.
10
12
*/
11
13
12
- var matcher = / ^ (?: \w + : ) ? \/ \/ ( [ ^ \s \. ] + \. \S { 2 } | l o c a l h o s t [ \: ? \d ] * ) \S * $ / ;
14
+ var protocolAndDomainRE = / ^ (?: \w + : ) ? \/ \/ ( \S + ) $ / ;
15
+
16
+ var localhostDomainRE = / ^ l o c a l h o s t [ \: ? \d ] * (?: [ ^ \: ? \d ] \S * ) ? $ /
17
+ var nonLocalhostDomainRE = / ^ [ ^ \s \. ] + \. \S { 2 , } $ / ;
13
18
14
19
/**
15
20
* Loosely validate a URL `string`.
@@ -19,5 +24,20 @@ var matcher = /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/;
19
24
*/
20
25
21
26
function isUrl ( string ) {
22
- return matcher . test ( string ) ;
27
+ var match = string . match ( protocolAndDomainRE ) ;
28
+ if ( ! match ) {
29
+ return false ;
30
+ }
31
+
32
+ var everythingAfterProtocol = match [ 1 ] ;
33
+ if ( ! everythingAfterProtocol ) {
34
+ return false ;
35
+ }
36
+
37
+ if ( localhostDomainRE . test ( everythingAfterProtocol ) ||
38
+ nonLocalhostDomainRE . test ( everythingAfterProtocol ) ) {
39
+ return true ;
40
+ }
41
+
42
+ return false ;
23
43
}
Original file line number Diff line number Diff line change @@ -119,4 +119,15 @@ describe('is-url', function () {
119
119
assert ( ! url ( 'google.com' ) ) ;
120
120
} ) ;
121
121
} ) ;
122
+
123
+ describe ( 'redos' , function ( ) {
124
+ it ( 'redos exploit' , function ( ) {
125
+ // Invalid. This should be discovered in under 1 second.
126
+ var attackString = 'a://localhost' + '9' . repeat ( 100000 ) + '\t' ;
127
+ var before = process . hrtime ( ) ;
128
+ assert ( ! url ( attackString ) , 'attackString was valid' ) ;
129
+ var elapsed = process . hrtime ( before ) ;
130
+ assert ( elapsed [ 0 ] < 1 , 'attackString took ' + elapsed [ 0 ] + ' > 1 seconds' ) ;
131
+ } ) ;
132
+ } ) ;
122
133
} ) ;
You can’t perform that action at this time.
0 commit comments