Passed
Pull Request — develop (#53)
by Peter
03:13
created

Tiqr_Service::finalizeEnrollment()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4.3035

Importance

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