fernet-0.1.4/.cargo_vcs_info.json0000644000000001120000000000000123120ustar { "git": { "sha1": "8b1264dc0e4cb98649e8e91a09864f7810c30ab6" } } fernet-0.1.4/.github/dependabot.yml000064400000000000000000000004330000000000000152560ustar 00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: daily allow: # Also update indirect dependencies - dependency-type: all - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" fernet-0.1.4/.github/workflows/ci.yml000064400000000000000000000030070000000000000156010ustar 00000000000000on: [pull_request, push] name: CI jobs: ci: runs-on: ubuntu-latest strategy: matrix: RUST: - stable - beta - nightly steps: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: ${{ matrix.RUST }} override: true components: rustfmt, clippy - uses: actions-rs/cargo@v1 with: command: build - uses: actions-rs/cargo@v1 with: command: test - uses: actions-rs/cargo@v1 with: command: fmt args: --all -- --check - uses: actions-rs/cargo@v1 with: command: clippy args: -- -D warnings - uses: actions-rs/audit-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }} fernet-0.1.4/.gitignore000064400000000000000000000000370000000000000130560ustar 00000000000000 /target **/*.rs.bk Cargo.lock fernet-0.1.4/CODE_OF_CONDUCT.md000064400000000000000000000007570000000000000136760ustar 00000000000000# Community Participation Guidelines This repository is governed by Mozilla's code of conduct and etiquette guidelines. For more details, please read the [Mozilla Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/). ## How to Report For more information on how to report violations of the Community Participation Guidelines, please read our '[How to Report](https://www.mozilla.org/about/governance/policies/participation/reporting/)' page. fernet-0.1.4/Cargo.toml0000644000000026760000000000000103310ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "fernet" version = "0.1.4" authors = ["Alex Gaynor ", "Ben Bangert "] description = "An implementation of fernet in Rust." homepage = "https://github.com/mozilla-services/fernet-rs/" readme = "README.md" license = "MPL-2.0" repository = "https://github.com/mozilla-services/fernet-rs/" [package.metadata.docs.rs] features = ["fernet_danger_timestamps"] [dependencies.base64] version = "0.13" [dependencies.byteorder] version = "1" [dependencies.getrandom] version = "0.2" [dependencies.openssl] version = "0.10" [dependencies.zeroize] version = "1.0" features = ["zeroize_derive"] [dev-dependencies.chrono] version = "0.4" [dev-dependencies.serde] version = "1.0" [dev-dependencies.serde_derive] version = "1.0" [dev-dependencies.serde_json] version = "1.0" [features] fernet_danger_timestamps = [] [badges.travis-ci] repository = "mozilla-services/fernet-rs" fernet-0.1.4/Cargo.toml.orig000064400000000000000000000014110000000000000137520ustar 00000000000000[package] name = "fernet" version = "0.1.4" authors = ["Alex Gaynor ", "Ben Bangert "] description = "An implementation of fernet in Rust." repository = "https://github.com/mozilla-services/fernet-rs/" homepage = "https://github.com/mozilla-services/fernet-rs/" license = "MPL-2.0" readme = "README.md" edition = "2018" [badges] travis-ci = { repository = "mozilla-services/fernet-rs" } [features] fernet_danger_timestamps = [] [package.metadata.docs.rs] features = [ "fernet_danger_timestamps" ] [dependencies] base64 = "0.13" byteorder = "1" openssl = "0.10" getrandom = "0.2" zeroize = { version = "1.0", features = ["zeroize_derive"] } [dev-dependencies] chrono = "0.4" serde = "1.0" serde_derive = "1.0" serde_json = "1.0" fernet-0.1.4/LICENSE000064400000000000000000000405250000000000000121010ustar 00000000000000Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. fernet-0.1.4/README.md000064400000000000000000000034520000000000000123510ustar 00000000000000fernet-rs ========= [![dependency status](https://deps.rs/repo/github/mozilla-services/fernet-rs/status.svg)](https://deps.rs/repo/github/mozilla-services/fernet-rs) An implementation of [fernet](https://github.com/fernet/spec) in Rust. What is Fernet? --------------- Fernet is a small library to help you encrypt parcels of data with optional expiry times. It's great for tokens or exchanging small strings or blobs of data. Fernet is designed to be easy to use, combining cryptographic primitives in a way that is hard to get wrong, prevents tampering and gives you confidence that the token is legitimate. You should consider this if you need: * Time limited authentication tokens in URLs or authorisation headers * To send small blobs of encrypted data between two points with a static key * Simple encryption of secrets to store to disk that can be read later * Many more ... Great! How do I start? ---------------------- Add fernet to your Cargo.toml: [dependencies] fernet = "0.1" And then have a look at our [API documentation] online, or run "cargo doc --open" in your project. [API documentation online]: https://docs.rs/fernet Testing Token Expiry -------------------- By default fernet wraps operations in an attempt to be safe - you should never be able to "hold it incorrectly". But we understand that sometimes you need to be able to do some more complicated operations. The major example of this is having your application test how it handles tokens that have expired past their ttl. To support this, we allow you to pass in timestamps to the `encrypt_at_time` and `decrypt_at_time` functions, but these are behind a feature gate. To activate these api's you need to add the following to Cargo.toml [dependencies] fernet = { version = "0.1", features = ["fernet_danger_timestamps"] } fernet-0.1.4/src/lib.rs000064400000000000000000000420530000000000000127750ustar 00000000000000#![deny(warnings)] //! Fernet provides symmetric-authenticated-encryption with an API that makes //! misusing it difficult. It is based on a public specification and there are //! interoperable implementations in Rust, Python, Ruby, Go, and Clojure. //! # Example //! ```rust //! // Store `key` somewhere safe! //! let key = fernet::Fernet::generate_key(); //! let fernet = fernet::Fernet::new(&key).unwrap(); //! let plaintext = b"my top secret message!"; //! let ciphertext = fernet.encrypt(plaintext); //! let decrypted_plaintext = fernet.decrypt(&ciphertext); //! assert_eq!(decrypted_plaintext.unwrap(), plaintext); // ``` use byteorder::ReadBytesExt; use std::error::Error; use std::fmt::{self, Display}; use std::io::{Cursor, Read}; use std::time; use zeroize::Zeroize; const MAX_CLOCK_SKEW: u64 = 60; // Automatically zero out the contents of the memory when the struct is drop'd. #[derive(Clone, Zeroize)] #[zeroize(drop)] pub struct Fernet { encryption_key: [u8; 16], signing_key: [u8; 16], } /// This error is returned when fernet cannot decrypt the ciphertext for any /// reason. It could be an expired token, incorrect key or other failure. If /// you recieve this error, you should consider the fernet token provided as /// invalid. #[derive(Debug, PartialEq, Eq)] pub struct DecryptionError; impl Error for DecryptionError {} impl Display for DecryptionError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Fernet decryption error") } } #[derive(Clone)] pub struct MultiFernet { fernets: Vec, } /// `MultiFernet` encapsulates the encrypt operation with the first `Fernet` /// instance and decryption with the `Fernet` instances provided in order /// until successful decryption or a `DecryptionError`. impl MultiFernet { pub fn new(keys: Vec) -> MultiFernet { assert!(!keys.is_empty(), "keys must not be empty"); MultiFernet { fernets: keys } } /// Encrypts data with the first `Fernet` instance. Returns a value /// (which is base64-encoded) that can be passed to `MultiFernet::decrypt`. pub fn encrypt(&self, data: &[u8]) -> String { self.fernets[0].encrypt(data) } /// Decrypts a ciphertext, using the `Fernet` instances provided. Returns /// either `Ok(plaintext)` if decryption is successful or /// `Err(DecryptionError)` if no decryption was possible across the set of /// fernet keys. pub fn decrypt(&self, token: &str) -> Result, DecryptionError> { for fernet in self.fernets.iter() { let res = fernet.decrypt(token); if res.is_ok() { return res; } } Err(DecryptionError) } } /// `Fernet` encapsulates encrypt and decrypt operations for a particular synchronous key. impl Fernet { /// Returns a new fernet instance with the provided key. The key should be /// 32-bytes, url-safe base64-encoded. Generating keys with `Fernet::generate_key` /// is recommended. DO NOT USE A HUMAN READABLE PASSWORD AS A KEY. Returns /// `None` if the key is not 32-bytes base64 encoded. pub fn new(key: &str) -> Option { let key = base64::decode_config(key, base64::URL_SAFE).ok()?; if key.len() != 32 { return None; } let mut signing_key: [u8; 16] = Default::default(); signing_key.copy_from_slice(&key[..16]); let mut encryption_key: [u8; 16] = Default::default(); encryption_key.copy_from_slice(&key[16..]); Some(Fernet { signing_key, encryption_key, }) } /// Generates a new, random, key. Can be safely passed to `Fernet::new()`. /// Store this somewhere safe! pub fn generate_key() -> String { let mut key: [u8; 32] = Default::default(); getrandom::getrandom(&mut key).expect("Error in getrandom"); base64::encode_config(&key, base64::URL_SAFE) } /// Encrypts data into a token. Returns a value (which is base64-encoded) that can be /// passed to `Fernet::decrypt` for decryption and verification.. pub fn encrypt(&self, data: &[u8]) -> String { let current_time = time::SystemTime::now() .duration_since(time::UNIX_EPOCH) .unwrap() .as_secs(); self._encrypt_at_time(data, current_time) } /// Encrypts data with the current_time. Returns a value (which is base64-encoded) that can be /// passed to `Fernet::decrypt`. /// /// This function has the capacity to be used incorrectly or insecurely due to /// to the "current_time" parameter. current_time must be the systems `time::SystemTime::now()` /// with `duraction_since(time::UNIX_EPOCH)` as seconds. /// /// The motivation for a function like this is for your application to be able to test /// ttl expiry of tokens in your API. This allows you to pass in mock time data to assert /// correct behaviour of your application. Care should be taken to ensure you always pass in /// correct current_time values for deployments. #[inline] #[cfg(feature = "fernet_danger_timestamps")] pub fn encrypt_at_time(&self, data: &[u8], current_time: u64) -> String { self._encrypt_at_time(data, current_time) } fn _encrypt_at_time(&self, data: &[u8], current_time: u64) -> String { let mut iv: [u8; 16] = Default::default(); getrandom::getrandom(&mut iv).expect("Error in getrandom"); self._encrypt_from_parts(data, current_time, &iv) } fn _encrypt_from_parts(&self, data: &[u8], current_time: u64, iv: &[u8]) -> String { let ciphertext = openssl::symm::encrypt( openssl::symm::Cipher::aes_128_cbc(), &self.encryption_key, Some(iv), data, ) .unwrap(); let mut result = vec![]; result.push(0x80); result.extend_from_slice(¤t_time.to_be_bytes()); result.extend_from_slice(iv); result.extend_from_slice(&ciphertext); let hmac_pkey = openssl::pkey::PKey::hmac(&self.signing_key).unwrap(); let mut hmac_signer = openssl::sign::Signer::new(openssl::hash::MessageDigest::sha256(), &hmac_pkey).unwrap(); hmac_signer.update(&result).unwrap(); result.extend_from_slice(&hmac_signer.sign_to_vec().unwrap()); base64::encode_config(&result, base64::URL_SAFE) } /// Decrypts a ciphertext. Returns either `Ok(plaintext)` if decryption is /// successful or `Err(DecryptionError)` if there are any errors. Errors could /// include incorrect key or tampering with the data. pub fn decrypt(&self, token: &str) -> Result, DecryptionError> { let current_time = time::SystemTime::now() .duration_since(time::UNIX_EPOCH) .unwrap() .as_secs(); self._decrypt_at_time(token, None, current_time) } /// Decrypts a ciphertext with a time-to-live. Returns either `Ok(plaintext)` /// if decryption is successful or `Err(DecryptionError)` if there are any errors. /// Note if the token timestamp + ttl > current time, then this will also yield a /// DecryptionError. The ttl is measured in seconds. This is a relative time, not /// the absolute time of expiry. IE you would use 60 as a ttl_secs if you wanted /// tokens to be considered invalid after that time. pub fn decrypt_with_ttl(&self, token: &str, ttl_secs: u64) -> Result, DecryptionError> { let current_time = time::SystemTime::now() .duration_since(time::UNIX_EPOCH) .unwrap() .as_secs(); self._decrypt_at_time(token, Some(ttl_secs), current_time) } /// Decrypt a ciphertext with a time-to-live, and the current time. /// Returns either `Ok(plaintext)` if decryption is /// successful or `Err(DecryptionError)` if there are any errors. /// /// This function has the capacity to be used incorrectly or insecurely due to /// to the "current_time" parameter. current_time must be the systems time::SystemTime::now() /// with duraction_since(time::UNIX_EPOCH) as seconds. /// /// The motivation for a function like this is for your application to be able to test /// ttl expiry of tokens in your API. This allows you to pass in mock time data to assert /// correct behaviour of your application. Care should be taken to ensure you always pass in /// correct current_time values for deployments. #[inline] #[cfg(feature = "fernet_danger_timestamps")] pub fn decrypt_at_time( &self, token: &str, ttl: Option, current_time: u64, ) -> Result, DecryptionError> { self._decrypt_at_time(token, ttl, current_time) } fn _decrypt_at_time( &self, token: &str, ttl: Option, current_time: u64, ) -> Result, DecryptionError> { let data = match base64::decode_config(token, base64::URL_SAFE) { Ok(data) => data, Err(_) => return Err(DecryptionError), }; let mut input = Cursor::new(data); match input.read_u8() { Ok(0x80) => {} _ => return Err(DecryptionError), } let timestamp = input .read_u64::() .map_err(|_| DecryptionError)?; if let Some(ttl) = ttl { if timestamp + ttl < current_time { return Err(DecryptionError); } } if current_time + MAX_CLOCK_SKEW < timestamp { return Err(DecryptionError); } let mut iv = vec![0; 16]; input.read_exact(&mut iv).map_err(|_| DecryptionError)?; let mut rest = vec![]; input.read_to_end(&mut rest).unwrap(); if rest.len() < 32 { return Err(DecryptionError); } let ciphertext = &rest[..rest.len() - 32]; let hmac = &rest[rest.len() - 32..]; let hmac_pkey = openssl::pkey::PKey::hmac(&self.signing_key).unwrap(); let mut hmac_signer = openssl::sign::Signer::new(openssl::hash::MessageDigest::sha256(), &hmac_pkey).unwrap(); hmac_signer .update(&input.get_ref()[..input.get_ref().len() - 32]) .unwrap(); let expected_hmac = hmac_signer.sign_to_vec().unwrap(); if !openssl::memcmp::eq(&expected_hmac, hmac) { return Err(DecryptionError); } let plaintext = openssl::symm::decrypt( openssl::symm::Cipher::aes_128_cbc(), &self.encryption_key, Some(&iv), ciphertext, ) .map_err(|_| DecryptionError)?; Ok(plaintext) } } #[cfg(test)] mod tests { use super::{DecryptionError, Fernet, MultiFernet}; use serde_derive::Deserialize; use std::collections::HashSet; #[derive(Deserialize)] struct GenerateVector<'a> { token: &'a str, now: &'a str, iv: Vec, src: &'a str, secret: &'a str, } #[derive(Deserialize)] struct VerifyVector<'a> { token: &'a str, now: &'a str, ttl_sec: u64, src: &'a str, secret: &'a str, } #[derive(Deserialize, Debug)] struct InvalidVector<'a> { token: &'a str, now: &'a str, ttl_sec: u64, secret: &'a str, } #[test] fn test_generate_vectors() { let vectors: Vec = serde_json::from_str(include_str!("../tests/generate.json")).unwrap(); for v in vectors { let f = Fernet::new(v.secret).unwrap(); let token = f._encrypt_from_parts( v.src.as_bytes(), chrono::DateTime::parse_from_rfc3339(v.now) .unwrap() .timestamp() as u64, &v.iv, ); assert_eq!(token, v.token); } } #[test] fn test_verify_vectors() { let vectors: Vec = serde_json::from_str(include_str!("../tests/verify.json")).unwrap(); for v in vectors { let f = Fernet::new(v.secret).unwrap(); let decrypted = f._decrypt_at_time( v.token, Some(v.ttl_sec), chrono::DateTime::parse_from_rfc3339(v.now) .unwrap() .timestamp() as u64, ); assert_eq!(decrypted, Ok(v.src.as_bytes().to_vec())); } } #[test] fn test_invalid_vectors() { let vectors: Vec = serde_json::from_str(include_str!("../tests/invalid.json")).unwrap(); for v in vectors { let f = Fernet::new(v.secret).unwrap(); let decrypted = f._decrypt_at_time( v.token, Some(v.ttl_sec), chrono::DateTime::parse_from_rfc3339(v.now) .unwrap() .timestamp() as u64, ); assert_eq!(decrypted, Err(DecryptionError)); } } #[test] fn test_invalid() { let f = Fernet::new(&base64::encode_config(&vec![0; 32], base64::URL_SAFE)).unwrap(); // Invalid version byte assert_eq!( f.decrypt(&base64::encode_config(b"\x81", base64::URL_SAFE)), Err(DecryptionError) ); // Timestamp too short assert_eq!( f.decrypt(&base64::encode_config( b"\x80\x00\x00\x00", base64::URL_SAFE )), Err(DecryptionError) ); // Invalid base64 assert_eq!(f.decrypt("\x00"), Err(DecryptionError)); } #[test] fn test_roundtrips() { let f = Fernet::new(&base64::encode_config(&vec![0; 32], base64::URL_SAFE)).unwrap(); for val in [b"".to_vec(), b"Abc".to_vec(), b"\x00\xFF\x00\x00".to_vec()].iter() { assert_eq!(f.decrypt(&f.encrypt(&val)), Ok(val.clone())); } } #[test] fn test_new_errors() { assert!(Fernet::new("axxx").is_none()); assert!(Fernet::new(&base64::encode_config(&vec![0, 33], base64::URL_SAFE)).is_none()); assert!(Fernet::new(&base64::encode_config(&vec![0, 31], base64::URL_SAFE)).is_none()); } #[test] fn test_generate_key() { let mut keys = HashSet::new(); for _ in 0..1024 { keys.insert(Fernet::generate_key()); } assert_eq!(keys.len(), 1024); } #[test] fn test_generate_key_roundtrips() { let k = Fernet::generate_key(); let f1 = Fernet::new(&k).unwrap(); let f2 = Fernet::new(&k).unwrap(); for val in [b"".to_vec(), b"Abc".to_vec(), b"\x00\xFF\x00\x00".to_vec()].iter() { assert_eq!(f1.decrypt(&f2.encrypt(&val)), Ok(val.clone())); assert_eq!(f2.decrypt(&f1.encrypt(&val)), Ok(val.clone())); } } #[test] fn test_multi_encrypt() { let key1 = Fernet::generate_key(); let key2 = Fernet::generate_key(); let f1 = Fernet::new(&key1).unwrap(); let f2 = Fernet::new(&key2).unwrap(); let f = MultiFernet::new(vec![ Fernet::new(&key1).unwrap(), Fernet::new(&key2).unwrap(), ]); assert_eq!(f1.decrypt(&f.encrypt(b"abc")).unwrap(), b"abc".to_vec()); assert_eq!(f2.decrypt(&f.encrypt(b"abc")), Err(DecryptionError)); } #[test] fn test_multi_decrypt() { let key1 = Fernet::generate_key(); let key2 = Fernet::generate_key(); let f1 = Fernet::new(&key1).unwrap(); let f2 = Fernet::new(&key2).unwrap(); let f = MultiFernet::new(vec![ Fernet::new(&key1).unwrap(), Fernet::new(&key2).unwrap(), ]); assert_eq!(f.decrypt(&f1.encrypt(b"abc")).unwrap(), b"abc".to_vec()); assert_eq!(f.decrypt(&f2.encrypt(b"abc")).unwrap(), b"abc".to_vec()); assert_eq!(f.decrypt("\x00"), Err(DecryptionError)); } #[test] #[should_panic] fn test_multi_no_fernets() { MultiFernet::new(vec![]); } #[test] fn test_multi_roundtrips() { let f = MultiFernet::new(vec![Fernet::new(&Fernet::generate_key()).unwrap()]); for val in [b"".to_vec(), b"Abc".to_vec(), b"\x00\xFF\x00\x00".to_vec()].iter() { assert_eq!(f.decrypt(&f.encrypt(&val)), Ok(val.clone())); } } #[test] fn test_danger_timestamps() { use std::time; let key = Fernet::generate_key(); let f = Fernet::new(&key).unwrap(); let current_time = time::SystemTime::now() .duration_since(time::UNIX_EPOCH) .unwrap() .as_secs(); let good_time = current_time + 1; let exp_time = current_time + 60; assert_eq!( f._decrypt_at_time( &f._encrypt_at_time(b"abc", current_time), Some(30), good_time ) .unwrap(), b"abc".to_vec() ); assert_eq!( f._decrypt_at_time( &f._encrypt_at_time(b"abc", current_time), Some(30), exp_time ) .unwrap_err(), DecryptionError ); } } fernet-0.1.4/tests/generate.json000064400000000000000000000004740000000000000147220ustar 00000000000000[ { "token": "gAAAAAAdwJ6wAAECAwQFBgcICQoLDA0ODy021cpGVWKZ_eEwCGM4BLLF_5CV9dOPmrhuVUPgJobwOz7JcbmrR64jVmpU4IwqDA==", "now": "1985-10-26T01:20:00-07:00", "iv": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], "src": "hello", "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" } ] fernet-0.1.4/tests/invalid.json000064400000000000000000000042700000000000000145540ustar 00000000000000[ { "desc": "incorrect mac", "token": "gAAAAAAdwJ6xAAECAwQFBgcICQoLDA0OD3HkMATM5lFqGaerZ-fWPAl1-szkFVzXTuGb4hR8AKtwcaX1YdykQUFBQUFBQUFBQQ==", "now": "1985-10-26T01:20:01-07:00", "ttl_sec": 60, "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" }, { "desc": "too short", "token": "gAAAAAAdwJ6xAAECAwQFBgcICQoLDA0OD3HkMATM5lFqGaerZ-fWPA==", "now": "1985-10-26T01:20:01-07:00", "ttl_sec": 60, "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" }, { "desc": "invalid base64", "token": "%%%%%%%%%%%%%AECAwQFBgcICQoLDA0OD3HkMATM5lFqGaerZ-fWPAl1-szkFVzXTuGb4hR8AKtwcaX1YdykRtfsH-p1YsUD2Q==", "now": "1985-10-26T01:20:01-07:00", "ttl_sec": 60, "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" }, { "desc": "payload size not multiple of block size", "token": "gAAAAAAdwJ6xAAECAwQFBgcICQoLDA0OD3HkMATM5lFqGaerZ-fWPOm73QeoCk9uGib28Xe5vz6oxq5nmxbx_v7mrfyudzUm", "now": "1985-10-26T01:20:01-07:00", "ttl_sec": 60, "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" }, { "desc": "payload padding error", "token": "gAAAAAAdwJ6xAAECAwQFBgcICQoLDA0ODz4LEpdELGQAad7aNEHbf-JkLPIpuiYRLQ3RtXatOYREu2FWke6CnJNYIbkuKNqOhw==", "now": "1985-10-26T01:20:01-07:00", "ttl_sec": 60, "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" }, { "desc": "far-future TS (unacceptable clock skew)", "token": "gAAAAAAdwStRAAECAwQFBgcICQoLDA0OD3HkMATM5lFqGaerZ-fWPAnja1xKYyhd-Y6mSkTOyTGJmw2Xc2a6kBd-iX9b_qXQcw==", "now": "1985-10-26T01:20:01-07:00", "ttl_sec": 60, "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" }, { "desc": "expired TTL", "token": "gAAAAAAdwJ6xAAECAwQFBgcICQoLDA0OD3HkMATM5lFqGaerZ-fWPAl1-szkFVzXTuGb4hR8AKtwcaX1YdykRtfsH-p1YsUD2Q==", "now": "1985-10-26T01:21:31-07:00", "ttl_sec": 60, "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" }, { "desc": "incorrect IV (causes padding error)", "token": "gAAAAAAdwJ6xBQECAwQFBgcICQoLDA0OD3HkMATM5lFqGaerZ-fWPAkLhFLHpGtDBRLRTZeUfWgHSv49TF2AUEZ1TIvcZjK1zQ==", "now": "1985-10-26T01:20:01-07:00", "ttl_sec": 60, "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" } ] fernet-0.1.4/tests/verify.json000064400000000000000000000004150000000000000144270ustar 00000000000000[ { "token": "gAAAAAAdwJ6wAAECAwQFBgcICQoLDA0ODy021cpGVWKZ_eEwCGM4BLLF_5CV9dOPmrhuVUPgJobwOz7JcbmrR64jVmpU4IwqDA==", "now": "1985-10-26T01:20:01-07:00", "ttl_sec": 60, "src": "hello", "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" } ]