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
/** character string for 64char encoding */
49
    const CHAR64 = 'Zabcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZa';
50
/** possible settings for TokenLifeTime in seconds */
51
    const LIFETIMES = [1800, 2700, 3600, 7200];  // seconds for 30min / 45min / 1h / 2h
52
/** lifetime in seconds to use in DEBUG mode if negative value is given (-1) */
53
    const DEBUG_LIFETIME = 300;
54

    
55
/** array to hold all tokens from the session */
56
    private $aTokens = array(
57
        'default' => array('value' => 0, 'expire' => 0)
58
    );
59
/** the salt for this run */
60
    private $sSalt            = '';
61
/** fingerprint of the current connection */
62
    private $sFingerprint     = '';
63
/** the FTAN token which is valid for this run */
64
    private $aLastCreatedFtan = null;
65
/* --- settings for SecureTokens ------------------------------------------------------ */
66
/** use fingerprinting to encode */
67
    private $bUseFingerprint = true;
68
/** maximum lifetime of a token in seconds */
69
    private $iTokenLifeTime   = 1800; // 30min / 45min / 1h / 2h (default = 30min)
70
/** bit length of the IPv4 Netmask (0-32 // 0 = off  default = 24) */
71
    private $iNetmaskLengthV4 = 0;
72
/** bit length of the IPv6 Netmask (0-128 // 0 = off  default = 64) */
73
    private $iNetmaskLengthV6 = 0;
74

    
75
/**
76
 * constructor
77
 * @param (void)
78
 */
79
    protected function __construct() {
80
    // load settings if available
81
        $this->getSettings();
82
    // load array of tokens from session
83
        $this->loadTokens();
84
    // at first of all remove expired tokens
85
        $this->removeExpiredTokens();
86
    // generate salt for calculations in this run
87
        $this->sSalt        = $this->generateSalt();
88
    // generate fingerprint for the current connection
89
        $this->sFingerprint = $this->buildFingerprint();
90
    }
91

    
92
/**
93
 * @param (void)
94
 * @return integer
95
 */
96
    public function getTokenLifeTime()
97
    {
98
        // return 5 seconds less then lifetime to compensate delay of transfer to the client
99
        return $this->iTokenLifeTime - 5;
100
    }
101
/**
102
 * Dummy method for backward compatibility
103
 * @return void
104
 * @deprecated from WB-2.8.3-SP5
105
 */
106
    final public function createFTAN() { ; } // do nothing
107

    
108
/**
109
 * Dummy method for backward compatibility
110
 * @return void
111
 * @deprecated from WB-2.8.3-SP5
112
 */
113
    final public function clearIDKEY() { ; } // do nothing
114

    
115
/**
116
 * returns the current FTAN
117
 * @param bool $mode: true or POST returns a complete prepared, hidden HTML-Input-Tag (default)
118
 *                     false or GET returns an GET argument 'key=value'
119
 * @return mixed:     array or string
120
 * @deprecated the param $mMode is set deprecated
121
 *              string retvals are set deprecated. From versions after 2.8.4 retval will be array only
122
 */
123
    final public function getFTAN($mMode = 'POST')
124
    {
125
        if (is_null($this->aLastCreatedFtan)) {
126
            $sFtan = md5($this->sSalt);
127
            $this->aLastCreatedFtan = $this->addToken(
128
                substr($sFtan, rand(0,15), 16),
129
                substr($sFtan, rand(0,15), 16)
130
            );
131
        }
132
        $aFtan = $this->aTokens[$this->aLastCreatedFtan];
133
        $aFtan['name']  = $this->aLastCreatedFtan;
134
        $aFtan['value'] = $this->encode64(md5($aFtan['value'].$this->sFingerprint));
135
        if (is_string($mMode)) {
136
            $mMode = strtoupper($mMode);
137
        } else {
138
            $mMode = $mMode === true ? 'POST' : 'GET';
139
        }
140
        switch ($mMode):
141
            case 'POST':
142
                return '<input type="hidden" name="'.$aFtan['name'].'" value="'
143
                      .$aFtan['value'].'" title="">';
144
                break;
145
            case 'GET':
146
                return $aFtan['name'].'='.$aFtan['value'];
147
                break;
148
            default:
149
                return array('name' => $aFtan['name'], 'value' => $aFtan['value']);
150
        endswitch;
151
    }
