@@ -222,6 +222,56 @@ public function crypt_password($cleartext_password) {
222222 $ salt .="$ " ;
223223 return crypt ($ cleartext_password , $ salt );
224224 }
225+
226+ public function csrf_token_get ($ form_name ) {
227+ /* CSRF PROTECTION */
228+ // generate csrf protection id and key
229+ $ _csrf_id = uniqid ($ form_name . '_ ' ); // form id
230+ $ _csrf_key = sha1 (uniqid (microtime (true ), true )); // the key
231+ if (!isset ($ _SESSION ['_csrf ' ])) $ _SESSION ['_csrf ' ] = array ();
232+ if (!isset ($ _SESSION ['_csrf_timeout ' ])) $ _SESSION ['_csrf_timeout ' ] = array ();
233+ $ _SESSION ['_csrf ' ][$ _csrf_id ] = $ _csrf_key ;
234+ $ _SESSION ['_csrf_timeout ' ][$ _csrf_id ] = time () + 3600 ; // timeout hash in 1 hour
235+
236+ return array ('csrf_id ' => $ _csrf_id ,'csrf_key ' => $ _csrf_key );
237+ }
238+
239+ public function csrf_token_check () {
240+ global $ app ;
241+
242+ if (isset ($ _POST ) && is_array ($ _POST )) {
243+ $ _csrf_valid = false ;
244+ if (isset ($ _POST ['_csrf_id ' ]) && isset ($ _POST ['_csrf_key ' ])) {
245+ $ _csrf_id = trim ($ _POST ['_csrf_id ' ]);
246+ $ _csrf_key = trim ($ _POST ['_csrf_key ' ]);
247+ if (isset ($ _SESSION ['_csrf ' ]) && isset ($ _SESSION ['_csrf ' ][$ _csrf_id ]) && isset ($ _SESSION ['_csrf_timeout ' ]) && isset ($ _SESSION ['_csrf_timeout ' ][$ _csrf_id ])) {
248+ if ($ _SESSION ['_csrf ' ][$ _csrf_id ] === $ _csrf_key && $ _SESSION ['_csrf_timeout ' ] >= time ()) $ _csrf_valid = true ;
249+ }
250+ }
251+ if ($ _csrf_valid !== true ) {
252+ $ app ->log ('CSRF attempt blocked. Referer: ' . (isset ($ _SERVER ['HTTP_REFERER ' ]) ? $ _SERVER ['HTTP_REFERER ' ] : 'unknown ' ), LOGLEVEL_WARN );
253+ $ app ->error ($ app ->lng ('err_csrf_attempt_blocked ' ));
254+ }
255+ $ _SESSION ['_csrf ' ][$ _csrf_id ] = null ;
256+ $ _SESSION ['_csrf_timeout ' ][$ _csrf_id ] = null ;
257+ unset($ _SESSION ['_csrf ' ][$ _csrf_id ]);
258+ unset($ _SESSION ['_csrf_timeout ' ][$ _csrf_id ]);
259+
260+ if (isset ($ _SESSION ['_csrf_timeout ' ]) && is_array ($ _SESSION ['_csrf_timeout ' ])) {
261+ $ to_unset = array ();
262+ foreach ($ _SESSION ['_csrf_timeout ' ] as $ _csrf_id => $ timeout ) {
263+ if ($ timeout < time ()) $ to_unset [] = $ _csrf_id ;
264+ }
265+ foreach ($ to_unset as $ _csrf_id ) {
266+ $ _SESSION ['_csrf ' ][$ _csrf_id ] = null ;
267+ $ _SESSION ['_csrf_timeout ' ][$ _csrf_id ] = null ;
268+ unset($ _SESSION ['_csrf ' ][$ _csrf_id ]);
269+ unset($ _SESSION ['_csrf_timeout ' ][$ _csrf_id ]);
270+ }
271+ unset($ to_unset );
272+ }
273+ }
274+ }
225275
226276}
227277
0 commit comments