Overview

Classes

  • u2flib_server\RegisterRequest
  • u2flib_server\Registration
  • u2flib_server\SignRequest
  • u2flib_server\U2F

Exceptions

  • Exception
  • u2flib_server\Error

Constants

  • u2flib_server\ERR_ATTESTATION_SIGNATURE
  • u2flib_server\ERR_ATTESTATION_VERIFICATION
  • u2flib_server\ERR_AUTHENTICATION_FAILURE
  • u2flib_server\ERR_BAD_RANDOM
  • u2flib_server\ERR_BAD_UA_RETURNING
  • u2flib_server\ERR_COUNTER_TOO_LOW
  • u2flib_server\ERR_NO_MATCHING_REGISTRATION
  • u2flib_server\ERR_NO_MATCHING_REQUEST
  • u2flib_server\ERR_PUBKEY_DECODE
  • u2flib_server\ERR_UNMATCHED_CHALLENGE
  • u2flib_server\U2F_VERSION
  • Overview
  • Class
  1: <?php
  2: 
  3:  /* Copyright (c) 2014 Yubico AB
  4:  * All rights reserved.
  5:  *
  6:  * Redistribution and use in source and binary forms, with or without
  7:  * modification, are permitted provided that the following conditions are
  8:  * met:
  9:  *
 10:  *   * Redistributions of source code must retain the above copyright
 11:  *     notice, this list of conditions and the following disclaimer.
 12:  *
 13:  *   * Redistributions in binary form must reproduce the above
 14:  *     copyright notice, this list of conditions and the following
 15:  *     disclaimer in the documentation and/or other materials provided
 16:  *     with the distribution.
 17:  *
 18:  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 19:  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 20:  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 21:  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 22:  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 23:  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 24:  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 25:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 26:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 27:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 28:  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 29:  */
 30: 
 31: namespace u2flib_server;
 32: 
 33: /** Constant for the version of the u2f protocol */
 34: const U2F_VERSION = "U2F_V2";
 35: 
 36: /** Error for the authentication message not matching any outstanding
 37:  * authentication request */
 38: const ERR_NO_MATCHING_REQUEST = 1;
 39: /** Error for the authentication message not matching any registration */
 40: const ERR_NO_MATCHING_REGISTRATION = 2;
 41: /** Error for the signature on the authentication message not verifying with
 42:  * the correct key */
 43: const ERR_AUTHENTICATION_FAILURE = 3;
 44: /** Error for the challenge in the registration message not matching the
 45:  * registration challenge */
 46: const ERR_UNMATCHED_CHALLENGE = 4;
 47: /** Error for the attestation signature on the registration message not
 48:  * verifying */
 49: const ERR_ATTESTATION_SIGNATURE = 5;
 50: /** Error for the attestation verification not verifying */
 51: const ERR_ATTESTATION_VERIFICATION = 6;
 52: /** Error for not getting good random from the system */
 53: const ERR_BAD_RANDOM = 7;
 54: /** Error when the counter is lower than expected */
 55: const ERR_COUNTER_TOO_LOW = 8;
 56: /** Error decoding public key */
 57: const ERR_PUBKEY_DECODE = 9;
 58: 
 59: /** Error user-agent returned error */
 60: const ERR_BAD_UA_RETURNING = 10;
 61: 
 62: /** @internal */
 63: const PUBKEY_LEN = 65;
 64: 
 65: class U2F {
 66:   private $appId;
 67:   private $attestDir;
 68: 
 69:   /** @internal */
 70:   private static $FIXCERTS = array(
 71:     '349bca1031f8c82c4ceca38b9cebf1a69df9fb3b94eed99eb3fb9aa3822d26e8',
 72:     'dd574527df608e47ae45fbba75a2afdd5c20fd94a02419381813cd55a2a3398f',
 73:     '1d8764f0f7cd1352df6150045c8f638e517270e8b5dda1c63ade9c2280240cae',
 74:     'd0edc9a91a1677435a953390865d208c55b3183c6759c9b5a7ff494c322558eb',
 75:     '6073c436dcd064a48127ddbf6032ac1a66fd59a0c24434f070d4e564c124c897',
 76:     'ca993121846c464d666096d35f13bf44c1b05af205f9b4a1e00cf6cc10c5e511');
 77: 
 78:   /**
 79:    * @param string Application id for the running application
 80:    * @param string Directory where trusted attestation roots may be found
 81:    */
 82:   public function __construct($appId, $attestDir = null) {
 83:     $this->appId = $appId;
 84:     $this->attestDir = $attestDir;
 85:   }
 86: 
 87:   /**
 88:    * Called to get a registration request to send to a user.
 89:    * Returns an array of one registration request and a array of sign requests.
 90:    * @param array optional list of current registrations for this
 91:    * user, to prevent the user from registering the same authenticator serveral
 92:    * times.
 93:    * @return array An array of two elements, the first containing a
 94:    * RegisterRequest the second being an array of SignRequest
 95:    * @throws Error
 96:    */
 97:   public function getRegisterData($registrations = array()) {
 98:     if( !is_array( $registrations ) ) {
 99:         throw new \InvalidArgumentException('$registrations of getRegisterData() method only accepts array.');
100:     }
101: 
102:     $challenge = U2F::createChallenge();
103:     $request = new RegisterRequest($challenge, $this->appId);
104:     $signs = $this->getAuthenticateData($registrations);
105:     return array($request, $signs);
106:   }
107: 
108:   /**
109:    * Called to verify and unpack a registration message.
110:    * @param RegisterRequest request this is a reply to
111:    * @param RegisterResponse response from a user
112:    * @param bool set to true if the attestation certificate should be
113:    * included in the returned Registration object
114:    * @return Registration
115:    * @throws Error
116:    */
117:   public function doRegister($request, $response, $include_cert = true) {
118:     if( !is_object( $request ) ) {
119:         throw new \InvalidArgumentException('$request of doRegister() method only accepts object.');
120:     }
121: 
122:     if( !is_object( $response ) ) {
123:         throw new \InvalidArgumentException('$response of doRegister() method only accepts object.');
124:     }
125: 
126:     if( property_exists( $response, 'errorCode') ) {
127:         throw new Error('User-agent returned error. Error code: ' . $response->errorCode, ERR_BAD_UA_RETURNING );
128:     }
129: 
130:     if( !is_bool( $include_cert ) ) {
131:         throw new \InvalidArgumentException('$include_cert of doRegister() method only accepts boolean.');
132:     }
133: 
134:     $rawReg =  U2F::base64u_decode($response->registrationData);
135:     $regData = array_values(unpack('C*', $rawReg));
136:     $clientData = U2F::base64u_decode($response->clientData);
137:     $cli = json_decode($clientData);
138: 
139:     if($cli->challenge !== $request->challenge) {
140:       throw new Error('Registration challenge does not match', ERR_UNMATCHED_CHALLENGE );
141:     }
142: 
143:     $registration = new Registration();
144:     $offs = 1;
145:     $pubKey = substr($rawReg, $offs, PUBKEY_LEN);
146:     $offs += PUBKEY_LEN;
147:     // decode the pubKey to make sure it's good
148:     $tmpkey = U2F::pubkey_to_pem($pubKey);
149:     if($tmpkey == null) {
150:       throw new Error('Decoding of public key failed', ERR_PUBKEY_DECODE );
151:     }
152:     $registration->publicKey = base64_encode($pubKey);
153:     $khLen = $regData[$offs++];
154:     $kh = substr($rawReg, $offs, $khLen);
155:     $offs += $khLen;
156:     $registration->keyHandle = U2F::base64u_encode($kh);
157: 
158:     // length of certificate is stored in byte 3 and 4 (excluding the first 4 bytes)
159:     $certLen = 4;
160:     $certLen += ($regData[$offs + 2] << 8);
161:     $certLen += $regData[$offs + 3];
162: 
163:     $rawCert = U2F::fixSignatureUnusedBits(substr($rawReg, $offs, $certLen));
164:     $offs += $certLen;
165:     $pemCert  = "-----BEGIN CERTIFICATE-----\r\n";
166:     $pemCert .= chunk_split(base64_encode($rawCert), 64);
167:     $pemCert .= "-----END CERTIFICATE-----";
168:     if($include_cert) {
169:       $registration->certificate = base64_encode($rawCert);
170:     }
171:     if($this->attestDir) {
172:       if(openssl_x509_checkpurpose($pemCert, -1, $this->get_certs()) !== true) {
173:         throw new Error('Attestation certificate can not be validated', ERR_ATTESTATION_VERIFICATION );
174:       }
175:     }
176: 
177:     if(!openssl_pkey_get_public($pemCert)) {
178:       throw new Error('Decoding of public key failed', ERR_PUBKEY_DECODE );
179:     }
180:     $signature = substr($rawReg, $offs);
181: 
182:     $dataToVerify  = chr(0);
183:     $dataToVerify .= hash('sha256', $request->appId, true);
184:     $dataToVerify .= hash('sha256', $clientData, true);
185:     $dataToVerify .= $kh;
186:     $dataToVerify .= $pubKey;
187: 
188:     if(openssl_verify($dataToVerify, $signature, $pemCert, 'sha256') === 1) {
189:       return $registration;
190:     } else {
191:       throw new Error('Attestation signature does not match', ERR_ATTESTATION_SIGNATURE );
192:     }
193:   }
194: 
195:   /**
196:    * Called to get an authentication request.
197:    * @param array An array of the registrations to create authentication requests for.
198:    * @return array An array of SignRequest
199:    * @throws Error
200:    */
201:   public function getAuthenticateData($registrations) {
202:     if( !is_array( $registrations ) ) {
203:         throw new \InvalidArgumentException('$registrations of getAuthenticateData() method only accepts array.');
204:     }
205: 
206:     $sigs = array();
207:     foreach ($registrations as $reg) {
208:       if( !is_object( $reg ) ) {
209:         throw new \InvalidArgumentException('$registrations of getAuthenticateData() method only accepts array of object.');
210:       }
211: 
212:       $sig = new SignRequest();
213:       $sig->appId = $this->appId;
214:       $sig->keyHandle = $reg->keyHandle;
215:       $sig->challenge = U2F::createChallenge();
216:       $sigs[] = $sig;
217:     }
218:     return $sigs;
219:   }
220: 
221:   /**
222:    * Called to verify an authentication response
223:    * @param array An array of outstanding authentication requests
224:    * @param array An array of current registrations
225:    * @param SignResponse A response from the authenticator
226:    * @return Registration
227:    * @throws Error
228:    *
229:    * The Registration object returned on success contains an updated counter
230:    * that should be saved for future authentications.
231:    * If the Error returned is ERR_COUNTER_TOO_LOW this is an indication of
232:    * token cloning or similar and appropriate action should be taken.
233:    */
234:   public function doAuthenticate($requests, $registrations, $response) {
235:     if( !is_array( $requests ) ) {
236:         throw new \InvalidArgumentException('$requests of doAuthenticate() method only accepts array.');
237:     }
238: 
239:     if( !is_array( $registrations ) ) {
240:         throw new \InvalidArgumentException('$registrations of doAuthenticate() method only accepts array.');
241:     }
242: 
243:     if( !is_object( $response ) ) {
244:         throw new \InvalidArgumentException('$response of doAuthenticate() method only accepts object.');
245:     }
246: 
247:     if( property_exists( $response, 'errorCode') ) {
248:         throw new Error('User-agent returned error. Error code: ' . $response->errorCode, ERR_BAD_UA_RETURNING );
249:     }
250: 
251:     $req = null;
252:     $reg = null;
253:     $clientData = U2F::base64u_decode($response->clientData);
254:     $decodedClient = json_decode($clientData);
255:     foreach ($requests as $req) {
256:       if( !is_object( $req ) ) {
257:         throw new \InvalidArgumentException('$requests of doAuthenticate() method only accepts array of object.');
258:       }
259: 
260:       if($req->keyHandle === $response->keyHandle && $req->challenge === $decodedClient->challenge) {
261:         break;
262:       }
263:       $req = null;
264:     }
265:     if($req === null) {
266:       throw new Error('No matching request found', ERR_NO_MATCHING_REQUEST );
267:     }
268:     foreach ($registrations as $reg) {
269:       if( !is_object( $reg ) ) {
270:         throw new \InvalidArgumentException('$registrations of doAuthenticate() method only accepts array of object.');
271:       }
272: 
273:       if($reg->keyHandle === $response->keyHandle) {
274:         break;
275:       }
276:       $reg = null;
277:     }
278:     if($reg === null) {
279:       throw new Error('No matching registration found', ERR_NO_MATCHING_REGISTRATION );
280:     }
281:     $pemKey = U2F::pubkey_to_pem(U2F::base64u_decode($reg->publicKey));
282:     if($pemKey == null) {
283:       throw new Error('Decoding of public key failed', ERR_PUBKEY_DECODE );
284:     }
285: 
286:     $signData = U2F::base64u_decode($response->signatureData);
287:     $dataToVerify  = hash('sha256', $req->appId, true);
288:     $dataToVerify .= substr($signData, 0, 5);
289:     $dataToVerify .= hash('sha256', $clientData, true);
290:     $signature = substr($signData, 5);
291: 
292:     if(openssl_verify($dataToVerify, $signature, $pemKey, 'sha256') === 1) {
293:       $ctr = unpack("Nctr", substr($signData, 1, 4));
294:       $counter = $ctr['ctr'];
295:       /* TODO: wrap-around should be handled somehow.. */
296:       if($counter > $reg->counter) {
297:         $reg->counter = $counter;
298:         return $reg;
299:       } else {
300:         throw new Error('Counter too low.', ERR_COUNTER_TOO_LOW );
301:       }
302:     } else {
303:       throw new Error('Authentication failed', ERR_AUTHENTICATION_FAILURE );
304:     }
305:   }
306: 
307:   private function get_certs() {
308:     $files = array();
309:     $dir = $this->attestDir;
310:     if ($dir && $handle = opendir($dir)) {
311:       while(false !== ($entry = readdir($handle))) {
312:         if(is_file("$dir/$entry")) {
313:           $files[] = "$dir/$entry";
314:         }
315:       }
316:       closedir($handle);
317:     }
318:     return $files;
319:   }
320: 
321:   private static function base64u_encode($data) {
322:     return trim(strtr(base64_encode($data), '+/', '-_'), '=');
323:   }
324: 
325:   private static function base64u_decode($data) {
326:     return base64_decode(strtr($data, '-_', '+/'));
327:   }
328: 
329:   private static function pubkey_to_pem($key) {
330:     if(strlen($key) != PUBKEY_LEN || $key[0] != "\x04") {
331:       return null;
332:     }
333: 
334:     /*
335:      * Convert the public key to binary DER format first
336:      * Using the ECC SubjectPublicKeyInfo OIDs from RFC 5480
337:      *
338:      *  SEQUENCE(2 elem)                        30 59
339:      *   SEQUENCE(2 elem)                       30 13
340:      *    OID1.2.840.10045.2.1 (id-ecPublicKey) 06 07 2a 86 48 ce 3d 02 01
341:      *    OID1.2.840.10045.3.1.7 (secp256r1)    06 08 2a 86 48 ce 3d 03 01 07
342:      *   BIT STRING(520 bit)                    03 42 ..key..
343:      */
344:     $der  = "\x30\x59\x30\x13\x06\x07\x2a\x86\x48\xce\x3d\x02\x01";
345:     $der .= "\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x07\x03\x42";
346:     $der .= "\0".$key;
347: 
348:     $pem  = "-----BEGIN PUBLIC KEY-----\r\n";
349:     $pem .= chunk_split(base64_encode($der), 64);
350:     $pem .= "-----END PUBLIC KEY-----";
351: 
352:     return $pem;
353:   }
354: 
355:   private static function createChallenge() {
356:     $challenge = openssl_random_pseudo_bytes(32, $crypto_strong );
357:     if( $crypto_strong != true ) {
358:           throw new Error('Unable to obtain a good source of randomness', ERR_BAD_RANDOM );
359:     }
360: 
361:     $challenge = U2F::base64u_encode( $challenge );
362: 
363:     return $challenge;
364:   }
365: 
366:   /**
367:    * Fixes a certificate where the signature contains unused bits.
368:    */
369:   private static function fixSignatureUnusedBits($cert) {
370:     if(in_array(hash('sha256', $cert), self::$FIXCERTS)) {
371:       $cert[strlen($cert) - 257] = "\0";
372:     }
373:     return $cert;
374:   }
375: }
376: 
377: /** Class for building a registration request */
378: class RegisterRequest {
379:   /** Protocol version */
380:   public $version = U2F_VERSION;
381:   /** Registration challenge */
382:   public $challenge;
383:   /** Application id */
384:   public $appId;
385: 
386:   /** @internal */
387:   public function __construct($challenge, $appId) {
388:     $this->challenge = $challenge;
389:     $this->appId = $appId;
390:   }
391: }
392: 
393: /** Class for building up an authentication request */
394: class SignRequest {
395:   /** Protocol version */
396:   public $version = U2F_VERSION;
397:   /** Authenticateion challenge */
398:   public $challenge;
399:   /** Key handle of a registered authenticator */
400:   public $keyHandle;
401:   /** Application id */
402:   public $appId;
403: }
404: 
405: /** Class returned for successful registrations */
406: class Registration {
407:   /** The key handle of the registered authenticator */
408:   public $keyHandle;
409:   /** The public key of the registered authenticator */
410:   public $publicKey;
411:   /** The attestation certificate of the registered authenticator */
412:   public $certificate;
413:   /** The counter associated with this registration */
414:   public $counter = 0;
415: }
416: 
417: /** Error class, returned on errors */
418: class Error extends \Exception {
419:   /* Override constructor and make messange and code mandatory */
420:   public function __construct($message, $code, Exception $previous = null) {
421:     parent::__construct($message, $code, $previous);
422:   }
423: }
424: 
php-u2flib-server API API documentation generated by ApiGen 2.8.0