Passed
Pull Request — develop (#42)
by Pieter van der
02:58
created

Tiqr_Service::startEnrollmentSession()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

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