Exercise C: Session Handling

Advanced

Some authentication requirements can’t be replayed. A TOTP (time-based one-time password) code, an HMAC (hash-based message authentication code) signature over the current timestamp, a rotating nonce: capture any of them once and it’s stale seconds later. Every replayed or scanned request then fails authentication. Manually pasting a fresh code into each request doesn’t scale.

Burp solves this with session handling actions: a rule fires as Burp is about to send a request (from any tool) and lets an extension rewrite it first. In this exercise you’ll register an action that generates a fresh TOTP code and injects it. You’ll then connect it to a session handling rule so Repeater, Scanner, and Intruder all authenticate against a TOTP-protected endpoint. TOTP is the concrete example; the same shape fits any credential with a short time-to-live (TTL).

Note: Burp can now handle TOTP natively through recorded logins, in both DAST and Burp Suite Professional. This exercise uses TOTP as a familiar, self-contained example of scripting a custom authentication flow: the value is the session handling pattern, which you can apply to any short-lived credential Burp doesn’t handle for you.

Note: Why not a proxy request handler or an HTTP handler? A ProxyRequestHandler only sees traffic that flows through the Proxy tool, so Repeater, Scanner, and Intruder would never receive the code. An HttpHandler sees every tool’s traffic, but then you’d hand-roll the scoping and tool filtering yourself, and it fires on every request whether or not it needs a code. A session handling action leaves that to a session handling rule: you point the rule at the tools and URLs that need the credential, and Burp only invokes your action there.

Reference: customsessiontokens in the Montoya API examples repo. JavaDoc: Http.registerSessionHandlingAction() · SessionHandlingAction

Table of contents

  1. The goal
  2. How TOTP works
  3. Before you start
    1. Demo target
  4. How to approach it
    1. Step 1: Generate the TOTP code with a library
    2. Step 1 (reference): Write the generator yourself
    3. Step 2: Write the session handling action
    4. Step 3: Register the action
    5. Step 4: Create the session handling rule
    6. Step 5: Build, reload, and test
  5. Check your work
  6. The complete extension
  7. Taking it further
    1. Inject into a body parameter instead of a header

The goal

Build a session handling action. It should:

  • Generate a fresh TOTP code for the current time window.
  • Inject it into the request (header, parameter, or body) as Burp sends it.
  • Run for whichever tools and URLs you scope its session handling rule to.

How TOTP works

TOTP (RFC 6238) computes an HMAC-SHA1 of the current Unix time, floored to a 30-second window, with a shared secret. That produces a time-based one-time password. Client and server run the same calculation and arrive at the same six-digit code. The easiest route is to pull in a library and skip the cryptography entirely, so this exercise leads with that. It then shows the pure-Java version as a reference, for when you hit a credential no library covers.

Before you start

This exercise starts from the extension starter project, the same one every exercise uses. If you haven’t already downloaded it and opened it in IntelliJ, follow Set up your development environment on the overview page (Exercise A also walks through it inline). Have the jar task building and the extension loading in Extensions without errors before you start.

Demo target

No Web Security Academy lab exercises TOTP injection, so we ship a demo server that guards /login/totp. It demands a valid, current code in the X-TOTP-Code header and rejects anything stale, so you can’t replay a captured one. That’s what the exercise addresses.

Download TotpDemo.java

It’s a single file with no build step or dependencies, and runs on http://localhost:8888. It’s preconfigured to match the solution below, so a correct extension works against it without changes. See the TOTP demo server page for how to run it, the endpoints, response codes, and how to drive it from Burp.


How to approach it

Step 1: Generate the TOTP code with a library

Create TotpGenerator.java. This is self-contained cryptography, independent of Burp. Keeping it in its own class, separate from the session handling action that calls it (Step 2), is a deliberate split: the generator holds reusable logic with one job, and the action’s job is to talk to Burp. No interface forces this split; you split here for readability and reuse. Add the class by selecting src/main/java/ and pressing Alt+Insert (⌘N on macOS) > Java Class. See Working with classes for the reasoning, and IntelliJ shortcuts.

