74a5d99205ca17ae3903126bc7d7f2b15ac7bcb3
bernd webinterface => /webinterface

bernd authored 17 years ago

1) <?php
2) 
3) function output($arg)
4) {
5)   global $output;
6)   $output .= $arg;
7) }
8) 
9) 
10) function random_string($nc, $a='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') {
11)     $l=strlen($a)-1; $r='';
12)     while($nc-->0) $r.=$a{mt_rand(0,$l)};
13)     return $r;
14)  }
15) 
16) 
17) function are_you_sure($query_string, $question)
18) {
19)   $token = random_string(20);
bernd XSRF-kram fixed

bernd authored 16 years ago

20)   $_SESSION['are_you_sure_token'] = $token;
bernd webinterface => /webinterface

bernd authored 17 years ago

21)   output("<form action=\"?{$query_string}\" method=\"post\">\n");
22)   output("<p class=\"confirmation\">{$question}<br />\n");
23)   output("<input type=\"hidden\" name=\"random_token\" value=\"{$token}\" />\n");
bernd </form>

bernd authored 17 years ago

24)   output("<input type=\"submit\" name=\"really\" value=\"Ja\" />\n<input type=\"submit\" name=\"not_really\" value=\"Nein\" /></p>\n");
25)   output("</form>\n");
bernd webinterface => /webinterface

bernd authored 17 years ago

26) }
27) 
28) 
29) function user_is_sure()
30) {
31)   if (isset($_POST['really']))
32)   {
bernd XSRF-kram fixed

bernd authored 16 years ago

33)     if ($_POST['random_token'] == $_SESSION['are_you_sure_token'])
bernd webinterface => /webinterface

bernd authored 17 years ago

34)       return true;
35)     else
36)       system_failure("Possible Cross-site-request-forgery detected!");
37)   }
38)   elseif (isset($_POST['not_really']))
39)     return false;
40)   else
41)     return NULL;
42) }
43) 
44) 
45) 
bernd XSRF-kram fixed

bernd authored 16 years ago

46) function generate_form_token($form_id)
47) {
48)   require_once("inc/debug.php");
49)   $sessid = session_id();
50)   if ($sessid == "") 
51)   {
52)     DEBUG("Uh? Session not running? Wtf?");
53)     return '';
54)   }
55)   if (! isset($_SESSION['session_token']))
56)     $_SESSION['session_token'] = random_string(10);
57)   $session_token = $_SESSION['session_token'];
58)   $formtoken = hash('sha256', $sessid.$form_id.$session_token);
59)   return '<input type="hidden" name="formtoken" value="'.$formtoken.'" />'."\n";
60) }
61) 
62) 
63) function check_form_token($form_id)
64) {
65)   $formtoken = $_POST['formtoken'];
66)   $sessid = session_id();
67)   if ($sessid == "") 
68)   {
69)     DEBUG("Uh? Session not running? Wtf?");
70)     return '';
71)   }
72) 
73)   $session_token = $_SESSION['session_token'];
74)   $correct_formtoken = hash('sha256', $sessid.$form_id.$session_token);
75) 
76)   if (! ($formtoken == $correct_formtoken))
77)     system_failure("Possible cross-site-request-forgery!");
78) }
79)