152

    
153
/**
154
 * checks received form-transactionnumbers against session-stored one
155
 * @param string $mode: requestmethode POST(default) or GET
156
 * @return bool:    true if numbers matches against stored ones
157
 *
158
 * requirements: an active session must be available
159
 * this check will prevent from multiple sending a form. history.back() also will never work
160
 */
161
    final public function checkFTAN($mMode = 'POST')
162
    {
163
        $bRetval = false;
164
        // get the POST/GET arguments
165
        $aArguments = (strtoupper($mMode) == 'POST' ? $_POST : $_GET);
166
        // encode the value of all matching tokens
167
        $aMatchingTokens = array_map(
168
            function ($aToken) {
169
                return $this->encode64(md5($aToken['value'].$this->sFingerprint));
170
            },
171
            // extract all matching tokens from $this->aTokens
172
            array_intersect_key($this->aTokens, $aArguments)
173
        );
174
        // extract all matching arguments from $aArguments
175
        $aMatchingArguments = array_intersect_key($aArguments, $this->aTokens);
176
        // get all tokens with matching values from match lists
177
        $aHits = array_intersect($aMatchingTokens, $aMatchingArguments);
178
        foreach ($aHits as $sTokenName => $sValue) {
179
            $bRetval = true;
180
            $this->removeToken($sTokenName);
181
        }
182
        return $bRetval;
183
    }
184
/**
185
 * store value in session and returns an accesskey to it
186
 * @param mixed $mValue can be numeric, string or array
187
 * @return string
188
 */
189
    final public function getIDKEY($mValue)
190
    {
191
        if (is_array($mValue) == true) {
192
            // serialize value, if it's an array
193
            $mValue = serialize($mValue);
194
        }
195
        // crypt value with salt into md5-hash and return a 16-digit block from random start position
196
        $sTokenName = $this->addToken(
197
            substr(md5($this->sSalt.(string)$mValue), rand(0,15), 16),
198
            $mValue
199
        );
200
        return $sTokenName;
201
    }
202

    
203
/*
204
 * search for key in session and returns the original value
205
 * @param string $sFieldname: name of the POST/GET-Field containing the key or hex-key itself
206
 * @param mixed $mDefault: returnvalue if key not exist (default 0)
207
 * @param string $sRequest: requestmethode can be POST or GET or '' (default POST)
208
 * @return mixed: the original value (string, numeric, array) or DEFAULT if request fails
209
 * @description: each IDKEY can be checked only once. Unused Keys stay in list until they expire
210
 */
211
    final public function checkIDKEY( $sFieldname, $mDefault = 0, $sRequest = 'POST' )
212
    {
213
        $mReturnValue = $mDefault; // set returnvalue to default
214
        $sRequest = strtoupper($sRequest);
215
        switch ($sRequest) {
216
            case 'POST':
217
            case 'GET':
218
                $sTokenName = @$GLOBALS['_'.$sRequest][$sFieldname] ?: $sFieldname;
219
                break;
220
            default:
221
                $sTokenName = $sFieldname;
222
        }
223
        if (preg_match('/[0-9a-f]{16}$/i', $sTokenName)) {
224
        // key must be a 16-digit hexvalue
225
            if (array_key_exists($sTokenName, $this->aTokens)) {
226
            // check if key is stored in IDKEYs-list
227
                $mReturnValue = $this->aTokens[$sTokenName]['value']; // get stored value
228
                $this->removeToken($sTokenName);   // remove from list to prevent multiuse
229
                if (preg_match('/.*(?<!\{).*(\d:\{.*;\}).*(?!\}).*/', $mReturnValue)) {
230
                // if value is a serialized array, then deserialize it
231
                    $mReturnValue = unserialize($mReturnValue);
232
                }
233
            }
234
        }
235
        return $mReturnValue;
236
    }
237
// *** from here private methods only ****************************************************
238

    
239
/**
240
 * load all tokens from session
241
 */
242
    private function loadTokens()
243
    {
244
        if (isset($_SESSION['TOKENS'])) {
245
            $this->aTokens = unserialize($_SESSION['TOKENS']);
246
        } else {
247
            $this->saveTokens();
248
        }
249
    }
