Evitando CSRF con Remix

Rate this content
Bookmark

Las 'Escrituras de Datos' de Remix vuelven a los fundamentos de la web cuando se trata de envío de formularios. Pero ahí radica una trampa si no tienes cuidado: el Cross-Site Request Forgery (CSRF) puede aparecer. En esta sesión exploraremos qué es CSRF, cómo puede ser explotado y qué puedes hacer para asegurarte de que tu aplicación Remix no sea vulnerable.

7 min
10 Jun, 2022

Video Summary and Transcription

Bienvenido a mi sesión sobre cómo evitar CSRF con Remix. Remix ayuda a proteger contra CSRF al pensar en acciones en términos de elementos de formulario HTML. Para evitar CSRF con Remix, establece el mismo atributo de sitio en las cookies y considera usar un token además del atributo. El enfoque basado en tokens implica generar un token único por sesión y formulario, transmitirlo con el formulario, enviarlo de vuelta cuando el usuario envía el formulario y validar de forma segura en el lado del servidor.

Available in English

1. Introducción a CSRF y Remix

Short description:

Bienvenido a mi sesión sobre cómo evitar CSRF con Remix. CSRF significa Cross-Site Request Forgery, donde el atacante engaña al usuario para que acceda a una URL y realice una acción utilizando su sesión existente. Incluso si se utiliza el método POST, se puede lograr una explotación con un iframe y una URL separada. Remix ayuda a proteger contra CSRF al pensar en las acciones en términos de elementos de formulario HTML. Para evitar CSRF con Remix, establezca el mismo atributo de sitio en las cookies y considere utilizar un token además del atributo.

Hola y bienvenido a mi sesión sobre cómo evitar CSRF con Remix. Esta es una charla rápida, así que vamos a pasar por esto de manera bastante rápida. Comencemos hablando de qué es CSRF. Como la mayoría de las explotaciones de seguridad, tiene un acrónimo y significa Cross-Site Request Forgery. Y en este escenario, básicamente el atacante engaña al usuario para que acceda a la URL y luego esta URL realizará una acción utilizando su sesión existente.

Un ejemplo simple, o tal vez el peor ejemplo, es una imagen con una URL y esa URL realiza una acción. Antes de que digas que quieres escribir código como este, he visto esto en aplicaciones que he auditado, y obviamente lo primero que el usuario está haciendo mal aquí es que está utilizando GET para realizar alguna acción. Pero igualmente, este tipo de explotación se puede lograr incluso si se utiliza POST. Y lo hacemos teniendo un iframe con una altura y ancho ocultos, y eso incrusta una URL separada. Y en esa URL tenemos el formulario, el POST a ese endpoint, y tenemos una función onload que lo envía tan pronto como se carga el formulario.

Así que hablemos un poco de Remix. Remix te hace pensar en las acciones en términos de los bloques de construcción de la web, que son los elementos de formulario HTML. Y si has estado construyendo aplicaciones con JavaScript, probablemente hayas estado usando cosas como Fetch o Axios, y en estos escenarios, por supuesto, te protege. A menos que, por supuesto, estés usando access, allow origin, ya sabes, star, y estás permitiendo que las credenciales pasen. Y en ese caso, estás en la misma situación. Así que porque estamos enviando formularios nuevamente a través de datos de formulario multiparte, necesitamos pensar en Cross-Site Request Forgery.

Así que veamos un ejemplo simple de formulario Remix. Aquí tenemos un formulario primitivo con un campo de texto y un botón de enviar. Tenemos algún tipo de cargador para verificar que el usuario tenga una sesión autenticada porque Cross-Site Request Forgery requiere que estén conectados. Ya sabes, estás realizando una acción utilizando su sesión existente que no pretendían hacer. Y por lo tanto, no vamos a entrar en los detalles aquí, pero sí, el cargador se asegura de que el usuario tenga una sesión. Luego tenemos una acción en nuestro componente que hace alguna escritura en la base de datos o similar. Algo que realiza alguna acción que, ya sabes, no se puede revertir. Entonces, ¿cómo evitas Cross-Site Request Forgery con Remix en este escenario? Bueno, lo primero que debes hacer es establecer el mismo atributo de sitio en tus cookies. Puedes establecerlo como lax, lo que significa que el navegador solo enviará las cookies si es una solicitud GET que proviene de otro dominio. O puedes establecerlo como strict, lo que significa que no enviará ninguna cookie para ninguna solicitud que se origine desde otro dominio. Por lo tanto, es posible que debas verificar si estás utilizando algún tipo de flujo de autenticación que redirige a otros sitios para determinar cuál es el más apropiado para tu sitio. Pero desafortunadamente, según OWASP, esto no es suficiente y no debemos reemplazarlo con un token. Y la razón principal de eso es que solo el 93% de los navegadores admiten el atributo de mismo sitio en esta etapa. Casi estamos allí.