You rarely need to implement TOTP by hand. An extension is an ordinary Gradle project, so you can pull in any library from Maven Central and let it handle the cryptography. Reaching for a maintained library is usually the more robust route: someone else already handled the edge cases, and it’s one of the easiest ways to add capability to an extension.

Add the dependency to build.gradle.kts. Use implementation (not compileOnly) so the library lands on the runtime classpath:

dependencies {
    compileOnly("net.portswigger.burp.extensions:montoya-api:2026.4")
    implementation("com.warrenstrange:googleauth:1.5.0")
}

Tip: After editing build.gradle.kts, refresh Gradle so IntelliJ fetches the library and puts it on the classpath. Open the Gradle tool window (the elephant icon on the right edge) and click the reload icon (the circular arrows) at the top of it. Skip this and the import com.warrenstrange.googleauth... line stays unresolved in red, because the dependency isn’t on the classpath yet.

Note: Burp loads a single JAR, so any library your code uses has to be bundled inside it. The starter project’s jar task already does this: it packs everything on the runtime classpath into the JAR, so ./gradlew jar bundles the library for you. No extra plugin to configure.

With the library on the classpath, the generator collapses to a few lines:

Solution: `TotpGenerator.java`

import com.warrenstrange.googleauth.GoogleAuthenticator;

public class TotpGenerator {

    public static String generate(String base32Secret) {
        // GoogleAuthenticator's defaults match the demo server: 6 digits, 30-second window, HMAC-SHA1
        int code = new GoogleAuthenticator().getTotpPassword(base32Secret);
        return String.format("%06d", code);
    }
}

getTotpPassword() takes the Base32 secret straight from an authenticator app and returns the current code as an int, so the only work left is zero-padding it to six digits. The Base32 decode, the HMAC, and the truncation step all live inside the library.

Tip: When IntelliJ flags a line in red, put the caret on it and press Alt+Enter for the context-action menu: it offers the relevant fix, whether that’s importing a missing class, stubbing an interface method, or creating a symbol. To fix every import at once, run Add or optimize imports. See IntelliJ shortcuts.

Step 1 (reference): Write the generator yourself

Reaching for the library is the right default, but it’s worth reading the pure-Java version once to see how TOTP works. You’ll need it for real when you hit a credential no library covers (a bespoke HMAC scheme, a vendor’s own signing quirk): then you’re writing this logic yourself, and this is the shape it takes. The signature is identical, so Steps 2 to 5 don’t change either way: the action, registration, and rule all still call TotpGenerator.generate(totpSecret).

It needs to:

  1. Base32-decode the shared secret (that’s the format authenticator apps show).
  2. Compute the current time step: unixSeconds / 30.
  3. Pack the time step into an 8-byte big-endian array.
  4. HMAC-SHA1 it with the key.
  5. Apply the RFC’s dynamic-truncation step and reduce to six digits, zero-padded.

Hint: the tricky parts

Java’s javax.crypto.Mac with "HmacSHA1" does the HMAC. There’s no Base32 in the JDK, so write a minimal decoder over the alphabet ABCDEFGHIJKLMNOPQRSTUVWXYZ234567. For dynamic truncation, the low nibble of the last hash byte is the offset into the hash where you read a 4-byte integer.