250

    
251
/**
252
 * save all tokens into session
253
 */
254
    private function saveTokens()
255
    {
256
        $_SESSION['TOKENS'] = serialize($this->aTokens);
257
    }
258

    
259
/**
260
 * add new token to the list
261
 * @param string $sTokenName
262
 * @param string $sValue
263
 * @return string  name(index) of the token
264
 */
265
    private function addToken($sTokenName, $sValue)
266
    {
267
        $sTokenName = substr($sTokenName, 0, 16);
268
        $sTokenName[0] = dechex(10 + (hexdec($sTokenName[0]) % 5));
269
        while (isset($this->aTokens[$sTokenName])) {
270
            $sTokenName = sprintf('%16x', hexdec($sTokenName)+1);
271
        }
272
        $this->aTokens[$sTokenName] = array(
273
            'value'  => $sValue,
274
            'expire' => time()+$this->iTokenLifeTime
275
        );
276
        $this->saveTokens();
277
        return $sTokenName;
278
    }
279

    
280
/**
281
 * remove the token, called sTokenName from list
282
 * @param type $sTokenName
283
 */
284
    private function removeToken($sTokenName)
285
    {
286
        if (isset($this->aTokens[$sTokenName])) {
287
            unset($this->aTokens[$sTokenName]);
288
        }
289
        $this->saveTokens();
290
    }
291

    
292
/**
293
 * remove all expired tokens from list
294
 */
295
    private function removeExpiredTokens()
296
    {
297
        $iTimestamp = time();
298
        foreach ($this->aTokens as $sTokenName => $aToken) {
299
            if ($aToken['expire'] <= $iTimestamp && $aToken['expire'] != 0){
300
                unset($this->aTokens[$sTokenName]);
301
            }
302
        }
303
        $this->saveTokens();
304
    }
305

    
306
/**
307
 * generate a runtime depended hash
308
 * @return string  md5 hash
309
 */
310
    private function generateSalt()
311
    {
312
        list($fUsec, $fSec) = explode(" ", microtime());
313
        $sSalt = (string)rand(10000, 99999)
314
               . (string)((float)$fUsec + (float)$fSec)
315
               . (string)rand(10000, 99999);
316
        return md5($sSalt);
317
    }
318

    
319
/**
320
 * build a simple fingerprint
321
 * @return string
322
 */
323
    private function buildFingerprint()
324
    {
325
        if (!$this->bUseFingerprint) { return md5('dummy'); }
326
        $sClientIp = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
327
        $sFingerprint = __FILE__.PHP_VERSION
328
                      . isset($_SERVER['SERVER_SIGNATURE']) ? $_SERVER['SERVER_SIGNATURE'] : 'unknown'
329
                      . isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'AGENT'
330
                      . $this->calcClientIpHash($sClientIp);
331
        return md5($sFingerprint);
332
    }
333

    
334
/**
335
 * mask IPv4 as well IPv6 addresses with netmask and make a md5 hash from
336
 * @param string $sClientIp IP as string from $_SERVER['REMOTE_ADDR']
337
 * @return md5 value of masked ip
338
 * @description this method does not accept the IPv6/IPv4 mixed format
339
 *               like "2222:3333:4444:5555:6666:7777:192.168.1.200"
340
 */
341
    private function calcClientIpHash($sRawIp)
