Programming Search⌘K

Weaknesscore

Missing authentication for a critical function

Also called missing authentication for critical function, missing authentication for critical functionality, no authentication for critical function, unauthenticated endpoint, cwe-306.

Missing authentication happens when a function that needs a known user, such as an admin endpoint or a debug port, accepts requests from anyone who can reach it.

Abstraction
base
OWASP Top 10 (2025)
A07
CWE Top 25 (2025)
rank 21
Languages affected
any

Description

Authentication answers the question "who is this user?". Most of a program's functions need that answer before they run. Missing authentication happens when the product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.1 The function works, and nothing in normal use shows a problem. But anyone who can reach it can call it.

CWE describes the result in one sentence. Exposing critical functionality essentially provides an attacker with the privilege level of that functionality.1 An endpoint that changes the configuration gives the attacker the rights of an administrator. A debug port that opens a shell gives the attacker the rights of the process.

The weakness is easy to make for four reasons:

  • A second channel. CWE describes a login on one network port that opens a second port for the real work. The second port has no check, because the developer assumes that only the authenticated party will connect to it.1 An admin port, a metrics port and a debug port often follow the same idea: nobody else knows about it.
  • A route added later. The first routes of a service pass through the login check. A new route, written in a hurry or for the support team, does not. Each route makes its own decision, so one missing line opens one function.
  • A debug feature left on. A tool that helps during development stays in the release. CWE-489, Active Debug Code, names this case: the product is released with debugging code still enabled or active.8
  • An open default. A product ships with authentication off, so that the first install is easy to try. CWE-1188 covers a default that is intended to be changed by the installer but is not secure.9 Many installs never change it.

CWE also lists the move to the cloud. Data on an internal network was protected by that network. In a storage bucket without authentication, it is reachable from the Internet.1

CWE-306 is a base weakness and a child of CWE-287, Improper Authentication.1 Its child CWE-288 covers a product that requires authentication but has an alternate path or channel that does not.7 CWE-306 is rank 21 on the 2025 CWE Top 25, up from rank 25 the year before.4 The OWASP Top 10:2025 maps it to A07:2025 Authentication Failures.5 The A02:2025 Security Misconfiguration category lists unnecessary ports, services, pages, accounts and testing frameworks that are enabled.6

Two related weaknesses have their own pages. With Missing authorization, the program knows who the user is but never asks whether the user may act. With Hard-coded credentials, a check exists, but its password is the same in every copy of the product.

History

The Internet worm was released on the evening of 2 November 1988.2 It used errors in two network programs, sendmail and fingerd. In sendmail it used a non-standard "debug" command, and it propagated itself through that command into remote hosts.2 Steven Bellovin wrote in the RISKS Digest a week later that debugging came enabled in the standard distributions of both Berkeley and Sun. He named the flaw: "The flaw is not that debug mode was possible; rather, that sendmail's debug mode (a) was accessible remotely; and (b) expanded the range of inputs accepted by the program".3 That is CWE-306 in its first well-known form: a powerful function, reachable from the network, with no check of who calls it.

CWE-306 entered CWE in July 2006, from the PLOVER list.1

Vulnerable code

The program below runs two servers on 127.0.0.1. The application server checks a bearer token before it shows the orders. The operators also asked for a way to put the service into maintenance mode, so a developer added a second server on another port. That port is not in the public documentation, so the developer gave it no login. The demonstration is a request to the second port with no credentials.

This code runs but gives a wrong answer on purpose.

import secrets
import threading
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

TOKEN = secrets.token_hex(16)  # made at start; the operators get it
SETTINGS = {"maintenance": False}


class Handler(BaseHTTPRequestHandler):
    def reply(self, status, text):
        body = text.encode()
        self.send_response(status)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):
        pass


class AppHandler(Handler):
    def do_GET(self):
        if self.path == "/orders":
            if self.headers.get("Authorization") != "Bearer " + TOKEN:
                return self.reply(401, "login required")
            return self.reply(200, "3 orders")
        self.reply(404, "not found")


class DebugHandler(Handler):
    # A second port for the operators. Nobody else knows it, so it has no login.
    def do_POST(self):
        if self.path == "/maintenance":
            SETTINGS["maintenance"] = True
            return self.reply(200, "maintenance mode on")
        self.reply(404, "not found")