Solution: `TotpGenerator.java` (hand-rolled)

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class TotpGenerator {

    private static final int DIGITS = 6;
    private static final int PERIOD = 30;

    /**
     * Generates a TOTP code for the current time window.
     *
     * @param base32Secret the shared secret, Base32-encoded (as shown in authenticator apps)
     * @return a 6-digit TOTP code string, zero-padded
     */
    public static String generate(String base32Secret) throws Exception {
        byte[] key = base32Decode(base32Secret);
        long timeStep = System.currentTimeMillis() / 1000 / PERIOD;

        // Pack the time step into an 8-byte big-endian array
        byte[] timeBytes = new byte[8];
        for (int i = 7; i >= 0; i--) {
            timeBytes[i] = (byte) (timeStep & 0xFF);
            timeStep >>= 8;
        }

        // HMAC-SHA1
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(key, "HmacSHA1"));
        byte[] hash = mac.doFinal(timeBytes);

        // Dynamic truncation
        int offset = hash[hash.length - 1] & 0x0F;
        int code = ((hash[offset] & 0x7F) << 24)
                 | ((hash[offset + 1] & 0xFF) << 16)
                 | ((hash[offset + 2] & 0xFF) << 8)
                 | (hash[offset + 3] & 0xFF);

        code = code % (int) Math.pow(10, DIGITS);
        return String.format("%0" + DIGITS + "d", code);
    }

    // Minimal Base32 decoder: handles the standard alphabet used by authenticator apps
    private static byte[] base32Decode(String input) {
        input = input.toUpperCase().replaceAll("=", "");
        String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
        int buffer = 0;
        int bitsLeft = 0;
        byte[] result = new byte[input.length() * 5 / 8];
        int index = 0;

        for (char c : input.toCharArray()) {
            buffer = (buffer << 5) | alphabet.indexOf(c);
            bitsLeft += 5;
            if (bitsLeft >= 8) {
                result[index++] = (byte) (buffer >> (bitsLeft - 8));
                bitsLeft -= 8;
            }
        }
        return result;
    }
}

Step 2: Write the session handling action

Create TotpSessionHandlingAction.java implementing SessionHandlingAction. The interface declares:

  • name(): the label Burp shows in the session-handling-rule dropdown when you select “Invoke a Burp extension”.
  • performAction(...): Burp calls this as it is about to send an in-scope request. Read the request from actionData.request(), and return an ActionResult wrapping the (possibly modified) request.

Notice what’s not here: no path matching. The session handling rule’s scope decides which requests this runs on (Step 4), not code, so the action generates a code and injects it. Wrap the generation in a try/catch so a failure returns the request unchanged rather than dropping it.

Tip: On implementing the interface and handling failures, see Programming Concepts: Interfaces and @Override and try/catch.

Hint: immutability

Montoya HTTP objects are immutable. withUpdatedHeader(...) returns a new request. You must pass that new object to ActionResult.actionResult(...), not the original. If you return the original, Burp silently discards your change.

Solution: `TotpSessionHandlingAction.java`

import burp.api.montoya.MontoyaApi;
import burp.api.montoya.http.message.requests.HttpRequest;
import burp.api.montoya.http.sessions.ActionResult;
import burp.api.montoya.http.sessions.SessionHandlingAction;
import burp.api.montoya.http.sessions.SessionHandlingActionData;

import static burp.api.montoya.http.sessions.ActionResult.actionResult;

public class TotpSessionHandlingAction implements SessionHandlingAction {

    private final MontoyaApi api;
    private final String totpSecret;

    // The header the application expects the TOTP code in
    private static final String TOTP_HEADER = "X-TOTP-Code";

    public TotpSessionHandlingAction(MontoyaApi api, String totpSecret) {
        this.api = api;
        this.totpSecret = totpSecret;
    }

    @Override
    public String name() {
        // This is what appears in the session-handling-rule action dropdown
        return "Inject fresh TOTP code";
    }

