Passed
Push — 1.0.0-dev ( 83bedf...ceb5d8 )
by nguereza
02:34
created

Security::getLogger()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 2
eloc 4
c 1
b 1
f 0
nc 2
nop 0
dl 0
loc 6
rs 10
1
<?php
2
	defined('ROOT_PATH') or exit('Access denied');
3
	/**
4
	 * TNH Framework
5
	 *
6
	 * A simple PHP framework using HMVC architecture
7
	 *
8
	 * This content is released under the GNU GPL License (GPL)
9
	 *
10
	 * Copyright (C) 2017 Tony NGUEREZA
11
	 *
12
	 * This program is free software; you can redistribute it and/or
13
	 * modify it under the terms of the GNU General Public License
14
	 * as published by the Free Software Foundation; either version 3
15
	 * of the License, or (at your option) any later version.
16
	 *
17
	 * This program is distributed in the hope that it will be useful,
18
	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
	 * GNU General Public License for more details.
21
	 *
22
	 * You should have received a copy of the GNU General Public License
23
	 * along with this program; if not, write to the Free Software
24
	 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
	*/
26
27
	class Security{
28
		
29
		/**
30
		 * The logger instance
31
		 * @var Log
32
		 */
33
		private static $logger;
34
35
		/**
36
		 * Get the logger singleton instance
37
		 * @return Log the logger instance
38
		 */
39
		private static function getLogger(){
40
			if(self::$logger == null){
41
				self::$logger[0] =& class_loader('Log', 'classes');
42
				self::$logger[0]->setLogger('Library::Security');
43
			}
44
			return self::$logger[0];
45
		}
46
47
48
		/**
49
		 * This method is used to generate the CSRF token
50
		 * @return string the generated CSRF token
51
		 */
52
		public static function generateCSRF(){
53
			$logger = self::getLogger();
54
			$logger->debug('Generation of CSRF ...');
55
			
56
			$key = get_config('csrf_key', 'csrf_key');
57
			$expire = get_config('csrf_expire', 60);
58
			$keyExpire = 'csrf_expire';
59
			$currentTime = time();
60
			if(Session::exists($key) && Session::exists($keyExpire) && Session::get($keyExpire) > $currentTime){
61
				$logger->info('The CSRF token not yet expire just return it');
62
				return Session::get($key);
63
			}
64
			else{
65
				$newTime = $currentTime + $expire;
66
				$token = sha1(uniqid()) . sha1(uniqid());
67
				$logger->info('The CSRF informations are listed below: key [' .$key. '], key expire [' .$keyExpire. '], expire time [' .$expire. '], token [' .$token. ']');
68
				Session::set($keyExpire, $newTime);
69
				Session::set($key, $token);
70
				return Session::get($key);
71
			}
72
		}
73
74
		/**
75
		 * This method is used to check the CSRF if is valid, not yet expire, etc.
76
		 * @return boolean true if valid, false if not valid
77
		 */
78
		public static function validateCSRF(){
79
			$logger = self::getLogger();
80
			$logger->debug('Validation of CSRF ...');
81
				
82
			$key = get_config('csrf_key', 'csrf_key');
83
			$expire = get_config('csrf_expire', 60);
84
			$keyExpire = 'csrf_expire';
85
			$currentTime = time();
86
			$logger->info('The CSRF informations are listed below: key [' .$key. '], key expire [' .$keyExpire. '], expire time [' .$expire. ']');
87
			if(! Session::exists($key) || Session::get($keyExpire) <= $currentTime){
88
				$logger->warning('The CSRF session data is not valide');
89
				return false;
90
			}
91
			//perform form data
92
			//need use request->query() for best retrieve
93
			//super instance
94
			$obj = & get_instance();
95
			$token = $obj->request->query($key);
96
			if(! $token || $token !== Session::get($key) || Session::get($keyExpire) <= $currentTime){
97
				$logger->warning('The CSRF data [' .$token. '] is not valide may be attacker do his job');
98
				return false;
99
			}
100
			$logger->info('The CSRF data [' .$token. '] is valide the form data is safe continue');
101
			//remove the token from session
102
			Session::clear($key);
103
			Session::clear($keyExpire);
104
			return true;
105
		}
106
		
107
		/**
108
		 * This method is used to check the whitelist IP address access
109
		 */
110
		 public static function checkWhiteListIpAccess(){
111
			$logger = self::getLogger();
112
			$logger->debug('Validation of the IP address access ...');
113
			$logger->debug('Check if whitelist IP access is enabled in the configuration ...');
114
			$isEnable = get_config('white_list_ip_enable', false);
115
			if($isEnable){
116
				$logger->info('Whitelist IP access is enabled in the configuration');
117
				$list = get_config('white_list_ip_addresses', array());
118
				if(! empty($list)){
119
					//Can't use Loader::functions() at this time because teh "Loader" library is loader after the security prossessing
120
					require_once CORE_FUNCTIONS_PATH . 'function_user_agent.php';
121
					$ip = get_ip();
122
					if((count($list) == 1 && $list[0] == '*') || in_array($ip, $list)){
123
						$logger->info('IP address ' . $ip . ' allowed using the wildcard "*" or the full IP');
124
						//wildcard to access all ip address
125
						return;
126
					}
127
					else{
128
						// go through all whitelisted ips
129
						foreach ($list as $ipaddr) {
130
							// find the wild card * in whitelisted ip (f.e. find position in "127.0.*" or "127*")
131
							$wildcardPosition = strpos($ipaddr, '*');
132
							if ($wildcardPosition === false) {
133
								// no wild card in whitelisted ip --continue searching
134
								continue;
135
							}
136
							// cut ip at the position where we got the wild card on the whitelisted ip
137
							// and add the wold card to get the same pattern
138
							if (substr($ip, 0, $wildcardPosition) . '*' === $ipaddr) {
139
								// f.e. we got
140
								//  ip "127.0.0.1"
141
								//  whitelisted ip "127.0.*"
142
								// then we compared "127.0.*" with "127.0.*"
143
								// return success
144
								$logger->info('IP address ' . $ip . ' allowed using the wildcard like "x.x.x.*"');
145
								return;
146
							}
147
						}
148
						$logger->warning('IP address ' . $ip . ' is not allowed to access to this application');
149
						show_error('Access to this application is not allowed');
150
					}
151
				}
152
			}
153
			else{
154
				$logger->info('Whitelist IP access is not enabled in the configuration, ignore checking');
155
			}
156
		 }
157
	}
158