def start(handler):
    server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    return server


def call(method, server, path):
    url = f"http://127.0.0.1:{server.server_port}{path}"
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
    try:
        with opener.open(urllib.request.Request(url, method=method)) as response:
            return response.status, response.read().decode()
    except urllib.error.HTTPError as error:
        return error.code, error.read().decode()


app = start(AppHandler)
debug = start(DebugHandler)
print("app   GET /orders      ", call("GET", app, "/orders"))
print("debug POST /maintenance", call("POST", debug, "/maintenance"))
print(SETTINGS)
Output
app   GET /orders       (401, 'login required')
debug POST /maintenance (200, 'maintenance mode on')
{'maintenance': True}

The main port refuses the request without a token. The second port accepts the same caller and changes the state of the service. A port scan can find the second port, so the secret of its number does not protect it. In a real deployment both servers listen on an address that other machines can reach. The demonstration uses 127.0.0.1 so that it runs without a network.

Fixed code

The fixed code moves the decision out of the handlers. Every handler class inherits from GatedHandler. Each class lists its routes in a table, and each route says whether it is public. The only public route is /health. A route that is not in the table gets 404. A route that is not public gets 401 unless the request has the token. The second port uses the same base class, so it gets the same check.

import hmac
import secrets
import threading
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

TOKEN = secrets.token_hex(16)  # made at start; the operators get it
SETTINGS = {"maintenance": False}


class GatedHandler(BaseHTTPRequestHandler):
    # Each subclass lists its routes: (method, path) -> (method name, public).
    ROUTES = {}

    def dispatch(self, method):
        route = self.ROUTES.get((method, self.path))
        if route is None:
            return self.reply(404, "not found")
        name, public = route
        if not public and not self.authenticated():
            return self.reply(401, "login required")
        getattr(self, name)()

    def authenticated(self):
        sent = self.headers.get("Authorization", "")
        return hmac.compare_digest(sent.encode(), ("Bearer " + TOKEN).encode())

    def do_GET(self):
        self.dispatch("GET")

    def do_POST(self):
        self.dispatch("POST")

    def reply(self, status, text):
        body = text.encode()
        self.send_response(status)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):
        pass


class AppHandler(GatedHandler):
    ROUTES = {("GET", "/health"): ("health", True), ("GET", "/orders"): ("orders", False)}

    def health(self):
        self.reply(200, "ok")

    def orders(self):
        self.reply(200, "3 orders")


class DebugHandler(GatedHandler):
    ROUTES = {("POST", "/maintenance"): ("maintenance", False)}

    def maintenance(self):
        SETTINGS["maintenance"] = True
        self.reply(200, "maintenance mode on")


def start(handler):
    server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    return server


def call(method, server, path, token=None):
    url = f"http://127.0.0.1:{server.server_port}{path}"
    headers = {"Authorization": "Bearer " + token} if token else {}
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
    try:
        with opener.open(urllib.request.Request(url, method=method, headers=headers)) as response:
            return response.status, response.read().decode()
    except urllib.error.HTTPError as error:
        return error.code, error.read().decode()


app = start(AppHandler)
debug = start(DebugHandler)
print("app   GET /health      ", call("GET", app, "/health"))
print("app   GET /orders      ", call("GET", app, "/orders"))
print("debug POST /maintenance", call("POST", debug, "/maintenance"))
print(SETTINGS)
print("debug POST /maintenance", call("POST", debug, "/maintenance", TOKEN))
print(SETTINGS)
Output
app   GET /health       (200, 'ok')
app   GET /orders       (401, 'login required')
debug POST /maintenance (401, 'login required')
{'maintenance': False}
debug POST /maintenance (200, 'maintenance mode on')
{'maintenance': True}

Three choices make the fix hold when the code grows:

  • Authenticated by default. A new route must say True to be public. If a developer forgets the flag, the route is protected. The OWASP Authorization Cheat Sheet asks for the same deny-by-default stance whenever new functionality is exposed.10
  • One check for every channel. CWE asks developers to identify all potential channels and to protect the ones that are assumed to be reachable only by authorized parties.1 The debug port here is a channel like any other.
  • A comparison in constant time. hmac.compare_digest compares the token without an early exit on the first wrong byte. The page Exposure of sensitive information explains why that matters.

