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

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