cybersecurity · intermediate · ~12 min · safe pentest lab

Extract the method from a SIP request

Bounded text-token extraction with character allow-list.

Challenge

Your job

Implement:

int parse_sip_method(const char *msg, char *out, size_t cap);

Copy the leading method token (everything up to the first space) into out, NUL-terminating. Return the number of bytes written.

Return -1 on any of these:

  • NULL msg or NULL out or cap == 0
  • No space found within the first 16 bytes
  • Method would overflow cap (need room for the NUL too)
  • Any character before the first space is not in A-Z

Examples

  • "INVITE sip:alice@... SIP/2.0\r\n", cap=8 → out="INVITE", return 6
  • "REGISTER ...", cap=8 → out="REGISTER"? cap-1=7 chars + NUL doesn't fit → return -1
  • "register sip:..." → -1 (lowercase)
  • "INVALID\0..." (NUL before space) → -1

Hints

  1. (concept) Find the first space, validate each byte before it, bounded-copy.
  2. (direction) for (i = 0; i < 16; ++i) if (msg[i] == ' ') break; then check i < 16.

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.