http.server itself is a teaching tool. Its documentation says that it is not recommended for production and that it only implements basic security checks.12 A production service uses the authentication of its framework, and the same rules apply there.

Debug endpoints

Debug and profiling tools often register their handlers as a side effect. Go's net/http/pprof package is typically only imported for the side effect of registering its HTTP handlers, and its paths all begin with /debug/pprof/.11 The handlers go on http.DefaultServeMux. A service that serves the default mux on its public port then serves the profiles to anyone. One of them, /debug/pprof/cmdline, returns the command line of the running program,11 which may hold a path or a flag that the operators did not mean to publish. The Go example file shows the problem and the fix: a separate mux for the public server, and the pprof handlers registered by hand on a second mux behind a check.

Debug output is not the only risk. Bellovin's point from 1988 still holds: the debug mode of sendmail was dangerous because it accepted more kinds of input than the normal program did.3 A debug endpoint that runs commands, changes settings or dumps memory is a critical function, and it needs the same check as the admin page.

How to detect it

  • List every listener and every route. Start from the network side: which ports does the process open, and what answers on each one? Then list every route on each port with its authentication rule. CWE notes that manual analysis, such as penetration testing and threat modeling, can find this weakness, and it rates architecture and design review as highly effective.1
  • Send requests with no credentials. Call each route without a token, without a cookie and with an expired session. A test that expects 401 for every route that is not public fails when a new route forgets the check.
  • Look for registration by side effect. Search for imports such as net/http/pprof, for admin consoles and for actuator or metrics endpoints that a framework or a library adds.
  • Check the defaults. Read the configuration that a fresh install gets. If authentication is off until an administrator turns it on, many installs will run with it off. The Airflow case below is an example.
  • Static analysis. CWE rates automated static analysis as limited here. Tools find common authentication libraries, but they have difficulty with custom schemes. Some functions are public by design, so a tool that reports every function without a check reports false positives.1

How to prevent it

  • Divide the product into areas. CWE suggests anonymous, normal, privileged and administrative areas. Decide which areas need a proven identity, and use one central authentication capability for them.1
  • Authenticate by default. Make a route public only by an explicit choice in code, as the fixed example does.10
  • Protect every channel. A second port, a message queue, a serial console and a management interface each need a check. CWE gives a UART debug port as an observed example.1
  • Ship with debug features off. Remove debug code from release builds, or make it a separate binary. OWASP asks for a minimal platform without unnecessary features.6
  • Ship with authentication on. Do not ship an open default that the installer must change. OWASP also says not to ship or deploy with default credentials, particularly for admin users.5
  • Use the authentication of the framework. CWE advises against custom authentication routines where the environment provides them.1 The Java HttpServer has HttpContext.setAuthenticator. Once an authenticator is set on a context, all client requests to it must be authenticated.13
  • Duplicate client checks on the server. A login screen in a mobile app or a desktop client does not protect the server. CWE gives this as a mitigation.1
  • Add network controls as a second layer. Bind admin and debug listeners to the loopback address, or put them behind a firewall. This narrows who can reach the port. It does not replace the check.

Real cases

Case Date What happened
CVE-2020-10263 published 2020-04-08 Attackers with access to the UART interface of the XIAOMI XIAOAI speaker Pro LX06 could get a root shell.17 CWE lists it as debug functionality on the UART port with no authentication.1
CVE-2020-13927 published 2020-11-10 The previous default setting of the Experimental API of Apache Airflow allowed all API requests without authentication. From Airflow 1.10.11, the default denies all requests.14 CWE notes that it was exploited in the wild, per the CISA KEV catalog.1
CVE-2021-21972 published 2021-02-24 A vCenter Server plugin in the vSphere Client had a remote code execution vulnerability for an actor with network access to port 443.15 CWE lists it as a chain: an upload of a tar file with no authentication, then path traversal in the file.1
CVE-2021-37415 published 2021-09-01 Zoho ManageEngine ServiceDesk Plus before 11302 allowed a few REST API URLs without authentication.16 CWE notes that it was exploited in the wild, per the CISA KEV catalog.1
CVE-2024-11680 published 2024-11-26 Unauthenticated requests to options.php of ProjectSend before r1720 could change the configuration of the application.18
PythonGitHub

