Project

General

Profile

1
<?php
2

    
3
/*
4
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19

    
20
/**
21
 * SecureTokens.php
22
 *
23
 * @category      Core
24
 * @package       Core_Security
25
 * @subpackage    WB-2.8.4 and up
26
 * @copyright     Manuela v.d.Decken <manuela@isteam.de>
27
 * @author        Manuela v.d.Decken <manuela@isteam.de>
28
 * @license       http://www.gnu.org/licenses/gpl.html   GPL License
29
 * @
30
 * @version       0.1.2
31
 * @revision      $Revision: $
32
 * @link          $HeadURL: $
33
 * @lastmodified $Date: $
34
 * @since         File available since 12.09.2015
35
 * @description
36
 * This class is a replacement for the former class SecureForm using the SecureTokensInterface
37
 *
38
 * Settings for this class
39
 * TYPE    KONSTANTE             REGISTY-VAR                  DEFAULTWERT
40
 * boolean SEC_TOKEN_FINGERPRINT ($oReg->SecTokenFingerprint) [default=true]
41
 * integer SEC_TOKEN_NETMASK4    ($oReg->SecTokenNetmask4)    0-255 [default=24]
42
 * integer SEC_TOKEN_NETMASK6    ($oReg->SecTokenNetmask6)    0-128 [default=64]
43
 * integer SEC_TOKEN_LIFE_TIME   ($oReg->SecTokenLifeTime)    1800 | 2700 | 3600[default] | 7200
44
*/
45

    
46
class SecureTokens
47
{
48
/**
49
 * possible settings for TokenLifeTime in seconds
50
 * @description seconds for 30min / 45min / 1h / 75min / 90min / 105min / 2h
51
 */
52
/** minimum lifetime in seconds */
53
    const LIFETIME_MIN  = 1800; // 30min
54
/** maximum lifetime in seconds */
55
    const LIFETIME_MAX  = 7200; // 120min (2h)
56
/** stepwidth between min and max */
57
    const LIFETIME_STEP =  900; // 15min
58
/** lifetime in seconds to use in DEBUG mode if negative value is given (-1) */
59
    const DEBUG_LIFETIME = 300; // 5
60
/** array to hold all tokens from the session */
61
    private $aTokens = array(
62
        'default' => array('value' => 0, 'expire' => 0, 'instance' => 0)
63
    );
64
/** the salt for this instance */
65
    private $sSalt            = '';
66
/** fingerprint of the current connection */
67
    private $sFingerprint     = '';
68
/** the FTAN token which is valid for this instance */
69
    private $aLastCreatedFtan = null;
70
/** the time when tokens expired if they created in this instance */
71
    private $iExpireTime      = 0;
72
/** remove selected tokens only and update all others */
73
    private $bPreserveAllOtherTokens = false;
74
/** id of the current instance */
75
    private $sCurrentInstance  = null;
76
/** id of the instance to remove */
77
    private $sInstanceToDelete = null;
78
/** id of the instance to update expire time */
79
    private $sInstanceToUpdate = null;
80
/* --- settings for SecureTokens ------------------------------------------------------ */
81
/** use fingerprinting to encode */
82
    private $bUseFingerprint = true;
83
/** maximum lifetime of a token in seconds */
84
    private $iTokenLifeTime   = 1800; // between LIFETIME_MIN and LIFETIME_MAX (default = 30min)
85
/** bit length of the IPv4 Netmask (0-32 // 0 = off  default = 24) */
86
    private $iNetmaskLengthV4 = 0;
87
/** bit length of the IPv6 Netmask (0-128 // 0 = off  default = 64) */
88
    private $iNetmaskLengthV6 = 0;
89

    
90
/**
91
 * constructor
92
 * @param (void)
93
 */
94
    protected function __construct()
95
    {
96
    // load settings if available
97
        $this->getSettings();
98
    // generate salt for calculations in this instance
99
        $this->sSalt        = $this->generateSalt();
100
    // generate fingerprint for the current connection
101
        $this->sFingerprint = $this->buildFingerprint();
102
    // define the expiretime for this instance
103
        $this->iExpireTime  = time() + $this->iTokenLifeTime;
104
    // calculate the instance id for this instance
105
        $this->sCurrentInstance = $this->encode64(md5($this->iExpireTime.$this->sSalt));
106
    // load array of tokens from session
107
        $this->loadTokens();
108
    // at first of all remove expired tokens
109
        $this->removeExpiredTokens();
110
    }
111

    
112
/**
113
 * destructor
114
 */
115
    final public function __destruct()
116
    {
117
        foreach ($this->aTokens as $sKey => $aToken) {
118
            if ($aToken['instance'] == $this->sInstanceToUpdate) {
119
                $this->aTokens[$sKey]['instance'] = $this->sCurrentInstance;
120
                $this->aTokens[$sKey]['expire']   = $this->iExpireTime;
121
            } elseif ($aToken['instance'] == $this->sInstanceToDelete) {
122
                unset($this->aTokens[$sKey]);
123
            }
124
        }
125
        $this->saveTokens();
126
    }
127

    
128
/**
129
 * returns all TokenLifeTime values
130
 * @return array
131
 */
132
    final public function getTokenLifeTime()
133
    {
134
        return array(
135
            'min'   => self::LIFETIME_MIN,
136
            'max'   => self::LIFETIME_MAX,
137
            'step'  => self::LIFETIME_STEP,
138
            'value' => $this->iTokenLifeTime
139
        );
140
    }
141

    
142
/**
143
 * Dummy method for backward compatibility
144
 * @return void
145
 * @deprecated from WB-2.8.3-SP5
146
 */
147
    final public function createFTAN() { ; } // do nothing
148

    
149
/**
150
 * Dummy method for backward compatibility
151
 * @return void
152
 * @deprecated from WB-2.8.3-SP5
153
 */
154
    final public function clearIDKEY() { ; } // do nothing
155

    
156
/**
157
 * returns the current FTAN
158
 * @param bool $mode: true or POST returns a complete prepared, hidden HTML-Input-Tag (default)
159
 *                     false or GET returns an GET argument 'key=value'
160
 * @return mixed:     array or string
161
 * @deprecated the param $mMode is set deprecated
162
 *              string retvals are set deprecated. From versions after 2.8.4 retval will be array only
163
 */
164
    final public function getFTAN($mMode = 'POST')
165
    {
166
        if (is_null($this->aLastCreatedFtan)) {
167
            $sFtan = md5($this->sSalt);
168
            $this->aLastCreatedFtan = $this->addToken(
169
                substr($sFtan, rand(0,15), 16),
170
                substr($sFtan, rand(0,15), 16)
171
            );
172
        }
173
        $aFtan = $this->aTokens[$this->aLastCreatedFtan];
174
        $aFtan['name']  = $this->aLastCreatedFtan;
175
        $aFtan['value'] = $this->encode64(md5($aFtan['value'].$this->sFingerprint));
176
        if (is_string($mMode)) {
177
            $mMode = strtoupper($mMode);
178
        } else {
179
            $mMode = $mMode === true ? 'POST' : 'GET';
180
        }
181
        switch ($mMode):
182
            case 'POST':
183
                return '<input type="hidden" name="'.$aFtan['name'].'" value="'
184
                      .$aFtan['value'].'" title="">';
185
                break;
186
            case 'GET':
187
                return $aFtan['name'].'='.$aFtan['value'];
188
                break;
189
            default:
190
                return array('name' => $aFtan['name'], 'value' => $aFtan['value']);
191
        endswitch;
192
    }
193

    
194
/**
195
 * checks received form-transactionnumbers against session-stored one
196
 * @param string $mode: requestmethode POST(default) or GET
197
 * @param bool $bPreserve (default=false)
198
 * @return bool:    true if numbers matches against stored ones
199
 *
200
 * requirements: an active session must be available
201
 * this check will prevent from multiple sending a form. history.back() also will never work
202
 */
203
    final public function checkFTAN($mMode = 'POST', $bPreserve = false)
204
    {
205
        $bRetval = false;
206
        $this->bPreserveAllOtherTokens = $bPreserve ?: $this->bPreserveAllOtherTokens;
207
        // get the POST/GET arguments
208
        $aArguments = (strtoupper($mMode) == 'POST' ? $_POST : $_GET);
209
        // encode the value of all matching tokens
210
        $aMatchingTokens = array_map(
211
            function ($aToken) {
212
                return $this->encode64(md5($aToken['value'].$this->sFingerprint));
213
            },
214
            // extract all matching tokens from $this->aTokens
215
            array_intersect_key($this->aTokens, $aArguments)
216
        );
217
        // extract all matching arguments from $aArguments
218
        $aMatchingArguments = array_intersect_key($aArguments, $this->aTokens);
219
        // get all tokens with matching values from match lists
220
        $aHits = array_intersect($aMatchingTokens, $aMatchingArguments);
221
        foreach ($aHits as $sTokenName => $sValue) {
222
            $bRetval = true;
223
            $this->removeToken($sTokenName);
224
        }
225
        return $bRetval;
226
    }
227
/**
228
 * store value in session and returns an accesskey to it
229
 * @param mixed $mValue can be numeric, string or array
230
 * @return string
231
 */
232
    final public function getIDKEY($mValue)
233
    {
234
        if (is_array($mValue) == true) {
235
            // serialize value, if it's an array
236
            $mValue = serialize($mValue);
237
        }
238
        // crypt value with salt into md5-hash and return a 16-digit block from random start position
239
        $sTokenName = $this->addToken(
240
            substr(md5($this->sSalt.(string)$mValue), rand(0,15), 16),
241
            $mValue
242
        );
243
        return $sTokenName;
244
    }
245

    
246
/*
247
 * search for key in session and returns the original value
248
 * @param string $sFieldname: name of the POST/GET-Field containing the key or hex-key itself
249
 * @param mixed $mDefault: returnvalue if key not exist (default 0)
250
 * @param string $sRequest: requestmethode can be POST or GET or '' (default POST)
251
 * @param bool $bPreserve (default=false)
252
 * @return mixed: the original value (string, numeric, array) or DEFAULT if request fails
253
 * @description: each IDKEY can be checked only once. Unused Keys stay in list until they expire
254
 */
255
    final public function checkIDKEY($sFieldname, $mDefault = 0, $sRequest = 'POST', $bPreserve = false)
256
    {
257
        $mReturnValue = $mDefault; // set returnvalue to default
258
        $this->bPreserveAllOtherTokens = $bPreserve ?: $this->bPreserveAllOtherTokens;
259
        $sRequest = strtoupper($sRequest);
260
        switch ($sRequest) {
261
            case 'POST':
262
            case 'GET':
263
                $sTokenName = @$GLOBALS['_'.$sRequest][$sFieldname] ?: $sFieldname;
264
                break;
265
            default:
266
                $sTokenName = $sFieldname;
267
        }
268
        if (preg_match('/[0-9a-f]{16}$/i', $sTokenName)) {
269
        // key must be a 16-digit hexvalue
270
            if (array_key_exists($sTokenName, $this->aTokens)) {
271
            // check if key is stored in IDKEYs-list
272
                $mReturnValue = $this->aTokens[$sTokenName]['value']; // get stored value
273
                $this->removeToken($sTokenName);   // remove from list to prevent multiuse
274
                if (preg_match('/.*(?<!\{).*(\d:\{.*;\}).*(?!\}).*/', $mReturnValue)) {
275
                // if value is a serialized array, then deserialize it
276
                    $mReturnValue = unserialize($mReturnValue);
277
                }
278
            }
279
        }
280
        return $mReturnValue;
281
    }
282

    
283
/**
284
 * make a valid LifeTime value from given integer on the rules of class SecureTokens
285
 * @param integer  $iLifeTime
286
 * @return integer
287
 */
288
    final public function sanitizeLifeTime($iLifeTime)
289
    {
290
        $iLifeTime = intval($iLifeTime);
291
        for ($i = self::LIFETIME_MIN; $i <= self::LIFETIME_MAX; $i += self::LIFETIME_STEP) {
292
            $aLifeTimes[] = $i;
293
        }
294
        $iRetval = array_pop($aLifeTimes);
295
        foreach ($aLifeTimes as $iValue) {
296
            if ($iLifeTime <= $iValue) {
297
                $iRetval = $iValue;
298
                break;
299
            }
300
        }
301
        return $iRetval;
302
    }
303
/* ************************************************************************************ */
304
/* *** from here private methods only                                               *** */
305
/* ************************************************************************************ */
306
/**
307
 * load all tokens from session
308
 */
309
    private function loadTokens()
310
    {
311
        if (isset($_SESSION['TOKENS'])) {
312
            $this->aTokens = unserialize($_SESSION['TOKENS']);
313
        } else {
314
            $this->saveTokens();
315
        }
316
    }
317

    
318
/**
319
 * save all tokens into session
320
 */
321
    private function saveTokens()
322
    {
323
        $_SESSION['TOKENS'] = serialize($this->aTokens);
324
    }
325

    
326
/**
327
 * add new token to the list
328
 * @param string $sTokenName
329
 * @param string $sValue
330
 * @return string  name(index) of the token
331
 */
332
    private function addToken($sTokenName, $sValue)
333
    {
334
        $sTokenName = substr($sTokenName, 0, 16);
335
        $sTokenName[0] = dechex(10 + (hexdec($sTokenName[0]) % 5));
336
        while (isset($this->aTokens[$sTokenName])) {
337
            $sTokenName = sprintf('%16x', hexdec($sTokenName)+1);
338
        }
339
        $this->aTokens[$sTokenName] = array(
340
            'value'    => $sValue,
341
            'expire'   => $this->iExpireTime,
342
            'instance' => $this->sCurrentInstance
343
        );
344
        return $sTokenName;
345
    }
346

    
347
/**
348
 * remove the token, called sTokenName from list
349
 * @param type $sTokenName
350
 */
351
    private function removeToken($sTokenName)
352
    {
353
        if (isset($this->aTokens[$sTokenName])) {
354
            if ($this->bPreserveAllOtherTokens) {
355
                $this->sInstanceToUpdate = $this->aTokens[$sTokenName]['instance'];
356
            } else {
357
                $this->sInstanceToDelete = $this->aTokens[$sTokenName]['instance'];
358
            }
359
            unset($this->aTokens[$sTokenName]);
360
        }
361
    }
362

    
363
/**
364
 * remove all expired tokens from list
365
 */
366
    private function removeExpiredTokens()
367
    {
368
        $iTimestamp = time();
369
        foreach ($this->aTokens as $sTokenName => $aToken) {
370
            if ($aToken['expire'] <= $iTimestamp && $aToken['expire'] != 0){
371
                unset($this->aTokens[$sTokenName]);
372
            }
373
        }
374
    }
375

    
376
/**
377
 * generate a runtime depended hash
378
 * @return string  md5 hash
379
 */
380
    private function generateSalt()
381
    {
382
        list($fUsec, $fSec) = explode(" ", microtime());
383
        $sSalt = (string)rand(10000, 99999)
384
               . (string)((float)$fUsec + (float)$fSec)
385
               . (string)rand(10000, 99999);
386
        return md5($sSalt);
387
    }
388

    
389
/**
390
 * build a simple fingerprint
391
 * @return string
392
 */
393
    private function buildFingerprint()
394
    {
395
        if (!$this->bUseFingerprint) { return md5('dummy'); }
396
        $sClientIp = '127.0.0.1';
397
        if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)){
398
            $sClientIp = array_pop(preg_split('/\s*?,\s*?/', $_SERVER['HTTP_X_FORWARDED_FOR'], null, PREG_SPLIT_NO_EMPTY));
399
        }else if (array_key_exists('REMOTE_ADDR', $_SERVER)) {
400
            $sClientIp = $_SERVER['REMOTE_ADDR'];
401
        }else if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
