Implementing XSRF Tokens
view all blogs...

Justin Bess :: June 5, 2018

Explaining XSRF

XSRF is a malicious attack, in which an unauthorized action is taken on behalf of a client, and the server trusts that command, as if it was authenticated. There are a number of possible ways that an attacker could hijack your session and attempt to make requests on your behalf. Some exploits may be available due to poor security of the application itself. A malicious user may take advantage of a poor comment field, which allows HTML image tags to be used, without doing some checks. Let’s take a look at an example

Let’s assume that the application has a button attached to a form event. This event logs a user out and the script for this is located at /logout.php and now let’s also assume that a user with malicious intent comments the following HTML.
<img src="/logout.php"></img>
As you can see, the image tag is not being used correctly here to load an image. Instead, it’s being used with the link to the logout script. When the browser loads the page, it will request the /logout.php page. When this happens, it will undoubtedly log the user out!

Defeating XSRF with Tokens

Now that you know what XSRF is, we’ll talk about the steps to prevent these types of malicious attacks. The most common approach to solve this issue, is the Synchronizer token pattern, also simply known by it’s acronym (STP). STP is a technique where a token that is purely random and unique is generated, and then validated on the server side of the application. If the token is purely random and unique, then an attacker can not figure out the token, or possibly generate a valid token for the request. An example in an HTML form field, may look similar to the following
<input type="hidden" name="xsrf-token" value="KbyUmhTLMpYj7CD2di7JKP1P3qmLlkPt" />

Creating the Token

There are many ways you can generate the token, I’ll only cover a PHP 7+ way, to give you an idea of how it works. There are a ton of stacks, and possible technologies that could be used for this, so it wouldn’t be worth writing out examples for all of them.

