Skip to content
Permalink
Browse files Browse the repository at this point in the history
Fix path traversal vulnerability
  • Loading branch information
jarofghosts committed Feb 2, 2023
1 parent cb27565 commit 8cecfe9
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 8 deletions.
12 changes: 6 additions & 6 deletions index.js
Expand Up @@ -24,7 +24,7 @@ function Glance(options) {
this.port = options.port
this.hideindex = options.hideindex
this.indices = options.indices
this.dir = path.normalize(options.dir)
this.dir = path.resolve(options.dir)
this.nodot = options.nodot

return this
Expand Down Expand Up @@ -72,7 +72,7 @@ Glance.prototype.serveRequest = function Glance$serveRequest(req, res) {
request.response = res

// prevent traversing directories that are parents of the root
if (request.fullPath.slice(0, self.dir.length) !== self.dir) {
if (path.relative(self.dir, request.fullPath).startsWith('..')) {
return self.emit('error', 403, request, res)
}

Expand Down Expand Up @@ -193,10 +193,10 @@ function renderPage(title, body, res) {

function errorTitle(errorCode) {
var mappings = {
'404': 'File Not Found',
'403': 'Forbidden',
'405': 'Method Not Allowed',
'500': 'Internal Server Error',
404: 'File Not Found',
403: 'Forbidden',
405: 'Method Not Allowed',
500: 'Internal Server Error',
}
return mappings[errorCode.toString()]
}
Expand Down
1 change: 1 addition & 0 deletions test/glance-test-exploit/secret.txt
@@ -0,0 +1 @@
wee
35 changes: 33 additions & 2 deletions test/index.js
@@ -1,4 +1,5 @@
var http = require('http')
var net = require('net')

var test = require('tape')

Expand Down Expand Up @@ -74,8 +75,38 @@ test('403s on dir list if configured', function (t) {
test('fails if path traversal is attempted', function (t) {
t.plan(1)

http.get('http://localhost:1666/../index.js', function (res) {
t.notStrictEqual(res.statusCode, 200)
var socket = new net.Socket()
socket.connect(1666, 'localhost', function () {
socket.on('data', function (data) {
var result = data.toString().split('\n')[0]
t.equals(result.trim(), 'HTTP/1.1 403 Forbidden')
socket.end()
})
socket.write(`GET /../index.js HTTP/1.1
Host: localhost
user-agent: test/1.2.3
accept: */*
`)
})
})

test('fails if path traversal with conveniently-named directory is attempted', function (t) {
t.plan(1)

var socket = new net.Socket()
socket.connect(1666, 'localhost', function () {
socket.on('data', function (data) {
var result = data.toString().split('\n')[0]
t.equals(result.trim(), 'HTTP/1.1 403 Forbidden')
socket.end()
})
socket.write(`GET /../glance-test-exploit/secret.txt HTTP/1.1
Host: localhost
user-agent: test/1.2.3
accept: */*
`)
})
})

Expand Down

0 comments on commit 8cecfe9

Please sign in to comment.