Passed
Pull Request — develop (#49)
by Pieter van der
25:39 queued 15:03
created

Tiqr_Service::authenticate()   B

Complexity

Conditions 10
Paths 10

Size

Total Lines 60
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 12.4464

Importance

Changes 4
Bugs 0 Features 1
Metric Value
eloc 33
c 4
b 0
f 1
dl 0
loc 60
ccs 22
cts 31
cp 0.7097
rs 7.6666
cc 10
nc 10
nop 4
crap 12.4464

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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