2. Generación y Validación de Tokens CSRF

Short description:

El enfoque basado en tokens implica un proceso de cuatro pasos: generar un token único por sesión y formulario, transmitirlo con el formulario, enviarlo de vuelta cuando el usuario envía el formulario y validarlo de forma segura en el lado del servidor. Para generar el token, se generan claves aleatorias seguras, incluyendo una sal de hash y una clave privada. El token se transmite con el cargador y se devuelve en los datos del cargador, que se pueden acceder en el formulario. La validación se realiza regenerando el token y comparándolo con la versión enviada. Si no coinciden, se genera un error.

Tu aplicación puede tener más dependiendo de la mezcla de navegadores de tus usuarios. Por lo tanto, el enfoque basado en tokens se llama comúnmente el patrón de token sincronizado y básicamente es un proceso de cuatro pasos.

Lo primero que debes hacer es generar un token único por sesión, por formulario. Debes transmitirlo con el formulario. Debes enviarlo de vuelta cuando el usuario envía el formulario y luego debes validarlo de forma segura en el lado del servidor.

Así que comenzamos generando algunas claves aleatorias seguras. Generamos una sal de hash y esto es algo que no debes almacenar en tu database. Debe estar en disco o en variables de entorno para que si tu database se ve comprometida incluso entonces la sal de hash no se filtre. También debes tener una clave privada y ambas puedes generarlas usando el paquete de bytes aleatorios de crypto.

Entonces, el primer paso es generar una semilla aleatoria única por sesión y lo hacemos comprobando si la semilla ya existe en la sesión. Si existe, la utilizamos. Si no existe, generamos una nueva semilla utilizando nuevamente la función de bytes aleatorios y la almacenamos en la sesión. Luego necesitamos generar un token único por sesión e identificador y en este escenario el identificador sería algo único para ese formulario u operación y esto evita que el mismo token sea válido para dos operaciones diferentes y evita la reutilización de tokens.

Para hacer esto, tomamos ese hash, por lo que tomamos nuestra clave privada, también tomamos la semilla y combinamos las tres y creamos un digest HMAC de eso, que es básicamente un hash. Nos da un token único agradable. Tenemos que transmitir ese token con el cargador. Lo primero que hacemos es generar el token y devolverlo en nuestros datos del cargador y eso significa que luego podemos obtenerlo en nuestro formulario usando los datos de la ruta. Así obtenemos nuestro token CSRF de allí y lo transmitimos en el formulario en nuestro campo oculto.

Luego necesitamos validar el código, por lo que si escribimos una pequeña función de utilidad para validar lo regenerará el token basado en el identificador único y la sesión y luego comparará los dos usando equals seguro en tiempo contra la versión que se envió con el formulario. Usamos equals seguro en tiempo aquí para evitar ataques de tiempo.

Entonces, ¿cómo usamos esta función de utilidad? En nuestra acción, simplemente podemos llamar a validate CRSF token usando el valor del formulario enviado y si los dos no coinciden, lanzamos un error. Así es como se realiza la validación de CSRF en Remix. Si tienes alguna pregunta, por favor contáctame a través del servidor de Discord de GitHub para esta conferencia o puedes enviarme un mensaje en Twitter. Gracias.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

React Summit Remote Edition 2021React Summit Remote Edition 2021
33 min
Building Better Websites with Remix
Top Content
Remix is a new web framework from the creators of React Router that helps you build better, faster websites through a solid understanding of web fundamentals. Remix takes care of the heavy lifting like server rendering, code splitting, prefetching, and navigation and leaves you with the fun part: building something awesome!
React Advanced Conference 2021React Advanced Conference 2021
39 min
Don't Solve Problems, Eliminate Them
Top Content
Humans are natural problem solvers and we're good enough at it that we've survived over the centuries and become the dominant species of the planet. Because we're so good at it, we sometimes become problem seekers too–looking for problems we can solve. Those who most successfully accomplish their goals are the problem eliminators. Let's talk about the distinction between solving and eliminating problems with examples from inside and outside the coding world.
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
Do you have a large product built by many teams? Are you struggling to release often? Did your frontend turn into a massive unmaintainable monolith? If, like me, you’ve answered yes to any of those questions, this talk is for you! I’ll show you exactly how you can build a micro frontend architecture with Remix to solve those challenges.
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
Remix is a web framework that gives you the simple mental model of a Multi-Page App (MPA) but the power and capabilities of a Single-Page App (SPA). One of the big challenges of SPAs is network management resulting in a great deal of indirection and buggy code. This is especially noticeable in application state which Remix completely eliminates, but it's also an issue in individual components that communicate with a single-purpose backend endpoint (like a combobox search for example).
In this talk, Kent will demonstrate how Remix enables you to build complex UI components that are connected to a backend in the simplest and most powerful way you've ever seen. Leaving you time to chill with your family or whatever else you do for fun.
Node Congress 2022Node Congress 2022
26 min
It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Top Content
Do you know what’s really going on in your node_modules folder? Software supply chain attacks have exploded over the past 12 months and they’re only accelerating in 2022 and beyond. We’ll dive into examples of recent supply chain attacks and what concrete steps you can take to protect your team from this emerging threat.
You can check the slides for Feross' talk here.