342
    {
343
        if (strpos($sRawIp, ':') === false) {
344
        // calculate IPv4
345
            $iIpV4 = ip2long($sRawIp);
346
        // calculate netmask
347
            $iMask = ($this->iNetmaskLengthV4 < 1)
348
                ? 0
349
                : bindec(
350
                    str_repeat('1', $this->iNetmaskLengthV4).
351
                    str_repeat('0', 32 - $this->iNetmaskLengthV4)
352
                );
353
        // apply mask
354
            $sIp = long2ip($iIpV4 & $iMask);
355
        } else {
356
        // sanitize IPv6
357
            $iWords = 8 - count(preg_split('/:/', $sRawIp, null, PREG_SPLIT_NO_EMPTY));
358
            $sReplacement = $iWords ? implode(':', array_fill(0, $iWords, '0000')) : '';
359
            $sClientIp = trim(preg_replace('/\:\:/', ':'.$sReplacement.':', $sRawIp), ':');
360
            $aIpV6 = array_map(
361
                function($sPart) {
362
                    return str_pad($sPart, 4, '0', STR_PAD_LEFT);
363
                },
364
                preg_split('/:/', $sClientIp)
365
            );
366
        // calculate netmask
367
            $iMask = $this->iNetmaskLengthV6;
368
            if ($this->iNetmaskLengthV6 < 1) {
369
                $aMask = array_fill(0, 8, str_repeat('0', 16));
370
            } else {
371
                $aMask = str_split(
372
                    str_repeat('1', $this->iNetmaskLengthV6).
373
                    str_repeat('0', 128 - $this->iNetmaskLengthV6),
374
                    16
375
                );
376
            }
377
        // apply mask
378
            array_walk(
379
                $aIpV6,
380
                function(&$sWord, $iIndex) use ($aMask) {
381
                    $sWord = sprintf('%04x', hexdec($sWord) & bindec($aMask[$iIndex]));
382
                }
383
            );
384
            $sIp = implode(':', $aIpV6);
385
        }
386
        return md5($sIp); // return the hash
387
    }
388

    
389
/**
390
 * encode a hex string into a 64char based string
391
 * @param string $sMd5Hash
392
 * @return string
393
 * @description reduce the 32char length of a MD5 to 21 chars
394
 */
395
    private function encode64($sMd5Hash)
396
    {
397
        $sCharList = self::CHAR64;
398
        $sBin = implode(
399
            '',
400
            array_map(
401
                function($sPart) {
402
                    return sprintf('%032b', hexdec($sPart));
403
                },
404
                str_split($sMd5Hash, 8)
405
            )
406
        );
407
        $sResult = implode(
408
            '',
409
            array_map(
410
                function($sPart) use ($sCharList) {
411
                    $sPart = str_pad($sPart, 6, '0', STR_PAD_RIGHT);
412
                    return $sCharList[bindec($sPart)];
413
                },
414
                str_split($sBin, 6)
415
            )
416
        );
417
        return $sResult;
418
    }
419

    
420
/**
421
 * read settings if available
422
 */
423
    private function getSettings()
424
    {
425
        $this->bUseFingerprint  = isset($this->oReg->SecTokenFingerprint)
426
                                  ? $this->oReg->SecTokenFingerprint
427
                                  : $this->bUseFingerprint;
428
        $this->iNetmaskLengthV4 = isset($this->oReg->SecTokenNetmask4)
429
                                  ? $this->oReg->SecTokenNetmask4
430
                                  : $this->iNetmaskLengthV4;
431
        $this->iNetmaskLengthV6 = isset($this->oReg->SecTokenNetmask6)
432
                                  ? $this->oReg->SecTokenNetmask6
433
                                  : $this->iNetmaskLengthV6;
434
        $this->iTokenLifeTime   = isset($this->oReg->SecTokenLifeTime)
435
                                  ? $this->oReg->SecTokenLifeTime
436
                                  : $this->iTokenLifeTime;
437
        $this->iNetmaskLengthV4 = ($this->iNetmaskLengthV4 < 1 || $this->iNetmaskLengthV4 > 32)
438
                                  ? 0 :$this->iNetmaskLengthV4;
439
        $this->iNetmaskLengthV6 = ($this->iNetmaskLengthV6 < 1 || $this->iNetmaskLengthV6 > 128)
440
                                  ? 0 :$this->iNetmaskLengthV6;
441
        $aLifeTimes = self::LIFETIMES;
442
        sort($aLifeTimes);
443
        if ($this->iTokenLifeTime < 0 && DEBUG) {
444
            $this->iTokenLifeTime = self::DEBUG_LIFETIME;
445
        } else {
446
            $iRetval = array_pop($aLifeTimes);
447
            foreach ($aLifeTimes as $iValue) {
448
                if ($this->iTokenLifeTime <= $iValue) {
449
                    $iRetval = $iValue;
450
                    break;
451
                }
452
            }
453
            $this->iTokenLifeTime = $iRetval;
454
        }
455

    
456
    }
457

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