This code runs but gives a wrong answer on purpose.

import secrets
import threading
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

TOKEN = secrets.token_hex(16)  # made at start; the operators get it
SETTINGS = {"maintenance": False}


class Handler(BaseHTTPRequestHandler):
    def reply(self, status, text):
        body = text.encode()
        self.send_response(status)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):
        pass


class AppHandler(Handler):
    def do_GET(self):
        if self.path == "/orders":
            if self.headers.get("Authorization") != "Bearer " + TOKEN:
                return self.reply(401, "login required")
            return self.reply(200, "3 orders")
        self.reply(404, "not found")


class DebugHandler(Handler):
    # A second port for the operators. Nobody else knows it, so it has no login.
    def do_POST(self):
        if self.path == "/maintenance":
            SETTINGS["maintenance"] = True
            return self.reply(200, "maintenance mode on")
        self.reply(404, "not found")


def start(handler):
    server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    return server


def call(method, server, path):
    url = f"http://127.0.0.1:{server.server_port}{path}"
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
    try:
        with opener.open(urllib.request.Request(url, method=method)) as response:
            return response.status, response.read().decode()
    except urllib.error.HTTPError as error:
        return error.code, error.read().decode()


app = start(AppHandler)
debug = start(DebugHandler)
print("app   GET /orders      ", call("GET", app, "/orders"))
print("debug POST /maintenance", call("POST", debug, "/maintenance"))
print(SETTINGS)
Output
app   GET /orders       (401, 'login required')
debug POST /maintenance (200, 'maintenance mode on')
{'maintenance': True}

The second port has no check, so a caller with no token turns on maintenance mode.

import hmac
import secrets
import threading
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

TOKEN = secrets.token_hex(16)  # made at start; the operators get it
SETTINGS = {"maintenance": False}


class GatedHandler(BaseHTTPRequestHandler):
    # Each subclass lists its routes: (method, path) -> (method name, public).
    ROUTES = {}

    def dispatch(self, method):
        route = self.ROUTES.get((method, self.path))
        if route is None:
            return self.reply(404, "not found")
        name, public = route
        if not public and not self.authenticated():
            return self.reply(401, "login required")
        getattr(self, name)()

    def authenticated(self):
        sent = self.headers.get("Authorization", "")
        return hmac.compare_digest(sent.encode(), ("Bearer " + TOKEN).encode())

    def do_GET(self):
        self.dispatch("GET")

    def do_POST(self):
        self.dispatch("POST")

    def reply(self, status, text):
        body = text.encode()
        self.send_response(status)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):
        pass


class AppHandler(GatedHandler):
    ROUTES = {("GET", "/health"): ("health", True), ("GET", "/orders"): ("orders", False)}

    def health(self):
        self.reply(200, "ok")

    def orders(self):
        self.reply(200, "3 orders")


class DebugHandler(GatedHandler):
    ROUTES = {("POST", "/maintenance"): ("maintenance", False)}

    def maintenance(self):
        SETTINGS["maintenance"] = True
        self.reply(200, "maintenance mode on")


def start(handler):
    server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    return server


def call(method, server, path, token=None):
    url = f"http://127.0.0.1:{server.server_port}{path}"
    headers = {"Authorization": "Bearer " + token} if token else {}
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
    try:
        with opener.open(urllib.request.Request(url, method=method, headers=headers)) as response:
            return response.status, response.read().decode()
    except urllib.error.HTTPError as error:
        return error.code, error.read().decode()


app = start(AppHandler)
debug = start(DebugHandler)
print("app   GET /health      ", call("GET", app, "/health"))
print("app   GET /orders      ", call("GET", app, "/orders"))
print("debug POST /maintenance", call("POST", debug, "/maintenance"))
print(SETTINGS)
print("debug POST /maintenance", call("POST", debug, "/maintenance", TOKEN))
print(SETTINGS)
Output
app   GET /health       (200, 'ok')
app   GET /orders       (401, 'login required')
debug POST /maintenance (401, 'login required')
{'maintenance': False}
debug POST /maintenance (200, 'maintenance mode on')
{'maintenance': True}

