Csilk 0.2.1
A lightweight, high-performance C HTTP web framework
Loading...
Searching...
No Matches
csrf.c File Reference

Stateless CSRF protection middleware implementation. More...

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "csilk/core/internal.h"
#include "csilk/csilk.h"
Include dependency graph for csrf.c:

Functions

void csilk_csrf_middleware (csilk_ctx_t *c)
 Stateless CSRF protection middleware (cookie + header token comparison).
 
int csilk_csrf_generate_token (char *buf, size_t buf_size)
 Generate a cryptographically random CSRF token.
 

Detailed Description

Stateless CSRF protection middleware implementation.

Function Documentation

◆ csilk_csrf_generate_token()

int csilk_csrf_generate_token ( char *  buf,
size_t  buf_size 
)

Generate a cryptographically random CSRF token.

Reads 16 bytes from /dev/urandom and formats them as a 32-character hex string (plus null terminator). If /dev/urandom cannot be opened, falls back to a weak PRNG seeded with time XOR pid.

Parameters
bufOutput buffer to receive the null-terminated hex token.
buf_sizeSize of the output buffer. Must be at least 33 bytes.
Returns
0 on success, -1 if buf is NULL, buf_size < 33, or fread fails.
Warning
The fallback path uses rand_r() which is NOT cryptographically secure. Production deployments should always ensure /dev/urandom is available.

◆ csilk_csrf_middleware()

void csilk_csrf_middleware ( csilk_ctx_t *  c)

Stateless CSRF protection middleware (cookie + header token comparison).

Stateless CSRF protection middleware.

On safe HTTP methods (GET, HEAD, OPTIONS), the middleware ensures a CSRF cookie called "csrf_token" is present (generating one if missing) and proceeds to the next handler.

On state-changing methods (POST, PUT, DELETE, etc.), it validates the X-CSRF-Token request header against the csrf_token cookie. If the tokens do not match or the header is absent, a 403 Forbidden response is returned and the pipeline is aborted.

Parameters
cThe request context.
Note
Must be registered before any handler that mutates server state.
Warning
The token is generated from /dev/urandom when available, with a weak fallback (time + pid). In high-security deployments, ensure /dev/urandom is accessible.