Passed
Push — develop ( ff39c8...9bf9fa )
by Pieter van der
01:06 queued 14s
created

Tiqr_Service::startAuthenticationSession()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 5
Bugs 0 Features 1
Metric Value
eloc 11
c 5
b 0
f 1
dl 0
loc 22
ccs 12
cts 12
cp 1
rs 9.9
cc 4
nc 8
nop 3
crap 4
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
     * * For sending push notifications to Android devices using Google's firebase cloud messaging (FCM) API
227
     * - firebase.apikey: String containing the FCM API key
228
     *
229
     * - devicestorage: An array with the configuration of the storage for device push notification tokens. Only
230
     *                  necessary if you use the Tiqr Service to authenticate an already known userId (e.g. when using
231
     *                  tiqr a second authentication factor AND are using a tiqr client that uses the token exchange.
232
     *                  It has the following
233
     *                  keys:
234
     *                  - type: The type of  storage. (default: "dummy")
235
     *                  - parameters depending on the storage. See the classes inside the DeviceStorage folder for
236
     *                    supported types and their parameters.
237
     **
238
     * @param LoggerInterface $logger
239
     * @param array $options
240
     * @param int $version The tiqr protocol version to use (defaults to the latest)
241
     * @throws Exception
242
     */
243 8
    public function __construct(LoggerInterface $logger, array $options=array(), int $version = 2)
244
    {
245 8
        $this->_options = $options; // Used to later get settings for Tiqr_Message_*
246 8
        $this->logger = $logger;
247 8
        $this->_protocolAuth = $options["auth.protocol"] ?? 'tiqr';
248 8
        $this->_protocolEnroll = $options["enroll.protocol"] ?? 'tiqrenroll';
249 8
        $this->_ocraSuite = $options["ocra.suite"] ?? self::DEFAULT_OCRA_SUITE;
250 8
        $this->_identifier = $options["identifier"] ?? $_SERVER["SERVER_NAME"];
251 8
        $this->_name = $options["name"] ?? $_SERVER["SERVER_NAME"];
252 8
        $this->_logoUrl = $options["logoUrl"] ?? '';
253 8
        $this->_infoUrl = $options["infoUrl"] ?? '';
254
255
        // An idea is to create getStateStorage, getDeviceStorage and getOcraService functions to create these functions
256
        // at the point that we actually need them.
257
258
        // Create StateStorage
259 8
        if (!isset($options["statestorage"])) {
260
            throw new RuntimeException('No state storage configuration is configured, please provide one');
261
        }
262 8
        $this->_stateStorage = Tiqr_StateStorage::getStorage($options["statestorage"]["type"], $options["statestorage"], $logger);
263
264
        // Create DeviceStorage - required when using Push Notification with a token exchange
265 7
        if (isset($options["devicestorage"])) {
266 6
            $this->_deviceStorage = Tiqr_DeviceStorage::getStorage($options["devicestorage"]["type"], $options["devicestorage"], $logger);
267
        } else {
268 1
            $this->_deviceStorage = Tiqr_DeviceStorage::getStorage('dummy', array(), $logger);
269
        }
270
271
        // Set Tiqr protocol version, only version 2 is currently supported
272 7
        if ($version !== 2) {
273
            throw new Exception("Unsupported protocol version '${version}'");
274
        }
275 7
        $this->_protocolVersion = $version;
276
277
        // Create OcraService
278
        // Library versions before 3.0 (confusingly) used the usersecretstorage key for this configuration
279
        // and used 'tiqr' as type when no type explicitly set to oathserviceclient was configured
280 7
        if (isset($options['ocraservice']) && $options['ocraservice']['type'] != 'tiqr') {
281
            $options['ocraservice']['ocra.suite'] = $this->_ocraSuite;
282
            $this->_ocraService = Tiqr_OcraService::getOcraService($options['ocraservice']['type'], $options['ocraservice'], $logger);
283
        }
284
        else { // Create default ocraservice
285 7
            $this->_ocraService = Tiqr_OcraService::getOcraService('tiqr', array('ocra.suite' => $this->_ocraSuite), $logger);
286
        }
287 7
    }
288
    
289
    /**
290
     * Get the identifier of the service.
291
     * @return String identifier
292
     */
293 4
    public function getIdentifier(): string
294
    {
295 4
        return $this->_identifier;
296
    }
297
    
298
    /**
299
     * Generate an authentication challenge QR image and send it directly to 
300
     * the browser.
301
     * 
302
     * In normal authentication mode, you would not specify a userId - however
303
     * in step up mode, where a user is already authenticated using a
304
     * different mechanism, pass the userId of the authenticated user to this 
305
     * function. 
306
     * @param String $sessionKey The sessionKey identifying this auth session (typically returned by startAuthenticationSession)
307
     * @throws Exception
308
     */
309
    public function generateAuthQR(string $sessionKey): void
310
    {
311
        $challengeUrl = $this->_getChallengeUrl($sessionKey);
312
313
        $this->generateQR($challengeUrl);
314
    }
315
316
    /**
317
     * Generate a QR image and send it directly to
318
     * the browser.
319
     *
320
     * @param String $s The string to be encoded in the QR image
321
     */
322
    public function generateQR(string $s): void
323
    {
324
        QRcode::png($s, false, 4, 5);
325
    }
326
327
    /**
328
     * Send a push notification to a user containing an authentication challenge
329
     * @param String $sessionKey          The session key identifying this authentication session
330
     * @param String $notificationType    Notification type returned by the tiqr client: APNS, GCM, FCM, APNS_DIRECT or FCM_DIRECT
331
     * @param String $notificationAddress Notification address, e.g. device token, phone number etc.
332
     **
333
     * @throws Exception
334
     */
335
    public function sendAuthNotification(string $sessionKey, string $notificationType, string $notificationAddress): void
336
    {
337
        $message = NULL;
338
        try {
339
            switch ($notificationType) {
340
                case 'APNS':
341
                case 'APNS_DIRECT':
342
                    $message = new Tiqr_Message_APNS($this->_options);
343
                    break;
344
345
                case 'GCM':
346
                case 'FCM':
347
                case 'FCM_DIRECT':
348
                    $message = new Tiqr_Message_FCM($this->_options);
349
                    break;
350
351
                default:
352
                    throw new InvalidArgumentException("Unsupported notification type '$notificationType'");
353
            }
354
355
            $this->logger->info(sprintf('Creating and sending a %s push notification', $notificationType));
356
            $message->setId(time());
357
            $message->setText("Please authenticate for " . $this->_name);
358
            $message->setAddress($notificationAddress);
359
            $message->setCustomProperty('challenge', $this->_getChallengeUrl($sessionKey));
360
            $message->send();
361
        } catch (Exception $e) {
362
            $this->logger->error(
363
                sprintf('Sending "%s" push notification to address "%s" failed', $notificationType, $notificationAddress),
364
                array('exception' =>$e)
365
            );
366
            throw $e;
367
        }
368
    }
369
370
    /** 
371
     * Generate an authentication challenge URL.
372
     * This URL can be used to link directly to the authentication
373
     * application, for example to create a link in a mobile website on the
374
     * same device as where the application is installed
375
     * @param String $sessionKey The session key identifying this authentication session
376
     *
377
     * @return string Authentication URL for the tiqr client
378
     * @throws Exception
379
     */
380 3
    public function generateAuthURL(string $sessionKey): string
381
    {
382 3
        $challengeUrl = $this->_getChallengeUrl($sessionKey);  
383
        
384 3
        return $challengeUrl;
385
    }
386
387
    /**
388
     * Start an authentication session. This generates a challenge for this
389
     * session and stores it in memory. The returned sessionKey should be used
390
     * throughout the authentication process.
391
     *
392
     * @param String $userId The userId of the user to authenticate (optional), if this is left empty the
393
     *                       the client decides
394
     * @param String $sessionId The session id the application uses to identify its user sessions;
395
     *                          (optional defaults to the php session id).
396
     *                          This sessionId can later be used to get the authenticated user from the application
397
     *                          using getAuthenticatedUser(), or to clear the authentication state using logout()
398
     * @param String $spIdentifier If SP and IDP are 2 different things, pass the url/identifier of the SP the user is logging into.
399
     *                             For setups where IDP==SP, just leave this blank.
400
     * @return string The authentication sessionKey
401
     * @throws Exception when starting the authentication session failed
402
     */
403 3
    public function startAuthenticationSession(string $userId="", string $sessionId="", string $spIdentifier=""): string
404
    {
405 3
        if ($sessionId=="") {
406 2
            $sessionId = session_id();
407
        }
408
409 3
        if ($spIdentifier=="") {
410 3
            $spIdentifier = $this->_identifier;
411
        }
412
413 3
        $sessionKey = $this->_uniqueSessionKey();
414 3
        $challenge = $this->_ocraService->generateChallenge();
415
        
416 3
        $data = array("sessionId"=>$sessionId, "challenge"=>$challenge, "spIdentifier" => $spIdentifier);
417
        
418 3
        if ($userId!="") {
419 2
            $data["userId"] = $userId;
420
        }
421
        
422 3
        $this->_stateStorage->setValue(self::PREFIX_CHALLENGE . $sessionKey, $data, self::CHALLENGE_EXPIRE);
423
       
424 3
        return $sessionKey;
425
    }
426
    
427
    /**
428
     * Start an enrollment session. This can either be the enrollment of a new 
429
     * user or of an existing user, there is no difference from Tiqr's point
430
     * of view.
431
     * 
432
     * The call returns the temporary enrollmentKey that the phone needs to 
433
     * retrieve the metadata; you must therefor embed this key in the metadata
434
     * URL that you communicate to the phone.
435
     * 
436
     * @param String $userId The user's id
437
     * @param String $displayName The user's full name
438
     * @param String $sessionId The application's session identifier (defaults to php session)
439
     * @return String The enrollment key
440
     * @throws Exception when start the enrollement session failed
441
     */
442 2
    public function startEnrollmentSession(string $userId, string $displayName, string $sessionId=""): string
443
    {
444 2
        if ($sessionId=="") {
445 1
            $sessionId = session_id();
446
        }
447 2
        $enrollmentKey = $this->_uniqueSessionKey();
448
        $data = [
449 2
            "userId" => $userId,
450 2
            "displayName" => $displayName,
451 2
            "sessionId" => $sessionId
452
        ];
453 2
        $this->_stateStorage->setValue(self::PREFIX_ENROLLMENT . $enrollmentKey, $data, self::ENROLLMENT_EXPIRE);
454 2
        $this->_setEnrollmentStatus($sessionId, self::ENROLLMENT_STATUS_INITIALIZED);
455
456 2
        return $enrollmentKey;
457
    }
458
459
    /**
460
     * Reset an existing enrollment session. (start over)
461
     * @param string $sessionId The application's session identifier (defaults to php session)
462
     * @throws Exception when resetting the session failed
463
     */
464
    public function resetEnrollmentSession(string $sessionId=""): void
465
    {
466
        if ($sessionId=="") {
467
            $sessionId = session_id();
468
        }
469
470
        $this->_setEnrollmentStatus($sessionId, self::ENROLLMENT_STATUS_IDLE);
471
    }
472
473
    /**
474
     * Remove enrollment data based on the enrollment key (which is
475
     * encoded in the enrollment QR code).
476
     *
477
     * @param string $enrollmentKey returned by startEnrollmentSession
478
     * @throws Exception when clearing the enrollment state failed
479
     */
480
    public function clearEnrollmentState(string $enrollmentKey): void
481
    {
482
        $value = $this->_stateStorage->getValue(self::PREFIX_ENROLLMENT.$enrollmentKey);
483
        if (is_array($value) && array_key_exists('sessionId', $value)) {
484
            // Reset the enrollment session (used for polling the status of the enrollment)
485
            $this->resetEnrollmentSession($value['sessionId']);
486
        }
487
        // Remove the enrollment data for a specific enrollment key
488
        $this->_stateStorage->unsetValue(self::PREFIX_ENROLLMENT.$enrollmentKey);
489
    }
490
491
    /**
492
     * Retrieve the enrollment status of an enrollment session.
493
     * 
494
     * @param String $sessionId the application's session identifier 
495
     *                          (defaults to php session)
496
     * @return int Enrollment status.
497
     * @see Tiqr_Service for a definitation of the enrollment status codes
498
     *
499
     * @throws Exception when an error communicating with the state storage backend was detected
500
     */
501 1
    public function getEnrollmentStatus(string $sessionId=""): int
502
    { 
503 1
        if ($sessionId=="") {
504
            $sessionId = session_id(); 
505
        }
506 1
        $status = $this->_stateStorage->getValue(self::PREFIX_ENROLLMENT_STATUS.$sessionId);
507 1
        if (is_null($status)) return self::ENROLLMENT_STATUS_IDLE;
508 1
        return $status;
509
    }
510
        
511
    /**
512
     * Generate an enrollment QR code and send it to the browser.
513
     * @param String $metadataUrl The URL you provide to the phone to retrieve
514
     *                            metadata. This URL must contain the enrollmentKey
515
     *                            provided by startEnrollmentSession (you can choose
516
     *                            the variable name as you are responsible yourself
517
     *                            for retrieving this from the request and passing it
518
     *                            on to the Tiqr server.
519
     */
520
    public function generateEnrollmentQR(string $metadataUrl): void
521
    { 
522
        $enrollmentString = $this->_getEnrollString($metadataUrl);
523
        
524
        QRcode::png($enrollmentString, false, 4, 5);
525
    }
526
527
    /**
528
     * Generate an enroll string
529
     * This string can be used to feed to a QR code generator
530
     */
531 2
    public function generateEnrollString(string $metadataUrl): string
532
    {
533 2
        return $this->_getEnrollString($metadataUrl);
534
    }
535
    
536
    /**
537
     * Retrieve the metadata for an enrollment session.
538
     * 
539
     * When the phone calls the url that you have passed to
540
     * generateEnrollmentQR, you must provide it with the output
541
     * of this function. (Don't forget to json_encode the output.)
542
     * 
543
     * Note, you can call this function only once, as the enrollment session
544
     * data will be destroyed as soon as it is retrieved.
545
     *
546
     * When successful the enrollment status will be set to ENROLLMENT_STATUS_RETRIEVED
547
     *
548
     * @param String $enrollmentKey The enrollmentKey that the phone has posted along with its request.
549
     * @param String $authenticationUrl The url you provide to the phone to post authentication responses
550
     * @param String $enrollmentUrl The url you provide to the phone to post the generated user secret. You must include
551
     *                              a temporary enrollment secret in this URL to make this process secure.
552
     *                              Use getEnrollmentSecret() to get this secret
553
     * @return array An array of metadata that the phone needs to complete
554
     *               enrollment. You must encode it in JSON before you send
555
     *               it to the phone.
556
     * @throws Exception when generating the metadata failed
557
     */
558 1
    public function getEnrollmentMetadata(string $enrollmentKey, string $authenticationUrl, string $enrollmentUrl): array
559
    {
560 1
        $data = $this->_stateStorage->getValue(self::PREFIX_ENROLLMENT . $enrollmentKey);
561 1
        if (!is_array($data)) {
562 1
            $this->logger->error('Unable to find enrollment metadata in state storage');
563 1
            throw new Exception('Unable to find enrollment metadata in state storage');
564
        }
565
566
        $metadata = array("service"=>
567 1
                               array("displayName"       => $this->_name,
568 1
                                     "identifier"        => $this->_identifier,
569 1
                                     "logoUrl"           => $this->_logoUrl,
570 1
                                     "infoUrl"           => $this->_infoUrl,
571 1
                                     "authenticationUrl" => $authenticationUrl,
572 1
                                     "ocraSuite"         => $this->_ocraSuite,
573 1
                                     "enrollmentUrl"     => $enrollmentUrl
574
                               ),
575
                          "identity"=>
576 1
                               array("identifier" =>$data["userId"],
577 1
                                     "displayName"=>$data["displayName"]));
578
579 1
        $this->_stateStorage->unsetValue(self::PREFIX_ENROLLMENT . $enrollmentKey);
580
581 1
        $this->_setEnrollmentStatus($data["sessionId"], self::ENROLLMENT_STATUS_RETRIEVED);
582 1
        return $metadata;
583
    }
584
585
    /** 
586
     * Get a temporary enrollment secret to be able to securely post a user 
587
     * secret.
588
     *
589
     * In the last step of the enrollment process the phone will send the OCRA user secret.
590
     * This is the shared secret is used in the authentication process. To prevent an
591
     * attacker from impersonating a user during enrollment and post a user secret that is known to the attacker,
592
     * a temporary enrollment secret is added to the metadata. This secret must be included in the enrollmentUrl that is
593
     * passed to the getMetadata function so that when the client sends the OCRA user secret to the server this
594
     * enrollment secret is included. The server uses the enrollment secret to authenticate the client, and will
595
     * allow only one submission of a user secret for one enrollment secret.
596
     *
597
     * You MUST use validateEnrollmentSecret() to validate enrollment secret that the client sends before accepting
598
     * the associated OCRA client secret
599
     *
600
     * @param String $enrollmentKey The enrollmentKey generated by startEnrollmentSession() at the start of the
601
     *                              enrollment process.
602
     * @return String The enrollment secret
603
     * @throws Exception when generating the enrollment secret failed
604
     */
605 1
    public function getEnrollmentSecret(string $enrollmentKey): string
606
    {
607 1
         $data = $this->_stateStorage->getValue(self::PREFIX_ENROLLMENT . $enrollmentKey);
608 1
         if (!is_array($data)) {
609
             $this->logger->error('getEnrollmentSecret: enrollment key not found');
610
             throw new RuntimeException('enrollment key not found');
611
         }
612 1
         $userId = $data["userId"] ?? NULL;
613 1
         $sessionId = $data["sessionId"] ?? NULL;
614 1
         if (!is_string($userId) || !(is_string($sessionId))) {
615
             throw new RuntimeException('getEnrollmentSecret: invalid enrollment data');
616
         }
617
         $enrollmentData = [
618 1
             "userId" => $userId,
619 1
             "sessionId" => $sessionId
620
         ];
621 1
         $enrollmentSecret = $this->_uniqueSessionKey();
622 1
         $this->_stateStorage->setValue(
623 1
             self::PREFIX_ENROLLMENT_SECRET . $enrollmentSecret,
624 1
             $enrollmentData,
625 1
             self::ENROLLMENT_EXPIRE
626
         );
627 1
         return $enrollmentSecret;
628
    }
629
630
    /**
631
     * Validate if an enrollmentSecret that was passed from the phone is valid.
632
     *
633
     * Note: After validating the enrollmentSecret you must call finalizeEnrollment() to
634
     *       invalidate the enrollment secret.
635
     *
636
     * When successful the enrollment state will be set to ENROLLMENT_STATUS_PROCESSED
637
     *
638
     * @param string $enrollmentSecret The enrollmentSecret that the phone posted; it must match
639
     *                                 the enrollmentSecret that was generated using
640
     *                                 getEnrollmentSecret earlier in the process and that the phone
641
     *                                 received as part of the metadata.
642
     *                                 Note that this is not the OCRA user secret that the Phone posts to the server
643
     * @return string The userid of the user that was being enrolled if the enrollment secret is valid. The application
644
     *                should use this userid to store the OCRA user secret that the phone posted.
645
     *
646
     * @throws Exception when the validation failed
647
     */
648 1
    public function validateEnrollmentSecret(string $enrollmentSecret): string
649
    {
650
        try {
651 1
            $data = $this->_stateStorage->getValue(self::PREFIX_ENROLLMENT_SECRET . $enrollmentSecret);
652 1
            if (NULL === $data) {
653 1
                throw new RuntimeException('Enrollment secret not found');
654
            }
655 1
            if ( !is_array($data) || !is_string($data["userId"] ?? NULL)) {
656
                throw new RuntimeException('Invalid enrollment data');
657
            }
658
659
            // Secret is valid, application may accept the user secret.
660 1
            $this->_setEnrollmentStatus($data["sessionId"], self::ENROLLMENT_STATUS_PROCESSED);
661 1
            return $data["userId"];
662 1
        } catch (Exception $e) {
663 1
            $this->logger->error('Validation of enrollment secret failed', array('exception' => $e));
664 1
            throw $e;
665
        }
666
    }
667
668
    /**
669
     * Finalize the enrollment process.
670
     *
671
     * Invalidates $enrollmentSecret
672
     *
673
     * Call this after validateEnrollmentSecret
674
     * When successfull the enrollment state will be set to ENROLLMENT_STATUS_FINALIZED
675
     *
676
     * @param String The enrollment secret that was posted by the phone. This is the same secret used in the call to
677
     *               validateEnrollmentSecret()
678
     * @return bool true when finalize was successful, false otherwise
679
     *
680
     * Does not throw
681
     */
682 1
    public function finalizeEnrollment(string $enrollmentSecret): bool
683
    {
684
        try {
685 1
            $data = $this->_stateStorage->getValue(self::PREFIX_ENROLLMENT_SECRET . $enrollmentSecret);
686 1
            if (NULL === $data) {
687 1
                throw new RuntimeException('Enrollment secret not found');
688
            }
689 1
            if (is_array($data)) {
690
                // Enrollment is finalized, destroy our session data.
691 1
                $this->_stateStorage->unsetValue(self::PREFIX_ENROLLMENT_SECRET . $enrollmentSecret);
692 1
                $this->_setEnrollmentStatus($data["sessionId"], self::ENROLLMENT_STATUS_FINALIZED);
693
            } else {
694
                $this->logger->error(
695
                    'Enrollment status is not finalized, enrollmentsecret was not found in state storage. ' .
696
                    'Warning! the method will still return "true" as a result.'
697
                );
698
            }
699 1
            return true;
700 1
        } catch (Exception $e) {
701
            // Cleanup failed
702 1
            $this->logger->warning('finalizeEnrollment failed', array('exception' => $e));
703
        }
704 1
        return false;
705
    }
706
707
    /**
708
     * Authenticate a user.
709
     * This method should be called when the phone (tiqr client) posts a response to an
710
     * authentication challenge to the server. This method will validate the response and
711
     * returns one of the self::AUTH_RESULT_* codes to indicate success or error
712
     *
713
     * When the authentication was successful the user's session is marked as authenticated.
714
     * This essentially logs the user in. Use getauthenticateduser() and logout() with the
715
     * application's session sessionID to respectively get the authenticated user and clear
716
     * the authentication state.
717
     *
718
     * The default OCRA suite uses 6 digit response codes this makes the authentication vulnerable to a guessing attack
719
     * when the client has an unlimited amount of tries. It is important to limit the amount of times to allow a
720
     * AUTH_RESULT_INVALID_RESPONSE response. AUTH_RESULT_INVALID_RESPONSE counts as failed authentication attempt
721
     * (i.e. a wrong guess by the client). The other error results and exceptions mean that the response could
722
     * not be validated on the server and should therefore not reveal anything useful to the client.
723
     * The UserStorage class supports (temporarily) locking a user account. It is the responsibility of the application
724
     * to implement these measures
725
     *
726
     * @param String $userId The userid of the user that should be authenticated, as sent in the POST back by the tiqr
727
     *                       client. If $userId does not match the optional userId in startAuthenticationSession()
728
     *                       AUTH_RESULT_INVALID_USERID is returned
729
     * @param String $userSecret The OCRA user secret that the application previously stored for $userId using
730
     *                           e.g. a Tiqr_UserSecretStorage
731
     *                           Leave empty when using a OcraService that does not require a user secret
732
     * @param String $sessionKey The authentication session key that was returned by startAuthenticationSession()
733
     *                           If the session key cannot be found in the StateStorage AUTH_RESULT_INVALID_CHALLENGE
734
     *                           is returned
735
     * @param String $response   The response to the challenge that the tiqr client posted back to the server
736
     *
737
     * @return Int The result of the authentication. This is one of the AUTH_RESULT_* constants of the Tiqr_Server class.
738
     * @throws Exception when there was an error during the authentication process
739
     */
740 1
    public function authenticate(string $userId, string $userSecret, string $sessionKey, string $response): int
741
    {
742
        try {
743 1
            $state = $this->_stateStorage->getValue(self::PREFIX_CHALLENGE . $sessionKey);
744 1
            if (is_null($state)) {
745 1
                $this->logger->notice('The auth challenge could not be found in the state storage');
746 1
                return self::AUTH_RESULT_INVALID_CHALLENGE;
747
            }
748
        } catch (Exception $e) {
749
            $this->logger->error('Error looking up challenge in state storage', array('exception' => $e));
750
            throw $e;
751
        }
752
753 1
        $sessionId = $state["sessionId"] ?? NULL;   // Application's sessionId
754 1
        $challenge = $state["challenge"] ?? NULL;   // The challenge we sent to the Tiqr client
755 1
        if (!is_string($sessionId) || (!is_string($challenge)) ) {
756
            throw new RuntimeException('Invalid state for state storage');
757
        }
758
759
        // The user ID is optional, it is set when the application requested authentication of a specific userId
760
        // instead of letting the client decide
761 1
        $challengeUserId = $state["userId"] ?? NULL;
762
763
        // If the application requested a specific userId, verify that that is that userId that we're now authenticating
764 1
        if ($challengeUserId!==NULL && ($userId !== $challengeUserId)) {
765 1
            $this->logger->error(
766 1
                sprintf('Authentication failed: the requested userId "%s" does not match userId "%s" that is being authenticated',
767 1
                $challengeUserId, $userId)
768
            );
769 1
            return self::AUTH_RESULT_INVALID_USERID; // requested and actual userId do not match
770
        }
771
772
        try {
773 1
            $equal = $this->_ocraService->verifyResponse($response, $userId, $userSecret, $challenge, $sessionKey);
774
        } catch (Exception $e) {
775
            $this->logger->error(sprintf('Error verifying OCRA response for user "%s"', $userId), array('exception' => $e));
776
            throw $e;
777
        }
778
779 1
        if ($equal) {
780
            // Set application session as authenticated
781 1
            $this->_stateStorage->setValue(self::PREFIX_AUTHENTICATED . $sessionId, $userId, self::LOGIN_EXPIRE);
782 1
            $this->logger->notice(sprintf('Authenticated user "%s" in session "%s"', $userId, $sessionId));
783
784
            // Cleanup challenge
785
            // Future authentication attempts with this sessionKey will get a AUTH_RESULT_INVALID_CHALLENGE
786
            // This QR code / push notification cannot be used again
787
            // Cleaning up only after successful authentication enables the user to retry authentication after e.g. an
788
            // invalid response
789
            try {
790 1
                $this->_stateStorage->unsetValue(self::PREFIX_CHALLENGE . $sessionKey); // May throw
791
            } catch (Exception $e) {
792
                // Only log error
793
                $this->logger->warning('Could not delete authentication session key', array('error' => $e));
794
            }
795
796 1
            return self::AUTH_RESULT_AUTHENTICATED;
797
        }
798 1
        $this->logger->error('Authentication failed: invalid response');
799 1
        return self::AUTH_RESULT_INVALID_RESPONSE;
800
    }
801
802
    /**
803
     * Log the user out.
804
     * It is not an error is the $sessionId does not exists, or when the $sessionId has expired
805
     *
806
     * @param String $sessionId The application's session identifier (defaults
807
     *                          to the php session).
808
     *                          This is the application's sessionId that was provided to startAuthenticationSession()
809
     *
810
     * @throws Exception when there was an error communicating with the storage backed
811
     */
812 1
    public function logout(string $sessionId=""): void
813
    {
814 1
        if ($sessionId=="") {
815
            $sessionId = session_id(); 
816
        }
817
        
818 1
        $this->_stateStorage->unsetValue(self::PREFIX_AUTHENTICATED.$sessionId);
819 1
    }
820
    
821
    /**
822
     * Exchange a notificationToken for a deviceToken.
823
     * 
824
     * During enrollment, the phone will post a notificationAddress that can be 
825
     * used to send notifications. To actually send the notification, 
826
     * this address should be converted to the real device address.
827
     *
828
     * @param String $notificationType    The notification type.
829
     * @param String $notificationAddress The address that was stored during enrollment.
830
     *
831
     * @return String|bool The device address that can be used to send a notification.
832
     *                     false on error
833
     */
834
    public function translateNotificationAddress(string $notificationType, string $notificationAddress)
835
    {
836
        if ($notificationType == 'APNS' || $notificationType == 'FCM') {
837
            return $this->_deviceStorage->getDeviceToken($notificationAddress);
838
        } else {
839
            return $notificationAddress;
840
        }
841
    }
842
    
843
    /**
844
     * Retrieve the currently logged in user.
845
     * @param String $sessionId The application's session identifier (defaults
846
     *                          to the php session).
847
     *                          This is the application's sessionId that was provided to startAuthenticationSession()
848
     * @return string|NULL The userId of the authenticated user,
849
     *                     NULL if no user is logged in
850
     *                     NULL if the user's login state could not be determined
851
     *
852
     * Does not throw
853
     */
854 1
    public function getAuthenticatedUser(string $sessionId=""): ?string
855
    {
856 1
        if ($sessionId=="") {
857
            $this->logger->debug('Using the PHP session id, as no session id was provided');
858
            $sessionId = session_id(); 
859
        }
860
        
861
        try {
862 1
            return $this->_stateStorage->getValue("authenticated_".$sessionId);
863
        }
864
        catch (Exception $e) {
865
            $this->logger->error('getAuthenticatedUser failed', array('exception'=>$e));
866
            return NULL;
867
        }
868
    }
869
    
870
    /**
871
     * Generate a authentication challenge URL
872
     * @param String $sessionKey The authentication sessionKey
873
     *
874
     * @return string AuthenticationURL
875
     * @throws Exception
876
     */
877 3
    protected function _getChallengeUrl(string $sessionKey): string
878
    {
879
        // Lookup the authentication session data and use this to generate the application specific
880
        // authentication URL
881
        // The are two formats see: https://tiqr.org/technical/protocol/
882
        // We probably just generated the challenge and stored it in the StateStorage
883
        // We can save a roundtrip to the storage backend here by reusing this information
884
885 3
        $state = $this->_stateStorage->getValue(self::PREFIX_CHALLENGE . $sessionKey);
886 3
        if (is_null($state)) {
887
            $this->logger->error(
888
                sprintf(
889
                'Cannot get session key "%s"',
890
                    $sessionKey
891
                )
892
            );
893
            throw new Exception('Cannot find sessionkey');
894
        }
895
896 3
        $userId = $state["userId"] ?? NULL;
897 3
        $challenge = $state["challenge"] ?? '';
898 3
        $spIdentifier = $state["spIdentifier"] ?? '';
899
900 3
        if ( (strpos($this->_protocolAuth, 'https://') === 0) || (strpos($this->_protocolAuth, 'http://') === 0) ) {
901
            // Create universal Link
902 2
            $parameters=array();
903 2
            if (!is_null($userId)) {
904 1
                $parameters[]='u='.urlencode($userId);
905
            }
906 2
            $parameters[]='s='.urlencode($sessionKey);
907 2
            $parameters[]='q='.urlencode($challenge);
908 2
            $parameters[]='i='.urlencode($this->getIdentifier());
909 2
            $parameters[]='v='.urlencode($this->_protocolVersion);
910 2
            return $this->_protocolAuth.'?'.implode('&', $parameters);
911
        }
912
913
        // Create custom URL scheme
914
        // Last bit is the spIdentifier
915 1
        return $this->_protocolAuth."://".(!is_null($userId)?urlencode($userId).'@':'').$this->getIdentifier()."/".$sessionKey."/".$challenge."/".urlencode($spIdentifier)."/".$this->_protocolVersion;
916
    }
917
918
    /**
919
     * Generate an enrollment string
920
     * @param String $metadataUrl The URL you provide to the phone to retrieve metadata.
921
     */
922 2
    protected function _getEnrollString(string $metadataUrl): string
923
    {
924
        // The are two formats see: https://tiqr.org/technical/protocol/
925
926 2
        if ( (strpos($this->_protocolEnroll, 'https://') === 0) || (strpos($this->_protocolEnroll, 'http://') === 0) ) {
927
            // Create universal Link
928 1
            return $this->_protocolEnroll.'?metadata='.urlencode($metadataUrl);
929
        }
930
931
        // Create custom URL scheme
932 1
        return $this->_protocolEnroll."://".$metadataUrl;
933
    }
934
935
    /**
936
     * Generate a unique secure pseudo-random value to be used as session key in the
937
     * tiqr protocol. These keys are sent to the tiqr client during enrollment and authentication
938
     * And are used in the server as part of key for data in StateStorage
939
     * @return String The session key as HEX encoded string
940
     * @throws Exception When the key could not be generated
941
     */
942 5
    protected function _uniqueSessionKey(): string
943
    {
944
945 5
        return bin2hex( Tiqr_Random::randomBytes(self::SESSION_KEY_LENGTH_BYTES) );
946
    }
947
    
948
    /**
949
     * Internal function to set the enrollment status of a session.
950
     * @param String $sessionId The sessionId to set the status for
951
     * @param int $status The new enrollment status (one of the 
952
     *                    self::ENROLLMENT_STATUS_* constants)
953
     * @throws Exception when updating the status fails
954
     */
955 2
    protected function _setEnrollmentStatus(string $sessionId, int $status): void
956
    {
957 2
        if (($status < 1) || ($status > 6)) {
958
            // Must be one of the self::ENROLLMENT_STATUS_* constants
959
            throw new InvalidArgumentException('Invalid enrollment status');
960
        }
961 2
        $this->_stateStorage->setValue(self::PREFIX_ENROLLMENT_STATUS.$sessionId, $status, self::ENROLLMENT_EXPIRE);
962 2
    }
963
}
964