DAViCal
Loading...
Searching...
No Matches
csrf_tokens.php
1<?php
2
6function updateCsrf() {
7 if(!sessionExists()) {
8 session_start();
9 }
10
11 $_SESSION['csrf_token'] = generateCsrf();
12}
13
18function sessionExists() {
19 if (version_compare(phpversion(), '5.4.0', '>')) {
20 return session_id() !== '';
21 } else {
22 return session_status() === PHP_SESSION_ACTIVE;
23 }
24}
25
30function generateCsrf() {
31 if (version_compare(phpversion(), '7.0.0', '>=')) {
32 $random = generateRandom();
33 if($random !== false) return $random;
34 }
35
36 if (function_exists('mcrypt_create_iv')) {
37 return generateMcrypt();
38 }
39
40 return generateOpenssl();
41}
42
48function generateRandom() {
49 try {
50 return bin2hex(random_bytes(32));
51 } catch (Exception $e) {
52 return false;
53 }
54}
55
60function generateMcrypt() {
61 return bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
62}
63
68function generateOpenssl() {
69 return bin2hex(openssl_random_pseudo_bytes(32));
70}
71
78function getCsrf() {
79 if(!sessionExists()) {
80 session_start();
81 }
82
83 if(!array_key_exists('csrf_token', $_SESSION)) {
84 updateCsrf();
85 }
86
87 return $_SESSION['csrf_token'];
88}
89
94function getCsrfField() {
95 return sprintf("<input type=\"hidden\" name=\"csrf_token\" value=\"%s\">", getCsrf());
96}
97
103function verifyCsrf($csrf_token) {
104 $current_csrf = getCsrf();
105 // Prefer hash_equals over === because the latter is vulnerable to timing attacks
106 if(function_exists('hash_equals')) {
107 return hash_equals($current_csrf, $csrf_token);
108 }
109
110 return $current_csrf === $csrf_token;
111}
112
117function verifyCsrfPost() {
118 return (isset($_POST['csrf_token']) && verifyCsrf($_POST['csrf_token']));
119}