├── .gitignore ├── banner.png ├── tsconfig.json ├── src ├── u2f_crate │ ├── LICENSE │ ├── mod.rs │ ├── u2ferror.rs │ ├── messages.rs │ ├── authorization.rs │ ├── util.rs │ ├── register.rs │ ├── crypto.rs │ └── protocol.rs ├── error.rs ├── lib.rs ├── u2f.rs └── auth.rs ├── rollup.config.mjs ├── dist-js ├── index.d.ts ├── index.mjs.map ├── index.mjs ├── index.min.js └── index.min.js.map ├── Cargo.toml ├── package.json ├── LICENSE.spdx ├── LICENSE_MIT ├── guest-js └── index.ts ├── README.md └── LICENSE_APACHE-2.0 /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tauri-apps/tauri-plugin-authenticator/HEAD/banner.png -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.base.json", 3 | "include": ["guest-js/*.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /src/u2f_crate/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 2 | 3 | Licensed under either of 4 | 5 | * Apache License, Version 2.0, (http://www.apache.org/licenses/LICENSE-2.0) 6 | * MIT license (http://opensource.org/licenses/MIT) 7 | 8 | at your option. -------------------------------------------------------------------------------- /src/u2f_crate/mod.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Flavio Oliveira 2 | // SPDX-License-Identifier: Apache-2.0 3 | // SPDX-License-Identifier: MIT 4 | 5 | mod util; 6 | 7 | pub mod authorization; 8 | mod crypto; 9 | pub mod messages; 10 | pub mod protocol; 11 | pub mod register; 12 | pub mod u2ferror; 13 | -------------------------------------------------------------------------------- /rollup.config.mjs: -------------------------------------------------------------------------------- 1 | import { readFileSync } from "fs"; 2 | 3 | import { createConfig } from "../../shared/rollup.config.mjs"; 4 | 5 | export default createConfig({ 6 | input: "guest-js/index.ts", 7 | pkg: JSON.parse( 8 | readFileSync(new URL("./package.json", import.meta.url), "utf8"), 9 | ), 10 | external: [/^@tauri-apps\/api/], 11 | }); 12 | -------------------------------------------------------------------------------- /dist-js/index.d.ts: -------------------------------------------------------------------------------- 1 | export declare class Authenticator { 2 | init(): Promise; 3 | register(challenge: string, application: string): Promise; 4 | verifyRegistration(challenge: string, application: string, registerData: string, clientData: string): Promise; 5 | sign(challenge: string, application: string, keyHandle: string): Promise; 6 | verifySignature(challenge: string, application: string, signData: string, clientData: string, keyHandle: string, pubkey: string): Promise; 7 | } 8 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use serde::{Serialize, Serializer}; 2 | 3 | #[derive(Debug, thiserror::Error)] 4 | pub enum Error { 5 | #[error(transparent)] 6 | Base64Decode(#[from] base64::DecodeError), 7 | #[error(transparent)] 8 | JSON(#[from] serde_json::Error), 9 | #[error(transparent)] 10 | U2F(#[from] crate::u2f_crate::u2ferror::U2fError), 11 | #[error(transparent)] 12 | Auth(#[from] authenticator::errors::AuthenticatorError), 13 | } 14 | 15 | impl Serialize for Error { 16 | fn serialize(&self, serializer: S) -> std::result::Result 17 | where 18 | S: Serializer, 19 | { 20 | serializer.serialize_str(self.to_string().as_ref()) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tauri-plugin-authenticator" 3 | version = "0.0.0" 4 | description = "Use hardware security-keys in your Tauri App." 5 | authors = { workspace = true } 6 | license = { workspace = true } 7 | edition = { workspace = true } 8 | rust-version = { workspace = true } 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | [dependencies] 13 | serde = { workspace = true } 14 | serde_json = { workspace = true } 15 | tauri = { workspace = true } 16 | log = { workspace = true } 17 | thiserror = { workspace = true } 18 | authenticator = "0.3.1" 19 | once_cell = "1" 20 | sha2 = "0.10" 21 | base64 = "0.22" 22 | chrono = "0.4" 23 | bytes = "1" 24 | byteorder = "1" 25 | openssl = "0.10" 26 | 27 | [dev-dependencies] 28 | rand = "0.8" 29 | rusty-fork = "0.3" 30 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tauri-plugin-authenticator-api", 3 | "version": "0.0.0", 4 | "description": "Use hardware security-keys in your Tauri App.", 5 | "license": "MIT or APACHE-2.0", 6 | "authors": [ 7 | "Tauri Programme within The Commons Conservancy" 8 | ], 9 | "type": "module", 10 | "browser": "dist-js/index.min.js", 11 | "module": "dist-js/index.mjs", 12 | "types": "dist-js/index.d.ts", 13 | "exports": { 14 | "import": "./dist-js/index.mjs", 15 | "types": "./dist-js/index.d.ts", 16 | "browser": "./dist-js/index.min.js" 17 | }, 18 | "scripts": { 19 | "build": "rollup -c" 20 | }, 21 | "files": [ 22 | "dist-js", 23 | "!dist-js/**/*.map", 24 | "README.md", 25 | "LICENSE" 26 | ], 27 | "devDependencies": { 28 | "tslib": "2.7.0" 29 | }, 30 | "dependencies": { 31 | "@tauri-apps/api": "1.6.0" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /dist-js/index.mjs.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"index.mjs","sources":["../guest-js/index.ts"],"sourcesContent":[null],"names":[],"mappings":";;MAEa,aAAa,CAAA;AACxB,IAAA,MAAM,IAAI,GAAA;AACR,QAAA,OAAO,MAAM,MAAM,CAAC,gCAAgC,CAAC,CAAC;KACvD;AAED,IAAA,MAAM,QAAQ,CAAC,SAAiB,EAAE,WAAmB,EAAA;AACnD,QAAA,OAAO,MAAM,MAAM,CAAC,+BAA+B,EAAE;AACnD,YAAA,OAAO,EAAE,KAAK;YACd,SAAS;YACT,WAAW;AACZ,SAAA,CAAC,CAAC;KACJ;IAED,MAAM,kBAAkB,CACtB,SAAiB,EACjB,WAAmB,EACnB,YAAoB,EACpB,UAAkB,EAAA;AAElB,QAAA,OAAO,MAAM,MAAM,CAAC,0CAA0C,EAAE;YAC9D,SAAS;YACT,WAAW;YACX,YAAY;YACZ,UAAU;AACX,SAAA,CAAC,CAAC;KACJ;AAED,IAAA,MAAM,IAAI,CACR,SAAiB,EACjB,WAAmB,EACnB,SAAiB,EAAA;AAEjB,QAAA,OAAO,MAAM,MAAM,CAAC,2BAA2B,EAAE;AAC/C,YAAA,OAAO,EAAE,KAAK;YACd,SAAS;YACT,WAAW;YACX,SAAS;AACV,SAAA,CAAC,CAAC;KACJ;AAED,IAAA,MAAM,eAAe,CACnB,SAAiB,EACjB,WAAmB,EACnB,QAAgB,EAChB,UAAkB,EAClB,SAAiB,EACjB,MAAc,EAAA;AAEd,QAAA,OAAO,MAAM,MAAM,CAAC,uCAAuC,EAAE;YAC3D,SAAS;YACT,WAAW;YACX,QAAQ;YACR,UAAU;YACV,SAAS;YACT,MAAM;AACP,SAAA,CAAC,CAAC;KACJ;AACF;;;;"} -------------------------------------------------------------------------------- /LICENSE.spdx: -------------------------------------------------------------------------------- 1 | SPDXVersion: SPDX-2.1 2 | DataLicense: CC0-1.0 3 | PackageName: tauri 4 | DataFormat: SPDXRef-1 5 | PackageSupplier: Organization: The Tauri Programme in the Commons Conservancy 6 | PackageHomePage: https://tauri.app 7 | PackageLicenseDeclared: Apache-2.0 8 | PackageLicenseDeclared: MIT 9 | PackageCopyrightText: 2019-2022, The Tauri Programme in the Commons Conservancy 10 | PackageSummary: Tauri is a rust project that enables developers to make secure 11 | and small desktop applications using a web frontend. 12 | 13 | PackageComment: The package includes the following libraries; see 14 | Relationship information. 15 | 16 | Created: 2019-05-20T09:00:00Z 17 | PackageDownloadLocation: git://github.com/tauri-apps/tauri 18 | PackageDownloadLocation: git+https://github.com/tauri-apps/tauri.git 19 | PackageDownloadLocation: git+ssh://github.com/tauri-apps/tauri.git 20 | Creator: Person: Daniel Thompson-Yvetot -------------------------------------------------------------------------------- /LICENSE_MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 - Present Tauri Apps Contributors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /src/u2f_crate/u2ferror.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Flavio Oliveira 2 | // SPDX-License-Identifier: Apache-2.0 3 | // SPDX-License-Identifier: MIT 4 | 5 | use thiserror::Error; 6 | 7 | #[derive(Debug, Error)] 8 | pub enum U2fError { 9 | #[error("ASM1 Decoder error")] 10 | Asm1DecoderError, 11 | #[error("Not able to verify signature")] 12 | BadSignature, 13 | #[error("Not able to generate random bytes")] 14 | RandomSecureBytesError, 15 | #[error("Invalid Reserved Byte")] 16 | InvalidReservedByte, 17 | #[error("Challenge Expired")] 18 | ChallengeExpired, 19 | #[error("Wrong Key Handler")] 20 | WrongKeyHandler, 21 | #[error("Invalid Client Data")] 22 | InvalidClientData, 23 | #[error("Invalid Signature Data")] 24 | InvalidSignatureData, 25 | #[error("Invalid User Presence Byte")] 26 | InvalidUserPresenceByte, 27 | #[error("Failed to parse certificate")] 28 | BadCertificate, 29 | #[error("Not Trusted Anchor")] 30 | NotTrustedAnchor, 31 | #[error("Counter too low")] 32 | CounterTooLow, 33 | #[error("Invalid public key")] 34 | OpenSSLNoCurveName, 35 | #[error("OpenSSL no curve name")] 36 | InvalidPublicKey, 37 | #[error(transparent)] 38 | OpenSSLError(#[from] openssl::error::ErrorStack), 39 | } 40 | -------------------------------------------------------------------------------- /dist-js/index.mjs: -------------------------------------------------------------------------------- 1 | import { invoke } from '@tauri-apps/api/tauri'; 2 | 3 | class Authenticator { 4 | async init() { 5 | return await invoke("plugin:authenticator|init_auth"); 6 | } 7 | async register(challenge, application) { 8 | return await invoke("plugin:authenticator|register", { 9 | timeout: 10000, 10 | challenge, 11 | application, 12 | }); 13 | } 14 | async verifyRegistration(challenge, application, registerData, clientData) { 15 | return await invoke("plugin:authenticator|verify_registration", { 16 | challenge, 17 | application, 18 | registerData, 19 | clientData, 20 | }); 21 | } 22 | async sign(challenge, application, keyHandle) { 23 | return await invoke("plugin:authenticator|sign", { 24 | timeout: 10000, 25 | challenge, 26 | application, 27 | keyHandle, 28 | }); 29 | } 30 | async verifySignature(challenge, application, signData, clientData, keyHandle, pubkey) { 31 | return await invoke("plugin:authenticator|verify_signature", { 32 | challenge, 33 | application, 34 | signData, 35 | clientData, 36 | keyHandle, 37 | pubkey, 38 | }); 39 | } 40 | } 41 | 42 | export { Authenticator }; 43 | //# sourceMappingURL=index.mjs.map 44 | -------------------------------------------------------------------------------- /guest-js/index.ts: -------------------------------------------------------------------------------- 1 | import { invoke } from "@tauri-apps/api/tauri"; 2 | 3 | export class Authenticator { 4 | async init(): Promise { 5 | return await invoke("plugin:authenticator|init_auth"); 6 | } 7 | 8 | async register(challenge: string, application: string): Promise { 9 | return await invoke("plugin:authenticator|register", { 10 | timeout: 10000, 11 | challenge, 12 | application, 13 | }); 14 | } 15 | 16 | async verifyRegistration( 17 | challenge: string, 18 | application: string, 19 | registerData: string, 20 | clientData: string, 21 | ): Promise { 22 | return await invoke("plugin:authenticator|verify_registration", { 23 | challenge, 24 | application, 25 | registerData, 26 | clientData, 27 | }); 28 | } 29 | 30 | async sign( 31 | challenge: string, 32 | application: string, 33 | keyHandle: string, 34 | ): Promise { 35 | return await invoke("plugin:authenticator|sign", { 36 | timeout: 10000, 37 | challenge, 38 | application, 39 | keyHandle, 40 | }); 41 | } 42 | 43 | async verifySignature( 44 | challenge: string, 45 | application: string, 46 | signData: string, 47 | clientData: string, 48 | keyHandle: string, 49 | pubkey: string, 50 | ): Promise { 51 | return await invoke("plugin:authenticator|verify_signature", { 52 | challenge, 53 | application, 54 | signData, 55 | clientData, 56 | keyHandle, 57 | pubkey, 58 | }); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/u2f_crate/messages.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Flavio Oliveira 2 | // SPDX-License-Identifier: Apache-2.0 3 | // SPDX-License-Identifier: MIT 4 | 5 | // As defined by FIDO U2F Javascript API. 6 | // https://fidoalliance.org/specs/fido-u2f-v1.0-nfc-bt-amendment-20150514/fido-u2f-javascript-api.html#registration 7 | 8 | use serde::{Deserialize, Serialize}; 9 | 10 | #[derive(Serialize)] 11 | #[serde(rename_all = "camelCase")] 12 | pub struct U2fRegisterRequest { 13 | pub app_id: String, 14 | pub register_requests: Vec, 15 | pub registered_keys: Vec, 16 | } 17 | 18 | #[derive(Serialize)] 19 | pub struct RegisterRequest { 20 | pub version: String, 21 | pub challenge: String, 22 | } 23 | 24 | #[derive(Serialize)] 25 | #[serde(rename_all = "camelCase")] 26 | pub struct RegisteredKey { 27 | pub version: String, 28 | pub key_handle: Option, 29 | pub app_id: String, 30 | } 31 | 32 | #[derive(Deserialize)] 33 | #[serde(rename_all = "camelCase")] 34 | pub struct RegisterResponse { 35 | pub registration_data: String, 36 | #[allow(dead_code)] 37 | pub version: String, 38 | pub client_data: String, 39 | } 40 | 41 | #[derive(Serialize)] 42 | #[serde(rename_all = "camelCase")] 43 | pub struct U2fSignRequest { 44 | pub app_id: String, 45 | pub challenge: String, 46 | pub registered_keys: Vec, 47 | } 48 | 49 | #[derive(Clone, Deserialize)] 50 | #[serde(rename_all = "camelCase")] 51 | pub struct SignResponse { 52 | pub key_handle: String, 53 | pub signature_data: String, 54 | pub client_data: String, 55 | } 56 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Tauri Programme within The Commons Conservancy 2 | // SPDX-License-Identifier: Apache-2.0 3 | // SPDX-License-Identifier: MIT 4 | 5 | mod auth; 6 | mod error; 7 | mod u2f; 8 | mod u2f_crate; 9 | 10 | use tauri::{ 11 | plugin::{Builder as PluginBuilder, TauriPlugin}, 12 | Runtime, 13 | }; 14 | 15 | pub use error::Error; 16 | type Result = std::result::Result; 17 | 18 | #[tauri::command] 19 | fn init_auth() { 20 | auth::init_usb(); 21 | } 22 | 23 | #[tauri::command] 24 | fn register(timeout: u64, challenge: String, application: String) -> crate::Result { 25 | auth::register(application, timeout, challenge) 26 | } 27 | 28 | #[tauri::command] 29 | fn verify_registration( 30 | challenge: String, 31 | application: String, 32 | register_data: String, 33 | client_data: String, 34 | ) -> crate::Result { 35 | u2f::verify_registration(application, challenge, register_data, client_data) 36 | } 37 | 38 | #[tauri::command] 39 | fn sign( 40 | timeout: u64, 41 | challenge: String, 42 | application: String, 43 | key_handle: String, 44 | ) -> crate::Result { 45 | auth::sign(application, timeout, challenge, key_handle) 46 | } 47 | 48 | #[tauri::command] 49 | fn verify_signature( 50 | challenge: String, 51 | application: String, 52 | sign_data: String, 53 | client_data: String, 54 | key_handle: String, 55 | pubkey: String, 56 | ) -> crate::Result { 57 | u2f::verify_signature( 58 | application, 59 | challenge, 60 | sign_data, 61 | client_data, 62 | key_handle, 63 | pubkey, 64 | ) 65 | } 66 | 67 | pub fn init() -> TauriPlugin { 68 | PluginBuilder::new("authenticator") 69 | .invoke_handler(tauri::generate_handler![ 70 | init_auth, 71 | register, 72 | verify_registration, 73 | sign, 74 | verify_signature 75 | ]) 76 | .build() 77 | } 78 | -------------------------------------------------------------------------------- /src/u2f_crate/authorization.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Flavio Oliveira 2 | // SPDX-License-Identifier: Apache-2.0 3 | // SPDX-License-Identifier: MIT 4 | 5 | use bytes::{Buf, BufMut}; 6 | use openssl::sha::sha256; 7 | use serde::Serialize; 8 | use std::io::Cursor; 9 | 10 | use crate::u2f_crate::u2ferror::U2fError; 11 | 12 | /// The `Result` type used in this crate. 13 | type Result = ::std::result::Result; 14 | 15 | #[derive(Serialize, Clone)] 16 | #[serde(rename_all = "camelCase")] 17 | pub struct Authorization { 18 | pub counter: u32, 19 | pub user_presence: bool, 20 | } 21 | 22 | pub fn parse_sign_response( 23 | app_id: String, 24 | client_data: Vec, 25 | public_key: Vec, 26 | sign_data: Vec, 27 | ) -> Result { 28 | if sign_data.len() <= 5 { 29 | return Err(U2fError::InvalidSignatureData); 30 | } 31 | 32 | let user_presence_flag = &sign_data[0]; 33 | let counter = &sign_data[1..=4]; 34 | let signature = &sign_data[5..]; 35 | 36 | // Let's build the msg to verify the signature 37 | let app_id_hash = sha256(&app_id.into_bytes()); 38 | let client_data_hash = sha256(&client_data[..]); 39 | 40 | let mut msg = vec![]; 41 | msg.put(app_id_hash.as_ref()); 42 | msg.put_u8(*user_presence_flag); 43 | msg.put(counter); 44 | msg.put(client_data_hash.as_ref()); 45 | 46 | let public_key = super::crypto::NISTP256Key::from_bytes(&public_key)?; 47 | 48 | // The signature is to be verified by the relying party using the public key obtained during registration. 49 | let verified = public_key.verify_signature(signature, msg.as_ref())?; 50 | if !verified { 51 | return Err(U2fError::BadSignature); 52 | } 53 | 54 | let authorization = Authorization { 55 | counter: get_counter(counter), 56 | user_presence: true, 57 | }; 58 | 59 | Ok(authorization) 60 | } 61 | 62 | fn get_counter(counter: &[u8]) -> u32 { 63 | let mut buf = Cursor::new(counter); 64 | buf.get_u32() 65 | } 66 | -------------------------------------------------------------------------------- /src/u2f_crate/util.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Flavio Oliveira 2 | // SPDX-License-Identifier: Apache-2.0 3 | // SPDX-License-Identifier: MIT 4 | 5 | use crate::u2f_crate::u2ferror::U2fError; 6 | use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; 7 | use bytes::Bytes; 8 | use chrono::prelude::*; 9 | use chrono::Duration; 10 | use openssl::rand; 11 | 12 | /// The `Result` type used in this crate. 13 | type Result = ::std::result::Result; 14 | 15 | pub const U2F_V2: &str = "U2F_V2"; 16 | 17 | // Generates a challenge from a secure, random source. 18 | pub fn generate_challenge(size: usize) -> Result> { 19 | let mut bytes: Vec = vec![0; size]; 20 | rand::rand_bytes(&mut bytes).map_err(|_e| U2fError::RandomSecureBytesError)?; 21 | Ok(bytes) 22 | } 23 | 24 | pub fn expiration(timestamp: String) -> Duration { 25 | let now: DateTime = Utc::now(); 26 | 27 | let ts = timestamp.parse::>(); 28 | 29 | now.signed_duration_since(ts.unwrap()) 30 | } 31 | 32 | // Decode initial bytes of buffer as ASN and return the length of the encoded structure. 33 | // http://en.wikipedia.org/wiki/X.690 34 | pub fn asn_length(mem: Bytes) -> Result { 35 | let buffer: &[u8] = &mem[..]; 36 | 37 | if mem.len() < 2 || buffer[0] != 0x30 { 38 | // Type 39 | return Err(U2fError::Asm1DecoderError); 40 | } 41 | 42 | let len = buffer[1]; // Len 43 | if len & 0x80 == 0 { 44 | return Ok((len & 0x7f) as usize); 45 | } 46 | 47 | let numbem_of_bytes = len & 0x7f; 48 | if numbem_of_bytes == 0 { 49 | return Err(U2fError::Asm1DecoderError); 50 | } 51 | 52 | let mut length: usize = 0; 53 | for num in 0..numbem_of_bytes { 54 | length = length * 0x100 + (buffer[(2 + num) as usize] as usize); 55 | } 56 | 57 | length += numbem_of_bytes as usize; 58 | 59 | Ok(length + 2) // Add the 2 initial bytes: type and length. 60 | } 61 | 62 | pub fn get_encoded(data: &[u8]) -> String { 63 | let encoded: String = URL_SAFE_NO_PAD.encode(data); 64 | 65 | encoded.trim_end_matches('=').to_string() 66 | } 67 | -------------------------------------------------------------------------------- /dist-js/index.min.js: -------------------------------------------------------------------------------- 1 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy 2 | // SPDX-License-Identifier: Apache-2.0 3 | // SPDX-License-Identifier: MIT 4 | /** @ignore */ 5 | function uid() { 6 | return window.crypto.getRandomValues(new Uint32Array(1))[0]; 7 | } 8 | /** 9 | * Transforms a callback function to a string identifier that can be passed to the backend. 10 | * The backend uses the identifier to `eval()` the callback. 11 | * 12 | * @return A unique identifier associated with the callback function. 13 | * 14 | * @since 1.0.0 15 | */ 16 | function transformCallback(callback, once = false) { 17 | const identifier = uid(); 18 | const prop = `_${identifier}`; 19 | Object.defineProperty(window, prop, { 20 | value: (result) => { 21 | if (once) { 22 | Reflect.deleteProperty(window, prop); 23 | } 24 | return callback === null || callback === void 0 ? void 0 : callback(result); 25 | }, 26 | writable: false, 27 | configurable: true 28 | }); 29 | return identifier; 30 | } 31 | /** 32 | * Sends a message to the backend. 33 | * @example 34 | * ```typescript 35 | * import { invoke } from '@tauri-apps/api/tauri'; 36 | * await invoke('login', { user: 'tauri', password: 'poiwe3h4r5ip3yrhtew9ty' }); 37 | * ``` 38 | * 39 | * @param cmd The command name. 40 | * @param args The optional arguments to pass to the command. 41 | * @return A promise resolving or rejecting to the backend response. 42 | * 43 | * @since 1.0.0 44 | */ 45 | async function invoke(cmd, args = {}) { 46 | return new Promise((resolve, reject) => { 47 | const callback = transformCallback((e) => { 48 | resolve(e); 49 | Reflect.deleteProperty(window, `_${error}`); 50 | }, true); 51 | const error = transformCallback((e) => { 52 | reject(e); 53 | Reflect.deleteProperty(window, `_${callback}`); 54 | }, true); 55 | window.__TAURI_IPC__({ 56 | cmd, 57 | callback, 58 | error, 59 | ...args 60 | }); 61 | }); 62 | } 63 | 64 | class Authenticator { 65 | async init() { 66 | return await invoke("plugin:authenticator|init_auth"); 67 | } 68 | async register(challenge, application) { 69 | return await invoke("plugin:authenticator|register", { 70 | timeout: 10000, 71 | challenge, 72 | application, 73 | }); 74 | } 75 | async verifyRegistration(challenge, application, registerData, clientData) { 76 | return await invoke("plugin:authenticator|verify_registration", { 77 | challenge, 78 | application, 79 | registerData, 80 | clientData, 81 | }); 82 | } 83 | async sign(challenge, application, keyHandle) { 84 | return await invoke("plugin:authenticator|sign", { 85 | timeout: 10000, 86 | challenge, 87 | application, 88 | keyHandle, 89 | }); 90 | } 91 | async verifySignature(challenge, application, signData, clientData, keyHandle, pubkey) { 92 | return await invoke("plugin:authenticator|verify_signature", { 93 | challenge, 94 | application, 95 | signData, 96 | clientData, 97 | keyHandle, 98 | pubkey, 99 | }); 100 | } 101 | } 102 | 103 | export { Authenticator }; 104 | //# sourceMappingURL=index.min.js.map 105 | -------------------------------------------------------------------------------- /src/u2f_crate/register.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Flavio Oliveira 2 | // SPDX-License-Identifier: Apache-2.0 3 | // SPDX-License-Identifier: MIT 4 | 5 | use byteorder::{BigEndian, ByteOrder}; 6 | use bytes::{BufMut, Bytes}; 7 | use openssl::sha::sha256; 8 | use serde::Serialize; 9 | 10 | use crate::u2f_crate::messages::RegisteredKey; 11 | use crate::u2f_crate::u2ferror::U2fError; 12 | use crate::u2f_crate::util::*; 13 | use std::convert::TryFrom; 14 | 15 | /// The `Result` type used in this crate. 16 | type Result = ::std::result::Result; 17 | 18 | // Single enrolment or pairing between an application and a token. 19 | #[derive(Serialize, Clone)] 20 | #[serde(rename_all = "camelCase")] 21 | pub struct Registration { 22 | pub key_handle: Vec, 23 | pub pub_key: Vec, 24 | 25 | // AttestationCert can be null for Authenticate requests. 26 | pub attestation_cert: Option>, 27 | pub device_name: Option, 28 | } 29 | 30 | pub fn parse_registration( 31 | app_id: String, 32 | client_data: Vec, 33 | registration_data: Vec, 34 | ) -> Result { 35 | let reserved_byte = registration_data[0]; 36 | if reserved_byte != 0x05 { 37 | return Err(U2fError::InvalidReservedByte); 38 | } 39 | 40 | let mut mem = Bytes::from(registration_data); 41 | 42 | //Start parsing ... advance the reserved byte. 43 | let _ = mem.split_to(1); 44 | 45 | // P-256 NIST elliptic curve 46 | let public_key = mem.split_to(65); 47 | 48 | // Key Handle 49 | let key_handle_size = mem.split_to(1); 50 | let key_len = BigEndian::read_uint(&key_handle_size[..], 1); 51 | let key_handle = mem.split_to(key_len as usize); 52 | 53 | // The certificate length needs to be inferred by parsing. 54 | let cert_len = asn_length(mem.clone()).unwrap(); 55 | let attestation_certificate = mem.split_to(cert_len); 56 | 57 | // Remaining data corresponds to the signature 58 | let signature = mem; 59 | 60 | // Let's build the msg to verify the signature 61 | let app_id_hash = sha256(&app_id.into_bytes()); 62 | let client_data_hash = sha256(&client_data[..]); 63 | 64 | let mut msg = vec![0x00]; // A byte reserved for future use [1 byte] with the value 0x00 65 | msg.put(app_id_hash.as_ref()); 66 | msg.put(client_data_hash.as_ref()); 67 | msg.put(key_handle.clone()); 68 | msg.put(public_key.clone()); 69 | 70 | // The signature is to be verified by the relying party using the public key certified 71 | // in the attestation certificate. 72 | let cerificate_public_key = 73 | super::crypto::X509PublicKey::try_from(&attestation_certificate[..])?; 74 | 75 | if !(cerificate_public_key.is_secp256r1()?) { 76 | return Err(U2fError::BadCertificate); 77 | } 78 | 79 | let verified = cerificate_public_key.verify_signature(&signature[..], &msg[..])?; 80 | 81 | if !verified { 82 | return Err(U2fError::BadCertificate); 83 | } 84 | 85 | let registration = Registration { 86 | key_handle: key_handle[..].to_vec(), 87 | pub_key: public_key[..].to_vec(), 88 | attestation_cert: Some(attestation_certificate[..].to_vec()), 89 | device_name: cerificate_public_key.common_name(), 90 | }; 91 | 92 | Ok(registration) 93 | } 94 | 95 | pub fn get_registered_key(app_id: String, key_handle: Vec) -> RegisteredKey { 96 | RegisteredKey { 97 | app_id, 98 | version: U2F_V2.into(), 99 | key_handle: Some(get_encoded(key_handle.as_slice())), 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/u2f.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Tauri Programme within The Commons Conservancy 2 | // SPDX-License-Identifier: Apache-2.0 3 | // SPDX-License-Identifier: MIT 4 | 5 | use crate::u2f_crate::messages::*; 6 | use crate::u2f_crate::protocol::*; 7 | use crate::u2f_crate::register::*; 8 | use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; 9 | use chrono::prelude::*; 10 | use serde::Serialize; 11 | use std::convert::Into; 12 | 13 | static VERSION: &str = "U2F_V2"; 14 | 15 | pub fn make_challenge(app_id: &str, challenge_bytes: Vec) -> Challenge { 16 | let utc: DateTime = Utc::now(); 17 | Challenge { 18 | challenge: URL_SAFE_NO_PAD.encode(challenge_bytes), 19 | timestamp: format!("{utc:?}"), 20 | app_id: app_id.to_string(), 21 | } 22 | } 23 | 24 | #[derive(Serialize, Clone)] 25 | #[serde(rename_all = "camelCase")] 26 | pub struct RegistrationVerification { 27 | pub key_handle: String, 28 | pub pubkey: String, 29 | pub device_name: Option, 30 | } 31 | 32 | pub fn verify_registration( 33 | app_id: String, 34 | challenge: String, 35 | register_data: String, 36 | client_data: String, 37 | ) -> crate::Result { 38 | let challenge_bytes = URL_SAFE_NO_PAD.decode(challenge)?; 39 | let challenge = make_challenge(&app_id, challenge_bytes); 40 | let client_data_bytes: Vec = client_data.as_bytes().into(); 41 | let client_data_base64 = URL_SAFE_NO_PAD.encode(client_data_bytes); 42 | let client = U2f::new(app_id); 43 | match client.register_response( 44 | challenge, 45 | RegisterResponse { 46 | registration_data: register_data, 47 | client_data: client_data_base64, 48 | version: VERSION.to_string(), 49 | }, 50 | ) { 51 | Ok(v) => { 52 | let rv = RegistrationVerification { 53 | key_handle: URL_SAFE_NO_PAD.encode(&v.key_handle), 54 | pubkey: URL_SAFE_NO_PAD.encode(&v.pub_key), 55 | device_name: v.device_name, 56 | }; 57 | Ok(serde_json::to_string(&rv)?) 58 | } 59 | Err(e) => Err(e.into()), 60 | } 61 | } 62 | 63 | #[derive(Serialize, Clone)] 64 | #[serde(rename_all = "camelCase")] 65 | pub struct SignatureVerification { 66 | pub counter: u8, 67 | } 68 | 69 | pub fn verify_signature( 70 | app_id: String, 71 | challenge: String, 72 | sign_data: String, 73 | client_data: String, 74 | key_handle: String, 75 | pub_key: String, 76 | ) -> crate::Result { 77 | let challenge_bytes = URL_SAFE_NO_PAD.decode(challenge)?; 78 | let chal = make_challenge(&app_id, challenge_bytes); 79 | let client_data_bytes: Vec = client_data.as_bytes().into(); 80 | let client_data_base64 = URL_SAFE_NO_PAD.encode(client_data_bytes); 81 | let key_handle_bytes = URL_SAFE_NO_PAD.decode(&key_handle)?; 82 | let pubkey_bytes = URL_SAFE_NO_PAD.decode(pub_key)?; 83 | let client = U2f::new(app_id); 84 | let mut _counter: u32 = 0; 85 | match client.sign_response( 86 | chal, 87 | Registration { 88 | // here only needs pubkey and keyhandle 89 | key_handle: key_handle_bytes, 90 | pub_key: pubkey_bytes, 91 | attestation_cert: None, 92 | device_name: None, 93 | }, 94 | SignResponse { 95 | // here needs client data and sig data and key_handle 96 | signature_data: sign_data, 97 | client_data: client_data_base64, 98 | key_handle, 99 | }, 100 | _counter, 101 | ) { 102 | Ok(v) => Ok(v), 103 | Err(e) => Err(e.into()), 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![plugin-authenticator](https://github.com/tauri-apps/plugins-workspace/raw/v1/plugins/authenticator/banner.png) 2 | 3 | Use hardware security-keys in your Tauri App. 4 | 5 | ## Install 6 | 7 | _This plugin requires a Rust version of at least **1.67**_ 8 | 9 | There are three general methods of installation that we can recommend. 10 | 11 | 1. Use crates.io and npm (easiest and requires you to trust that our publishing pipeline worked) 12 | 2. Pull sources directly from Github using git tags / revision hashes (most secure) 13 | 3. Git submodule install this repo in your tauri project and then use the file protocol to ingest the source (most secure, but inconvenient to use) 14 | 15 | Install the authenticator plugin by adding the following lines to your `Cargo.toml` file: 16 | 17 | `src-tauri/Cargo.toml` 18 | 19 | ```toml 20 | [dependencies] 21 | tauri-plugin-authenticator = "0.1" 22 | # or through git 23 | tauri-plugin-authenticator = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" } 24 | ``` 25 | 26 | You can install the JavaScript Guest bindings using your preferred JavaScript package manager: 27 | 28 | > Note: Since most JavaScript package managers are unable to install packages from git monorepos we provide read-only mirrors of each plugin. This makes installation option 2 more ergonomic to use. 29 | 30 | ```sh 31 | pnpm add https://github.com/tauri-apps/tauri-plugin-authenticator#v1 32 | # or 33 | npm add https://github.com/tauri-apps/tauri-plugin-authenticator#v1 34 | # or 35 | yarn add https://github.com/tauri-apps/tauri-plugin-authenticator#v1 36 | ``` 37 | 38 | ## Usage 39 | 40 | First, you need to register the authenticator plugin with Tauri: 41 | 42 | `src-tauri/src/main.rs` 43 | 44 | ```rust 45 | fn main() { 46 | tauri::Builder::default() 47 | .plugin(tauri_plugin_authenticator::init()) 48 | .run(tauri::generate_context!()) 49 | .expect("error while running tauri application"); 50 | } 51 | ``` 52 | 53 | Afterwards, all the plugin's APIs are available through the JavaScript guest bindings: 54 | 55 | ```javascript 56 | import { Authenticator } from "tauri-plugin-authenticator-api"; 57 | 58 | const auth = new Authenticator(); 59 | auth.init(); // initialize transports 60 | 61 | // generate a 32-bytes long random challenge 62 | const arr = new Uint32Array(32); 63 | window.crypto.getRandomValues(arr); 64 | const b64 = btoa(String.fromCharCode.apply(null, arr)); 65 | // web-safe base64 66 | const challenge = b64.replace(/\+/g, "-").replace(/\//g, "_"); 67 | 68 | const domain = "https://tauri.app"; 69 | 70 | // attempt to register with the security key 71 | const json = await auth.register(challenge, domain); 72 | const registerResult = JSON.parse(json); 73 | 74 | // verify the registration was successful 75 | const r2 = await auth.verifyRegistration( 76 | challenge, 77 | app, 78 | registerResult.registerData, 79 | registerResult.clientData, 80 | ); 81 | const j2 = JSON.parse(r2); 82 | 83 | // sign some data 84 | const json = await auth.sign(challenge, app, keyHandle); 85 | const signData = JSON.parse(json); 86 | 87 | // verify the signature again 88 | const counter = await auth.verifySignature( 89 | challenge, 90 | app, 91 | signData.signData, 92 | clientData, 93 | keyHandle, 94 | pubkey, 95 | ); 96 | 97 | if (counter && counter > 0) { 98 | console.log("SUCCESS!"); 99 | } 100 | ``` 101 | 102 | ## Contributing 103 | 104 | PRs accepted. Please make sure to read the Contributing Guide before making a pull request. 105 | 106 | ## Partners 107 | 108 | 109 | 110 | 111 | 116 | 117 | 118 |
112 | 113 | CrabNebula 114 | 115 |
119 | 120 | For the complete list of sponsors please visit our [website](https://tauri.app#sponsors) and [Open Collective](https://opencollective.com/tauri). 121 | 122 | ## License 123 | 124 | Code: (c) 2015 - Present - The Tauri Programme within The Commons Conservancy. 125 | 126 | MIT or MIT/Apache 2.0 where applicable. 127 | -------------------------------------------------------------------------------- /src/u2f_crate/crypto.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Flavio Oliveira 2 | // SPDX-License-Identifier: Apache-2.0 3 | // SPDX-License-Identifier: MIT 4 | 5 | //! Cryptographic operation wrapper for Webauthn. This module exists to 6 | //! allow ease of auditing, safe operation wrappers for the webauthn library, 7 | //! and cryptographic provider abstraction. This module currently uses OpenSSL 8 | //! as the cryptographic primitive provider. 9 | 10 | // Source can be found here: https://github.com/Firstyear/webauthn-rs/blob/master/src/crypto.rs 11 | 12 | #![allow(non_camel_case_types)] 13 | 14 | use openssl::{bn, ec, hash, nid, sign, x509}; 15 | use std::convert::TryFrom; 16 | 17 | // use super::constants::*; 18 | use crate::u2f_crate::u2ferror::U2fError; 19 | use openssl::pkey::Public; 20 | 21 | // use super::proto::*; 22 | 23 | // Why OpenSSL over another rust crate? 24 | // - Well, the openssl crate allows us to reconstruct a public key from the 25 | // x/y group coords, where most others want a pkcs formatted structure. As 26 | // a result, it's easiest to use openssl as it gives us exactly what we need 27 | // for these operations, and despite it's many challenges as a library, it 28 | // has resources and investment into it's maintenance, so we can a least 29 | // assert a higher level of confidence in it that . 30 | 31 | // Object({Integer(-3): Bytes([48, 185, 178, 204, 113, 186, 105, 138, 190, 33, 160, 46, 131, 253, 100, 177, 91, 243, 126, 128, 245, 119, 209, 59, 186, 41, 215, 196, 24, 222, 46, 102]), Integer(-2): Bytes([158, 212, 171, 234, 165, 197, 86, 55, 141, 122, 253, 6, 92, 242, 242, 114, 158, 221, 238, 163, 127, 214, 120, 157, 145, 226, 232, 250, 144, 150, 218, 138]), Integer(-1): U64(1), Integer(1): U64(2), Integer(3): I64(-7)}) 32 | // 33 | 34 | /// An X509PublicKey. This is what is otherwise known as a public certificate 35 | /// which comprises a public key and other signed metadata related to the issuer 36 | /// of the key. 37 | pub struct X509PublicKey { 38 | pubk: x509::X509, 39 | } 40 | 41 | impl std::fmt::Debug for X509PublicKey { 42 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 43 | write!(f, "X509PublicKey") 44 | } 45 | } 46 | 47 | impl TryFrom<&[u8]> for X509PublicKey { 48 | type Error = U2fError; 49 | 50 | // Must be DER bytes. If you have PEM, base64decode first! 51 | fn try_from(d: &[u8]) -> Result { 52 | let pubk = x509::X509::from_der(d)?; 53 | Ok(X509PublicKey { pubk }) 54 | } 55 | } 56 | 57 | impl X509PublicKey { 58 | pub(crate) fn common_name(&self) -> Option { 59 | let cert = &self.pubk; 60 | 61 | let subject = cert.subject_name(); 62 | let common = subject 63 | .entries_by_nid(openssl::nid::Nid::COMMONNAME) 64 | .next() 65 | .map(|b| b.data().as_slice()); 66 | 67 | if let Some(common) = common { 68 | std::str::from_utf8(common).ok().map(|s| s.to_string()) 69 | } else { 70 | None 71 | } 72 | } 73 | 74 | pub(crate) fn is_secp256r1(&self) -> Result { 75 | // Can we get the public key? 76 | let pk = self.pubk.public_key()?; 77 | 78 | let ec_key = pk.ec_key()?; 79 | 80 | ec_key.check_key()?; 81 | 82 | let ec_grpref = ec_key.group(); 83 | 84 | let ec_curve = ec_grpref.curve_name().ok_or(U2fError::OpenSSLNoCurveName)?; 85 | 86 | Ok(ec_curve == nid::Nid::X9_62_PRIME256V1) 87 | } 88 | 89 | pub(crate) fn verify_signature( 90 | &self, 91 | signature: &[u8], 92 | verification_data: &[u8], 93 | ) -> Result { 94 | let pkey = self.pubk.public_key()?; 95 | 96 | // TODO: Should this determine the hash type from the x509 cert? Or other? 97 | let mut verifier = sign::Verifier::new(hash::MessageDigest::sha256(), &pkey)?; 98 | verifier.update(verification_data)?; 99 | Ok(verifier.verify(signature)?) 100 | } 101 | } 102 | 103 | pub struct NISTP256Key { 104 | /// The key's public X coordinate. 105 | pub x: [u8; 32], 106 | /// The key's public Y coordinate. 107 | pub y: [u8; 32], 108 | } 109 | 110 | impl NISTP256Key { 111 | pub fn from_bytes(public_key_bytes: &[u8]) -> Result { 112 | if public_key_bytes.len() != 65 { 113 | return Err(U2fError::InvalidPublicKey); 114 | } 115 | 116 | if public_key_bytes[0] != 0x04 { 117 | return Err(U2fError::InvalidPublicKey); 118 | } 119 | 120 | let mut x: [u8; 32] = Default::default(); 121 | x.copy_from_slice(&public_key_bytes[1..=32]); 122 | 123 | let mut y: [u8; 32] = Default::default(); 124 | y.copy_from_slice(&public_key_bytes[33..=64]); 125 | 126 | Ok(NISTP256Key { x, y }) 127 | } 128 | 129 | fn get_key(&self) -> Result, U2fError> { 130 | let ec_group = ec::EcGroup::from_curve_name(openssl::nid::Nid::X9_62_PRIME256V1)?; 131 | 132 | let xbn = bn::BigNum::from_slice(&self.x)?; 133 | let ybn = bn::BigNum::from_slice(&self.y)?; 134 | 135 | let ec_key = openssl::ec::EcKey::from_public_key_affine_coordinates(&ec_group, &xbn, &ybn)?; 136 | 137 | // Validate the key is sound. IIRC this actually checks the values 138 | // are correctly on the curve as specified 139 | ec_key.check_key()?; 140 | 141 | Ok(ec_key) 142 | } 143 | 144 | pub fn verify_signature( 145 | &self, 146 | signature: &[u8], 147 | verification_data: &[u8], 148 | ) -> Result { 149 | let pkey = self.get_key()?; 150 | 151 | let signature = openssl::ecdsa::EcdsaSig::from_der(signature)?; 152 | let hash = openssl::sha::sha256(verification_data); 153 | 154 | Ok(signature.verify(hash.as_ref(), &pkey)?) 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /dist-js/index.min.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"index.min.js","sources":["../../../node_modules/.pnpm/@tauri-apps+api@1.6.0/node_modules/@tauri-apps/api/tauri.js","../guest-js/index.ts"],"sourcesContent":["// Copyright 2019-2023 Tauri Programme within The Commons Conservancy\n// SPDX-License-Identifier: Apache-2.0\n// SPDX-License-Identifier: MIT\n/** @ignore */\nfunction uid() {\n return window.crypto.getRandomValues(new Uint32Array(1))[0];\n}\n/**\n * Transforms a callback function to a string identifier that can be passed to the backend.\n * The backend uses the identifier to `eval()` the callback.\n *\n * @return A unique identifier associated with the callback function.\n *\n * @since 1.0.0\n */\nfunction transformCallback(callback, once = false) {\n const identifier = uid();\n const prop = `_${identifier}`;\n Object.defineProperty(window, prop, {\n value: (result) => {\n if (once) {\n Reflect.deleteProperty(window, prop);\n }\n return callback === null || callback === void 0 ? void 0 : callback(result);\n },\n writable: false,\n configurable: true\n });\n return identifier;\n}\n/**\n * Sends a message to the backend.\n * @example\n * ```typescript\n * import { invoke } from '@tauri-apps/api/tauri';\n * await invoke('login', { user: 'tauri', password: 'poiwe3h4r5ip3yrhtew9ty' });\n * ```\n *\n * @param cmd The command name.\n * @param args The optional arguments to pass to the command.\n * @return A promise resolving or rejecting to the backend response.\n *\n * @since 1.0.0\n */\nasync function invoke(cmd, args = {}) {\n return new Promise((resolve, reject) => {\n const callback = transformCallback((e) => {\n resolve(e);\n Reflect.deleteProperty(window, `_${error}`);\n }, true);\n const error = transformCallback((e) => {\n reject(e);\n Reflect.deleteProperty(window, `_${callback}`);\n }, true);\n window.__TAURI_IPC__({\n cmd,\n callback,\n error,\n ...args\n });\n });\n}\n/**\n * Convert a device file path to an URL that can be loaded by the webview.\n * Note that `asset:` and `https://asset.localhost` must be added to [`tauri.security.csp`](https://tauri.app/v1/api/config/#securityconfig.csp) in `tauri.conf.json`.\n * Example CSP value: `\"csp\": \"default-src 'self'; img-src 'self' asset: https://asset.localhost\"` to use the asset protocol on image sources.\n *\n * Additionally, `asset` must be added to [`tauri.allowlist.protocol`](https://tauri.app/v1/api/config/#allowlistconfig.protocol)\n * in `tauri.conf.json` and its access scope must be defined on the `assetScope` array on the same `protocol` object.\n * For example:\n * ```json\n * {\n * \"tauri\": {\n * \"allowlist\": {\n * \"protocol\": {\n * \"asset\": true,\n * \"assetScope\": [\"$APPDATA/assets/*\"]\n * }\n * }\n * }\n * }\n * ```\n *\n * @param filePath The file path.\n * @param protocol The protocol to use. Defaults to `asset`. You only need to set this when using a custom protocol.\n * @example\n * ```typescript\n * import { appDataDir, join } from '@tauri-apps/api/path';\n * import { convertFileSrc } from '@tauri-apps/api/tauri';\n * const appDataDirPath = await appDataDir();\n * const filePath = await join(appDataDirPath, 'assets/video.mp4');\n * const assetUrl = convertFileSrc(filePath);\n *\n * const video = document.getElementById('my-video');\n * const source = document.createElement('source');\n * source.type = 'video/mp4';\n * source.src = assetUrl;\n * video.appendChild(source);\n * video.load();\n * ```\n *\n * @return the URL that can be used as source on the webview.\n *\n * @since 1.0.0\n */\nfunction convertFileSrc(filePath, protocol = 'asset') {\n return window.__TAURI__.convertFileSrc(filePath, protocol);\n}\n\nexport { convertFileSrc, invoke, transformCallback };\n",null],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA,SAAS,GAAG,GAAG;AACf,IAAI,OAAO,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAChE,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,iBAAiB,CAAC,QAAQ,EAAE,IAAI,GAAG,KAAK,EAAE;AACnD,IAAI,MAAM,UAAU,GAAG,GAAG,EAAE,CAAC;AAC7B,IAAI,MAAM,IAAI,GAAG,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC;AAClC,IAAI,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,IAAI,EAAE;AACxC,QAAQ,KAAK,EAAE,CAAC,MAAM,KAAK;AAC3B,YAAY,IAAI,IAAI,EAAE;AACtB,gBAAgB,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AACrD,aAAa;AACb,YAAY,OAAO,QAAQ,KAAK,IAAI,IAAI,QAAQ,KAAK,KAAK,CAAC,GAAG,KAAK,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;AACxF,SAAS;AACT,QAAQ,QAAQ,EAAE,KAAK;AACvB,QAAQ,YAAY,EAAE,IAAI;AAC1B,KAAK,CAAC,CAAC;AACP,IAAI,OAAO,UAAU,CAAC;AACtB,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,MAAM,CAAC,GAAG,EAAE,IAAI,GAAG,EAAE,EAAE;AACtC,IAAI,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK;AAC5C,QAAQ,MAAM,QAAQ,GAAG,iBAAiB,CAAC,CAAC,CAAC,KAAK;AAClD,YAAY,OAAO,CAAC,CAAC,CAAC,CAAC;AACvB,YAAY,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;AACxD,SAAS,EAAE,IAAI,CAAC,CAAC;AACjB,QAAQ,MAAM,KAAK,GAAG,iBAAiB,CAAC,CAAC,CAAC,KAAK;AAC/C,YAAY,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,YAAY,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;AAC3D,SAAS,EAAE,IAAI,CAAC,CAAC;AACjB,QAAQ,MAAM,CAAC,aAAa,CAAC;AAC7B,YAAY,GAAG;AACf,YAAY,QAAQ;AACpB,YAAY,KAAK;AACjB,YAAY,GAAG,IAAI;AACnB,SAAS,CAAC,CAAC;AACX,KAAK,CAAC,CAAC;AACP;;MC3Da,aAAa,CAAA;AACxB,IAAA,MAAM,IAAI,GAAA;AACR,QAAA,OAAO,MAAM,MAAM,CAAC,gCAAgC,CAAC,CAAC;KACvD;AAED,IAAA,MAAM,QAAQ,CAAC,SAAiB,EAAE,WAAmB,EAAA;AACnD,QAAA,OAAO,MAAM,MAAM,CAAC,+BAA+B,EAAE;AACnD,YAAA,OAAO,EAAE,KAAK;YACd,SAAS;YACT,WAAW;AACZ,SAAA,CAAC,CAAC;KACJ;IAED,MAAM,kBAAkB,CACtB,SAAiB,EACjB,WAAmB,EACnB,YAAoB,EACpB,UAAkB,EAAA;AAElB,QAAA,OAAO,MAAM,MAAM,CAAC,0CAA0C,EAAE;YAC9D,SAAS;YACT,WAAW;YACX,YAAY;YACZ,UAAU;AACX,SAAA,CAAC,CAAC;KACJ;AAED,IAAA,MAAM,IAAI,CACR,SAAiB,EACjB,WAAmB,EACnB,SAAiB,EAAA;AAEjB,QAAA,OAAO,MAAM,MAAM,CAAC,2BAA2B,EAAE;AAC/C,YAAA,OAAO,EAAE,KAAK;YACd,SAAS;YACT,WAAW;YACX,SAAS;AACV,SAAA,CAAC,CAAC;KACJ;AAED,IAAA,MAAM,eAAe,CACnB,SAAiB,EACjB,WAAmB,EACnB,QAAgB,EAChB,UAAkB,EAClB,SAAiB,EACjB,MAAc,EAAA;AAEd,QAAA,OAAO,MAAM,MAAM,CAAC,uCAAuC,EAAE;YAC3D,SAAS;YACT,WAAW;YACX,QAAQ;YACR,UAAU;YACV,SAAS;YACT,MAAM;AACP,SAAA,CAAC,CAAC;KACJ;AACF;;;;","x_google_ignoreList":[0]} -------------------------------------------------------------------------------- /src/u2f_crate/protocol.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Flavio Oliveira 2 | // SPDX-License-Identifier: Apache-2.0 3 | // SPDX-License-Identifier: MIT 4 | 5 | use crate::u2f_crate::authorization::*; 6 | use crate::u2f_crate::messages::*; 7 | use crate::u2f_crate::register::*; 8 | use crate::u2f_crate::u2ferror::U2fError; 9 | use crate::u2f_crate::util::*; 10 | 11 | use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; 12 | use chrono::prelude::*; 13 | use chrono::Duration; 14 | use serde::{Deserialize, Serialize}; 15 | 16 | type Result = ::std::result::Result; 17 | 18 | #[derive(Clone)] 19 | pub struct U2f { 20 | app_id: String, 21 | } 22 | 23 | #[derive(Deserialize, Serialize, Clone)] 24 | #[serde(rename_all = "camelCase")] 25 | pub struct Challenge { 26 | pub app_id: String, 27 | pub challenge: String, 28 | pub timestamp: String, 29 | } 30 | 31 | impl Challenge { 32 | // Not used in this plugin. 33 | #[allow(dead_code)] 34 | pub fn new() -> Self { 35 | Challenge { 36 | app_id: String::new(), 37 | challenge: String::new(), 38 | timestamp: String::new(), 39 | } 40 | } 41 | } 42 | 43 | impl U2f { 44 | // The app ID is a string used to uniquely identify an U2F app 45 | pub fn new(app_id: String) -> Self { 46 | U2f { app_id } 47 | } 48 | 49 | // Not used in this plugin. 50 | #[allow(dead_code)] 51 | pub fn generate_challenge(&self) -> Result { 52 | let utc: DateTime = Utc::now(); 53 | 54 | let challenge_bytes = generate_challenge(32)?; 55 | let challenge = Challenge { 56 | challenge: URL_SAFE_NO_PAD.encode(challenge_bytes), 57 | timestamp: format!("{:?}", utc), 58 | app_id: self.app_id.clone(), 59 | }; 60 | 61 | Ok(challenge.clone()) 62 | } 63 | 64 | // Not used in this plugin. 65 | #[allow(dead_code)] 66 | pub fn request( 67 | &self, 68 | challenge: Challenge, 69 | registrations: Vec, 70 | ) -> Result { 71 | let u2f_request = U2fRegisterRequest { 72 | app_id: self.app_id.clone(), 73 | register_requests: self.register_request(challenge), 74 | registered_keys: self.registered_keys(registrations), 75 | }; 76 | 77 | Ok(u2f_request) 78 | } 79 | 80 | fn register_request(&self, challenge: Challenge) -> Vec { 81 | let mut requests: Vec = vec![]; 82 | 83 | let request = RegisterRequest { 84 | version: U2F_V2.into(), 85 | challenge: challenge.challenge, 86 | }; 87 | requests.push(request); 88 | 89 | requests 90 | } 91 | 92 | pub fn register_response( 93 | &self, 94 | challenge: Challenge, 95 | response: RegisterResponse, 96 | ) -> Result { 97 | if expiration(challenge.timestamp) > Duration::seconds(300) { 98 | return Err(U2fError::ChallengeExpired); 99 | } 100 | 101 | let registration_data: Vec = URL_SAFE_NO_PAD 102 | .decode(&response.registration_data[..]) 103 | .unwrap(); 104 | let client_data: Vec = URL_SAFE_NO_PAD.decode(&response.client_data[..]).unwrap(); 105 | 106 | parse_registration(challenge.app_id, client_data, registration_data) 107 | } 108 | 109 | fn registered_keys(&self, registrations: Vec) -> Vec { 110 | let mut keys: Vec = vec![]; 111 | 112 | for registration in registrations { 113 | keys.push(get_registered_key( 114 | self.app_id.clone(), 115 | registration.key_handle, 116 | )); 117 | } 118 | 119 | keys 120 | } 121 | 122 | // Not used in this plugin. 123 | #[allow(dead_code)] 124 | pub fn sign_request( 125 | &self, 126 | challenge: Challenge, 127 | registrations: Vec, 128 | ) -> U2fSignRequest { 129 | let mut keys: Vec = vec![]; 130 | 131 | for registration in registrations { 132 | keys.push(get_registered_key( 133 | self.app_id.clone(), 134 | registration.key_handle, 135 | )); 136 | } 137 | 138 | let signed_request = U2fSignRequest { 139 | app_id: self.app_id.clone(), 140 | challenge: URL_SAFE_NO_PAD.encode(challenge.challenge.as_bytes()), 141 | registered_keys: keys, 142 | }; 143 | 144 | signed_request 145 | } 146 | 147 | pub fn sign_response( 148 | &self, 149 | challenge: Challenge, 150 | reg: Registration, 151 | sign_resp: SignResponse, 152 | counter: u32, 153 | ) -> Result { 154 | if expiration(challenge.timestamp) > Duration::seconds(300) { 155 | return Err(U2fError::ChallengeExpired); 156 | } 157 | 158 | if sign_resp.key_handle != get_encoded(®.key_handle[..]) { 159 | return Err(U2fError::WrongKeyHandler); 160 | } 161 | 162 | let client_data: Vec = URL_SAFE_NO_PAD 163 | .decode(&sign_resp.client_data[..]) 164 | .map_err(|_e| U2fError::InvalidClientData)?; 165 | let sign_data: Vec = URL_SAFE_NO_PAD 166 | .decode(&sign_resp.signature_data[..]) 167 | .map_err(|_e| U2fError::InvalidSignatureData)?; 168 | 169 | let public_key = reg.pub_key; 170 | 171 | let auth = parse_sign_response( 172 | self.app_id.clone(), 173 | client_data.clone(), 174 | public_key, 175 | sign_data.clone(), 176 | ); 177 | 178 | match auth { 179 | Ok(ref res) => { 180 | // CounterTooLow is raised when the counter value received from the device is 181 | // lower than last stored counter value. 182 | if res.counter < counter { 183 | Err(U2fError::CounterTooLow) 184 | } else { 185 | Ok(res.counter) 186 | } 187 | } 188 | Err(e) => Err(e), 189 | } 190 | } 191 | } 192 | -------------------------------------------------------------------------------- /src/auth.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Tauri Programme within The Commons Conservancy 2 | // SPDX-License-Identifier: Apache-2.0 3 | // SPDX-License-Identifier: MIT 4 | 5 | use authenticator::{ 6 | authenticatorservice::AuthenticatorService, statecallback::StateCallback, 7 | AuthenticatorTransports, KeyHandle, RegisterFlags, SignFlags, StatusUpdate, 8 | }; 9 | use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; 10 | use once_cell::sync::Lazy; 11 | use serde::Serialize; 12 | use sha2::{Digest, Sha256}; 13 | use std::io; 14 | use std::sync::mpsc::channel; 15 | use std::{convert::Into, sync::Mutex}; 16 | 17 | static MANAGER: Lazy> = Lazy::new(|| { 18 | let manager = AuthenticatorService::new().expect("The auth service should initialize safely"); 19 | Mutex::new(manager) 20 | }); 21 | 22 | pub fn init_usb() { 23 | let mut manager = MANAGER.lock().unwrap(); 24 | // theres also "add_detected_transports()" in the docs? 25 | manager.add_u2f_usb_hid_platform_transports(); 26 | } 27 | 28 | #[derive(Serialize, Clone)] 29 | #[serde(rename_all = "camelCase")] 30 | pub struct Registration { 31 | pub key_handle: String, 32 | pub pubkey: String, 33 | pub register_data: String, 34 | pub client_data: String, 35 | } 36 | 37 | pub fn register(application: String, timeout: u64, challenge: String) -> crate::Result { 38 | let (chall_bytes, app_bytes, client_data_string) = 39 | format_client_data(application.as_str(), challenge.as_str()); 40 | 41 | // log the status rx? 42 | let (status_tx, _status_rx) = channel::(); 43 | 44 | let mut manager = MANAGER.lock().unwrap(); 45 | 46 | let (register_tx, register_rx) = channel(); 47 | let callback = StateCallback::new(Box::new(move |rv| { 48 | register_tx.send(rv).unwrap(); 49 | })); 50 | 51 | let res = manager.register( 52 | RegisterFlags::empty(), 53 | timeout, 54 | chall_bytes, 55 | app_bytes, 56 | vec![], 57 | status_tx, 58 | callback, 59 | ); 60 | 61 | match res { 62 | Ok(_r) => { 63 | let register_result = register_rx 64 | .recv() 65 | .expect("Problem receiving, unable to continue"); 66 | 67 | if let Err(e) = register_result { 68 | return Err(e.into()); 69 | } 70 | 71 | let (register_data, device_info) = register_result.unwrap(); // error already has been checked 72 | 73 | // println!("Register result: {}", base64::encode(®ister_data)); 74 | println!("Device info: {}", &device_info); 75 | 76 | let (key_handle, public_key) = 77 | _u2f_get_key_handle_and_public_key_from_register_response(®ister_data).unwrap(); 78 | let key_handle_base64 = URL_SAFE_NO_PAD.encode(key_handle); 79 | let public_key_base64 = URL_SAFE_NO_PAD.encode(public_key); 80 | let register_data_base64 = URL_SAFE_NO_PAD.encode(®ister_data); 81 | println!("Key Handle: {}", &key_handle_base64); 82 | println!("Public Key: {}", &public_key_base64); 83 | 84 | // Ok(base64::encode(®ister_data)) 85 | // Ok(key_handle_base64) 86 | let res = serde_json::to_string(&Registration { 87 | key_handle: key_handle_base64, 88 | pubkey: public_key_base64, 89 | register_data: register_data_base64, 90 | client_data: client_data_string, 91 | })?; 92 | Ok(res) 93 | } 94 | Err(e) => Err(e.into()), 95 | } 96 | } 97 | 98 | #[derive(Serialize, Clone)] 99 | #[serde(rename_all = "camelCase")] 100 | pub struct Signature { 101 | pub key_handle: String, 102 | pub sign_data: String, 103 | } 104 | 105 | pub fn sign( 106 | application: String, 107 | timeout: u64, 108 | challenge: String, 109 | key_handle: String, 110 | ) -> crate::Result { 111 | let credential = match URL_SAFE_NO_PAD.decode(key_handle) { 112 | Ok(v) => v, 113 | Err(e) => { 114 | return Err(e.into()); 115 | } 116 | }; 117 | let key_handle = KeyHandle { 118 | credential, 119 | transports: AuthenticatorTransports::empty(), 120 | }; 121 | 122 | let (chall_bytes, app_bytes, _) = format_client_data(application.as_str(), challenge.as_str()); 123 | 124 | let (sign_tx, sign_rx) = channel(); 125 | let callback = StateCallback::new(Box::new(move |rv| { 126 | sign_tx.send(rv).unwrap(); 127 | })); 128 | 129 | // log the status rx? 130 | let (status_tx, _status_rx) = channel::(); 131 | 132 | let mut manager = MANAGER.lock().unwrap(); 133 | 134 | let res = manager.sign( 135 | SignFlags::empty(), 136 | timeout, 137 | chall_bytes, 138 | vec![app_bytes], 139 | vec![key_handle], 140 | status_tx, 141 | callback, 142 | ); 143 | match res { 144 | Ok(_v) => { 145 | let sign_result = sign_rx 146 | .recv() 147 | .expect("Problem receiving, unable to continue"); 148 | 149 | if let Err(e) = sign_result { 150 | return Err(e.into()); 151 | } 152 | 153 | let (_, handle_used, sign_data, device_info) = sign_result.unwrap(); 154 | 155 | let sig = URL_SAFE_NO_PAD.encode(sign_data); 156 | 157 | println!("Sign result: {sig}"); 158 | println!("Key handle used: {}", URL_SAFE_NO_PAD.encode(&handle_used)); 159 | println!("Device info: {}", &device_info); 160 | println!("Done."); 161 | 162 | let res = serde_json::to_string(&Signature { 163 | sign_data: sig, 164 | key_handle: URL_SAFE_NO_PAD.encode(&handle_used), 165 | })?; 166 | Ok(res) 167 | } 168 | Err(e) => Err(e.into()), 169 | } 170 | } 171 | 172 | fn format_client_data(application: &str, challenge: &str) -> (Vec, Vec, String) { 173 | let d = 174 | format!(r#"{{"challenge": "{challenge}", "version": "U2F_V2", "appId": "{application}"}}"#); 175 | let mut challenge = Sha256::new(); 176 | challenge.update(d.as_bytes()); 177 | let chall_bytes = challenge.finalize().to_vec(); 178 | 179 | let mut app = Sha256::new(); 180 | app.update(application.as_bytes()); 181 | let app_bytes = app.finalize().to_vec(); 182 | 183 | (chall_bytes, app_bytes, d) 184 | } 185 | 186 | fn _u2f_get_key_handle_and_public_key_from_register_response( 187 | register_response: &[u8], 188 | ) -> io::Result<(Vec, Vec)> { 189 | if register_response[0] != 0x05 { 190 | return Err(io::Error::new( 191 | io::ErrorKind::InvalidData, 192 | "Reserved byte not set correctly", 193 | )); 194 | } 195 | 196 | // 1: reserved 197 | // 65: public key 198 | // 1: key handle length 199 | // key handle 200 | // x.509 cert 201 | // sig 202 | 203 | let key_handle_len = register_response[66] as usize; 204 | let mut public_key = register_response.to_owned(); 205 | let mut key_handle = public_key.split_off(67); 206 | let _attestation = key_handle.split_off(key_handle_len); 207 | 208 | // remove fist (reserved) and last (handle len) bytes 209 | let pk: Vec = public_key[1..public_key.len() - 1].to_vec(); 210 | 211 | Ok((key_handle, pk)) 212 | } 213 | -------------------------------------------------------------------------------- /LICENSE_APACHE-2.0: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS --------------------------------------------------------------------------------