    @Override
    public ActionResult performAction(SessionHandlingActionData actionData) {
        HttpRequest request = actionData.request();

        try {
            String code = TotpGenerator.generate(totpSecret);
            api.logging().logToOutput("Injecting TOTP code: " + code);

            // Add (or replace) the TOTP header, then return the NEW request
            HttpRequest updated = request.withUpdatedHeader(TOTP_HEADER, code);
            return actionResult(updated);

        } catch (Exception e) {
            api.logging().logToError("TOTP generation failed: " + e.getMessage());
            return actionResult(request); // send unchanged rather than dropping it
        }
    }
}
  • TOTP_HEADER: where the application expects the code. If it’s a parameter or body field, use withUpdatedParameters() or withBody() instead of withUpdatedHeader() (see Taking it further).
  • No target-path check: the session handling rule’s scope decides which requests reach this action.

Step 3: Register the action

In initialize(), register the action with montoyaApi.http().registerSessionHandlingAction(...). Supply the shared secret. Registering it makes the action available to session handling rules. It doesn’t run anything on its own; that’s what Step 4 sets up.

Tip: On initialize() and the montoyaApi object, see Programming Concepts: The MontoyaApi entry point.

Solution

@Override
public void initialize(MontoyaApi montoyaApi) {
    montoyaApi.extension().setName("TOTP Session Handler");
    montoyaApi.logging().logToOutput("TOTP Session Handler loaded.");

    // Replace this with your actual shared secret (Base32-encoded)
    String totpSecret = "JBSWY3DPEHPK3PXP";

    montoyaApi.http().registerSessionHandlingAction(new TotpSessionHandlingAction(montoyaApi, totpSecret));
}

Note: Hardcoding the secret is fine for a workshop. In production, retrieve it from api.persistence() (stored in the Burp project file) or from a UI input field registered via api.userInterface().

Step 4: Create the session handling rule

Registering the action isn’t enough. A session handling rule is what invokes it. This is the step that makes the code fire, and the one people miss. In Burp:

  1. Open Settings (top of the window) and go to Sessions (under Project settings; type “sessions” in the settings search if you can’t spot it).
  2. Click Add under Session handling rules. The rule editor opens.
  3. Go to the Details tab and give it a description such as Inject TOTP.
  4. Add the action:
    1. Click Add > Invoke a Burp extension under Rule actions.
    2. In the Select extension action handler dropdown, select Inject fresh TOTP code (the name() you returned).
    3. Click OK.
  5. Go to the Scope tab:
    • Tools scope: select the tools the rule should apply to. For this exercise select Repeater (add Scanner / Intruder too if you want to try them).
    • URL scope: select Include all URLs for the workshop. (In real use, scope this to your target so you’re not attaching the header everywhere.)
  6. Click OK to save the rule.

What this rule does

From now on, whenever an in-scope tool is about to send a request to an in-scope URL, Burp runs your action first and sends the modified request. That’s how one action covers Repeater, Scanner, and Intruder at once, something a proxy handler can’t do, because those tools never touch the Proxy.

Step 5: Build, reload, and test

Run ./gradlew jar. With auto-reload enabled, Burp reloads the extension for you. Confirm TOTP Session Handler loaded. in Extensions > Output. (Reloading re-registers the action; the rule from Step 4 keeps pointing at it by name.)

  1. Start the TOTP demo server.
  2. Send a request to http://localhost:8888/login/totp in Repeater. Don’t add the header yourself. The rule invokes your action, which does.
  3. Watch Extensions > Output for Injecting TOTP code: XXXXXX, and the demo server’s console, which prints the received code, expected code, and verdict.

A correct code returns 200 {"status":"granted"}; a missing or stale one returns 401.

The real proof this beats a captured code: click Send again a minute later. A static code you’d pasted in would be stale by now, but your action regenerates every time, so it still returns 200.

Debugging

  • Action never fires? The most common cause is the rule, not the code. Confirm the session handling rule exists, its Tools scope includes Repeater (or whichever tool you’re using), and its URL scope covers the target. A registered action with no rule does nothing.
  • Fires but nothing changes? Confirm you pass the result of withUpdatedHeader() to actionResult(...). Montoya objects are immutable, so the change lives in the new object, not the original.
  • Action missing from the dropdown? Make sure the extension loaded without errors (Extensions > Output) before you open the rule editor.

