File: TimeLimitedToken.php

package info (click to toggle)
simplesamlphp 1.13.1-2%2Bdeb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 11,304 kB
  • sloc: php: 65,124; xml: 629; python: 376; sh: 193; perl: 185; makefile: 43
file content (86 lines) | stat: -rw-r--r-- 2,333 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php


class SimpleSAML_Auth_TimeLimitedToken {

	var $secretSalt;
	var $lifetime;
	var $skew;

	/**
	 * @param $secretSalt Must be random and unique per installation
	 * @param $lifeTime Token lifetime in seconds
	 * @param $skew  Allowed time skew between server that generates and the one that calculates the token
	 */
	public function __construct( $lifetime = 900, $secretSalt = NULL, $skew = 1) {
		if ($secretSalt === NULL) {
			$secretSalt = SimpleSAML_Utilities::getSecretSalt();
		}
	
		$this->secretSalt = $secretSalt;
		$this->lifetime = $lifetime;
		$this->skew = $skew;
	}
	
	public function addVerificationData($data) {
		$this->secretSalt .= '|' . $data;
	}
	
	
	/**
	 * Calculate the current time offset to the current time slot.
	 * With some amount of time skew
	 */
	private function get_offset() {
		return ( (time() - $this->skew) % ($this->lifetime + $this->skew) );
	}
	
	/**
	 * Calculate the given time slot for a given offset.
	 */
	private function calculate_time_slot($offset) {
	
		#echo 'lifetime is: ' . $this->lifetime;
		
		$timeslot = floor( (time() - $offset) / ($this->lifetime + $this->skew) );
		return $timeslot;
	}
	
	/**
	 * Calculates a token value for a given offset
	 */
	private function calculate_tokenvalue($offset) {
		// A secret salt that should be randomly generated for each installation.
		#echo 'Secret salt is: ' . $this->secretSalt;
		
		#echo '<p>Calculating sha1( ' . $this->calculate_time_slot($offset) . ':' . $this->secretSalt . '  )<br />';
		
		return sha1($offset . ':' . $this->calculate_time_slot($offset) . ':' . $this->secretSalt);
	}
	
	/**
	 * Generates a token which contains of a offset and a token value. Using current offset
	 */
	public function generate_token() {
		$current_offset = $this->get_offset();
		return dechex($current_offset) . '-' . $this->calculate_tokenvalue($current_offset);
	}
	
	/**
	 * Validates a full token, by calculating the token value for the provided 
	 * offset and compares.
	 */
	public function validate_token($token) {
		$splittedtoken = explode('-', $token);
		$offset = hexdec($splittedtoken[0]);
		$value  = $splittedtoken[1];
		
		
		#echo 'compare [' . $this->calculate_tokenvalue($offset). '] with [' . $value . '] offset was [' . $offset. ']';
		
		return ($this->calculate_tokenvalue($offset) === $value);
	}
	
}