1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29:
30:
31: namespace u2flib_server;
32:
33:
34: const U2F_VERSION = "U2F_V2";
35:
36: 37:
38: const ERR_NO_MATCHING_REQUEST = 1;
39:
40: const ERR_NO_MATCHING_REGISTRATION = 2;
41: 42:
43: const ERR_AUTHENTICATION_FAILURE = 3;
44: 45:
46: const ERR_UNMATCHED_CHALLENGE = 4;
47: 48:
49: const ERR_ATTESTATION_SIGNATURE = 5;
50:
51: const ERR_ATTESTATION_VERIFICATION = 6;
52:
53: const ERR_BAD_RANDOM = 7;
54:
55: const ERR_COUNTER_TOO_LOW = 8;
56:
57: const ERR_PUBKEY_DECODE = 9;
58:
59:
60: const ERR_BAD_UA_RETURNING = 10;
61:
62:
63: const PUBKEY_LEN = 65;
64:
65: class U2F {
66: private $appId;
67: private $attestDir;
68:
69:
70: private static $FIXCERTS = array(
71: '349bca1031f8c82c4ceca38b9cebf1a69df9fb3b94eed99eb3fb9aa3822d26e8',
72: 'dd574527df608e47ae45fbba75a2afdd5c20fd94a02419381813cd55a2a3398f',
73: '1d8764f0f7cd1352df6150045c8f638e517270e8b5dda1c63ade9c2280240cae',
74: 'd0edc9a91a1677435a953390865d208c55b3183c6759c9b5a7ff494c322558eb',
75: '6073c436dcd064a48127ddbf6032ac1a66fd59a0c24434f070d4e564c124c897',
76: 'ca993121846c464d666096d35f13bf44c1b05af205f9b4a1e00cf6cc10c5e511');
77:
78: 79: 80: 81:
82: public function __construct($appId, $attestDir = null) {
83: $this->appId = $appId;
84: $this->attestDir = $attestDir;
85: }
86:
87: 88: 89: 90: 91: 92: 93: 94: 95: 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: 110: 111: 112: 113: 114: 115: 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:
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:
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: 197: 198: 199: 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: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 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:
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: 336: 337: 338: 339: 340: 341: 342: 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: 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:
378: class RegisterRequest {
379:
380: public $version = U2F_VERSION;
381:
382: public $challenge;
383:
384: public $appId;
385:
386:
387: public function __construct($challenge, $appId) {
388: $this->challenge = $challenge;
389: $this->appId = $appId;
390: }
391: }
392:
393:
394: class SignRequest {
395:
396: public $version = U2F_VERSION;
397:
398: public $challenge;
399:
400: public $keyHandle;
401:
402: public $appId;
403: }
404:
405:
406: class Registration {
407:
408: public $keyHandle;
409:
410: public $publicKey;
411:
412: public $certificate;
413:
414: public $counter = 0;
415: }
416:
417:
418: class Error extends \Exception {
419:
420: public function __construct($message, $code, Exception $previous = null) {
421: parent::__construct($message, $code, $previous);
422: }
423: }
424: