Skip to content

Commit 5a039bc

Browse files
committed
Fix additional hole in solution to exercise 20.2
Issue marijnh#226
1 parent af8852d commit 5a039bc

File tree

2 files changed

+15
-10
lines changed

2 files changed

+15
-10
lines changed

20_node.txt

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1146,14 +1146,13 @@ system might be used to do bad things to your machine.
11461146
(((replace method)))(((file server example)))(((leak)))(((period
11471147
character)))(((slash character)))(((backslash
11481148
character)))(((decodeURIComponent function)))It is enough to strip out
1149-
all occurrences of two dots that have a slash, a backslash, or
1150-
the end of the string on both sides. Using the `replace` method with a
1151-
((regular expression)) is the easiest way to do this. Do not forget
1152-
the `g` flag on the expression, or `replace` will replace only a
1153-
single instance, and people could still get around this safety measure
1154-
by including additional double dots in their paths! Also make sure you
1155-
do the replace _after_ decoding the string, or it would be possible to
1156-
foil the check by encoding a dot or a slash.
1149+
all occurrences of two dots that have a slash, a backslash, or the end
1150+
of the string on both sides. Using the `replace` method with a
1151+
((regular expression)) is the easiest way to do this. But since such
1152+
instances may overlap (as in `"/../../f"`), you may have to apply
1153+
`replace` multiple times, until the string no longer changes. Also
1154+
make sure you do the replace _after_ decoding the string, or it would
1155+
be possible to foil the check by encoding a dot or a slash.
11571156

11581157
(((path,file system)))(((slash character)))Another potentially
11591158
worrying case is when paths start with a slash, which are interpreted as

code/solutions/20_2_fixing_a_leak.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,12 @@
33

44
function urlToPath(url) {
55
var path = require("url").parse(url).pathname;
6-
var decoded = decodeURIComponent(path);
7-
return "." + decoded.replace(/(\/|\\)\.\.(\/|\\|$)/g, "/");
6+
var result = "." + decodeURIComponent(path);
7+
for (;;) {
8+
// Remove any instances of '/../' or similar
9+
var simplified = result.replace(/(\/|\\)\.\.(\/|\\|$)/, "/");
10+
// Keep doing this until it no longer changes the string
11+
if (simplified == result) return result
12+
result = simplified
13+
}
814
}

0 commit comments

Comments
 (0)