402
            $sClientIp = $_SERVER['HTTP_CLIENT_IP'];
403
        }
404
        $sFingerprint = __FILE__.PHP_VERSION
405
                      . isset($_SERVER['SERVER_SIGNATURE']) ? $_SERVER['SERVER_SIGNATURE'] : 'unknown'
406
                      . isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'AGENT'
407
                      . $this->calcClientIpHash($sClientIp);
408
        return md5($sFingerprint);
409
    }
410

    
411
/**
412
 * mask IPv4 as well IPv6 addresses with netmask and make a md5 hash from
413
 * @param string $sClientIp IP as string from $_SERVER['REMOTE_ADDR']
414
 * @return md5 value of masked ip
415
 * @description this method does not accept the IPv6/IPv4 mixed format
416
 *               like "2222:3333:4444:5555:6666:7777:192.168.1.200"
417
 */
418
    private function calcClientIpHash($sRawIp)
419
    {
420
        if (strpos($sRawIp, ':') === false) {
421
        // calculate IPv4
422
            $iIpV4 = ip2long($sRawIp);
423
        // calculate netmask
424
            $iMask = ($this->iNetmaskLengthV4 < 1)
425
                ? 0
426
                : bindec(
427
                    str_repeat('1', $this->iNetmaskLengthV4).
428
                    str_repeat('0', 32 - $this->iNetmaskLengthV4)
429
                );
430
        // apply mask
431
            $sIp = long2ip($iIpV4 & $iMask);
432
        } else {
433
        // sanitize IPv6
434
            $iWords = 8 - count(preg_split('/:/', $sRawIp, null, PREG_SPLIT_NO_EMPTY));
435
            $sReplacement = $iWords ? implode(':', array_fill(0, $iWords, '0000')) : '';
436
            $sClientIp = trim(preg_replace('/\:\:/', ':'.$sReplacement.':', $sRawIp), ':');
437
            $aIpV6 = array_map(
438
                function($sPart) {
439
                    return str_pad($sPart, 4, '0', STR_PAD_LEFT);
440
                },
441
                preg_split('/:/', $sClientIp)
442
            );
443
        // calculate netmask
444
            $iMask = $this->iNetmaskLengthV6;
445
            if ($this->iNetmaskLengthV6 < 1) {
446
                $aMask = array_fill(0, 8, str_repeat('0', 16));
447
            } else {
448
                $aMask = str_split(
449
                    str_repeat('1', $this->iNetmaskLengthV6).
450
                    str_repeat('0', 128 - $this->iNetmaskLengthV6),
451
                    16
452
                );
453
            }
454
        // apply mask
455
            array_walk(
456
                $aIpV6,
457
                function(&$sWord, $iIndex) use ($aMask) {
458
                    $sWord = sprintf('%04x', hexdec($sWord) & bindec($aMask[$iIndex]));
459
                }
460
            );
461
            $sIp = implode(':', $aIpV6);
462
        }
463
        return md5($sIp); // return the hash
464
    }
