Closed richbai90 closed 6 years ago
Whats the motive behind maintaining a whitelist like that? Did you disable the file system routing or are you still using that?
If there is a configuration that I'm missing I don't know. I ran my app through a vulnerability scan and it told me that it could access files outside of the webroot. So I came up with this solution.
Can you provide some more information on the scan that you used and what files it said that it could access? You shouldn't need to whitelist everything like that. Assuming that you are using a custom server, and are not using the filesystem routing, my approach is to:
app.render(req, res, '/my/view', query)
to render the page.app.getRequestHandler()
and then can be called like this handler(req, res, query)
. If it isn't a next build asset, the request will 404.edit: Also how are you running this in production? What is your start command? If it is yarn start
or npm start
what does that map to in your package.json?
I'm using OWASP ZAP scanner. Without any custom server implementation beyond an out of the box un-configured express server, here is what I get while running in development. To fix the xss and xframe concerns I implemented a CSP with a nonce to allow next-script
to execute. For the path traversal I implemented the whitelist strategy. In production on my local machine I run npm start
which simply maps to next start
when I run it in docker I run node node_modules/next/dist/bin/next start
. It's a best practice in docker to avoid using npm start
so that you may reduce the number of running processes and make node, not npm the entry point.
Risk Level | Number of Alerts |
---|---|
High | 1 |
Medium | 2 |
Low | 2 |
Informational | 0 |
The Path Traversal attack technique allows an attacker access to files, directories, and commands that potentially reside outside the web document root directory. An attacker may manipulate a URL in such a way that the web site will execute or reveal the contents of arbitrary files anywhere on the web server. Any device that exposes an HTTP-based interface is potentially vulnerable to Path Traversal.
Most web sites restrict user access to a specific portion of the file-system, typically called the "web document root" or "CGI root" directory. These directories contain the files intended for user access and the executable necessary to drive web application functionality. To access files or execute commands anywhere on the file-system, Path Traversal attacks will utilize the ability of special-characters sequences.
The most basic Path Traversal attack uses the "../" special-character sequence to alter the resource location requested in the URL. Although most popular web servers will prevent this technique from escaping the web document root, alternate encodings of the "../" sequence may help bypass the security filters. These method variations include valid and invalid Unicode-encoding ("..%u2216" or "..%c0%af") of the forward slash character, backslash characters ("..\") on Windows-based servers, URL encoded characters "%2e%2e%2f"), and double URL encoding ("..%255c") of the backslash character.
Even if the web server properly restricts Path Traversal attempts in the URL path, a web application itself may still be vulnerable due to improper handling of user-supplied input. This is a common problem of web applications that use template mechanisms or load static text from files. In variations of the attack, the original URL parameter value is substituted with the file name of one of the web application's dynamic scripts. Consequently, the results can reveal source code because the file is interpreted as text instead of an executable script. These techniques often employ additional special characters such as the dot (".") to reveal the listing of the current working directory, or "%00" NULL characters in order to bypass rudimentary file extension checks.
URL: http://localhost:3000/_next/static/development/pages/_app.js?query=c%3A%2F
Method: GET
Parameter: query
Attack: c:/
Evidence: etc
URL: http://localhost:3000/_next/static/development/pages/home.js?query=c%3A%2F
Method: GET
Parameter: query
Attack: c:/
Evidence: etc
Instances: 2
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. Do not rely exclusively on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). However, blacklists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if you are expecting colors such as "red" or "blue."
For filenames, use stringent whitelists that limit the character set to be used. If feasible, only allow a single "." character in the filename to avoid weaknesses, and exclude directory separators such as "/". Use a whitelist of allowable file extensions.
Warning: if you attempt to cleanse your data, then do so that the end result is not in the form that can be dangerous. A sanitizing mechanism can remove characters such as '.' and ';' which may be required for some exploits. An attacker can try to fool the sanitizing mechanism into "cleaning" data into a dangerous form. Suppose the attacker injects a '.' inside a filename (e.g. "sensi.tiveFile") and the sanitizing mechanism removes the character resulting in the valid filename, "sensitiveFile". If the input data are now assumed to be safe, then the file may be compromised.
Inputs should be decoded and canonicalized to the application's current internal representation before being validated. Make sure that your application does not decode the same input twice. Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they have been checked.
Use a built-in path canonicalization function (such as realpath() in C) that produces the canonical version of the pathname, which effectively removes ".." sequences and symbolic links.
Run your code using the lowest privileges that are required to accomplish the necessary tasks. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.
When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs.
Run your code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which files can be accessed in a particular directory or which commands can be executed by your software.
OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general, managed code may provide some protection. For example, java.io.FilePermission in the Java SecurityManager allows you to specify restrictions on file operations.
This may not be a feasible solution, and it only limits the impact to the operating system; the rest of your application may still be subject to compromise.
X-Frame-Options header is not included in the HTTP response to protect against 'ClickJacking' attacks.
Method: GET
Parameter: X-Frame-Options
Instances: 1
Most modern Web browsers support the X-Frame-Options HTTP header. Ensure it's set on all web pages returned by your site (if you expect the page to be framed only by pages on your server (e.g. it's part of a FRAMESET) then you'll want to use SAMEORIGIN, otherwise if you never expect the page to be framed, you should use DENY. ALLOW-FROM allows specific websites to frame the web page in supported web browsers).
This page contains an error/warning message that may disclose sensitive information like the location of the file that produced the unhandled exception. This information can be used to launch further attacks against the web application. The alert could be a false positive if the error message is found inside a documentation page.
URL: http://localhost:3000/_next/static/development/pages/_error.js
Method: GET
Evidence: Internal Server Error
Instances: 1
Review the source code of this page. Implement custom error pages. Consider implementing a mechanism to provide a unique error reference/identifier to the client (browser) while logging the details on the server side and not exposing them to the user.
Web Browser XSS Protection is not enabled, or is disabled by the configuration of the 'X-XSS-Protection' HTTP response header on the web server
Method: GET
Parameter: X-XSS-Protection
URL: http://localhost:3000/sitemap.xml
Method: GET
Parameter: X-XSS-Protection
URL: http://localhost:3000/robots.txt
Method: GET
Parameter: X-XSS-Protection
URL: http://localhost:3000/about
Method: GET
Parameter: X-XSS-Protection
Instances: 4
Ensure that the web browser's XSS filter is enabled, by setting the X-XSS-Protection HTTP response header to '1'.
The X-XSS-Protection HTTP response header allows the web server to enable or disable the web browser's XSS protection mechanism. The following values would attempt to enable it:
X-XSS-Protection: 1; mode=block
X-XSS-Protection: 1; report=http://www.example.com/xss
The following values would disable it:
X-XSS-Protection: 0
The X-XSS-Protection HTTP response header is currently supported on Internet Explorer, Chrome and Safari (WebKit).
Note that this alert is only raised if the response body could potentially contain an XSS payload (with a text-based content type, with a non-zero length).
The Anti-MIME-Sniffing header X-Content-Type-Options was not set to 'nosniff'. This allows older versions of Internet Explorer and Chrome to perform MIME-sniffing on the response body, potentially causing the response body to be interpreted and displayed as a content type other than the declared content type. Current (early 2014) and legacy versions of Firefox will use the declared content type (if one is set), rather than performing MIME-sniffing.
URL: http://localhost:3000/_next/static/development/pages/home.js
Method: GET
Parameter: X-Content-Type-Options
Method: GET
Parameter: X-Content-Type-Options
URL: http://localhost:3000/_next/static/development/dll/dll_cdf5cfc256f9500f2e4b.js
Method: GET
Parameter: X-Content-Type-Options
URL: http://localhost:3000/_next/static/runtime/main.js
Method: GET
Parameter: X-Content-Type-Options
URL: http://localhost:3000/_next/static/development/pages/_app.js
Method: GET
Parameter: X-Content-Type-Options
URL: http://localhost:3000/_next/static/development/pages/_error.js
Method: GET
Parameter: X-Content-Type-Options
URL: http://localhost:3000/_next/static/runtime/webpack.js
Method: GET
Parameter: X-Content-Type-Options
Instances: 7
Ensure that the application/web server sets the Content-Type header appropriately, and that it sets the X-Content-Type-Options header to 'nosniff' for all web pages.
If possible, ensure that the end user uses a standards-compliant and modern web browser that does not perform MIME-sniffing at all, or that can be directed by the web application/web server to not perform MIME-sniffing.
This issue still applies to error type pages (401, 403, 500, etc) as those pages are often still affected by injection issues, in which case there is still concern for browsers sniffing pages away from their actual content type.
At "High" threshold this scanner will not alert on client or server error responses.
You shouldn't be running the scanner in development mode. Development mode exposes access points and additional URLs that aren't available in a production ENV. If you remove your whitelist logic and allow for next to handle resolving the requests and mapping them to files, it should at least remove the path traversal alert and your routes should work.
Good to know, I'll give that a shot and let you know if it helps with the nonce issue
Just had time to update the app, see the new server.js file in the issue. Unfortunately it did nothing to help with the error.
TypeError: Cannot read property 'nonce' of undefined at Function.getInitialProps (/Users/rich/code/webclient-appsvr/.next/server/static/TtAPU~ueU_78OvpI7QS5T/pages/_document.js:402:32) at _callee$ (/Users/rich/code/webclient-appsvr/node_modules/next/dist/lib/utils.js:135:30) at tryCatch (/Users/rich/code/webclient-appsvr/node_modules/regenerator-runtime/runtime.js:62:40) at Generator.invoke [as _invoke] (/Users/rich/code/webclient-appsvr/node_modules/regenerator-runtime/runtime.js:288:22) at Generator.prototype.(anonymous function) [as next] (/Users/rich/code/webclient-appsvr/node_modules/regenerator-runtime/runtime.js:114:21) at asyncGeneratorStep (/Users/rich/code/webclient-appsvr/node_modules/@babel/runtime-corejs2/helpers/asyncToGenerator.js:5:24) at _next (/Users/rich/code/webclient-appsvr/node_modules/@babel/runtime-corejs2/helpers/asyncToGenerator.js:27:9) at /Users/rich/code/webclient-appsvr/node_modules/@babel/runtime-corejs2/helpers/asyncToGenerator.js:34:7 at new Promise (
) at new F (/Users/rich/code/webclient-appsvr/node_modules/core-js/library/modules/_export.js:36:28)
What it's complaining about as near as I can tell is here:
nonce = ctx.res.locals.nonce!;
and it's insisting that ctx.res.locals is undefined even though it works great in dev.
@richbai90 See this gist https://gist.github.com/kyle-mccarthy/d04f94f4cc972a4c9b43a86d74ce9d02
TLDR;
A custom server using express with a
nonce
is working when running in dev but gives a type error after building successfully, when running in production.Cannot read property 'nonce' of undefined at Function.getInitialProps (/home/node/webclient-appsvr/.next/server/static/CAR87GSCQfuY4qyqbJ2sz/pages/_document.js:402:32)
Full Description
I have a custom server that works great in development. The main changes are that I'm using an express server with
lusca
for CSP and some custom middleware to prevent access to pages outside of the web directory. Per thelusca
documentation, the nonce is generated on every request and placed inres.locals
Where I get it in a custom_document
page.EDIT: simplified server.js based on comments
Server.js
_document.tsx
There are a lot of moving parts and variables with this setup, I'm using typescript and material-ui among other things but it all works perfectly when I run it using
npm run dev
but if I donpm run build && npm start
It builds fine but I get an error