BioTorrents.de’s version of Gazelle
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

u2f.class.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. <?php
  2. # https://github.com/Yubico/php-u2flib-server/blob/master/src/u2flib_server/U2F.php
  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. namespace u2f;
  31. #namespace u2flib_server;
  32. /** Constant for the version of the u2f protocol */
  33. const U2F_VERSION = "U2F_V2";
  34. /** Constant for the type value in registration clientData */
  35. const REQUEST_TYPE_REGISTER = "navigator.id.finishEnrollment";
  36. /** Constant for the type value in authentication clientData */
  37. const REQUEST_TYPE_AUTHENTICATE = "navigator.id.getAssertion";
  38. /** Error for the authentication message not matching any outstanding
  39. * authentication request */
  40. const ERR_NO_MATCHING_REQUEST = 1;
  41. /** Error for the authentication message not matching any registration */
  42. const ERR_NO_MATCHING_REGISTRATION = 2;
  43. /** Error for the signature on the authentication message not verifying with
  44. * the correct key */
  45. const ERR_AUTHENTICATION_FAILURE = 3;
  46. /** Error for the challenge in the registration message not matching the
  47. * registration challenge */
  48. const ERR_UNMATCHED_CHALLENGE = 4;
  49. /** Error for the attestation signature on the registration message not
  50. * verifying */
  51. const ERR_ATTESTATION_SIGNATURE = 5;
  52. /** Error for the attestation verification not verifying */
  53. const ERR_ATTESTATION_VERIFICATION = 6;
  54. /** Error for not getting good random from the system */
  55. const ERR_BAD_RANDOM = 7;
  56. /** Error when the counter is lower than expected */
  57. const ERR_COUNTER_TOO_LOW = 8;
  58. /** Error decoding public key */
  59. const ERR_PUBKEY_DECODE = 9;
  60. /** Error user-agent returned error */
  61. const ERR_BAD_UA_RETURNING = 10;
  62. /** Error old OpenSSL version */
  63. const ERR_OLD_OPENSSL = 11;
  64. /** Error for the origin not matching the appId */
  65. const ERR_NO_MATCHING_ORIGIN = 12;
  66. /** Error for the type in clientData being invalid */
  67. const ERR_BAD_TYPE = 13;
  68. /** Error for bad user presence byte value */
  69. const ERR_BAD_USER_PRESENCE = 14;
  70. /** @internal */
  71. const PUBKEY_LEN = 65;
  72. class U2F
  73. {
  74. /** @var string */
  75. private $appId;
  76. /** @var null|string */
  77. private $attestDir;
  78. /** @var array */
  79. private $facetIds;
  80. /** @internal */
  81. private $FIXCERTS = array(
  82. '349bca1031f8c82c4ceca38b9cebf1a69df9fb3b94eed99eb3fb9aa3822d26e8',
  83. 'dd574527df608e47ae45fbba75a2afdd5c20fd94a02419381813cd55a2a3398f',
  84. '1d8764f0f7cd1352df6150045c8f638e517270e8b5dda1c63ade9c2280240cae',
  85. 'd0edc9a91a1677435a953390865d208c55b3183c6759c9b5a7ff494c322558eb',
  86. '6073c436dcd064a48127ddbf6032ac1a66fd59a0c24434f070d4e564c124c897',
  87. 'ca993121846c464d666096d35f13bf44c1b05af205f9b4a1e00cf6cc10c5e511'
  88. );
  89. /**
  90. * @param string $appId Application id for the running application
  91. * @param string|null $attestDir Directory where trusted attestation roots may be found
  92. * @param array|null $facetIds List of trusted Facet IDs
  93. * @throws Error If OpenSSL older than 1.0.0 is used
  94. */
  95. public function __construct($appId, $attestDir = null, $facetIds = null)
  96. {
  97. if(OPENSSL_VERSION_NUMBER < 0x10000000) {
  98. throw new Error('OpenSSL has to be at least version 1.0.0, this is ' . OPENSSL_VERSION_TEXT, ERR_OLD_OPENSSL);
  99. }
  100. $this->appId = $appId;
  101. $this->attestDir = $attestDir;
  102. if(!is_array($facetIds)) {
  103. $facetIds = [$appId];
  104. }
  105. $this->facetIds = $facetIds;
  106. }
  107. /**
  108. * Called to get a registration request to send to a user.
  109. * Returns an array of one registration request and a array of sign requests.
  110. *
  111. * @param array $registrations List of current registrations for this
  112. * user, to prevent the user from registering the same authenticator several
  113. * times.
  114. * @return array An array of two elements, the first containing a
  115. * RegisterRequest the second being an array of SignRequest
  116. * @throws Error
  117. */
  118. public function getRegisterData(array $registrations = array())
  119. {
  120. $challenge = $this->createChallenge();
  121. $request = new RegisterRequest($challenge, $this->appId);
  122. $signs = $this->getAuthenticateData($registrations);
  123. return array($request, $signs);
  124. }
  125. /**
  126. * Called to verify and unpack a registration message.
  127. *
  128. * @param RegisterRequest $request this is a reply to
  129. * @param object $response response from a user
  130. * @param bool $includeCert set to true if the attestation certificate should be
  131. * included in the returned Registration object
  132. * @return Registration
  133. * @throws Error
  134. */
  135. public function doRegister($request, $response, $includeCert = true)
  136. {
  137. if( !is_object( $request ) ) {
  138. throw new \InvalidArgumentException('$request of doRegister() method only accepts object.');
  139. }
  140. if( !is_object( $response ) ) {
  141. throw new \InvalidArgumentException('$response of doRegister() method only accepts object.');
  142. }
  143. if( property_exists( $response, 'errorCode') && $response->errorCode !== 0 ) {
  144. throw new Error('User-agent returned error. Error code: ' . $response->errorCode, ERR_BAD_UA_RETURNING );
  145. }
  146. if( !is_bool( $includeCert ) ) {
  147. throw new \InvalidArgumentException('$include_cert of doRegister() method only accepts boolean.');
  148. }
  149. $rawReg = $this->base64u_decode($response->registrationData);
  150. $regData = array_values(unpack('C*', $rawReg));
  151. $clientData = $this->base64u_decode($response->clientData);
  152. $cli = json_decode($clientData);
  153. if($cli->challenge !== $request->challenge) {
  154. throw new Error('Registration challenge does not match', ERR_UNMATCHED_CHALLENGE );
  155. }
  156. if(isset($cli->typ) && $cli->typ !== REQUEST_TYPE_REGISTER) {
  157. throw new Error('ClientData type is invalid', ERR_BAD_TYPE);
  158. }
  159. if(isset($cli->origin) && !in_array($cli->origin, $this->facetIds, true)) {
  160. throw new Error('App ID does not match the origin', ERR_NO_MATCHING_ORIGIN);
  161. }
  162. $registration = new Registration();
  163. $offs = 1;
  164. $pubKey = substr($rawReg, $offs, PUBKEY_LEN);
  165. $offs += PUBKEY_LEN;
  166. // decode the pubKey to make sure it's good
  167. $tmpKey = $this->pubkey_to_pem($pubKey);
  168. if($tmpKey === null) {
  169. throw new Error('Decoding of public key failed', ERR_PUBKEY_DECODE );
  170. }
  171. $registration->publicKey = base64_encode($pubKey);
  172. $khLen = $regData[$offs++];
  173. $kh = substr($rawReg, $offs, $khLen);
  174. $offs += $khLen;
  175. $registration->keyHandle = $this->base64u_encode($kh);
  176. // length of certificate is stored in byte 3 and 4 (excluding the first 4 bytes)
  177. $certLen = 4;
  178. $certLen += ($regData[$offs + 2] << 8);
  179. $certLen += $regData[$offs + 3];
  180. $rawCert = $this->fixSignatureUnusedBits(substr($rawReg, $offs, $certLen));
  181. $offs += $certLen;
  182. $pemCert = "-----BEGIN CERTIFICATE-----\r\n";
  183. $pemCert .= chunk_split(base64_encode($rawCert), 64);
  184. $pemCert .= "-----END CERTIFICATE-----";
  185. if($includeCert) {
  186. $registration->certificate = base64_encode($rawCert);
  187. }
  188. if($this->attestDir) {
  189. if(openssl_x509_checkpurpose($pemCert, -1, $this->get_certs()) !== true) {
  190. throw new Error('Attestation certificate can not be validated', ERR_ATTESTATION_VERIFICATION );
  191. }
  192. }
  193. if(!openssl_pkey_get_public($pemCert)) {
  194. throw new Error('Decoding of public key failed', ERR_PUBKEY_DECODE );
  195. }
  196. $signature = substr($rawReg, $offs);
  197. $dataToVerify = pack('C', 0);
  198. $dataToVerify .= hash('sha256', $request->appId, true);
  199. $dataToVerify .= hash('sha256', $clientData, true);
  200. $dataToVerify .= $kh;
  201. $dataToVerify .= $pubKey;
  202. if(openssl_verify($dataToVerify, $signature, $pemCert, 'sha256') === 1) {
  203. return $registration;
  204. } else {
  205. throw new Error('Attestation signature does not match', ERR_ATTESTATION_SIGNATURE );
  206. }
  207. }
  208. /**
  209. * Called to get an authentication request.
  210. *
  211. * @param array $registrations An array of the registrations to create authentication requests for.
  212. * @return array An array of SignRequest
  213. * @throws Error
  214. */
  215. public function getAuthenticateData(array $registrations)
  216. {
  217. $sigs = array();
  218. $challenge = $this->createChallenge();
  219. foreach ($registrations as $reg) {
  220. if( !is_object( $reg ) ) {
  221. throw new \InvalidArgumentException('$registrations of getAuthenticateData() method only accepts array of object.');
  222. }
  223. /** @var Registration $reg */
  224. $sig = new SignRequest();
  225. $sig->appId = $this->appId;
  226. $sig->keyHandle = $reg->keyHandle;
  227. $sig->challenge = $challenge;
  228. $sigs[] = $sig;
  229. }
  230. return $sigs;
  231. }
  232. /**
  233. * Called to verify an authentication response
  234. *
  235. * @param array $requests An array of outstanding authentication requests
  236. * @param array $registrations An array of current registrations
  237. * @param object $response A response from the authenticator
  238. * @return Registration
  239. * @throws Error
  240. *
  241. * The Registration object returned on success contains an updated counter
  242. * that should be saved for future authentications.
  243. * If the Error returned is ERR_COUNTER_TOO_LOW this is an indication of
  244. * token cloning or similar and appropriate action should be taken.
  245. */
  246. public function doAuthenticate(array $requests, array $registrations, $response)
  247. {
  248. if( !is_object( $response ) ) {
  249. throw new \InvalidArgumentException('$response of doAuthenticate() method only accepts object.');
  250. }
  251. if( property_exists( $response, 'errorCode') && $response->errorCode !== 0 ) {
  252. throw new Error('User-agent returned error. Error code: ' . $response->errorCode, ERR_BAD_UA_RETURNING );
  253. }
  254. /** @var object|null $req */
  255. $req = null;
  256. /** @var object|null $reg */
  257. $reg = null;
  258. $clientData = $this->base64u_decode($response->clientData);
  259. $decodedClient = json_decode($clientData);
  260. if(isset($decodedClient->typ) && $decodedClient->typ !== REQUEST_TYPE_AUTHENTICATE) {
  261. throw new Error('ClientData type is invalid', ERR_BAD_TYPE);
  262. }
  263. foreach ($requests as $req) {
  264. if( !is_object( $req ) ) {
  265. throw new \InvalidArgumentException('$requests of doAuthenticate() method only accepts array of object.');
  266. }
  267. if($req->keyHandle === $response->keyHandle && $req->challenge === $decodedClient->challenge) {
  268. break;
  269. }
  270. $req = null;
  271. }
  272. if($req === null) {
  273. throw new Error('No matching request found', ERR_NO_MATCHING_REQUEST );
  274. }
  275. if(isset($decodedClient->origin) && !in_array($decodedClient->origin, $this->facetIds, true)) {
  276. throw new Error('App ID does not match the origin', ERR_NO_MATCHING_ORIGIN);
  277. }
  278. foreach ($registrations as $reg) {
  279. if( !is_object( $reg ) ) {
  280. throw new \InvalidArgumentException('$registrations of doAuthenticate() method only accepts array of object.');
  281. }
  282. if($reg->keyHandle === $response->keyHandle) {
  283. break;
  284. }
  285. $reg = null;
  286. }
  287. if($reg === null) {
  288. throw new Error('No matching registration found', ERR_NO_MATCHING_REGISTRATION );
  289. }
  290. $pemKey = $this->pubkey_to_pem($this->base64u_decode($reg->publicKey));
  291. if($pemKey === null) {
  292. throw new Error('Decoding of public key failed', ERR_PUBKEY_DECODE );
  293. }
  294. $signData = $this->base64u_decode($response->signatureData);
  295. $dataToVerify = hash('sha256', $req->appId, true);
  296. $dataToVerify .= substr($signData, 0, 5);
  297. $dataToVerify .= hash('sha256', $clientData, true);
  298. $signature = substr($signData, 5);
  299. if(openssl_verify($dataToVerify, $signature, $pemKey, 'sha256') === 1) {
  300. $upb = unpack("Cupb", substr($signData, 0, 1));
  301. if($upb['upb'] !== 1) {
  302. throw new Error('User presence byte value is invalid', ERR_BAD_USER_PRESENCE );
  303. }
  304. $ctr = unpack("Nctr", substr($signData, 1, 4));
  305. $counter = $ctr['ctr'];
  306. /* TODO: wrap-around should be handled somehow.. */
  307. if($counter > $reg->counter) {
  308. $reg->counter = $counter;
  309. return self::castObjectToRegistration($reg);
  310. } else {
  311. throw new Error('Counter too low.', ERR_COUNTER_TOO_LOW );
  312. }
  313. } else {
  314. throw new Error('Authentication failed', ERR_AUTHENTICATION_FAILURE );
  315. }
  316. }
  317. /**
  318. * @param object $object
  319. * @return Registration
  320. */
  321. protected static function castObjectToRegistration($object)
  322. {
  323. $reg = new Registration();
  324. if (isset($object->publicKey)) {
  325. $reg->publicKey = $object->publicKey;
  326. }
  327. if (isset($object->certificate)) {
  328. $reg->certificate = $object->certificate;
  329. }
  330. if (isset($object->counter)) {
  331. $reg->counter = $object->counter;
  332. }
  333. if (isset($object->keyHandle)) {
  334. $reg->keyHandle = $object->keyHandle;
  335. }
  336. return $reg;
  337. }
  338. /**
  339. * @return array
  340. */
  341. private function get_certs()
  342. {
  343. $files = array();
  344. $dir = $this->attestDir;
  345. if($dir !== null && is_dir($dir) && $handle = opendir($dir)) {
  346. while(false !== ($entry = readdir($handle))) {
  347. if(is_file("$dir/$entry")) {
  348. $files[] = "$dir/$entry";
  349. }
  350. }
  351. closedir($handle);
  352. } elseif (is_file("$dir")) {
  353. $files[] = "$dir";
  354. }
  355. return $files;
  356. }
  357. /**
  358. * @param string $data
  359. * @return string
  360. */
  361. private function base64u_encode($data)
  362. {
  363. return trim(strtr(base64_encode($data), '+/', '-_'), '=');
  364. }
  365. /**
  366. * @param string $data
  367. * @return string
  368. */
  369. private function base64u_decode($data)
  370. {
  371. return base64_decode(strtr($data, '-_', '+/'));
  372. }
  373. /**
  374. * @param string $key
  375. * @return null|string
  376. */
  377. private function pubkey_to_pem($key)
  378. {
  379. if(strlen($key) !== PUBKEY_LEN || $key[0] !== "\x04") {
  380. return null;
  381. }
  382. /*
  383. * Convert the public key to binary DER format first
  384. * Using the ECC SubjectPublicKeyInfo OIDs from RFC 5480
  385. *
  386. * SEQUENCE(2 elem) 30 59
  387. * SEQUENCE(2 elem) 30 13
  388. * OID1.2.840.10045.2.1 (id-ecPublicKey) 06 07 2a 86 48 ce 3d 02 01
  389. * OID1.2.840.10045.3.1.7 (secp256r1) 06 08 2a 86 48 ce 3d 03 01 07
  390. * BIT STRING(520 bit) 03 42 ..key..
  391. */
  392. $der = "\x30\x59\x30\x13\x06\x07\x2a\x86\x48\xce\x3d\x02\x01";
  393. $der .= "\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x07\x03\x42";
  394. $der .= "\0".$key;
  395. $pem = "-----BEGIN PUBLIC KEY-----\r\n";
  396. $pem .= chunk_split(base64_encode($der), 64);
  397. $pem .= "-----END PUBLIC KEY-----";
  398. return $pem;
  399. }
  400. /**
  401. * @return string
  402. * @throws Error
  403. */
  404. private function createChallenge()
  405. {
  406. $challenge = random_bytes(32);
  407. $challenge = $this->base64u_encode( $challenge );
  408. return $challenge;
  409. }
  410. /**
  411. * Fixes a certificate where the signature contains unused bits.
  412. *
  413. * @param string $cert
  414. * @return mixed
  415. */
  416. private function fixSignatureUnusedBits($cert)
  417. {
  418. if(in_array(hash('sha256', $cert), $this->FIXCERTS, true)) {
  419. $cert[strlen($cert) - 257] = "\0";
  420. }
  421. return $cert;
  422. }
  423. }
  424. /**
  425. * Class for building a registration request
  426. *
  427. * @package u2flib_server
  428. */
  429. class RegisterRequest
  430. {
  431. /** @var string Protocol version */
  432. public $version = U2F_VERSION;
  433. /** @var string Registration challenge */
  434. public $challenge;
  435. /** @var string Application id */
  436. public $appId;
  437. /**
  438. * @param string $challenge
  439. * @param string $appId
  440. * @internal
  441. */
  442. public function __construct($challenge, $appId)
  443. {
  444. $this->challenge = $challenge;
  445. $this->appId = $appId;
  446. }
  447. }
  448. /**
  449. * Class for building up an authentication request
  450. *
  451. * @package u2flib_server
  452. */
  453. class SignRequest
  454. {
  455. /** @var string Protocol version */
  456. public $version = U2F_VERSION;
  457. /** @var string Authentication challenge */
  458. public $challenge = '';
  459. /** @var string Key handle of a registered authenticator */
  460. public $keyHandle = '';
  461. /** @var string Application id */
  462. public $appId = '';
  463. }
  464. /**
  465. * Class returned for successful registrations
  466. *
  467. * @package u2flib_server
  468. */
  469. class Registration
  470. {
  471. /** @var string The key handle of the registered authenticator */
  472. public $keyHandle = '';
  473. /** @var string The public key of the registered authenticator */
  474. public $publicKey = '';
  475. /** @var string The attestation certificate of the registered authenticator */
  476. public $certificate = '';
  477. /** @var int The counter associated with this registration */
  478. public $counter = -1;
  479. }
  480. /**
  481. * Error class, returned on errors
  482. *
  483. * @package u2flib_server
  484. */
  485. class Error extends \Exception
  486. {
  487. /**
  488. * Override constructor and make message and code mandatory
  489. * @param string $message
  490. * @param int $code
  491. * @param \Exception|null $previous
  492. */
  493. public function __construct($message, $code, \Exception $previous = null) {
  494. parent::__construct($message, $code, $previous);
  495. }
  496. }