Code to stop CSRF attacks.#1
Conversation
But doesn't yet verify it.
I think it's because Giraffe.Antiforgery is built against an older version of Giraffe.
Two CSRF vulnerabilities patched between versions 2.49 and 2.50. https://pkg.go.dev/vuln/GO-2023-2115 https://pkg.go.dev/vuln/GO-2023-2116 Conclusion, Fiber was written by amateurs.
This reverts commit 2b1f220.
| open Giraffe | ||
| open Giraffe.ViewEngine | ||
|
|
||
| // Generates a CSRF token using the Microsoft.AspNetCore.Antiforgery package, |
There was a problem hiding this comment.
Teerawat, I copied this code from https://github.com/pimbrouwers/Giraffe.Antiforgery. The main code doesn't call it yet. It doesn't seem to fit.
| bindQuery<CountPayload> (Some culture) (fun payload -> | ||
| htmlNodes (Views.counter payload.Count) | ||
| ) | ||
| let incrementHandler(next: HttpFunc)(ctx: HttpContext): HttpFuncResult = |
There was a problem hiding this comment.
Teerawat, please review lines 20 through 60 in this file. incrementHandler correctly validates the antiforgery token, and embeds the token in the form, but not in a way that's convenient to re-use in another handler.
I wish to refactor the code so the logic between lines 42 through 51 (minus the call to Views.counter) is easily reusable.
| [<CLIMutable>] | ||
| type CountPayload = { Count: int } | ||
| type IncrementForm = { Count: int } | ||
|
|
There was a problem hiding this comment.
| let requiresCsrfToken (invalidTokenHandler : HttpHandler) : HttpHandler = | |
| fun (next: HttpFunc) (ctx : HttpContext) -> | |
| let antiFrg = ctx.GetService<IAntiforgery>() | |
| (match antiFrg.IsRequestValidAsync(ctx) |> Async.AwaitTask |> Async.RunSynchronously with | |
| | true -> next | |
| | false -> invalidTokenHandler earlyReturn) ctx |
I think this handler can be used for validate Csrf Token. I copied this one from https://github.dev/pimbrouwers/Giraffe.Antiforgery
| htmlNodes (Views.counter payload.Count (af.GetAndStoreTokens ctx))) next ctx | ||
| | false -> RequestErrors.FORBIDDEN "forbidden" next ctx) | ||
|
|
||
| let counterHandler(next: HttpFunc)(ctx: HttpContext): HttpFuncResult = |
There was a problem hiding this comment.
I don't think we need this any more if you use csrfHtmlView function below
Teerawat's suggestions. Co-authored-by: Teerawat Wuttiwat <781147+twuttiwat@users.noreply.github.com>
|
@twuttiwat, With suggested changes, the code fails to compile with: /home/jeff/gitrepos/blazor-compared/GiraffeApp/Program.fs(44,49): error FS0039: The value, namespace, type or module 'af' is not defined. [/home/jeff/gitrepos/blazor-compared/GiraffeApp/GiraffeApp.fsproj] The build failed. Fix the build errors and run again. |
|
Please check at my recent PR. (Fix AntiForgery) @surferjeff |
still doesn't feel right.
…ntain its complexity with a csrfTokenFrom() function.
No description provided.