Every handler class inherits the check from GatedHandler. A route is public only when its entry says True.

  • Verdict: stdlib. http.server and urllib.request run both servers and the client. hmac.compare_digest compares the token in constant time, and secrets.token_hex makes it.
  • The Python documentation says that http.server is not recommended for production. A real service uses the authentication of its framework, with the same rule: every route is protected unless the code says otherwise.
  • urllib.request.ProxyHandler({}) turns off proxies from the environment, so the requests go straight to 127.0.0.1.
  • The token is made at start for the demonstration. A real service gets it from a secret store, never from the source code. See Hard-coded credentials.
JavaGitHub

This code runs but gives a wrong answer on purpose.

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;

public class Main {
    static final List<String> USERS = new ArrayList<>(List.of("ana", "bao", "chi"));
    static final String TOKEN = java.util.UUID.randomUUID().toString();

    static void reply(HttpExchange ex, int code, String body) throws IOException {
        byte[] b = body.getBytes();
        ex.sendResponseHeaders(code, b.length);
        ex.getResponseBody().write(b);
        ex.close();
    }

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        server.createContext("/users", ex -> {
            if (!("Bearer " + TOKEN).equals(ex.getRequestHeaders().getFirst("Authorization"))) {
                reply(ex, 401, "login required");
                return;
            }
            reply(ex, 200, USERS.toString());
        });
        // Added later for the support team. It has no check.
        server.createContext("/admin/delete-user", ex -> {
            String name = ex.getRequestURI().getQuery().replace("name=", "");
            USERS.remove(name);
            reply(ex, 200, "deleted " + name);
        });
        server.start();

        HttpClient client = HttpClient.newBuilder().proxy(HttpClient.Builder.NO_PROXY).build();
        String base = "http://127.0.0.1:" + server.getAddress().getPort();
        for (String path : List.of("/users", "/admin/delete-user?name=bao")) {
            HttpResponse<String> r = client.send(
                HttpRequest.newBuilder(URI.create(base + path)).POST(HttpRequest.BodyPublishers.noBody()).build(),
                HttpResponse.BodyHandlers.ofString());
            System.out.println(path + " " + r.statusCode() + " " + r.body());
        }
        System.out.println(USERS);
        server.stop(0);
    }
}
Output
/users 401 login required
/admin/delete-user?name=bao 200 deleted bao
[ana, chi]

The context /users checks the token in its handler. The context /admin/delete-user was added later, and its handler has no check. The first request with no token gets 401. The second one deletes a user.

import com.sun.net.httpserver.Authenticator;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpPrincipal;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class Main {
    static final List<String> USERS = new ArrayList<>(List.of("ana", "bao", "chi"));
    static final String TOKEN = java.util.UUID.randomUUID().toString();
    static final Set<String> PUBLIC = Set.of("/health");

    // The authenticator runs before the handler of the context.
    static final Authenticator BEARER = new Authenticator() {
        @Override
        public Result authenticate(HttpExchange ex) {
            String got = ex.getRequestHeaders().getFirst("Authorization");
            byte[] a = String.valueOf(got).getBytes(StandardCharsets.UTF_8);
            byte[] b = ("Bearer " + TOKEN).getBytes(StandardCharsets.UTF_8);
            if (MessageDigest.isEqual(a, b)) {
                return new Success(new HttpPrincipal("operator", "app"));
            }
            return new Failure(401);
        }
    };

    // Every route goes through this method. A route is protected unless it is in PUBLIC.
    static void route(HttpServer server, String path, HttpHandler handler) {
        var context = server.createContext(path, handler);
        if (!PUBLIC.contains(path)) {
            context.setAuthenticator(BEARER);
        }
    }

    static void reply(HttpExchange ex, int code, String body) throws IOException {
        byte[] b = body.getBytes(StandardCharsets.UTF_8);
        ex.sendResponseHeaders(code, b.length);
        ex.getResponseBody().write(b);
        ex.close();
    }

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        route(server, "/health", ex -> reply(ex, 200, "ok"));
        route(server, "/users", ex -> reply(ex, 200, USERS.toString()));
        route(server, "/admin/delete-user", ex -> {
            String name = ex.getRequestURI().getQuery().replace("name=", "");
            USERS.remove(name);
            reply(ex, 200, "deleted " + name);
        });
        server.start();

        HttpClient client = HttpClient.newBuilder().proxy(HttpClient.Builder.NO_PROXY).build();
        String base = "http://127.0.0.1:" + server.getAddress().getPort();
        String[][] calls = {
            {"/health", ""},
            {"/users", ""},
            {"/admin/delete-user?name=bao", ""},
            {"/admin/delete-user?name=bao", "Bearer " + TOKEN},
        };
        for (String[] call : calls) {
            var builder = HttpRequest.newBuilder(URI.create(base + call[0]))
                .POST(HttpRequest.BodyPublishers.noBody());
            if (!call[1].isEmpty()) {
                builder.header("Authorization", call[1]);
            }
            HttpResponse<String> r = client.send(builder.build(), HttpResponse.BodyHandlers.ofString());
            String who = call[1].isEmpty() ? "no token  " : "with token";
            System.out.println(who + " " + call[0] + " " + r.statusCode() + " " + r.body());
            if (call[0].startsWith("/admin")) {
                System.out.println(USERS);
            }
        }
        server.stop(0);
    }
}
Output
no token   /health 200 ok
no token   /users 401
no token   /admin/delete-user?name=bao 401
[ana, bao, chi]
with token /admin/delete-user?name=bao 200 deleted bao
[ana, chi]

