Oppaitime'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.js 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. // Modified U2F client API by Google (https://demo.yubico.com/js/u2f-api.js)
  2. // Copyright 2014-2015 Google Inc. All rights reserved.
  3. //
  4. // Use of this source code is governed by a BSD-style
  5. // license that can be found in the LICENSE file or at
  6. // https://developers.google.com/open-source/licenses/bsd
  7. 'use strict';
  8. if (!u2f) {
  9. // Namespace for the U2F api.
  10. var u2f = u2f || {};
  11. // FIDO U2F Javascript API Version
  12. var js_api_version;
  13. // The U2F extension id
  14. u2f.EXTENSION_ID = 'kmendfapggjehodndflmmgagdbamhnfd';
  15. // Message types for messsages to/from the extension
  16. u2f.MessageTypes = {
  17. 'U2F_REGISTER_REQUEST': 'u2f_register_request',
  18. 'U2F_REGISTER_RESPONSE': 'u2f_register_response',
  19. 'U2F_SIGN_REQUEST': 'u2f_sign_request',
  20. 'U2F_SIGN_RESPONSE': 'u2f_sign_response',
  21. 'U2F_GET_API_VERSION_REQUEST': 'u2f_get_api_version_request',
  22. 'U2F_GET_API_VERSION_RESPONSE': 'u2f_get_api_version_response'
  23. };
  24. // A message for registration requests
  25. u2f.U2fRequest;
  26. // A message for registration responses
  27. u2f.U2fResponse;
  28. // An error object for responses
  29. u2f.Error;
  30. // Data object for a single sign request.
  31. u2f.Transport;
  32. // Data object for a single sign request.
  33. u2f.Transports;
  34. // Data object for a single sign request.
  35. u2f.SignRequest;
  36. // Data object for a sign response.
  37. u2f.SignResponse;
  38. // Data object for a registration request.
  39. u2f.RegisterRequest;
  40. // Data object for a registration response.
  41. u2f.RegisterResponse;
  42. // Data object for a registered key.
  43. u2f.RegisteredKey;
  44. // Data object for a get API register response.
  45. u2f.GetJsApiVersionResponse;
  46. //Low level MessagePort API support
  47. // Sets up a MessagePort to the U2F extension using the
  48. u2f.getMessagePort = function(callback) {
  49. if (typeof chrome != 'undefined' && chrome.runtime) {
  50. // The actual message here does not matter, but we need to get a reply
  51. // for the callback to run. Thus, send an empty signature request
  52. // in order to get a failure response.
  53. var msg = {
  54. type: u2f.MessageTypes.U2F_SIGN_REQUEST,
  55. signRequests: []
  56. };
  57. chrome.runtime.sendMessage(u2f.EXTENSION_ID, msg, function() {
  58. if (!chrome.runtime.lastError) {
  59. // We are on a whitelisted origin and can talk directly
  60. // with the extension.
  61. u2f.getChromeRuntimePort_(callback);
  62. } else {
  63. // chrome.runtime was available, but we couldn't message
  64. // the extension directly, use iframe
  65. u2f.getIframePort_(callback);
  66. }
  67. });
  68. } else if (u2f.isAndroidChrome_()) {
  69. u2f.getAuthenticatorPort_(callback);
  70. } else if (u2f.isIosChrome_()) {
  71. u2f.getIosPort_(callback);
  72. } else {
  73. // chrome.runtime was not available at all, which is normal
  74. // when this origin doesn't have access to any extensions.
  75. u2f.getIframePort_(callback);
  76. }
  77. };
  78. // Detect chrome running on android based on the browser's useragent.
  79. u2f.isAndroidChrome_ = function() {
  80. var userAgent = navigator.userAgent;
  81. return userAgent.indexOf('Chrome') != -1 &&
  82. userAgent.indexOf('Android') != -1;
  83. };
  84. // Detect chrome running on iOS based on the browser's platform.
  85. u2f.isIosChrome_ = function() {
  86. return ["iPhone", "iPad", "iPod"].indexOf(navigator.platform) > -1;
  87. };
  88. // Connects directly to the extension via chrome.runtime.connect.
  89. u2f.getChromeRuntimePort_ = function(callback) {
  90. var port = chrome.runtime.connect(u2f.EXTENSION_ID,
  91. {'includeTlsChannelId': true});
  92. setTimeout(function() {
  93. callback(new u2f.WrappedChromeRuntimePort_(port));
  94. }, 0);
  95. };
  96. // Return a 'port' abstraction to the Authenticator app.
  97. u2f.getAuthenticatorPort_ = function(callback) {
  98. setTimeout(function() {
  99. callback(new u2f.WrappedAuthenticatorPort_());
  100. }, 0);
  101. };
  102. // Return a 'port' abstraction to the iOS client app.
  103. u2f.getIosPort_ = function(callback) {
  104. setTimeout(function() {
  105. callback(new u2f.WrappedIosPort_());
  106. }, 0);
  107. };
  108. // A wrapper for chrome.runtime.Port that is compatible with MessagePort.
  109. u2f.WrappedChromeRuntimePort_ = function(port) {
  110. this.port_ = port;
  111. };
  112. // Format and return a sign request compliant with the JS API version supported by the extension.
  113. u2f.formatSignRequest_ =
  114. function(appId, challenge, registeredKeys, timeoutSeconds, reqId) {
  115. if (js_api_version === undefined || js_api_version < 1.1) {
  116. // Adapt request to the 1.0 JS API
  117. var signRequests = [];
  118. for (var i = 0; i < registeredKeys.length; i++) {
  119. signRequests[i] = {
  120. version: registeredKeys[i].version,
  121. challenge: challenge,
  122. keyHandle: registeredKeys[i].keyHandle,
  123. appId: appId
  124. };
  125. }
  126. return {
  127. type: u2f.MessageTypes.U2F_SIGN_REQUEST,
  128. signRequests: signRequests,
  129. timeoutSeconds: timeoutSeconds,
  130. requestId: reqId
  131. };
  132. }
  133. // JS 1.1 API
  134. return {
  135. type: u2f.MessageTypes.U2F_SIGN_REQUEST,
  136. appId: appId,
  137. challenge: challenge,
  138. registeredKeys: registeredKeys,
  139. timeoutSeconds: timeoutSeconds,
  140. requestId: reqId
  141. };
  142. };
  143. // Format and return a register request compliant with the JS API version supported by the extension.
  144. u2f.formatRegisterRequest_ =
  145. function(appId, registeredKeys, registerRequests, timeoutSeconds, reqId) {
  146. if (js_api_version === undefined || js_api_version < 1.1) {
  147. // Adapt request to the 1.0 JS API
  148. for (var i = 0; i < registerRequests.length; i++) {
  149. registerRequests[i].appId = appId;
  150. }
  151. var signRequests = [];
  152. for (var i = 0; i < registeredKeys.length; i++) {
  153. signRequests[i] = {
  154. version: registeredKeys[i].version,
  155. challenge: registerRequests[0],
  156. keyHandle: registeredKeys[i].keyHandle,
  157. appId: appId
  158. };
  159. }
  160. return {
  161. type: u2f.MessageTypes.U2F_REGISTER_REQUEST,
  162. signRequests: signRequests,
  163. registerRequests: registerRequests,
  164. timeoutSeconds: timeoutSeconds,
  165. requestId: reqId
  166. };
  167. }
  168. // JS 1.1 API
  169. return {
  170. type: u2f.MessageTypes.U2F_REGISTER_REQUEST,
  171. appId: appId,
  172. registerRequests: registerRequests,
  173. registeredKeys: registeredKeys,
  174. timeoutSeconds: timeoutSeconds,
  175. requestId: reqId
  176. };
  177. };
  178. // Posts a message on the underlying channel.
  179. u2f.WrappedChromeRuntimePort_.prototype.postMessage = function(message) {
  180. this.port_.postMessage(message);
  181. };
  182. // Emulates the HTML 5 addEventListener interface. Works only for the onmessage event, which is hooked up to the chrome.runtime.Port.onMessage.
  183. u2f.WrappedChromeRuntimePort_.prototype.addEventListener =
  184. function(eventName, handler) {
  185. var name = eventName.toLowerCase();
  186. if (name == 'message' || name == 'onmessage') {
  187. this.port_.onMessage.addListener(function(message) {
  188. // Emulate a minimal MessageEvent object
  189. handler({'data': message});
  190. });
  191. } else {
  192. console.error('WrappedChromeRuntimePort only supports onMessage');
  193. }
  194. };
  195. // Wrap the Authenticator app with a MessagePort interface.
  196. u2f.WrappedAuthenticatorPort_ = function() {
  197. this.requestId_ = -1;
  198. this.requestObject_ = null;
  199. }
  200. // Launch the Authenticator intent.
  201. u2f.WrappedAuthenticatorPort_.prototype.postMessage = function(message) {
  202. var intentUrl =
  203. u2f.WrappedAuthenticatorPort_.INTENT_URL_BASE_ +
  204. ';S.request=' + encodeURIComponent(JSON.stringify(message)) +
  205. ';end';
  206. document.location = intentUrl;
  207. };
  208. // Tells what type of port this is.
  209. u2f.WrappedAuthenticatorPort_.prototype.getPortType = function() {
  210. return "WrappedAuthenticatorPort_";
  211. };
  212. // Emulates the HTML 5 addEventListener interface.
  213. u2f.WrappedAuthenticatorPort_.prototype.addEventListener = function(eventName, handler) {
  214. var name = eventName.toLowerCase();
  215. if (name == 'message') {
  216. var self = this;
  217. // Register a callback to that executes when chrome injects the response.
  218. window.addEventListener('message', self.onRequestUpdate_.bind(self, handler), false);
  219. } else {
  220. console.error('WrappedAuthenticatorPort only supports message');
  221. }
  222. };
  223. // Callback invoked when a response is received from the Authenticator.
  224. u2f.WrappedAuthenticatorPort_.prototype.onRequestUpdate_ =
  225. function(callback, message) {
  226. var messageObject = JSON.parse(message.data);
  227. var intentUrl = messageObject['intentURL'];
  228. var errorCode = messageObject['errorCode'];
  229. var responseObject = null;
  230. if (messageObject.hasOwnProperty('data')) {
  231. responseObject = /** @type {Object} */ (
  232. JSON.parse(messageObject['data']));
  233. }
  234. callback({'data': responseObject});
  235. };
  236. // Base URL for intents to Authenticator.
  237. u2f.WrappedAuthenticatorPort_.INTENT_URL_BASE_ =
  238. 'intent:#Intent;action=com.google.android.apps.authenticator.AUTHENTICATE';
  239. // Wrap the iOS client app with a MessagePort interface.
  240. u2f.WrappedIosPort_ = function() {};
  241. // Launch the iOS client app request
  242. u2f.WrappedIosPort_.prototype.postMessage = function(message) {
  243. var str = JSON.stringify(message);
  244. var url = "u2f://auth?" + encodeURI(str);
  245. location.replace(url);
  246. };
  247. // Tells what type of port this is.
  248. u2f.WrappedIosPort_.prototype.getPortType = function() {
  249. return "WrappedIosPort_";
  250. };
  251. // Emulates the HTML 5 addEventListener interface.
  252. u2f.WrappedIosPort_.prototype.addEventListener = function(eventName, handler) {
  253. var name = eventName.toLowerCase();
  254. if (name !== 'message') {
  255. console.error('WrappedIosPort only supports message');
  256. }
  257. };
  258. // Sets up an embedded trampoline iframe, sourced from the extension.
  259. u2f.getIframePort_ = function(callback) {
  260. // Create the iframe
  261. var iframeOrigin = 'chrome-extension://' + u2f.EXTENSION_ID;
  262. var iframe = document.createElement('iframe');
  263. iframe.src = iframeOrigin + '/u2f-comms.html';
  264. iframe.setAttribute('style', 'display:none');
  265. document.body.appendChild(iframe);
  266. var channel = new MessageChannel();
  267. var ready = function(message) {
  268. if (message.data == 'ready') {
  269. channel.port1.removeEventListener('message', ready);
  270. callback(channel.port1);
  271. } else {
  272. console.error('First event on iframe port was not "ready"');
  273. }
  274. };
  275. channel.port1.addEventListener('message', ready);
  276. channel.port1.start();
  277. iframe.addEventListener('load', function() {
  278. // Deliver the port to the iframe and initialize
  279. iframe.contentWindow.postMessage('init', iframeOrigin, [channel.port2]);
  280. });
  281. };
  282. //High-level JS API
  283. // Default extension response timeout in seconds.
  284. u2f.EXTENSION_TIMEOUT_SEC = 30;
  285. // A singleton instance for a MessagePort to the extension.
  286. u2f.port_ = null;
  287. // Callbacks waiting for a port
  288. u2f.waitingForPort_ = [];
  289. // A counter for requestIds.
  290. u2f.reqCounter_ = 0;
  291. // A map from requestIds to client callbacks
  292. u2f.callbackMap_ = {};
  293. // Creates or retrieves the MessagePort singleton to use.
  294. u2f.getPortSingleton_ = function(callback) {
  295. if (u2f.port_) {
  296. callback(u2f.port_);
  297. } else {
  298. if (u2f.waitingForPort_.length == 0) {
  299. u2f.getMessagePort(function(port) {
  300. u2f.port_ = port;
  301. u2f.port_.addEventListener('message', (u2f.responseHandler_));
  302. // Careful, here be async callbacks. Maybe.
  303. while (u2f.waitingForPort_.length)
  304. u2f.waitingForPort_.shift()(u2f.port_);
  305. });
  306. }
  307. u2f.waitingForPort_.push(callback);
  308. }
  309. };
  310. // Handles response messages from the extension.
  311. u2f.responseHandler_ = function(message) {
  312. var response = message.data;
  313. var reqId = response['requestId'];
  314. if (!reqId || !u2f.callbackMap_[reqId]) {
  315. console.error('Unknown or missing requestId in response.');
  316. return;
  317. }
  318. var cb = u2f.callbackMap_[reqId];
  319. delete u2f.callbackMap_[reqId];
  320. cb(response['responseData']);
  321. };
  322. // Dispatches an array of sign requests to available U2F tokens.
  323. // If the JS API version supported by the extension is unknown, it first sends a
  324. // message to the extension to find out the supported API version and then it sends
  325. // the sign request.
  326. u2f.sign = function(appId, challenge, registeredKeys, callback, opt_timeoutSeconds) {
  327. if (js_api_version === undefined) {
  328. // Send a message to get the extension to JS API version, then send the actual sign request.
  329. u2f.getApiVersion(
  330. function (response) {
  331. js_api_version = response['js_api_version'] === undefined ? 0 : response['js_api_version'];
  332. console.log("Extension JS API Version: ", js_api_version);
  333. u2f.sendSignRequest(appId, challenge, registeredKeys, callback, opt_timeoutSeconds);
  334. });
  335. } else {
  336. // We know the JS API version. Send the actual sign request in the supported API version.
  337. u2f.sendSignRequest(appId, challenge, registeredKeys, callback, opt_timeoutSeconds);
  338. }
  339. };
  340. // Dispatches an array of sign requests to available U2F tokens.
  341. u2f.sendSignRequest = function(appId, challenge, registeredKeys, callback, opt_timeoutSeconds) {
  342. u2f.getPortSingleton_(function(port) {
  343. var reqId = ++u2f.reqCounter_;
  344. u2f.callbackMap_[reqId] = callback;
  345. var timeoutSeconds = (typeof opt_timeoutSeconds !== 'undefined' ?
  346. opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC);
  347. var req = u2f.formatSignRequest_(appId, challenge, registeredKeys, timeoutSeconds, reqId);
  348. port.postMessage(req);
  349. });
  350. };
  351. // Dispatches register requests to available U2F tokens. An array of sign
  352. // requests identifies already registered tokens.
  353. // If the JS API version supported by the extension is unknown, it first sends a
  354. // message to the extension to find out the supported API version and then it sends
  355. // the register request.
  356. u2f.register = function(appId, registerRequests, registeredKeys, callback, opt_timeoutSeconds) {
  357. if (js_api_version === undefined) {
  358. // Send a message to get the extension to JS API version, then send the actual register request.
  359. u2f.getApiVersion(
  360. function (response) {
  361. js_api_version = response['js_api_version'] === undefined ? 0: response['js_api_version'];
  362. console.log("Extension JS API Version: ", js_api_version);
  363. u2f.sendRegisterRequest(appId, registerRequests, registeredKeys,
  364. callback, opt_timeoutSeconds);
  365. });
  366. } else {
  367. // We know the JS API version. Send the actual register request in the supported API version.
  368. u2f.sendRegisterRequest(appId, registerRequests, registeredKeys,
  369. callback, opt_timeoutSeconds);
  370. }
  371. };
  372. // Dispatches register requests to available U2F tokens. An array of sign
  373. // requests identifies already registered tokens.
  374. u2f.sendRegisterRequest = function(appId, registerRequests, registeredKeys, callback, opt_timeoutSeconds) {
  375. u2f.getPortSingleton_(function(port) {
  376. var reqId = ++u2f.reqCounter_;
  377. u2f.callbackMap_[reqId] = callback;
  378. var timeoutSeconds = (typeof opt_timeoutSeconds !== 'undefined' ?
  379. opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC);
  380. var req = u2f.formatRegisterRequest_(
  381. appId, registeredKeys, registerRequests, timeoutSeconds, reqId);
  382. port.postMessage(req);
  383. });
  384. };
  385. // Dispatches a message to the extension to find out the supported JS API version.
  386. // If the user is on a mobile phone and is thus using Google Authenticator instead
  387. // of the Chrome extension, don't send the request and simply return 0.
  388. u2f.getApiVersion = function(callback, opt_timeoutSeconds) {
  389. u2f.getPortSingleton_(function(port) {
  390. // If we are using Android Google Authenticator or iOS client app,
  391. // do not fire an intent to ask which JS API version to use.
  392. if (port.getPortType) {
  393. var apiVersion;
  394. switch (port.getPortType()) {
  395. case 'WrappedIosPort_':
  396. case 'WrappedAuthenticatorPort_':
  397. apiVersion = 1.1;
  398. break;
  399. default:
  400. apiVersion = 0;
  401. break;
  402. }
  403. callback({ 'js_api_version': apiVersion });
  404. return;
  405. }
  406. var reqId = ++u2f.reqCounter_;
  407. u2f.callbackMap_[reqId] = callback;
  408. var req = {
  409. type: u2f.MessageTypes.U2F_GET_API_VERSION_REQUEST,
  410. timeoutSeconds: (typeof opt_timeoutSeconds !== 'undefined' ?
  411. opt_timeoutSeconds : u2f.EXTENSION_TIMEOUT_SEC),
  412. requestId: reqId
  413. };
  414. port.postMessage(req);
  415. });
  416. };
  417. }
  418. // Response status codes
  419. u2f.ErrorCodes = {
  420. 'OK': 0,
  421. 'OTHER_ERROR': 1,
  422. 'BAD_REQUEST': 2,
  423. 'CONFIGURATION_UNSUPPORTED': 3,
  424. 'DEVICE_INELIGIBLE': 4,
  425. 'TIMEOUT': 5
  426. };
  427. // Everything below is Gazelle-specific and not part of the u2f API
  428. $(function() {
  429. if (document.querySelector('#u2f_register_form') && document.querySelector('[name="u2f-request"]')) {
  430. var req = JSON.parse($('[name="u2f-request"]').raw().value);
  431. var sigs = JSON.parse($('[name="u2f-sigs"]').raw().value);
  432. if (req) {
  433. u2f.register(req.appId, [req], sigs, function(data) {
  434. if (data.errorCode) {
  435. console.log('U2F Register Error: ' + Object.keys(u2f.ErrorCodes).find(k => u2f.ErrorCodes[k] == data.errorCode));
  436. return;
  437. }
  438. $('[name="u2f-response"]').raw().value = JSON.stringify(data);
  439. $('[value="U2F-E"]').raw().name = 'type'
  440. $('#u2f_register_form').submit();
  441. }, 3600)
  442. }
  443. }
  444. if (document.querySelector('#u2f_sign_form') && document.querySelector('[name="u2f-request"]')) {
  445. var req = JSON.parse($('[name="u2f-request"]').raw().value)[0];
  446. if (req) {
  447. u2f.sign(req.appId, req.challenge, [{version:req.version, keyHandle:req.keyHandle}], function(data) {
  448. if (data.errorCode) {
  449. console.log('U2F Sign Error: ' + Object.keys(u2f.ErrorCodes).find(k => u2f.ErrorCodes[k] == data.errorCode));
  450. return;
  451. }
  452. $('[name="u2f-response"]').raw().value = JSON.stringify(data);
  453. $('#u2f_sign_form').submit();
  454. }, 3600)
  455. }
  456. }
  457. })