@@ -201,6 +201,56 @@ public function crypt_password($cleartext_password) {
201201 $ salt .="$ " ;
202202 return crypt ($ cleartext_password , $ salt );
203203 }
204+
205+ public function csrf_token_get ($ form_name ) {
206+ /* CSRF PROTECTION */
207+ // generate csrf protection id and key
208+ $ _csrf_id = uniqid ($ form_name . '_ ' ); // form id
209+ $ _csrf_key = sha1 (uniqid (microtime (true ), true )); // the key
210+ if (!isset ($ _SESSION ['_csrf ' ])) $ _SESSION ['_csrf ' ] = array ();
211+ if (!isset ($ _SESSION ['_csrf_timeout ' ])) $ _SESSION ['_csrf_timeout ' ] = array ();
212+ $ _SESSION ['_csrf ' ][$ _csrf_id ] = $ _csrf_key ;
213+ $ _SESSION ['_csrf_timeout ' ][$ _csrf_id ] = time () + 3600 ; // timeout hash in 1 hour
214+
215+ return array ('csrf_id ' => $ _csrf_id ,'csrf_key ' => $ _csrf_key );
216+ }
217+
218+ public function csrf_token_check () {
219+ global $ app ;
220+
221+ if (isset ($ _POST ) && is_array ($ _POST )) {
222+ $ _csrf_valid = false ;
223+ if (isset ($ _POST ['_csrf_id ' ]) && isset ($ _POST ['_csrf_key ' ])) {
224+ $ _csrf_id = trim ($ _POST ['_csrf_id ' ]);
225+ $ _csrf_key = trim ($ _POST ['_csrf_key ' ]);
226+ if (isset ($ _SESSION ['_csrf ' ]) && isset ($ _SESSION ['_csrf ' ][$ _csrf_id ]) && isset ($ _SESSION ['_csrf_timeout ' ]) && isset ($ _SESSION ['_csrf_timeout ' ][$ _csrf_id ])) {
227+ if ($ _SESSION ['_csrf ' ][$ _csrf_id ] === $ _csrf_key && $ _SESSION ['_csrf_timeout ' ] >= time ()) $ _csrf_valid = true ;
228+ }
229+ }
230+ if ($ _csrf_valid !== true ) {
231+ $ app ->log ('CSRF attempt blocked. Referer: ' . (isset ($ _SERVER ['HTTP_REFERER ' ]) ? $ _SERVER ['HTTP_REFERER ' ] : 'unknown ' ), LOGLEVEL_WARN );
232+ $ app ->error ($ app ->lng ('err_csrf_attempt_blocked ' ));
233+ }
234+ $ _SESSION ['_csrf ' ][$ _csrf_id ] = null ;
235+ $ _SESSION ['_csrf_timeout ' ][$ _csrf_id ] = null ;
236+ unset($ _SESSION ['_csrf ' ][$ _csrf_id ]);
237+ unset($ _SESSION ['_csrf_timeout ' ][$ _csrf_id ]);
238+
239+ if (isset ($ _SESSION ['_csrf_timeout ' ]) && is_array ($ _SESSION ['_csrf_timeout ' ])) {
240+ $ to_unset = array ();
241+ foreach ($ _SESSION ['_csrf_timeout ' ] as $ _csrf_id => $ timeout ) {
242+ if ($ timeout < time ()) $ to_unset [] = $ _csrf_id ;
243+ }
244+ foreach ($ to_unset as $ _csrf_id ) {
245+ $ _SESSION ['_csrf ' ][$ _csrf_id ] = null ;
246+ $ _SESSION ['_csrf_timeout ' ][$ _csrf_id ] = null ;
247+ unset($ _SESSION ['_csrf ' ][$ _csrf_id ]);
248+ unset($ _SESSION ['_csrf_timeout ' ][$ _csrf_id ]);
249+ }
250+ unset($ to_unset );
251+ }
252+ }
253+ }
204254
205255}
206256
0 commit comments