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 return session_status() === PHP_SESSION_ACTIVE;
20}
21
26function generateCsrf() {
27 if (version_compare(phpversion(), '7.0.0', '>=')) {
28 $random = generateRandom();
29 if($random !== false) return $random;
30 }
31
32 if (function_exists('mcrypt_create_iv')) {
33 return generateMcrypt();
34 }
35
36 return generateOpenssl();
37}
38
44function generateRandom() {
45 try {
46 return bin2hex(random_bytes(32));
47 } catch (Exception $e) {
48 return false;
49 }
50}
51
56function generateMcrypt() {
57 return bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
58}
59
64function generateOpenssl() {
65 return bin2hex(openssl_random_pseudo_bytes(32));
66}
67
74function getCsrf() {
75 if(!sessionExists()) {
76 session_start();
77 }
78
79 if(!array_key_exists('csrf_token', $_SESSION)) {
80 updateCsrf();
81 }
82
83 return $_SESSION['csrf_token'];
84}
85
90function getCsrfField() {
91 return sprintf("<input type=\"hidden\" name=\"csrf_token\" value=\"%s\">", getCsrf());
92}
93
99function verifyCsrf($csrf_token) {
100 $current_csrf = getCsrf();
101 // Prefer hash_equals over === because the latter is vulnerable to timing attacks
102 if(function_exists('hash_equals')) {
103 return hash_equals($current_csrf, $csrf_token);
104 }
105
106 return $current_csrf === $csrf_token;
107}
108
113function verifyCsrfPost() {
114 return (isset($_POST['csrf_token']) && verifyCsrf($_POST['csrf_token']));
115}