Workshops on related topic

React Summit 2022React Summit 2022
136 min
Remix Fundamentals
Top Content
Featured WorkshopFree
Building modern web applications is riddled with complexity And that's only if you bother to deal with the problems
Tired of wiring up onSubmit to backend APIs and making sure your client-side cache stays up-to-date? Wouldn't it be cool to be able to use the global nature of CSS to your benefit, rather than find tools or conventions to avoid or work around it? And how would you like nested layouts with intelligent and performance optimized data management that just works™?
Remix solves some of these problems, and completely eliminates the rest. You don't even have to think about server cache management or global CSS namespace clashes. It's not that Remix has APIs to avoid these problems, they simply don't exist when you're using Remix. Oh, and you don't need that huge complex graphql client when you're using Remix. They've got you covered. Ready to build faster apps faster?
At the end of this workshop, you'll know how to:- Create Remix Routes- Style Remix applications- Load data in Remix loaders- Mutate data with forms and actions
React Summit 2023React Summit 2023
106 min
Back to the Roots With Remix
Featured Workshop
The modern web would be different without rich client-side applications supported by powerful frameworks: React, Angular, Vue, Lit, and many others. These frameworks rely on client-side JavaScript, which is their core. However, there are other approaches to rendering. One of them (quite old, by the way) is server-side rendering entirely without JavaScript. Let's find out if this is a good idea and how Remix can help us with it?
Prerequisites- Good understanding of JavaScript or TypeScript- It would help to have experience with React, Redux, Node.js and writing FrontEnd and BackEnd applications- Preinstall Node.js, npm- We prefer to use VSCode, but also cloud IDEs such as codesandbox (other IDEs are also ok)
Remix Conf Europe 2022Remix Conf Europe 2022
195 min
How to Solve Real-World Problems with Remix
Featured Workshop
- Errors? How to render and log your server and client errorsa - When to return errors vs throwb - Setup logging service like Sentry, LogRocket, and Bugsnag- Forms? How to validate and handle multi-page formsa - Use zod to validate form data in your actionb - Step through multi-page forms without losing data- Stuck? How to patch bugs or missing features in Remix so you can move ona - Use patch-package to quickly fix your Remix installb - Show tool for managing multiple patches and cherry-pick open PRs- Users? How to handle multi-tenant apps with Prismaa - Determine tenant by host or by userb - Multiple database or single database/multiple schemasc - Ensures tenant data always separate from others
Remix Conf Europe 2022Remix Conf Europe 2022
156 min
Build and Launch a personal blog using Remix and Vercel
Featured Workshop
In this workshop we will learn how to build a personal blog from scratch using Remix, TailwindCSS. The blog will be hosted on Vercel and all the content will be dynamically served from a separate GitHub repository. We will be using HTTP Caching for the blog posts.
What we want to achieve at the end of the workshop is to have a list of our blog posts displayed on the deployed version of the website, the ability to filter them and to read them individually.
Table of contents: - Setup a Remix Project with a predefined stack- Install additional dependencies- Read content from GiHub- Display Content from GitHub- Parse the content and load it within our app using mdx-bundler- Create separate blog post page to have them displayed standalone- Add filters on the initial list of blog posts
React Summit 2023React Summit 2023
56 min
0 to Auth in an hour with ReactJS
WorkshopFree
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool. There are multiple alternatives that are much better than passwords to identify and authenticate your users - including SSO, SAML, OAuth, Magic Links, One-Time Passwords, and Authenticator Apps.
While addressing security aspects and avoiding common pitfalls, we will enhance a full-stack JS application (Node.js backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session securely for subsequent client requests, validating / refreshing sessions- Basic Authorization - extracting and validating claims from the session token JWT and handling authorization in backend flows
At the end of the workshop, we will also touch other approaches of authentication implementation with Descope - using frontend or backend SDKs.
React Advanced Conference 2023React Advanced Conference 2023
104 min
Building High-Performance Online Stores with Shopify Hydrogen and Remix
WorkshopFree
I. Introduction- Overview of Shopify Hydrogen and Remix- Importance of headless e-commerce and its impact on the industry
II. Setting up Shopify Hydrogen- Installing and setting up Hydrogen with Remix- Setting up the project structure and components
III. Creating Collections and Products- Creating collections and products using Hydrogen’s React components- Implementing a Shopping Cart- Building a shopping cart using Hydrogen’s built-in components
VI. Building the home page with Storyblok- Cloning the space and explaining how it works- Implementing Storyblok in the repo- Creating the Blok components- Creating the Shopify components- Implementing personalisation