session_start();
if (empty($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
}
$token = $_SESSION['token'];

Some notes to take away from this, is to not use md5(uniqid(rand(), TRUE)); This is because rand() is predictable and uniqid() only adds 29 bits of entropy. In addition, md5() itself does not add entropy, it only jumbles the data deterministically.

Comments

      November 23, 2018


      zvodret iluret

      I think other site proprietors should take this site as an model, very clean and excellent user friendly style and design, as well as the content. You are an expert in this topic!

      http://www.zvodretiluret.com/

      December 12, 2018


      SannyMok

      Nice posts! 🙂
      ___
      Sanny

      February 15, 2019


      BennyBYDAY

      Viagra

      February 15, 2019


      MichaelCrere

      paxil

      February 17, 2019


      BennyBYDAY

      Cialis

      February 18, 2019


      BrettFopsy

      Paxil

      February 18, 2019


      cialis generic

      Cialis Online medications may not be as popular as the industry-leading Viagra, but the ingredients in Cialis offer even better benefits to a man who suffers from impotence or erectile dysfunction.

      February 19, 2019


      BennyBYDAY

      xenical

      February 21, 2019


      comprar levitra

      La disfunción eréctil es un problema bastante frecuente en los hombres. El médico le realizará diversas preguntas con el objetivo de descubrir posibles factores de riesgo que podrían causar la Disfunción Eréctil o contribuir a su desarrollo. Es importante aclarar que, los hombres que toman alguna medicación para el tratamiento de la angina de pecho, no deben tomar estos fármacos. Comprar Levitra 20 mg contrareembolso. En muchos casos, la ansiedad por el desempeño se desencadena por un diálogo interno negativo: se preocupa por poder lograr una erección, complacer a un compañero o eyacular demasiado pronto.

      February 21, 2019


      Douglastup

      Xenical

      February 22, 2019


      comprar viagra

      Es fundamental implantar en el día a día unos hábitos de vida saludables, tales como una correcta alimentación y nutrición, practicar deporte y mantener unas horas de sueño suficientes y, muy importante, que den un descanso de calidad. En ausencia de problemas de salud física, debemos profundizar un poco más para determinar la causa subyacente de la disfunción eréctil. Comprar Viagra generico barato contrareembolso. La dificultad de la aplicación y la aparición de dolor y priapismo (duración de la erección de más de 2-3 horas), reducen mucho su uso. Existe un cuestionario, consensuado por la comunidad médica internacional, que está diseñado para ayudarle a identificar en que medida padece o no un problema de Disfunción Eréctil.

      February 22, 2019


      comprar levitra genérico

      Otra de las causas que pueden desencadenar este trastorno es padecer alguna enfermedad no diagnosticada que necesite un tratamiento. El tratamiento de la disfunción eréctil requiere una consulta franca y honesta entre el paciente y el médico y de ser posible, la pareja. La obesidad no solo afecta a las erecciones, sino también al deseo sexual. Los hombres a partir de los 40 son más propensos a sufrir problemas de impotencia durante las relaciones sexuales, algo que es meramente físico. https://comprarlevitra.com/

      February 23, 2019


      buy cialis online

      Your doctor can determine if your sexual disorder is caused by an underlying condition that requires treatment. An erection is the result of increased blood flow into your penis. Blood flow is usually stimulated by either sexual thoughts or direct contact with your penis. When a man becomes sexually excited, muscles in their penis relax. This relaxation allows for increased blood flow through the penile arteries. This blood fills two chambers inside the penis called the corpora cavernosa. As the chambers fill with blood, the penis grows rigid. Erection ends when the muscles contract and the accumulated blood can flow out through the penile veins.

      February 23, 2019


      cialis online

      This information will help your doctor understand your ED problem. Sometimes erectile dysfunction only occurs in certain situations. The medical history can reveal diseases and treatments that lead to ED. Color images on a computer screen show the speed and direction blood is flowing through a blood vessel. Like the rest of the ageing body, muscle tone in the penis reduces with age, as do many other aspects of sexual function. http://buycialis.online/blog/know-the-basics-of-cialis-before-you-start-taking-this-ed-drug.html

      February 24, 2019


      MichaelCrere

      orlistat

      February 24, 2019


      BennyBYDAY

      prozac

      February 25, 2019


      Charlesbox

      zofran

      February 26, 2019


      BennyBYDAY

      Toradol

      February 26, 2019


      BennyBYDAY

      abilify

      February 26, 2019


      MichaelCrere

      baclofen

      February 26, 2019


      Charlesbox

      toradol

      February 26, 2019


      BennyBYDAY

      valtrex

      February 27, 2019


      Kimbox

      cial

      February 27, 2019


      Charlesbox

      zoloft

      February 27, 2019


      Charlesbox

      abilify

      February 27, 2019


      Charlesbox

      lexapro

      February 28, 2019


      MichaelCrere

      valtrex

      February 28, 2019


      Charlesbox

      levitra

      March 1, 2019


      Charlesbox

      clomid

      March 2, 2019


      Janebox

      lasix

      March 2, 2019


      nike air force 1 low

      I happen to be writing to make you understand what a fine encounter my girl went through going through yuor web blog. She came to find lots of things, with the inclusion of how it is like to possess a marvelous teaching mood to get many more without hassle comprehend a number of advanced topics. You truly exceeded readers’ expectations. Many thanks for providing such beneficial, healthy, educational and in addition unique tips about this topic to Mary.

      March 2, 2019


      MichaelCrere

      Alli

      March 3, 2019


      Kiabox

      lasix

      March 4, 2019


      Charlesbox

      eurax

      March 4, 2019


      Kiabox

      lasix

      March 4, 2019


      Janebox

      lasix

      March 4, 2019


      Payday Loans Online

      va loans

      March 4, 2019


      MichaelCrere

      prozac

      March 5, 2019


      Charlesbox

      Viagra

      March 5, 2019


      Charlesbox

      home

      March 6, 2019


      MichaelCrere

      Inderal

      March 6, 2019


      Charlesbox

      prosac

      March 6, 2019


      Kiabox

      lasix

      March 7, 2019


      BennyBYDAY

      zofran

      March 8, 2019


      MichaelCrere

      levitra

      March 9, 2019


      MichaelCrere

      cialis

      March 9, 2019


      MichaelCrere

      valtrex

      March 10, 2019


      Charlesbox

      cialis

      March 10, 2019


      BennyBYDAY

      lexapro

      March 10, 2019


      MichaelCrere

      Effexor

      March 10, 2019


      Charlesbox

      CIALIS

      March 10, 2019


      BennyBYDAY

      cialis

      March 11, 2019


      Charlesbox

      cialis

      March 11, 2019


      Charlesbox

      Zoloft

      March 11, 2019


      BennyBYDAY

      valtre

      March 12, 2019


      MichaelCrere

      abilify

      March 12, 2019


      BennyBYDAY

      lasix

      March 12, 2019


      MichaelCrere

      effexor

      March 13, 2019


      BennyBYDAY

      Viagra

      March 13, 2019


      Charlesbox

      VALTREX

      March 14, 2019


      Charlesbox

      levitra

      March 15, 2019


      MichaelCrere

      cialis

      March 15, 2019


      Charlesbox

      levitra

      March 15, 2019


      Charlesbox

      example

      March 15, 2019


      BennyBYDAY

      prozac

      March 16, 2019


      BennyBYDAY

      Abilify

      March 16, 2019


      Charlesbox

      lasix

      March 16, 2019


      BennyBYDAY

      prozac

      March 17, 2019


      MichaelCrere

      retin-a

      March 18, 2019


      MichaelCrere

      retin-a

      March 18, 2019


      Kennethinvom

      cialis

      March 18, 2019


      MichaelCrere

      Viagra

      March 18, 2019


      Charlesbox

      Valtrex

      March 18, 2019


      MichaelCrere

      proscar