The method route is the only way to add a context. It sets the authenticator on every context that is not in PUBLIC. The handlers no longer contain a check, so a new handler cannot forget it.

  • Verdict: stdlib. com.sun.net.httpserver in the module jdk.httpserver has the server, and HttpContext.setAuthenticator applies an Authenticator to every request of a context. java.net.http.HttpClient is the client.
  • The documentation of setAuthenticator says that once an authenticator is set on a context, all client requests must be authenticated. The package also has BasicAuthenticator for HTTP Basic authentication.
  • MessageDigest.isEqual compares the token. Its implementation note says that the time depends only on the length of the first array, not on the contents of either array.
  • The token is made at start for the demonstration. A real service reads it from a secret store. See Hard-coded credentials.
JavaScriptGitHub

This code runs but gives a wrong answer on purpose.

const http = require("node:http");
const { randomBytes } = require("node:crypto");

const TOKEN = randomBytes(16).toString("hex");
const settings = { signups: "open" };

const server = http.createServer((req, res) => {
  if (req.url === "/settings") {
    if (req.headers.authorization !== `Bearer ${TOKEN}`) {
      res.writeHead(401).end("login required");
      return;
    }
    res.end(JSON.stringify(settings));
  } else if (req.url === "/admin/close-signups" && req.method === "POST") {
    // The admin page that shows this button needs a login.
    // The endpoint behind the button does not check.
    settings.signups = "closed";
    res.end("signups closed");
  } else {
    res.writeHead(404).end("not found");
  }
});

function call(method, path) {
  const { port } = server.address();
  return new Promise((resolve, reject) => {
    const req = http.request({ host: "127.0.0.1", port, method, path }, (res) => {
      let body = "";
      res.on("data", (chunk) => (body += chunk));
      res.on("end", () => resolve(`${method} ${path} ${res.statusCode} ${body}`));
    });
    req.on("error", reject);
    req.end();
  });
}

server.listen(0, "127.0.0.1", async () => {
  console.log(await call("GET", "/settings"));
  console.log(await call("POST", "/admin/close-signups"));
  console.log(settings);
  server.close();
});
Output
GET /settings 401 login required
POST /admin/close-signups 200 signups closed
{ signups: 'closed' }

The admin page that shows the button needs a login, so the developer thought the action was protected. The server answers the request to the endpoint itself, and that endpoint makes no check.

const http = require("node:http");
const { randomBytes, timingSafeEqual } = require("node:crypto");

const TOKEN = randomBytes(16).toString("hex");
const settings = { signups: "open" };

// Each route says if it is public. The default is that it is not.
const routes = new Map([
  ["GET /health", { handler: (req, res) => res.end("ok"), public: true }],
  ["GET /settings", { handler: (req, res) => res.end(JSON.stringify(settings)) }],
  [
    "POST /admin/close-signups",
    {
      handler: (req, res) => {
        settings.signups = "closed";
        res.end("signups closed");
      },
    },
  ],
]);

