cybersecurity · intermediate · ~12 min · safe pentest lab

Extract the method from a SIP request

Bounded text-token extraction with character allow-list.

Challenge

Extract the method token from a SIP request, validating it strictly — SIP gateways live on the public internet, so rejecting malformed methods early is cheap insurance.

Task

Implement int parse_sip_method(const char *msg, char *out, size_t cap) that copies the leading method token (everything up to the first space) into out, NUL-terminating, and returns the number of bytes written.

Input

  • msg: a NUL-terminated SIP message the grader passes.
  • out, cap: the output buffer and its capacity.

Output

Returns int: the number of bytes written (the method length) on success, or -1 on failure.

Example

"INVITE sip:a@b SIP/2.0\r\n", cap 8   ->   out = "INVITE", returns 6
"REGISTER sip:a", cap 8                ->   -1   (8 chars + NUL exceeds cap)
"register sip:...", cap 32             ->   -1   (lowercase)

Edge cases

  • NULL msg, NULL out, or cap == 0 returns -1.
  • No space within the first 16 bytes returns -1 (no real method is that long).
  • Any character before the first space outside A-Z returns -1 (this also rejects an embedded NUL).
  • The method must fit in cap with room for the NUL.

Rules

  • Allow-list A-Z only for method characters.

Why this matters

SIP gateways live on the public internet. Rejecting malformed methods at the door is cheap; missing the check is expensive.

Input format

A NUL-terminated SIP message, a bounded output buffer, and its capacity.

Output format

Bytes written (positive int) on success, -1 on any failure.

Constraints

Allow-list A-Z only. Reject if method >= 16 bytes (no method is that long).

Starter code

#include <stddef.h>

int parse_sip_method(const char *msg, char *out, size_t cap) {
    /* TODO */
    (void)msg; (void)out; (void)cap;
    return -1;
}

Common mistakes

Forgetting room for the NUL. Allowing the empty method. Not capping the search at 16 bytes (potential read past a small buffer).

Edge cases to handle

cap exactly len+1 (just fits). First byte is space → empty method → -1. NULL inputs.

Complexity

O(1) — bounded loop over at most 16 bytes.

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.