U2F.php 16 KB

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