Passed
Push — develop ( 43506b...705360 )
by Pieter van der
03:49 queued 12s
created

Tiqr_Service::generateAuthQR()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 2
c 3
b 0
f 0
dl 0
loc 5
ccs 0
cts 3
cp 0
rs 10
cc 1
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * This file is part of the tiqr project.
4
 * 
5
 * The tiqr project aims to provide an open implementation for 
6
 * authentication using mobile devices. It was initiated by 
7
 * SURFnet and developed by Egeniq.
8
 *
9
 * More information: http://www.tiqr.org
10
 *
11
 * @author Ivo Jansch <[email protected]>
12
 * 
13
 * @package tiqr
14
 *
15
 * @license New BSD License - See LICENSE file for details.
16
 *
17
 * @copyright (C) 2010-2011 SURFnet BV
18
 */
19
20
/** 
21
 * @internal includes of utility classes
22
 */
23 1
require_once("Tiqr/StateStorage.php");
24 1
require_once("Tiqr/DeviceStorage.php");
25 1
require_once("Tiqr/Random.php");
26
27 1
require_once("Tiqr/OcraService.php");
28
29
use Psr\Log\LoggerInterface;
30
31
/** 
32
 * The main Tiqr Service class.
33
 * This is the class that an application interacts with to implement authentication and enrollment using the tiqr
34
 * protocol, used with the tiqr.org mobile authentication apps
35
 * See https://tiqr.org/technical/protocol/ for a specification of the protocol
36
 */
