Passed
Push — develop ( a4ee47...43506b )
by Pieter van der
01:15 queued 13s
created

Tiqr_Service::translateNotificationAddress()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

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