Check your work

  • The action appears as Inject fresh TOTP code in the “Invoke a Burp extension” dropdown when you edit a session handling rule.
  • A request sent from an in-scope tool carries a fresh, correct code (compare against an authenticator app seeded with the same secret).
  • Re-sending the same request after the 30-second window still authenticates: the code is regenerated, not replayed.
  • Requests outside the rule’s scope pass through untouched.

The complete extension

Every file in its finished state. These files go in src/main/java/ in the starter project: Extension.java (replacing the template’s), the TOTP generator, and the session handling action. You configure the session handling rule from Step 4 in Burp’s UI, not in code.

`Extension.java`

import burp.api.montoya.BurpExtension;
import burp.api.montoya.MontoyaApi;

public class Extension implements BurpExtension {
    @Override
    public void initialize(MontoyaApi montoyaApi) {
        montoyaApi.extension().setName("TOTP Session Handler");
        montoyaApi.logging().logToOutput("TOTP Session Handler loaded.");

        // Replace this with your actual shared secret (Base32-encoded)
        String totpSecret = "JBSWY3DPEHPK3PXP";

        montoyaApi.http().registerSessionHandlingAction(new TotpSessionHandlingAction(montoyaApi, totpSecret));
    }
}

`TotpGenerator.java`

This is the library version from Step 1, with com.warrenstrange:googleauth:1.5.0 on the runtime classpath. For the pure-Java equivalent, see Step 1 (reference).

import com.warrenstrange.googleauth.GoogleAuthenticator;

public class TotpGenerator {

    public static String generate(String base32Secret) {
        // GoogleAuthenticator's defaults match the demo server: 6 digits, 30-second window, HMAC-SHA1
        int code = new GoogleAuthenticator().getTotpPassword(base32Secret);
        return String.format("%06d", code);
    }
}

`TotpSessionHandlingAction.java`

import burp.api.montoya.MontoyaApi;
import burp.api.montoya.http.message.requests.HttpRequest;
import burp.api.montoya.http.sessions.ActionResult;
import burp.api.montoya.http.sessions.SessionHandlingAction;
import burp.api.montoya.http.sessions.SessionHandlingActionData;

import static burp.api.montoya.http.sessions.ActionResult.actionResult;

public class TotpSessionHandlingAction implements SessionHandlingAction {

    private final MontoyaApi api;
    private final String totpSecret;

    // The header the application expects the TOTP code in
    private static final String TOTP_HEADER = "X-TOTP-Code";

    public TotpSessionHandlingAction(MontoyaApi api, String totpSecret) {
        this.api = api;
        this.totpSecret = totpSecret;
    }

    @Override
    public String name() {
        // This is what appears in the session-handling-rule action dropdown
        return "Inject fresh TOTP code";
    }

    @Override
    public ActionResult performAction(SessionHandlingActionData actionData) {
        HttpRequest request = actionData.request();

        try {
            String code = TotpGenerator.generate(totpSecret);
            api.logging().logToOutput("Injecting TOTP code: " + code);

            // Add (or replace) the TOTP header, then return the NEW request
            HttpRequest updated = request.withUpdatedHeader(TOTP_HEADER, code);
            return actionResult(updated);

        } catch (Exception e) {
            api.logging().logToError("TOTP generation failed: " + e.getMessage());
            return actionResult(request); // send unchanged rather than dropping it
        }
    }
}

Taking it further

Inject into a body parameter instead of a header

If the application expects the code in the body rather than a header, update the body. For an application/x-www-form-urlencoded POST:

Show the body-injection variant

// Get the current request and its body
HttpRequest request = actionData.request();
String body = request.bodyToString();

// Add or replace the totp parameter
String newBody = body + (body.isEmpty() ? "" : "&") + "totp=" + code;

return actionResult(request.withBody(newBody));