function authenticated(req) {
  const sent = Buffer.from(req.headers.authorization ?? "");
  const expected = Buffer.from(`Bearer ${TOKEN}`);
  return sent.length === expected.length && timingSafeEqual(sent, expected);
}

// The only request handler. No route runs before this check.
const server = http.createServer((req, res) => {
  const route = routes.get(`${req.method} ${req.url}`);
  if (route === undefined) {
    res.writeHead(404).end("not found");
  } else if (!route.public && !authenticated(req)) {
    res.writeHead(401).end("login required");
  } else {
    route.handler(req, res);
  }
});

function call(method, path, auth) {
  const { port } = server.address();
  const headers = auth ? { authorization: auth } : {};
  return new Promise((resolve, reject) => {
    const req = http.request({ host: "127.0.0.1", port, method, path, headers }, (res) => {
      let body = "";
      res.on("data", (chunk) => (body += chunk));
      res.on("end", () => resolve(`${method} ${path} ${res.statusCode} ${body}`));
    });
    req.on("error", reject);
    req.end();
  });
}

server.listen(0, "127.0.0.1", async () => {
  console.log(await call("GET", "/health"));
  console.log(await call("POST", "/admin/close-signups"));
  console.log(settings);
  console.log(await call("POST", "/admin/close-signups", `Bearer ${TOKEN}`));
  console.log(settings);
  server.close();
});
Output
GET /health 200 ok
POST /admin/close-signups 401 login required
{ signups: 'open' }
POST /admin/close-signups 200 signups closed
{ signups: 'closed' }

The server has one request handler. It finds the route in a table and checks the token before any route runs, unless the route says public: true.

  • Verdict: stdlib. node:http runs the server and the client, and crypto.timingSafeEqual compares the token. It throws when the lengths differ, so the code checks the length first.
  • Express and similar frameworks put the same check in a middleware that runs before the routes. Register it before the routes, not on each route, so that a new route gets it without any change.
  • The demonstration uses http.request to 127.0.0.1, so no proxy or network is involved.

This code runs but gives a wrong answer on purpose.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	_ "net/http/pprof" // registers /debug/pprof/ on http.DefaultServeMux
)

func main() {
	http.HandleFunc("GET /orders", func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("Authorization") == "" {
			http.Error(w, "login required", http.StatusUnauthorized)
			return
		}
		fmt.Fprintln(w, "3 orders")
	})

	// The public server serves the default mux, so it also serves pprof.
	app := httptest.NewServer(http.DefaultServeMux) // listens on 127.0.0.1
	defer app.Close()

	for _, path := range []string{"/orders", "/debug/pprof/", "/debug/pprof/cmdline"} {
		resp, err := http.Get(app.URL + path)
		if err != nil {
			fmt.Println(err)
			return
		}
		resp.Body.Close()
		fmt.Println("GET", path, resp.StatusCode)
	}
}
Output
GET /orders 401
GET /debug/pprof/ 200
GET /debug/pprof/cmdline 200

The blank import of net/http/pprof adds its handlers to http.DefaultServeMux. The application serves that mux on its public port, so the profiles and the command line of the process are open to any caller. The route /orders has a check, and the debug routes have none.

package main

import (
	"crypto/rand"
	"crypto/subtle"
	"encoding/hex"
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/http/pprof"
)

var token = newToken() // made at start; the operators get it

func newToken() string {
	b := make([]byte, 16)
	rand.Read(b)
	return hex.EncodeToString(b)
}

// requireAuth runs next only for a request with the token.
func requireAuth(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		got := []byte(r.Header.Get("Authorization"))
		want := []byte("Bearer " + token)
		if subtle.ConstantTimeCompare(got, want) != 1 {
			http.Error(w, "login required", http.StatusUnauthorized)
			return
		}
		next.ServeHTTP(w, r)
	})
}