465

    
466
/**
467
 * encode a hex string into a 64char based string
468
 * @param string $sMd5Hash
469
 * @return string
470
 * @description reduce the 32char length of a MD5 to 22 chars
471
 */
472
    private function encode64($sMd5Hash)
473
    {
474
        return rtrim(base64_encode(pack('h*',$sMd5Hash)), '+-= ');
475
    }
476

    
477
/**
478
 * read settings if available
479
 */
480
    private function getSettings()
481
    {
482
        if (!class_exists('WbAdaptor', false)) {
483
        // for WB before 2.8.4
484
            $this->bUseFingerprint  = defined('SEC_TOKEN_FINGERPRINT')
485
                                      ? SEC_TOKEN_FINGERPRINT
486
                                      : $this->bUseFingerprint;
487
            $this->iNetmaskLengthV4 = defined('SEC_TOKEN_NETMASK4')
488
                                      ? SEC_TOKEN_NETMASK4
489
                                      : $this->iNetmaskLengthV4;
490
            $this->iNetmaskLengthV6 = defined('SEC_TOKEN_NETMASK6')
491
                                      ? SEC_TOKEN_NETMASK6
492
                                      : $this->iNetmaskLengthV6;
493
            $this->iTokenLifeTime   = defined('SEC_TOKEN_LIFE_TIME')
494
                                      ? SEC_TOKEN_LIFE_TIME
495
                                      : $this->iTokenLifeTime;
496
        } else {
497
        // for WB from 2.8.4 and up
498
            $this->bUseFingerprint  = isset($this->oReg->SecTokenFingerprint)
499
                                      ? $this->oReg->SecTokenFingerprint
500
                                      : $this->bUseFingerprint;
501
            $this->iNetmaskLengthV4 = isset($this->oReg->SecTokenNetmask4)
502
                                      ? $this->oReg->SecTokenNetmask4
503
                                      : $this->iNetmaskLengthV4;
504
            $this->iNetmaskLengthV6 = isset($this->oReg->SecTokenNetmask6)
505
                                      ? $this->oReg->SecTokenNetmask6
506
                                      : $this->iNetmaskLengthV6;
507
            $this->iTokenLifeTime   = isset($this->oReg->SecTokenLifeTime)
508
                                      ? $this->oReg->SecTokenLifeTime
509
                                      : $this->iTokenLifeTime;
510
        }
511
        $this->iNetmaskLengthV4 = ($this->iNetmaskLengthV4 < 1 || $this->iNetmaskLengthV4 > 32)
512
                                  ? 0 :$this->iNetmaskLengthV4;
513
        $this->iNetmaskLengthV6 = ($this->iNetmaskLengthV6 < 1 || $this->iNetmaskLengthV6 > 128)
514
                                  ? 0 :$this->iNetmaskLengthV6;
515
        $this->iTokenLifeTime   = $this->sanitizeLifeTime($this->iTokenLifeTime);
516
        if ($this->iTokenLifeTime <= self::LIFETIME_MIN && DEBUG) {
517
            $this->iTokenLifeTime = self::DEBUG_LIFETIME;
518
        }
519
    }
520

    
521

    
522
} // end of class SecureTokens
(11-11/40)