37
class Tiqr_Service
38
{
39
    /**
40
     * @internal Various variables internal to the service class
41
     */
42
    /** @var array  */
43
    protected $_options;
44
45
    /** @var string */
46
    protected $_protocolAuth;
47
    /** @var string */
48
    protected $_protocolEnroll;
49
    /** @var string */
50
    protected $_identifier;
51
    /** @var string */
52
    protected $_ocraSuite;
53
    /** @var string */
54
    protected $_name;
55
    /** @var string */
56
    protected $_logoUrl;
57
    /** @var string */
58
    protected $_infoUrl;
59
    /** @var int */
60
    protected $_protocolVersion;
61
    /** @var Tiqr_StateStorage_StateStorageInterface */
62
    protected $_stateStorage;
63
    /** @var Tiqr_DeviceStorage_Abstract */
64
    protected $_deviceStorage;
65
    /** @var Tiqr_OcraService_Interface */
66
    protected $_ocraService;
67
    /** @var string */
68
    protected $_stateStorageSalt; // The salt used for creating stable hashes for use with the StateStorage
69
70
    /** @var LoggerInterface */
71
    private $logger;
72
73
    /**
74
     * Enrollment status codes
75
     */
76
    // IDLE: There is no enrollment going on in this session, or there was an error getting the enrollment status
77
    const ENROLLMENT_STATUS_IDLE = 1;
78
    // INITIALIZED: The enrollment session was started but the tiqr client has not retrieved the metadata yet
79
    const ENROLLMENT_STATUS_INITIALIZED = 2;
80
    // RETRIEVED: The tiqr client has retrieved the metadata
81
    const ENROLLMENT_STATUS_RETRIEVED = 3;
82
    // PROCESSED: The tiqr client has sent back the tiqr authentication secret
83
    const ENROLLMENT_STATUS_PROCESSED = 4;
84
    // FINALIZED: The server has stored the authentication secret
85
    const ENROLLMENT_STATUS_FINALIZED = 5;
86
    // VALIDATED: A first successful authentication was performed
87
    // Note: Not currently used
88
    const ENROLLMENT_STATUS_VALIDATED = 6;
89
90
    /**
91
     * Prefixes for StateStorage keys
92
     */
93
    const PREFIX_ENROLLMENT_SECRET = 'enrollsecret';
94
    const PREFIX_ENROLLMENT = 'enroll';
95
    const PREFIX_CHALLENGE = 'challenge';
96
    const PREFIX_ENROLLMENT_STATUS = 'enrollstatus';
97
    const PREFIX_AUTHENTICATED = 'authenticated_';
98
99
    /**
100
     * Default timeout values
101
     */
102
    const LOGIN_EXPIRE      = 3600; // Logins timeout after an hour
103
    const ENROLLMENT_EXPIRE = 300; // If enrollment isn't completed within 5 minutes, we discard data
104
    const CHALLENGE_EXPIRE  = 180; // If login is not performed within 3 minutes, we discard the challenge
105
106
    /**
107
     * Authentication result codes
108
     */
109
    // INVALID_REQUEST: Not currently used by the Tiqr_service
110
    const AUTH_RESULT_INVALID_REQUEST   = 1;
111
    // AUTHENTICATED: The user was successfully authenticated
112
    const AUTH_RESULT_AUTHENTICATED     = 2;
113
    // INVALID_RESPONSE: The response that was returned by the client was not correct
114
    const AUTH_RESULT_INVALID_RESPONSE  = 3;
115
    // INVALID_CHALLENGE: The server could find the challenge in its state storage. It may have been expired or the
116
    // client could have sent an invalid sessionKey
117
    const AUTH_RESULT_INVALID_CHALLENGE = 4;
118
    // INVALID_USERID: The client authenticated a different user than the server expected. This error is returned when
119
    // the application stated an authentication session specifying the userId and later during the authentication
120
    // provides a different userId
121
    const AUTH_RESULT_INVALID_USERID    = 5;
122
    
123
    /**
124
     * The default OCRA Suite (RFC 6287) to use for authentication in Tiqr
125
     * This basically calculates the HMAC-SHA1 over a buffer with:
126
     * - A 10 hex digit long challenge
127
     * - authentication session ID (32 hex digits)
128
     * - client secret key (64 hex digits)
129
     * and then from the calculated HMAC-SHA1 calculates a 6 decimal digit long response
130
     * This means that a client has a 1 in 10^6 chance of guessing the right response.
131
     * This is a tradeoff between having responses that a user can easily copy during offline authentication
132
     * and resistance against guessing.
133
     * The application must implement anti-guessing counter measures, e.g. locking an account after N-tries when using
134
     * the default of 6.
135
     * Chances of correctly guessing a 6 digit response code ofter N tries (calculated by multiplying N floats, YMMV):
136
     * N=1: 1/10^6 = 0.0001%; N=2: 0.0003%; N=3: 0.0006%; N=4: 0,0010%; N=5: 0,0015%; N=6: 0,0021%; N=7: 0,0028%;
137
     * N=8: 0,0036%; N=9: 0,0045%; N=10: 0,0055%l N=20: 0,0210; N=50: 0,1274%; N=100: 0,5037%; N=200: 1,708%
138
     */
139
    const DEFAULT_OCRA_SUITE = "OCRA-1:HOTP-SHA1-6:QH10-S";
140
141
    /**
142
     * session keys are used in multiple places during authentication and enrollment
143
     * and are generated by _uniqueSessionKey() using a secure pseudo-random number generator
144
     * SESSION_KEY_LENGTH_BYTES specifies the number of bytes of entropy in these keys.
145
     * Session keys are HEX encoded, so a 16 byte key (128 bits) will be 32 characters long
146
     *
147
     * We guarantee uniqueness by using a sufficiently number of bytes
148
     * By using 16 bytes (128 bits) we can expect a collision after having
149
     * generated 2^64 IDs. This more than enough for our purposes, the session
150
     * keys in the tiqr protocol are not persisted and have a lifetime of no
151
     * more than a few minutes
152
     *
153
     * It must be infeasible for an attacker to predict or guess session keys during enrollment
154
     * 128 bits should be sufficiently long for this purpose because of the short
155
     * lifetime of these keys
156
     *
157
     * A session key is used as session information in the OCRA authentication. Even if the session keys, challenges
158
     * and the correct responses of many authentications are known to an attacker it should be infeasible to
159
     * get the user secret as that is equivalent to reversing a hmac sha1 of a string the length of the secret
160
     * (32 bytes - 2^256 possibilities for a typical tiqr client implementation)
161
     *
162
     * When using the tiqr v1 protocol, with the v1 version of the OCRAWrapper, the library used
163
     * 16 bytes keys (i.e. 32 hex digits long). When using the v2 algorithm 32 byte keys (64 hex digits long) were
164
     * used.
165
     * 16 bytes should be more than enough. Using 32 bytes makes the QR codes bigger, because both for
166
     * authentication and enrollment a session key is embedded in the uri that is encoded in the QR code.
167
     */
168
    const SESSION_KEY_LENGTH_BYTES = 16;
169
170
    /**
171
     * Construct an instance of the Tiqr_Service. 
172
     * The server is configured using an array of options. All options have
173
     * reasonable defaults but it's recommended to at least specify a custom 
174
     * name and identifier and a randomly generated sessions secret.
175
     * If you use the Tiqr Service with your own apps, you must also specify
176
     * a custom auth.protocol and enroll.protocol specifier.
177
     * 
178
     * The options are:
179
     * - auth.protocol: The protocol specifier that the server uses to communicate challenge urls to the
180
     *                  iOS/Android tiqr app. This must match the url handler configuration in the app's build
181
     *                  settings.
182
     *                  Default: "tiqr".
183
     *                  Two formats are supported:
184
     *                  1. Custom URL scheme: Set the scheme's name. E.g. "tiqrauth". Do not add '://'.
185
     *                     This will generate authentication URLs of the form:
186
     *                     tiqrauth://<userId>@<idp_identifier>/<session_key>/<challenge>/<sp_idenitfier>/<version>
187
     *                  2. Universal link: Set the http or https URL. E.g. "https://tiqr.org/tiqrauth/"
188
     *                     This will generate authentication URLs of the form:
189
     *                     https://tiqr.org/tiqrauth/?u=<userid>&s=<session_key>&q=<challenge/question>&i=<idp_identifier>&v=<version>
190
     *
191
     * - enroll.protocol: The protocol specifier that the server uses to start the enrollment of a new account in the
192
     *                    iOS/Android tiqr app. This must match the url handler configuration in the app's build
193
     *                    settings.
194
     *                    Default: "tiqrenroll"
195
     *                    Two formats are supported:
196
     *                    1. Custom URL scheme: Set the protocol name. E.g. "tiqrenroll". Do not add '://'.
197
     *                       This will generate enrollment URLs of the form:
198
     *                       tiqrenroll://<metadata URL>
199
     *                    2. Universal link: Set the http or https URL. "https://tiqr.org/tiqrenroll/"
200
     *                       This will generate enrollment URLs of the form:
201
     *                       https://eduid.nl/tiqrenroll/?metadata=<URL encoded metadata URL>
202
     *
203
     * - ocra.suite: The OCRA suite to use. Defaults to DEFAULT_OCRA_SUITE.
204
     *
205
     * - identifier: A short ASCII identifier for your service. Defaults to the SERVER_NAME of the server. This is what
206
     *               a tiqr client will use to identify the server.
207
     * - name: A longer description of your service. Defaults to the SERVER_NAME of the server. A descriptive name for
208
     *         display purposes
209
     *
210
     * - logoUrl: A full http url pointing to a logo for your service.
211
     * - infoUrl: An http url pointing to an info page of your service
212
     *
213
     * - ocraservice: Configuration for the OcraService to use.
214
     *                - type: The ocra service type. (default: "tiqr")
215
     *                - parameters depending on the ocra service. See classes inside to OcraService directory for
216
     *                  supported types and their parameters.
217
     *
218
     * - statestorage: An array with the configuration of the storage for temporary data. It has the following sub keys:
219
     *                 - type: The type of state storage. (default: "file")
220
     *                 - salt: The salt is used to hash the keys used the StateStorage
221
     *                 - parameters depending on the storage. See the classes inside the StateStorage folder for
222
     *                   supported types and their parameters.
223
     *
224
     *
225
     *  * For sending push notifications using the Apple push notification service (APNS)
226
     * - apns.certificate: The location of the file with the Apple push notification client certificate and private key
227
     *                     in PEM format.
228
     *                     Defaults to ../certificates/cert.pem
229
     * - apns.environment: Whether to use apple's "sandbox" or "production" apns environment
230
     * - apns.version:     Which version of the APNS protocol to use. Default: 1
231
     *                     Version 1: The deprecated binary APNS protocol (gateway.push.apple.com)
232
     *                     Version 2: The HTTP/2 based protocol (api.push.apple.com)
233
     * * For sending push notifications to Android devices using Google's firebase cloud messaging (FCM) API
234
     * - firebase.apikey: String containing the FCM API key
235
     *
236
     * - devicestorage: An array with the configuration of the storage for device push notification tokens. Only
237
     *                  necessary if you use the Tiqr Service to authenticate an already known userId (e.g. when using
238
     *                  tiqr a second authentication factor AND are using a tiqr client that uses the token exchange.
239
     *                  It has the following
240
     *                  keys:
241
     *                  - type: The type of  storage. (default: "dummy")
242
     *                  - parameters depending on the storage. See the classes inside the DeviceStorage folder for
243
     *                    supported types and their parameters.
244
     **
245
     * @param LoggerInterface $logger
246
     * @param array $options
247
     * @param int $version The tiqr protocol version to use (defaults to the latest)
248
     * @throws Exception
249
     */
250 8
    public function __construct(LoggerInterface $logger, array $options=array(), int $version = 2)
251
    {
252 8
        $this->_options = $options; // Used to later get settings for Tiqr_Message_*
253 8
        $this->logger = $logger;
254 8
        $this->_protocolAuth = $options["auth.protocol"] ?? 'tiqr';
255 8
        $this->_protocolEnroll = $options["enroll.protocol"] ?? 'tiqrenroll';
256 8
        $this->_ocraSuite = $options["ocra.suite"] ?? self::DEFAULT_OCRA_SUITE;
257 8
        $this->_identifier = $options["identifier"] ?? $_SERVER["SERVER_NAME"];
258 8
        $this->_name = $options["name"] ?? $_SERVER["SERVER_NAME"];
259 8
        $this->_logoUrl = $options["logoUrl"] ?? '';
260 8
        $this->_infoUrl = $options["infoUrl"] ?? '';
261
262
        // An idea is to create getStateStorage, getDeviceStorage and getOcraService functions to create these functions
263
        // at the point that we actually need them.
264
265
        // Create StateStorage
266 8
        if (!isset($options["statestorage"])) {
267
            throw new RuntimeException('No state storage configuration is configured, please provide one');
268
        }
269 8
        $this->_stateStorage = Tiqr_StateStorage::getStorage($options["statestorage"]["type"], $options["statestorage"], $logger);
270
        // Set a default salt, with the SESSION_KEY_LENGTH_BYTES (16) length keys we're using a publicly
271
        // known salt already gives excellent protection.
272 7
        $this->_stateStorageSalt = $options["statestorage"]['salt'] ?? '8xwk2pFd';
273
274
        // Create DeviceStorage - required when using Push Notification with a token exchange
275 7
        if (isset($options["devicestorage"])) {
276 6
            $this->_deviceStorage = Tiqr_DeviceStorage::getStorage($options["devicestorage"]["type"], $options["devicestorage"], $logger);
277
        } else {
278 1
            $this->_deviceStorage = Tiqr_DeviceStorage::getStorage('dummy', array(), $logger);
279
        }
280
281
        // Set Tiqr protocol version, only version 2 is currently supported
282 7
        if ($version !== 2) {
283
            throw new Exception("Unsupported protocol version '${version}'");
284
        }
285 7
        $this->_protocolVersion = $version;
286
287
        // Create OcraService
288
        // Library versions before 3.0 (confusingly) used the usersecretstorage key for this configuration
289
        // and used 'tiqr' as type when no type explicitly set to oathserviceclient was configured
290 7
        if (isset($options['ocraservice']) && $options['ocraservice']['type'] != 'tiqr') {
291
            $options['ocraservice']['ocra.suite'] = $this->_ocraSuite;
292
            $this->_ocraService = Tiqr_OcraService::getOcraService($options['ocraservice']['type'], $options['ocraservice'], $logger);
293
        }
294
        else { // Create default ocraservice
295 7
            $this->_ocraService = Tiqr_OcraService::getOcraService('tiqr', array('ocra.suite' => $this->_ocraSuite), $logger);
296
        }
297 7
    }
298
    
299
    /**
300
     * Get the identifier of the service.
301
     * @return String identifier
302
     */
303 4
    public function getIdentifier(): string
304
    {
305 4
        return $this->_identifier;
306
    }
307
    
308
    /**
309
     * Generate an authentication challenge QR image and send it directly to 
310
     * the browser.
311
     * 
312
     * In normal authentication mode, you would not specify a userId - however
313
     * in step up mode, where a user is already authenticated using a
314
     * different mechanism, pass the userId of the authenticated user to this 
315
     * function. 
316
     * @param String $sessionKey The sessionKey identifying this auth session (typically returned by startAuthenticationSession)
317
     * @throws Exception
318
     */
319
    public function generateAuthQR(string $sessionKey): void
320
    {
321
        $challengeUrl = $this->_getChallengeUrl($sessionKey);
322
323
        $this->generateQR($challengeUrl);
324
    }
325
326
    /**
327
     * Generate a QR image and send it directly to
328
     * the browser.
329
     *
330
     * @param String $s The string to be encoded in the QR image
331
     */
332
    public function generateQR(string $s): void
333
    {
334
        QRcode::png($s, false, 4, 5);
335
    }
336
337
    /**
338
     * Send a push notification to a user containing an authentication challenge
339
     * @param String $sessionKey          The session key identifying this authentication session
340
     * @param String $notificationType    Notification type returned by the tiqr client: APNS, GCM, FCM, APNS_DIRECT or FCM_DIRECT
341
     * @param String $notificationAddress Notification address, e.g. device token, phone number etc.
342
     **
343
     * @throws Exception
344
     */
345
    public function sendAuthNotification(string $sessionKey, string $notificationType, string $notificationAddress): void
346
    {
347
        $message = NULL;
348
        try {
349
            switch ($notificationType) {
350
                case 'APNS':
351
                case 'APNS_DIRECT':
352
                    $apns_version = $this->_options['apns.version'] ?? 1;
353
                    if ($apns_version ==2 )
354
                        $message = new Tiqr_Message_APNS2($this->_options, $this->logger);
355
                    else
356
                        $message = new Tiqr_Message_APNS($this->_options, $this->logger);
357
                    break;
358
359
                case 'GCM':
360
                case 'FCM':
361
                case 'FCM_DIRECT':
362
                    $message = new Tiqr_Message_FCM($this->_options, $this->logger);
363
                    break;
364
365
                default:
366
                    throw new InvalidArgumentException("Unsupported notification type '$notificationType'");
367
            }
368
369
            $this->logger->info(sprintf('Creating and sending a %s push notification', $notificationType));
370
            $message->setId(time());
371
            $message->setText("Please authenticate for " . $this->_name);
372
            $message->setAddress($notificationAddress);
373
            $message->setCustomProperty('challenge', $this->_getChallengeUrl($sessionKey));
374
            $message->send();
375
        } catch (Exception $e) {
376
            $this->logger->error(
377
                sprintf('Sending "%s" push notification to address "%s" failed', $notificationType, $notificationAddress),
378
                array('exception' =>$e)
379
            );
380
            throw $e;
381
        }
382
    }
383
384
    /** 
385
     * Generate an authentication challenge URL.
386
     * This URL can be used to link directly to the authentication
387
     * application, for example to create a link in a mobile website on the
388
     * same device as where the application is installed
389
     * @param String $sessionKey The session key identifying this authentication session
390
     *
391
     * @return string Authentication URL for the tiqr client
392
     * @throws Exception
393
     */
394 3
    public function generateAuthURL(string $sessionKey): string
395
    {
396 3
        $challengeUrl = $this->_getChallengeUrl($sessionKey);  
397
        
398 3
        return $challengeUrl;
399
    }
400
401
    /**
402
     * Start an authentication session. This generates a challenge for this
403
     * session and stores it in memory. The returned sessionKey should be used
404
     * throughout the authentication process.
405
     *
406
     * @param String $userId The userId of the user to authenticate (optional), if this is left empty the
407
     *                       the client decides
408
     * @param String $sessionId The session id the application uses to identify its user sessions;
409
     *                          (optional defaults to the php session id).
410
     *                          This sessionId can later be used to get the authenticated user from the application
411
     *                          using getAuthenticatedUser(), or to clear the authentication state using logout()
412
     * @param String $spIdentifier If SP and IDP are 2 different things, pass the url/identifier of the SP the user is logging into.
413
     *                             For setups where IDP==SP, just leave this blank.
414
     * @return string The authentication sessionKey
415
     * @throws Exception when starting the authentication session failed
416
     */
417 3
    public function startAuthenticationSession(string $userId="", string $sessionId="", string $spIdentifier=""): string
418
    {
419 3
        if ($sessionId=="") {
420 2
            $sessionId = session_id();
421
        }
422
423 3
        if ($spIdentifier=="") {
424 3
            $spIdentifier = $this->_identifier;
425
        }
426
427 3
        $sessionKey = $this->_uniqueSessionKey();
428 3
        $challenge = $this->_ocraService->generateChallenge();
429
        
430 3
        $data = array("sessionId"=>$sessionId, "challenge"=>$challenge, "spIdentifier" => $spIdentifier);
431
        
432 3
        if ($userId!="") {
433 2
            $data["userId"] = $userId;
434
        }
435
        
436 3
        $this->_setStateValue(self::PREFIX_CHALLENGE, $sessionKey, $data, self::CHALLENGE_EXPIRE);
437
       
438 3
        return $sessionKey;
439
    }
440
    
441
    /**
442
     * Start an enrollment session. This can either be the enrollment of a new 
443
     * user or of an existing user, there is no difference from Tiqr's point
444
     * of view.
445
     * 
446
     * The call returns the temporary enrollmentKey that the phone needs to 
447
     * retrieve the metadata; you must therefor embed this key in the metadata
448
     * URL that you communicate to the phone.
449
     * 
450
     * @param String $userId The user's id
451
     * @param String $displayName The user's full name
452
     * @param String $sessionId The application's session identifier (defaults to php session)
453
     * @return String The enrollment key
454
     * @throws Exception when start the enrollement session failed
455
     */
456 2
    public function startEnrollmentSession(string $userId, string $displayName, string $sessionId=""): string
457
    {
458 2
        if ($sessionId=="") {
459 1
            $sessionId = session_id();
460
        }
461 2
        $enrollmentKey = $this->_uniqueSessionKey();
462
        $data = [
463 2
            "userId" => $userId,
464 2
            "displayName" => $displayName,
465 2
            "sessionId" => $sessionId
466
        ];
467 2
        $this->_setStateValue(self::PREFIX_ENROLLMENT, $enrollmentKey, $data, self::ENROLLMENT_EXPIRE);
468 2
        $this->_setEnrollmentStatus($sessionId, self::ENROLLMENT_STATUS_INITIALIZED);
469
470 2
        return $enrollmentKey;
471
    }
472
473
    /**
474
     * Reset an existing enrollment session. (start over)
475
     * @param string $sessionId The application's session identifier (defaults to php session)
476
     * @throws Exception when resetting the session failed
477
     */
478
    public function resetEnrollmentSession(string $sessionId=""): void
479
    {
480
        if ($sessionId=="") {
481
            $sessionId = session_id();
482
        }
483
484
        $this->_setEnrollmentStatus($sessionId, self::ENROLLMENT_STATUS_IDLE);
485
    }
486
487
    /**
488
     * Remove enrollment data based on the enrollment key (which is
489
     * encoded in the enrollment QR code).
490
     *
491
     * @param string $enrollmentKey returned by startEnrollmentSession
492
     * @throws Exception when clearing the enrollment state failed
493
     */
494
    public function clearEnrollmentState(string $enrollmentKey): void
495
    {
496
        $value = $this->_getStateValue(self::PREFIX_ENROLLMENT, $enrollmentKey);
497
        if (is_array($value) && array_key_exists('sessionId', $value)) {
498
            // Reset the enrollment session (used for polling the status of the enrollment)
499
            $this->resetEnrollmentSession($value['sessionId']);
500
        }
501
        // Remove the enrollment data for a specific enrollment key
502
        $this->_unsetStateValue(self::PREFIX_ENROLLMENT, $enrollmentKey);
503
    }
504
505
    /**
506
     * Retrieve the enrollment status of an enrollment session.
507
     * 
508
     * @param String $sessionId the application's session identifier 
509
     *                          (defaults to php session)
510
     * @return int Enrollment status.
511
     * @see Tiqr_Service for a definitation of the enrollment status codes
512
     *
513
     * @throws Exception when an error communicating with the state storage backend was detected
514
     */
515 1
    public function getEnrollmentStatus(string $sessionId=""): int
516
    { 
517 1
        if ($sessionId=="") {
518
            $sessionId = session_id(); 
519
        }
520 1
        $status = $this->_getStateValue(self::PREFIX_ENROLLMENT_STATUS, $sessionId);
521 1
        if (is_null($status)) return self::ENROLLMENT_STATUS_IDLE;
522 1
        return $status;
523
    }
524
        
525
    /**
526
     * Generate an enrollment QR code and send it to the browser.
527
     * @param String $metadataUrl The URL you provide to the phone to retrieve
528
     *                            metadata. This URL must contain the enrollmentKey
529
     *                            provided by startEnrollmentSession (you can choose
530
     *                            the variable name as you are responsible yourself
531
     *                            for retrieving this from the request and passing it
532
     *                            on to the Tiqr server.
533
     */
534
    public function generateEnrollmentQR(string $metadataUrl): void
535
    { 
536
        $enrollmentString = $this->_getEnrollString($metadataUrl);
537
        
538
        QRcode::png($enrollmentString, false, 4, 5);
539
    }
540
541
    /**
542
     * Generate an enroll string
543
     * This string can be used to feed to a QR code generator
544
     */
545 2
    public function generateEnrollString(string $metadataUrl): string
546
    {
547 2
        return $this->_getEnrollString($metadataUrl);
548
    }
549
    
550
    /**
551
     * Retrieve the metadata for an enrollment session.
552
     * 
553
     * When the phone calls the url that you have passed to
554
     * generateEnrollmentQR, you must provide it with the output
555
     * of this function. (Don't forget to json_encode the output.)
556
     * 
557
     * Note, you can call this function only once, as the enrollment session
558
     * data will be destroyed as soon as it is retrieved.
559
     *
560
     * When successful the enrollment status will be set to ENROLLMENT_STATUS_RETRIEVED
561
     *
562
     * @param String $enrollmentKey The enrollmentKey that the phone has posted along with its request.
563
     * @param String $authenticationUrl The url you provide to the phone to post authentication responses
564
     * @param String $enrollmentUrl The url you provide to the phone to post the generated user secret. You must include
565
     *                              a temporary enrollment secret in this URL to make this process secure.
566
     *                              Use getEnrollmentSecret() to get this secret
567
     * @return array An array of metadata that the phone needs to complete
568
     *               enrollment. You must encode it in JSON before you send
569
     *               it to the phone.
570
     * @throws Exception when generating the metadata failed
571
     */
572 1
    public function getEnrollmentMetadata(string $enrollmentKey, string $authenticationUrl, string $enrollmentUrl): array
573
    {
574 1
        $data = $this->_getStateValue(self::PREFIX_ENROLLMENT, $enrollmentKey);
575 1
        if (!is_array($data)) {
576 1
            $this->logger->error('Unable to find enrollment metadata in state storage');
577 1
            throw new Exception('Unable to find enrollment metadata in state storage');
578
        }
579
580
        $metadata = array("service"=>
581 1
                               array("displayName"       => $this->_name,
582 1
                                     "identifier"        => $this->_identifier,
583 1
                                     "logoUrl"           => $this->_logoUrl,
584 1
                                     "infoUrl"           => $this->_infoUrl,
585 1
                                     "authenticationUrl" => $authenticationUrl,
586 1
                                     "ocraSuite"         => $this->_ocraSuite,
587 1
                                     "enrollmentUrl"     => $enrollmentUrl
588
                               ),
589
                          "identity"=>
590 1
                               array("identifier" =>$data["userId"],
591 1
                                     "displayName"=>$data["displayName"]));
592
593 1
        $this->_unsetStateValue(self::PREFIX_ENROLLMENT, $enrollmentKey);
594
595 1
        $this->_setEnrollmentStatus($data["sessionId"], self::ENROLLMENT_STATUS_RETRIEVED);
596 1
        return $metadata;
597
    }
598
599
    /** 
600
     * Get a temporary enrollment secret to be able to securely post a user 
601
     * secret.
602
     *
603
     * In the last step of the enrollment process the phone will send the OCRA user secret.
604
     * This is the shared secret is used in the authentication process. To prevent an
605
     * attacker from impersonating a user during enrollment and post a user secret that is known to the attacker,
606
     * a temporary enrollment secret is added to the metadata. This secret must be included in the enrollmentUrl that is
607
     * passed to the getMetadata function so that when the client sends the OCRA user secret to the server this
608
     * enrollment secret is included. The server uses the enrollment secret to authenticate the client, and will
609
     * allow only one submission of a user secret for one enrollment secret.
610
     *
611
     * You MUST use validateEnrollmentSecret() to validate enrollment secret that the client sends before accepting
612
     * the associated OCRA client secret
613
     *
614
     * @param String $enrollmentKey The enrollmentKey generated by startEnrollmentSession() at the start of the
615
     *                              enrollment process.
616
     * @return String The enrollment secret
617
     * @throws Exception when generating the enrollment secret failed
618
     */
619 1
    public function getEnrollmentSecret(string $enrollmentKey): string
620
    {
621 1
         $data = $this->_getStateValue(self::PREFIX_ENROLLMENT, $enrollmentKey);
622 1
         if (!is_array($data)) {
623
             $this->logger->error('getEnrollmentSecret: enrollment key not found');
624
             throw new RuntimeException('enrollment key not found');
625
         }
626 1
         $userId = $data["userId"] ?? NULL;
627 1
         $sessionId = $data["sessionId"] ?? NULL;
628 1
         if (!is_string($userId) || !(is_string($sessionId))) {
629
             throw new RuntimeException('getEnrollmentSecret: invalid enrollment data');
630
         }
631
         $enrollmentData = [
632 1
             "userId" => $userId,
633 1
             "sessionId" => $sessionId
634
         ];
635 1
         $enrollmentSecret = $this->_uniqueSessionKey();
636 1
         $this->_setStateValue(
637 1
             self::PREFIX_ENROLLMENT_SECRET,
638 1
             $enrollmentSecret,
639 1
             $enrollmentData,
640 1
             self::ENROLLMENT_EXPIRE
641
         );
642 1
         return $enrollmentSecret;
643
    }
644
645
    /**
646
     * Validate if an enrollmentSecret that was passed from the phone is valid.
647
     *
648
     * Note: After validating the enrollmentSecret you must call finalizeEnrollment() to
649
     *       invalidate the enrollment secret.
650
     *
651
     * When successful the enrollment state will be set to ENROLLMENT_STATUS_PROCESSED
652
     *
653
     * @param string $enrollmentSecret The enrollmentSecret that the phone posted; it must match
654
     *                                 the enrollmentSecret that was generated using
655
     *                                 getEnrollmentSecret earlier in the process and that the phone
656
     *                                 received as part of the metadata.
657
     *                                 Note that this is not the OCRA user secret that the Phone posts to the server
658
     * @return string The userid of the user that was being enrolled if the enrollment secret is valid. The application
659
     *                should use this userid to store the OCRA user secret that the phone posted.
660
     *
661
     * @throws Exception when the validation failed
662
     */
663 1
    public function validateEnrollmentSecret(string $enrollmentSecret): string
664
    {
665
        try {
666 1
            $data = $this->_getStateValue(self::PREFIX_ENROLLMENT_SECRET, $enrollmentSecret);
667 1
            if (NULL === $data) {
668 1
                throw new RuntimeException('Enrollment secret not found');
669
            }
670 1
            if ( !is_array($data) || !is_string($data["userId"] ?? NULL)) {
671
                throw new RuntimeException('Invalid enrollment data');
672
            }
673
674
            // Secret is valid, application may accept the user secret.
675 1
            $this->_setEnrollmentStatus($data["sessionId"], self::ENROLLMENT_STATUS_PROCESSED);
676 1
            return $data["userId"];
677 1
        } catch (Exception $e) {
678 1
            $this->logger->error('Validation of enrollment secret failed', array('exception' => $e));
679 1
            throw $e;
680
        }
681
    }
682
683
    /**
684
     * Finalize the enrollment process.
685
     *
686
     * Invalidates $enrollmentSecret
687
     *
688
     * Call this after validateEnrollmentSecret
689
     * When successfull the enrollment state will be set to ENROLLMENT_STATUS_FINALIZED
690
     *
691
     * @param String The enrollment secret that was posted by the phone. This is the same secret used in the call to
692
     *               validateEnrollmentSecret()
693
     * @return bool true when finalize was successful, false otherwise
694
     *
695
     * Does not throw
696
     */
697 1
    public function finalizeEnrollment(string $enrollmentSecret): bool
698
    {
699
        try {
700 1
            $data = $this->_getStateValue(self::PREFIX_ENROLLMENT_SECRET, $enrollmentSecret);
701 1
            if (NULL === $data) {
702 1
                throw new RuntimeException('Enrollment secret not found');
703
            }
704 1
            if (is_array($data)) {
705
                // Enrollment is finalized, destroy our session data.
706 1
                $this->_unsetStateValue(self::PREFIX_ENROLLMENT_SECRET, $enrollmentSecret);
707 1
                $this->_setEnrollmentStatus($data["sessionId"], self::ENROLLMENT_STATUS_FINALIZED);
708
            } else {
709
                $this->logger->error(
710
                    'Enrollment status is not finalized, enrollmentsecret was not found in state storage. ' .
711
                    'Warning! the method will still return "true" as a result.'
712
                );
713
            }
714 1
            return true;
715 1
        } catch (Exception $e) {
716
            // Cleanup failed
717 1
            $this->logger->warning('finalizeEnrollment failed', array('exception' => $e));
718
        }
719 1
        return false;
720
    }
721
722
    /**
723
     * Authenticate a user.
724
     * This method should be called when the phone (tiqr client) posts a response to an
725
     * authentication challenge to the server. This method will validate the response and
726
     * returns one of the self::AUTH_RESULT_* codes to indicate success or error
727
     *
728
     * When the authentication was successful the user's session is marked as authenticated.
729
     * This essentially logs the user in. Use getauthenticateduser() and logout() with the
730
     * application's session sessionID to respectively get the authenticated user and clear
731
     * the authentication state.
732
     *
733
     * The default OCRA suite uses 6 digit response codes this makes the authentication vulnerable to a guessing attack
734
     * when the client has an unlimited amount of tries. It is important to limit the amount of times to allow a
735
     * AUTH_RESULT_INVALID_RESPONSE response. AUTH_RESULT_INVALID_RESPONSE counts as failed authentication attempt
736
     * (i.e. a wrong guess by the client). The other error results and exceptions mean that the response could
737
     * not be validated on the server and should therefore not reveal anything useful to the client.
738
     * The UserStorage class supports (temporarily) locking a user account. It is the responsibility of the application
739
     * to implement these measures
740
     *
741
     * @param String $userId The userid of the user that should be authenticated, as sent in the POST back by the tiqr
742
     *                       client. If $userId does not match the optional userId in startAuthenticationSession()
743
     *                       AUTH_RESULT_INVALID_USERID is returned
744
     * @param String $userSecret The OCRA user secret that the application previously stored for $userId using
745
     *                           e.g. a Tiqr_UserSecretStorage
746
     *                           Leave empty when using a OcraService that does not require a user secret
747
     * @param String $sessionKey The authentication session key that was returned by startAuthenticationSession()
748
     *                           If the session key cannot be found in the StateStorage AUTH_RESULT_INVALID_CHALLENGE
749
     *                           is returned
750
     * @param String $response   The response to the challenge that the tiqr client posted back to the server
751
     *
752
     * @return Int The result of the authentication. This is one of the AUTH_RESULT_* constants of the Tiqr_Server class.
753
     * @throws Exception when there was an error during the authentication process
754
     */
755 1
    public function authenticate(string $userId, string $userSecret, string $sessionKey, string $response): int
756
    {
757
        try {
758 1
            $state = $this->_getStateValue(self::PREFIX_CHALLENGE, $sessionKey);
759 1
            if (is_null($state)) {
760 1
                $this->logger->notice('The auth challenge could not be found in the state storage');
761 1
                return self::AUTH_RESULT_INVALID_CHALLENGE;
762
            }
763
        } catch (Exception $e) {
764
            $this->logger->error('Error looking up challenge in state storage', array('exception' => $e));
765
            throw $e;
766
        }
767
768 1
        $sessionId = $state["sessionId"] ?? NULL;   // Application's sessionId
769 1
        $challenge = $state["challenge"] ?? NULL;   // The challenge we sent to the Tiqr client
770 1
        if (!is_string($sessionId) || (!is_string($challenge)) ) {
771
            throw new RuntimeException('Invalid state for state storage');
772
        }
773
774
        // The user ID is optional, it is set when the application requested authentication of a specific userId
775
        // instead of letting the client decide
776 1
        $challengeUserId = $state["userId"] ?? NULL;
777
778
        // If the application requested a specific userId, verify that that is that userId that we're now authenticating
779 1
        if ($challengeUserId!==NULL && ($userId !== $challengeUserId)) {
780 1
            $this->logger->error(
781 1
                sprintf('Authentication failed: the requested userId "%s" does not match userId "%s" that is being authenticated',
782 1
                $challengeUserId, $userId)
783
            );
784 1
            return self::AUTH_RESULT_INVALID_USERID; // requested and actual userId do not match
785
        }
786
787
        try {
788 1
            $equal = $this->_ocraService->verifyResponse($response, $userId, $userSecret, $challenge, $sessionKey);
789
        } catch (Exception $e) {
790
            $this->logger->error(sprintf('Error verifying OCRA response for user "%s"', $userId), array('exception' => $e));
791
            throw $e;
792
        }
793
794 1
        if ($equal) {
795
            // Set application session as authenticated
796 1
            $this->_setStateValue(self::PREFIX_AUTHENTICATED, $sessionId, $userId, self::LOGIN_EXPIRE);
797 1
            $this->logger->notice(sprintf('Authenticated user "%s" in session "%s"', $userId, $sessionId));
798
799
            // Cleanup challenge
800
            // Future authentication attempts with this sessionKey will get a AUTH_RESULT_INVALID_CHALLENGE
801
            // This QR code / push notification cannot be used again
802
            // Cleaning up only after successful authentication enables the user to retry authentication after e.g. an
803
            // invalid response
804
            try {
805 1
                $this->_unsetStateValue(self::PREFIX_CHALLENGE, $sessionKey); // May throw
806
            } catch (Exception $e) {
807
                // Only log error
808
                $this->logger->warning('Could not delete authentication session key', array('error' => $e));
809
            }
810
811 1
            return self::AUTH_RESULT_AUTHENTICATED;
812
        }
813 1
        $this->logger->error('Authentication failed: invalid response');
814 1
        return self::AUTH_RESULT_INVALID_RESPONSE;
815
    }
816
817
    /**
818
     * Log the user out.
819
     * It is not an error is the $sessionId does not exists, or when the $sessionId has expired
820
     *
821
     * @param String $sessionId The application's session identifier (defaults
822
     *                          to the php session).
823
     *                          This is the application's sessionId that was provided to startAuthenticationSession()
824
     *
825
     * @throws Exception when there was an error communicating with the storage backed
826
     */
827 1
    public function logout(string $sessionId=""): void
828
    {
829 1
        if ($sessionId=="") {
830
            $sessionId = session_id(); 
831
        }
832
        
833 1
        $this->_unsetStateValue(self::PREFIX_AUTHENTICATED, $sessionId);
834 1
    }
835
    
836
    /**
837
     * Exchange a notificationToken for a deviceToken.
838
     * 
839
     * During enrollment, the phone will post a notificationAddress that can be 
840
     * used to send notifications. To actually send the notification, 
841
     * this address should be converted to the real device address.
842
     *
843
     * @param String $notificationType    The notification type.
844
     * @param String $notificationAddress The address that was stored during enrollment.
845
     *
846
     * @return String|bool The device address that can be used to send a notification.
847
     *                     false on error
848
     */
849
    public function translateNotificationAddress(string $notificationType, string $notificationAddress)
850
    {
851
        if ($notificationType == 'APNS' || $notificationType == 'FCM' || $notificationType == 'GCM') {
852
            return $this->_deviceStorage->getDeviceToken($notificationAddress);
853
        } else {
854
            return $notificationAddress;
855
        }
856
    }
857
    
858
    /**
859
     * Retrieve the currently logged in user.
860
     * @param String $sessionId The application's session identifier (defaults
861
     *                          to the php session).
862
     *                          This is the application's sessionId that was provided to startAuthenticationSession()
863
     * @return string|NULL The userId of the authenticated user,
864
     *                     NULL if no user is logged in
865
     *                     NULL if the user's login state could not be determined
866
     *
867
     * Does not throw
868
     */
869 1
    public function getAuthenticatedUser(string $sessionId=""): ?string
870
    {
871 1
        if ($sessionId=="") {
872
            $this->logger->debug('Using the PHP session id, as no session id was provided');
873
            $sessionId = session_id(); 
874
        }
875
        
876
        try {
877 1
            return $this->_getStateValue("authenticated_", $sessionId);
878
        }
879
        catch (Exception $e) {
880
            $this->logger->error('getAuthenticatedUser failed', array('exception'=>$e));
881
            return NULL;
882
        }
883
    }
884
    
885
    /**
886
     * Generate a authentication challenge URL
887
     * @param String $sessionKey The authentication sessionKey
888
     *
889
     * @return string AuthenticationURL
890
     * @throws Exception
891
     */
892 3
    protected function _getChallengeUrl(string $sessionKey): string
893
    {
894
        // Lookup the authentication session data and use this to generate the application specific
895
        // authentication URL
896
        // The are two formats see: https://tiqr.org/technical/protocol/
897
        // We probably just generated the challenge and stored it in the StateStorage
898
        // We can save a roundtrip to the storage backend here by reusing this information
899
900 3
        $state = $this->_getStateValue(self::PREFIX_CHALLENGE, $sessionKey);
901 3
        if (is_null($state)) {
902
            $this->logger->error(
903
                sprintf(
904
                'Cannot get session key "%s"',
905
                    $sessionKey
906
                )
907
            );
908
            throw new Exception('Cannot find sessionkey');
909
        }
910
911 3
        $userId = $state["userId"] ?? NULL;
912 3
        $challenge = $state["challenge"] ?? '';
913 3
        $spIdentifier = $state["spIdentifier"] ?? '';
914
915 3
        if ( (strpos($this->_protocolAuth, 'https://') === 0) || (strpos($this->_protocolAuth, 'http://') === 0) ) {
916
            // Create universal Link
917 2
            $parameters=array();
918 2
            if (!is_null($userId)) {
919 1
                $parameters[]='u='.urlencode($userId);
920
            }
921 2
            $parameters[]='s='.urlencode($sessionKey);
922 2
            $parameters[]='q='.urlencode($challenge);
923 2
            $parameters[]='i='.urlencode($this->getIdentifier());
924 2
            $parameters[]='v='.urlencode($this->_protocolVersion);
925 2
            return $this->_protocolAuth.'?'.implode('&', $parameters);
926
        }
927
928
        // Create custom URL scheme
929
        // Last bit is the spIdentifier
930 1
        return $this->_protocolAuth."://".(!is_null($userId)?urlencode($userId).'@':'').$this->getIdentifier()."/".$sessionKey."/".$challenge."/".urlencode($spIdentifier)."/".$this->_protocolVersion;
931
    }
932
933
    /**
934
     * Generate an enrollment string
935
     * @param String $metadataUrl The URL you provide to the phone to retrieve metadata.
936
     */
937 2
    protected function _getEnrollString(string $metadataUrl): string
938
    {
939
        // The are two formats see: https://tiqr.org/technical/protocol/
940
941 2
        if ( (strpos($this->_protocolEnroll, 'https://') === 0) || (strpos($this->_protocolEnroll, 'http://') === 0) ) {
942
            // Create universal Link
943 1
            return $this->_protocolEnroll.'?metadata='.urlencode($metadataUrl);
944
        }
945
946
        // Create custom URL scheme
947 1
        return $this->_protocolEnroll."://".$metadataUrl;
948
    }
949
950
    /**
951
     * Generate a unique secure pseudo-random value to be used as session key in the
952
     * tiqr protocol. These keys are sent to the tiqr client during enrollment and authentication
953
     * And are used in the server as part of key for data in StateStorage
954
     * @return String The session key as HEX encoded string
955
     * @throws Exception When the key could not be generated
956
     */
957 5
    protected function _uniqueSessionKey(): string
958
    {
959
960 5
        return bin2hex( Tiqr_Random::randomBytes(self::SESSION_KEY_LENGTH_BYTES) );
961
    }
962
    
963
    /**
964
     * Internal function to set the enrollment status of a session.
965
     * @param String $sessionId The sessionId to set the status for
966
     * @param int $status The new enrollment status (one of the 
967
     *                    self::ENROLLMENT_STATUS_* constants)
968
     * @throws Exception when updating the status fails
969
     */
970 2
    protected function _setEnrollmentStatus(string $sessionId, int $status): void
971
    {
972 2
        if (($status < 1) || ($status > 6)) {
973
            // Must be one of the self::ENROLLMENT_STATUS_* constants
974
            throw new InvalidArgumentException('Invalid enrollment status');
975
        }
976 2
        $this->_setStateValue(self::PREFIX_ENROLLMENT_STATUS, $sessionId, $status, self::ENROLLMENT_EXPIRE);
977 2
    }
978
979
    /** Store a value in StateStorage
980
     * @param string $key_prefix
981
     * @param string $key
982
     * @param mixed $value
983
     * @param int $expire
984
     * @return void
985
     * @throws Exception
986
     *
987
     * @see Tiqr_StateStorage_StateStorageInterface::setValue()
988
     */
989 5
    protected function _setStateValue(string $key_prefix, string $key, $value, int $expire): void {
990 5
        $this->_stateStorage->setValue(
991 5
            $key_prefix . $this->_hashKey($key),
992 5
            $value,
993 5
            $expire
994
        );
995 5
    }
996
997
    /** Get a value from StateStorage
998
     * @param string $key_prefix
999
     * @param string $key
1000
     * @return mixed
1001
     * @throws Exception
1002
     *
1003
     * @see Tiqr_StateStorage_StateStorageInterface::getValue()
1004
     */
1005
1006 4
    protected function _getStateValue(string $key_prefix, string $key) {
1007 4
        return $this->_stateStorage->getValue(
1008 4
            $key_prefix . $this->_hashKey($key)
1009
        );
1010
    }
1011
1012
    /** Remove a key and its value from StateStorage
1013
     * @param string $key_prefix
1014
     * @param string $key
1015
     * @return void
1016
     * @throws Exception
1017
     *
1018
     * @see Tiqr_StateStorage_StateStorageInterface::unsetValue()
1019
     */
1020 2
    protected function _unsetStateValue(string $key_prefix, string $key): void {
1021 2
        $this->_stateStorage->unsetValue(
1022 2
            $key_prefix . $this->_hashKey($key)
1023
        );
1024 2
    }
1025
1026
    /**
1027
     * Create a stable hash of a $key. Used to improve the security of stored keys
1028
     * @param string $key
1029
     * @return string hashed $key
1030
     */
1031 5
    protected function _hashKey(string $key): string
1032
    {
1033 5
        return hash_hmac('sha256', $key, $this->_stateStorageSalt);
1034
    }
1035
}
1036