func main() {
	// The public server has its own mux. It never serves http.DefaultServeMux.
	public := http.NewServeMux()
	public.Handle("GET /orders", requireAuth(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "3 orders")
	})))

	// The debug handlers go on a second mux, by hand, behind the same check.
	debug := http.NewServeMux()
	debug.Handle("GET /debug/pprof/", requireAuth(http.HandlerFunc(pprof.Index)))
	debug.Handle("GET /debug/pprof/cmdline", requireAuth(http.HandlerFunc(pprof.Cmdline)))

	app := httptest.NewServer(public)
	defer app.Close()
	ops := httptest.NewServer(debug) // a second listener on 127.0.0.1
	defer ops.Close()

	get := func(name, base, path, auth string) {
		req, _ := http.NewRequest("GET", base+path, nil)
		if auth != "" {
			req.Header.Set("Authorization", auth)
		}
		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			fmt.Println(err)
			return
		}
		resp.Body.Close()
		fmt.Println(name, "GET", path, resp.StatusCode)
	}
	get("app  ", app.URL, "/orders", "")
	get("app  ", app.URL, "/debug/pprof/", "")
	get("debug", ops.URL, "/debug/pprof/cmdline", "")
	get("debug", ops.URL, "/debug/pprof/cmdline", "Bearer "+token)
}
Output
app   GET /orders 401
app   GET /debug/pprof/ 404
debug GET /debug/pprof/cmdline 401
debug GET /debug/pprof/cmdline 200

The public server uses its own http.ServeMux, so a request for /debug/pprof/ gets 404 there. The debug server registers pprof.Index and pprof.Cmdline by hand, and requireAuth wraps each one.

  • Verdict: stdlib. net/http has the servers and the mux, net/http/httptest runs them on 127.0.0.1, and crypto/subtle.ConstantTimeCompare compares the token.
  • The import of net/http/pprof still adds its handlers to http.DefaultServeMux when the package starts. The fix is safe because no server serves the default mux. A call such as http.ListenAndServe(addr, nil) serves the default mux, so it would bring the handlers back.
  • The pprof documentation says that a program that does not use DefaultServeMux must register the handlers with the mux that it uses. pprof.Index serves the named profiles, such as /debug/pprof/heap. Cmdline, Profile, Symbol and Trace each need their own route.
  • In a real deployment, bind the debug listener to a loopback address, such as 127.0.0.1:6060, as a second layer. Keep the check as well, because other processes on the same machine can reach the loopback address.

References

  1. CWE-306: Missing Authentication for Critical Function, Description; Relationships; Modes Of Introduction; Common Consequences; Detection Methods; Potential Mitigations; Demonstrative Examples; Observed Examples; Content History
  2. J. Reynolds, RFC 1135: The Helminthiasis of the Internet, December 1989, section 1, Introduction; section 2.1, the paragraph on sendmail
  3. Steven Bellovin, The worm and the debug option, The RISKS Digest, Volume 7, Issue 74, 9 November 1988, the message "The worm and the debug option"
  4. 2025 CWE Top 25 Most Dangerous Software Weaknesses, the ranked list, rank 21, Rank Last Year
  5. OWASP Top 10:2025, A07:2025 Authentication Failures, How to prevent; List of Mapped CWEs
  6. OWASP Top 10:2025, A02:2025 Security Misconfiguration, Description, the list of misconfigurations; How to prevent; Example attack scenarios, Scenario 1; List of Mapped CWEs
  7. CWE-288: Authentication Bypass Using an Alternate Path or Channel, Description
  8. CWE-489: Active Debug Code, Description
  9. CWE-1188: Initialization of a Resource with an Insecure Default, Description
  10. OWASP Cheat Sheet Series, Authorization Cheat Sheet, Deny by Default; Validate the Permissions on Every Request
  11. Go standard library, net/http/pprof, Overview; func Cmdline
  12. The Python Standard Library, http.server, Python 3.14, the security warning at the top of the page
  13. Java SE 25 API, com.sun.net.httpserver.HttpContext, setAuthenticator
  14. CVE-2020-13927, Apache Airflow, the description and the publication date
  15. CVE-2021-21972, VMware vCenter Server, the description and the publication date
  16. CVE-2021-37415, Zoho ManageEngine ServiceDesk Plus, the description and the publication date
  17. CVE-2020-10263, XIAOMI XIAOAI speaker Pro LX06, the description and the publication date
  18. CVE-2024-11680, ProjectSend, the description, the CWE and the publication date

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/YF3BF4/text.yaml