FAQ - Help and questions

How do I add a cross-site request check (CSRF defence) to an axum app?

#axum#csrf#security#middlewarepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Browsers attach cookies to requests that another site triggers, so a forged form post can act as the logged-in user. Use SameSite cookies and a CSRF token on state-changing requests; as an extra layer, refuse unsafe methods whose Origin header names another site, as in the middleware below.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Cross-site request forgery works because a browser sends your site's cookies even when the request was started by a page on another site. The OWASP cheat sheet recommends tokens (the synchronizer token pattern) as the main defence, with SameSite cookies and checks of the Origin header as additional layers. This thread shows the Origin layer only; it is not a complete defence on its own.

src/main.rsrust
use axum::{
    body::{to_bytes, Body},
    extract::Request,
    http::{header, Method, StatusCode},
    middleware::{self, Next},
    response::Response,
    routing::{get, post},
    Router,
};
use tower::ServiceExt;

const SITE: &str = "https://shop.example";

/// Refuse state-changing requests that a browser says came from another site.
async fn same_origin_only(req: Request, next: Next) -> Result<Response, StatusCode> {
    let safe = matches!(*req.method(), Method::GET | Method::HEAD | Method::OPTIONS);
    if !safe {
        if let Some(origin) = req.headers().get(header::ORIGIN) {
            if origin.as_bytes() != SITE.as_bytes() {
                return Err(StatusCode::FORBIDDEN);
            }
        }
    }
    Ok(next.run(req).await)
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "page" }))
        .route("/delete-account", post(|| async { "deleted" }))
        .layer(middleware::from_fn(same_origin_only));
    for (method, uri, origin) in [
        ("GET", "/", Some("https://evil.example")),
        ("POST", "/delete-account", Some("https://shop.example")),
        ("POST", "/delete-account", Some("https://evil.example")),
        ("POST", "/delete-account", None),
    ] {
        let mut b = Request::builder().method(method).uri(uri);
        if let Some(o) = origin { b = b.header(header::ORIGIN, o); }
        let res = app.clone().oneshot(b.body(Body::empty()).unwrap()).await.unwrap();
        let status = res.status().as_u16();
        let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
        println!("{method} {uri} Origin={origin:?} -> {status} {:?}", String::from_utf8_lossy(&body));
    }
}
text
GET / Origin=Some("https://evil.example") -> 200 "page"
POST /delete-account Origin=Some("https://shop.example") -> 200 "deleted"
POST /delete-account Origin=Some("https://evil.example") -> 403 ""
POST /delete-account Origin=None -> 200 "deleted"
  • Safe methods (GET, HEAD, OPTIONS) pass: they must never change data.
  • A POST whose Origin is the site itself passes.
  • A POST whose Origin is another site gets 403.
  • A POST without an Origin header passed. This middleware chooses to allow it, because non-browser clients (scripts, curl) do not send one. That is a trade-off: a stricter site may want to require a token as well, which this thread does not show.

Common mistakes#

  • Changing data on GET requests (a "delete" link). No origin check can then help, since links are followed from other sites.
  • Relying on one measure. OWASP says SameSite alone is a defence in depth unless specific conditions hold; read the cheat sheet's list.
  • Comparing Origin with starts_with: https://shop.example.evil.example starts with the site's name. Compare the whole value, as the code does.

Where does the token go?#

Generate a random token per session, store it server-side, put it in a hidden form field, and compare it on every unsafe request. The OWASP page describes the patterns in detail; this thread did not compile token code.

Does CORS stop CSRF?#

No. CORS controls which pages may read responses; a forged form post is sent regardless (see the CORS thread).

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet