cybersecurity · intermediate · ~15 min · safe pentest lab

Write a USTAR tar header for one file

Bit-exact rendering of a fixed-layout binary header with self-referential checksum.

Challenge

Your job

Implement:

#include <stdint.h>
#include <stddef.h>
int write_ustar_header(const char *name, size_t size, uint8_t out[512]);

Fill out with a USTAR header for one file:

Offset Length Field Format
0 100 name NUL-padded ASCII
100 8 mode "0000644\0"
124 12 size octal ASCII + NUL
148 8 checksum 6 octal digits + NUL + space
156 1 typeflag '0'
257 6 magic "ustar\0"
263 2 version "00"

Everything else is zero.

Checksum: sum of all 512 bytes of the header as if the checksum field were 8 spaces, then write that sum as 6 octal digits + NUL + space at offset 148.

Return 0 on success, -1 if:

  • name is NULL, out is NULL
  • strlen(name) >= 100
  • size needs more than 11 octal digits (size > 0o77777777777, i.e.

    2^33 - 1)

Hints

  1. (concept) Write the spaces FIRST, sum the whole header, THEN overwrite the checksum field with the real value.
  2. (common bug) Writing size in decimal. tar is octal.
  3. (direction) snprintf((char*)out + 124, 12, "%011lo", (unsigned long)size);.

Why this matters

Engagement deliverables ship as .tar bundles. Reading a tar header by hand once means you can audit any archive a teammate hands you.

Input format

Filename string + file size + 512-byte output buffer.

Output format

0 on success, -1 on failure.

Constraints

USTAR format only. Size in octal. Checksum computed with the field as spaces.

Starter code

#include <stdint.h>
#include <stddef.h>
int write_ustar_header(const char *name, size_t size, uint8_t out[512]) {
    /* TODO */
    (void)name; (void)size; (void)out;
    return -1;
}

Common mistakes

Computing the checksum BEFORE the spaces are placed. Forgetting the NUL+space terminator on the checksum. Writing the size in decimal.

Edge cases to handle

Maximum 11-octal-digit size. Long name boundary at exactly 100 chars (must be < 100). NULL inputs.

Complexity

O(1) — fixed 512-byte buffer.

Background lessons

Up next

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