For JSON bodies, replace the relevant field with string manipulation or a JSON library added to build.gradle.

Persist the secret in the project file

Use api.persistence().extensionData() to store and retrieve the secret so it survives extension reloads. Load it in initialize(), seeding a default the first time.

Solution
import burp.api.montoya.persistence.PersistedObject;

// In initialize():
PersistedObject data = montoyaApi.persistence().extensionData();
String totpSecret = data.getString("totpSecret");
if (totpSecret == null) {
    totpSecret = "JBSWY3DPEHPK3PXP"; // default on first run
    data.setString("totpSecret", totpSecret);
}

montoyaApi.http().registerSessionHandlingAction(new TotpSessionHandlingAction(montoyaApi, totpSecret));

Add a settings panel

Build the panel with SettingsPanelBuilder instead of building the Swing UI by hand. Burp lays it out, adds it under Settings, and persists the values for you. PROJECT_SETTINGS stores them in the project file, the same way api.persistence() does, so you get storage and UI in one step. (The rule’s scope already handles which requests it applies to.)

Solution
import burp.api.montoya.ui.settings.SettingsPanelPersistence;
import burp.api.montoya.ui.settings.SettingsPanelWithData;

import static burp.api.montoya.ui.settings.SettingsPanelBuilder.settingsPanel;
import static burp.api.montoya.ui.settings.SettingsPanelSetting.stringSetting;

// In initialize():
SettingsPanelWithData settings = settingsPanel()
        .withPersistence(SettingsPanelPersistence.PROJECT_SETTINGS)
        .withTitle("TOTP Session Handler")
        .withDescription("Credential injected by the session handling action.")
        .withSettings(
                stringSetting("TOTP secret (Base32)", "JBSWY3DPEHPK3PXP"),
                stringSetting("Header name", "X-TOTP-Code"))
        .build();

montoyaApi.userInterface().registerSettingsPanel(settings);

// Hand the settings object to the action instead of a bare secret string
montoyaApi.http().registerSessionHandlingAction(new TotpSessionHandlingAction(montoyaApi, settings));

The action now holds the panel instead of a bare secret. Update its constructor and read both values inside performAction() by name, so a change in the UI takes effect on the next request with no rebuild:

import burp.api.montoya.ui.settings.SettingsPanelWithData;

private final MontoyaApi api;
private final SettingsPanelWithData settings;

public TotpSessionHandlingAction(MontoyaApi api, SettingsPanelWithData settings) {
    this.api = api;
    this.settings = settings;
}

// In performAction():
String code = TotpGenerator.generate(settings.getString("TOTP secret (Base32)"));
HttpRequest updated = request.withUpdatedHeader(settings.getString("Header name"), code);
return actionResult(updated);

Handle multiple endpoints or a different credential

Create a separate session handling rule per target, each scoped to its own URL, or inspect actionData.request() inside performAction() and branch on the host or path. For HMAC-signed timestamps, the same pattern applies: swap TotpGenerator for your signing logic.

Solution
@Override
public ActionResult performAction(SessionHandlingActionData actionData) {
    HttpRequest request = actionData.request();

    try {
        switch (request.httpService().host()) {
            case "api.example.com":
                // TOTP-protected endpoint
                return actionResult(request.withUpdatedHeader(
                        TOTP_HEADER, TotpGenerator.generate(totpSecret)));
            case "legacy.example.com":
                // A different credential entirely, same injection pattern
                return actionResult(request.withUpdatedHeader("X-Signature", sign(request)));
            default:
                return actionResult(request); // not a target we handle, pass through
        }
    } catch (Exception e) {
        api.logging().logToError("Credential injection failed: " + e.getMessage());
        return actionResult(request);
    }
}

sign(request) stands in for your own signing routine, for example an HMAC over the timestamp and path. The branching keeps one action covering several targets; the session handling rule’s scope still decides which requests reach it.