diff --git a/.github/workflows/benchmark.yaml b/.github/workflows/benchmark.yaml index 866f317..b5f1fe8 100644 --- a/.github/workflows/benchmark.yaml +++ b/.github/workflows/benchmark.yaml @@ -31,7 +31,7 @@ jobs: configuration: [release, debug] include: - os: ubuntu-latest - container: swiftlang/swift:nightly-6.4.x-noble + container: swift:6.4-noble steps: - name: Install dependencies (Linux) @@ -47,9 +47,8 @@ jobs: - name: Install Swift (macOS) if: ${{ runner.os == 'macOS' }} run: | - # Neither vapor/swiftly-action (Linux package managers only) nor swift-actions/setup-swift - # (hardcoded version table, no 6.4 yet) can install 6.4 on macOS, so drive swiftly directly: - # https://www.swift.org/install/macos/ + # vapor/swiftly-action only supports Linux package managers and swift-actions/setup-swift's + # hardcoded version table still lacks 6.4, so drive swiftly directly (https://www.swift.org/install/macos/). curl -sSL https://download.swift.org/swiftly/darwin/swiftly.pkg -o "${RUNNER_TEMP}/swiftly.pkg" installer -pkg "${RUNNER_TEMP}/swiftly.pkg" -target CurrentUserHomeDirectory ~/.swiftly/bin/swiftly init --assume-yes --skip-install --no-modify-profile --quiet-shell-followup diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 23c65f8..de63c5d 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -23,7 +23,7 @@ jobs: name: ${{ matrix.target }} runs-on: ubuntu-latest timeout-minutes: 40 - container: swiftlang/swift:nightly-6.4.x-noble + container: swift:6.4-noble strategy: fail-fast: false matrix: diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 33b3c3a..873d4d8 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -11,14 +11,25 @@ on: branches: [main] jobs: - unit-tests-linux: - name: Unit tests (Linux) - uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@main + test: + name: test + uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.15 with: - linux_swift_versions: '["nightly-6.4.x"]' + linux_swift_versions: '["6.4"]' linux_os_versions: '["noble"]' - enable_macos_checks: false - enable_windows_checks: false + enable_linux_static_sdk_build: true + linux_static_sdk_versions: '["6.4"]' + enable_wasm_sdk_build: true + wasm_sdk_versions: '["6.4"]' + enable_embedded_wasm_sdk_build: true + enable_android_sdk_build: true + android_sdk_versions: '["6.4"]' + # enable_macos_checks: true + # macos_xcode_versions: '["swift_6.4"]' + # enable_ios_checks: true + # ios_host_xcode_versions: '["swift_6.4"]' + enable_windows_checks: true + windows_swift_versions: '["nightly-6.4.x"]' unit-tests-macos: name: Unit tests (macOS) @@ -27,9 +38,6 @@ jobs: steps: - name: Install Swift run: | - # Neither vapor/swiftly-action (Linux package managers only) nor swift-actions/setup-swift - # (hardcoded version table, no 6.4 yet) can install 6.4 on macOS, so drive swiftly directly: - # https://www.swift.org/install/macos/ curl -sSL https://download.swift.org/swiftly/darwin/swiftly.pkg -o "${RUNNER_TEMP}/swiftly.pkg" installer -pkg "${RUNNER_TEMP}/swiftly.pkg" -target CurrentUserHomeDirectory ~/.swiftly/bin/swiftly init --assume-yes --skip-install --no-modify-profile --quiet-shell-followup @@ -40,7 +48,7 @@ jobs: echo "${SWIFTLY_BIN_DIR}" >> "${GITHUB_PATH}" swift --version - name: Check out code - uses: actions/checkout@v6 + uses: actions/checkout@v7 - name: Build run: swift build - name: Test @@ -52,7 +60,9 @@ jobs: with: format_check_enabled: true api_breakage_check_enabled: true - api_breakage_check_container_image: "swiftlang/swift:nightly-6.4.x-noble" + api_breakage_check_container_image: "swift:6.4-noble" + # Intentional pre-1.0 breaks; entries are removed once the next tag becomes the baseline. + api_breakage_check_allowlist_path: ".api-breakage-allowlist.txt" docs_check_enabled: false docs_check_analyze: false docs_check_macos_analyze: false diff --git a/LICENSE b/LICENSE index ec7490c..d907ad1 100644 --- a/LICENSE +++ b/LICENSE @@ -19,3 +19,68 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +-------------------------------------------------------------------------------- + +Third-party notices + +This package is a Swift port of the bcrypt password hashing implementation +and Blowfish block cipher from OpenBSD (lib/libc/crypt/bcrypt.c, +lib/libc/crypt/blowfish.c, include/blf.h). The original copyright and +permission notices are reproduced below, as their licenses require. + +bcrypt.c +-------- + +Copyright (c) 2014 Ted Unangst +Copyright (c) 1997 Niels Provos + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +This password hashing algorithm was designed by David Mazieres +. + +blowfish.c, blf.h +----------------- + +Blowfish block cipher for OpenBSD +Copyright 1997 Niels Provos +All rights reserved. + +Implementation advice by David Mazieres . + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The Blowfish code is derived from section 14.3 and the given source in +section V of Applied Cryptography, second edition. Blowfish is an +unpatented fast block cipher designed by Bruce Schneier. diff --git a/README.md b/README.md index 00646f5..32c04fd 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ A native, dependency and Foundation free Swift implementation of the bcrypt pass ## Installation ```swift -.package(url: "https://github.com/ptoffy/bcrypt.git", branch: "main") +.package(url: "https://github.com/ptoffy/bcrypt.git", branch: "0.4.0") ``` ```swift @@ -19,9 +19,12 @@ import Bcrypt let password = "password" let hash = try Bcrypt.hash(password: password) -let isValid = try Bcrypt.verify(password: password, hash: hash) +let isValid = try Bcrypt.verify(password: password, against: hash) ``` +> [!NOTE] +> Hashing passwords longer than 72 characters will result in a `.passwordTooLong` error, whereas verifying them will result in the excess characters being ignored. + ## Performance Benchmarks for hashing the password "password" at cost factor 12 using the @@ -34,9 +37,46 @@ func hash( into output: inout OutputSpan ) throws(BcryptError) ``` -API, compared to Vapor's C bcrypt ([vapor/authentication](https://github.com/vapor/authentication)), measured on an Apple M5 Pro with the [benchmark](https://github.com/ordo-one/benchmark) package. +API, compared to Vapor's C bcrypt ([vapor/authentication](https://github.com/vapor/authentication)) and the Rust [bcrypt](https://crates.io/crates/bcrypt) crate, measured on an Apple M5 Pro. The Swift rows use the [benchmark](https://github.com/ordo-one/benchmark) package; the Rust row uses `bcrypt::hash` (the `String`-returning API) in a plain timing loop with a counting global allocator, `lto = true` and `codegen-units = 1` for release. | | Release ms | Debug ms | Allocations Release | Allocations Debug | |------|------------|----------|---------------------|-------------------| -| vapor/authentication | 170ms | 270ms | 11 | 181 | | bcrypt | 149ms | 440ms | 0 | 0 | +| vapor/authentication | 170ms | 270ms | 11 | 181 | +| bcrypt (Rust 0.17) | 170ms | 650ms | 7 | 7 | + +## Security Information + +### Versions + +A bcrypt hash starts with a version prefix, chosen with the `version` parameter when hashing. All three compute exactly the same hash from the same password and salt; they differ only in the prefix and in how passwords longer than 72 bytes are treated. + +| Prefix | `BcryptVersion` | Origin | Passwords over 72 bytes | +|--------|-----------------|--------|-------------------------| +| `$2b$` | `.v2b` (default) | OpenBSD, 2014 | Rejected with `passwordTooLong` | +| `$2y$` | `.v2y` | PHP `password_hash`, Apache `htpasswd` | Rejected with `passwordTooLong` | +| `$2a$` | `.v2a` | Original 1999 revision | Silently truncated | + +`verify` accepts any of the three and keeps the prefix. Use the default unless you need to emit hashes for a system that only accepts a specific prefix. + +### Cost + +The cost is the base-2 logarithm of the number of key schedule rounds, so every increment doubles the time to hash and to verify. It ranges from 4 to 31; on an Apple M5 Pro in release builds: + +| Cost | Time | +|------|------| +| 4 | ~0.6 ms | +| 10 (default) | ~37 ms | +| 12 | ~150 ms | +| 14 | ~600 ms | +| 31 | ~22 hours | + +At this time 12 is considered a reasonable default cost factor for balancing security and performance. The cost is stored on the hash so verification of old hashes continues to work even if the default cost is increased in the future. + +### RNG + +Bcrypt relies on a secure random number generator (RNG) to generate salts for hashing passwords. This package currently uses `SystemRandomNumberGenerator`. + +### Zeroization + +Zeroization is the process of securely erasing sensitive data from memory, usually by overwriting it with zeros or random data before deallocating the memory. After using it, bcrypt zeroizes the key state which is derived from the password to ensure that no sensitive information remains in memory. The password itself is never copied so wiping it is the caller's responsibility. diff --git a/Sources/Bcrypt/Base64.swift b/Sources/Bcrypt/Base64.swift index 99b4ee2..57b2b7e 100644 --- a/Sources/Bcrypt/Base64.swift +++ b/Sources/Bcrypt/Base64.swift @@ -1,3 +1,7 @@ +// Ported from OpenBSD's bcrypt implementation (lib/libc/crypt/bcrypt.c). +// Copyright (c) 2014 Ted Unangst , Copyright (c) 1997 Niels Provos . +// Redistributed under the ISC license; the full notice is reproduced in LICENSE. + @usableFromInline enum Base64Error: Error { case invalidCharacter @@ -119,6 +123,10 @@ struct Base64 { } c4 = char64(of: s[off]) + if c4 == UInt8.max { + throw .invalidCharacter + } + off &+= 1 o = (c3 & 0x03) &<< 6 o |= c4 diff --git a/Sources/Bcrypt/Bcrypt.swift b/Sources/Bcrypt/Bcrypt.swift index aaa4d15..8d9ce4f 100644 --- a/Sources/Bcrypt/Bcrypt.swift +++ b/Sources/Bcrypt/Bcrypt.swift @@ -1 +1,48 @@ +/// A native Swift implementation of the bcrypt password hashing function. +/// +/// bcrypt derives a key from a password and a 128-bit salt with the EksBlowfish key schedule, whose cost +/// grows exponentially with the `cost` parameter, and encodes the result as a 60-character modular crypt +/// string: +/// +/// ``` +/// $2b$12$R9h/cIPz0gi.URNNX3kh2OPST9/PgBkqquzi.Ss7KIUgO2t0jWMUW +/// \__/\/ \____________________/\_____________________________/ +/// Alg Cost Salt Hash +/// ``` +/// +/// Use ``hash(password:cost:version:)-(String,_,_)`` to hash a new password with a random salt, and +/// ``verify(password:against:)-(String,_)`` to check a password against a stored hash. Both have overloads +/// for `[UInt8]` and `Span`; the `Span` overloads and +/// ``hash(password:cost:salt:version:into:)`` do not allocate. +/// +/// ## Password length +/// +/// bcrypt only keys on the first 72 bytes of the password (UTF-8 bytes), so anything past +/// that is not considered. To make sure no password is silently weakened, `hash` throws +/// ``BcryptError/passwordTooLong`` for longer inputs when creating ``BcryptVersion/v2b`` or +/// ``BcryptVersion/v2y`` hashes. `verify` instead truncates to 72 bytes, as OpenBSD, PHP and most other +/// implementations do when hashing, so hashes created elsewhere from longer passwords keep verifying. +/// +/// A trailing NUL byte in the password is treated as the C string terminator and not counted twice. +/// An empty password is rejected with ``BcryptError/emptyPassword``. +/// +/// ## Cost +/// +/// `cost` is the base-2 logarithm of the number of key schedule rounds and must be between 4 and 31. +/// Each increment doubles the time to hash and to verify; cost 12 takes around 150 ms on an Apple M5 Pro. +/// The default of 10 matches other implementations; 12 or more is recommended for new deployments. +/// +/// ## Salts and randomness +/// +/// Salts are 16 random bytes from `SystemRandomNumberGenerator`, which is backed by the platform's +/// cryptographic random source. Callers that supply their own salt must pass the 22-character +/// bcrypt-base64 encoding; the trailing bits that do not fit into 16 bytes are ignored and the salt +/// is re-encoded in the output. +/// +/// ## Timing +/// +/// Verification compares the full recomputed hash against the stored one without early exit. Malformed +/// hashes are rejected before any key schedule work is done, so invalid input costs nothing. The expanded +/// Blowfish state is zeroed after each hash; the password itself is never copied, so clearing it is the +/// caller's responsibility. public enum Bcrypt: Sendable {} diff --git a/Sources/Bcrypt/BcryptError.swift b/Sources/Bcrypt/BcryptError.swift index 8b9ba7d..8561e08 100644 --- a/Sources/Bcrypt/BcryptError.swift +++ b/Sources/Bcrypt/BcryptError.swift @@ -1,9 +1,19 @@ -public enum BcryptError: Error { +/// An error thrown by ``Bcrypt`` when a password, salt or hash cannot be processed. +@nonexhaustive public enum BcryptError: Error { + /// A caller-supplied salt is not exactly 22 characters long. case invalidSaltLength + /// A caller-supplied salt contains a character outside the bcrypt-base64 alphabet (`./A-Za-z0-9`). case invalidSalt + /// The hash passed to `verify` is not 60 characters long or does not have the `$2x$nn$` prefix layout. case invalidHash + /// The password is empty. case emptyPassword + /// The cost is outside the range 4...31, or the two cost digits in a hash are not decimal digits. case invalidCost + /// The password is longer than 72 bytes and the version is ``BcryptVersion/v2b`` or ``BcryptVersion/v2y``. + /// + /// Only thrown when creating a hash; `verify` truncates instead, see ``Bcrypt``. case passwordTooLong + /// The hash passed to `verify` starts with a version prefix other than `$2a$`, `$2b$` or `$2y$`. case invalidVersion } diff --git a/Sources/Bcrypt/BcryptVersion.swift b/Sources/Bcrypt/BcryptVersion.swift index 2858a38..e1d5f28 100644 --- a/Sources/Bcrypt/BcryptVersion.swift +++ b/Sources/Bcrypt/BcryptVersion.swift @@ -1,11 +1,27 @@ +/// The variant identifier written at the start of a bcrypt hash. +/// +/// All three variants compute the same hash from the same password and salt; they differ only in the +/// prefix and in how over-long passwords are treated. `verify` accepts any of them and preserves the +/// prefix, so a hash created with one variant round-trips unchanged. public enum BcryptVersion: Equatable, Sendable { + /// `$2a$`, the original 1999 revision. + /// + /// Passwords longer than 72 bytes are truncated rather than rejected, for compatibility with hashes + /// created by implementations that predate the length check. case v2a + /// `$2b$`, OpenBSD's 2014 revision and the default. + /// + /// Passwords longer than 72 bytes are rejected with ``BcryptError/passwordTooLong`` when hashing. case v2b + /// `$2y$`, the prefix used by PHP's `password_hash` and Apache `htpasswd`. + /// + /// Identical to ``v2b`` in every respect other than the prefix. + case v2y @usableFromInline var majorVersion: UInt8 { switch self { - case .v2a, .v2b: 0x32 + case .v2a, .v2b, .v2y: 0x32 } } @@ -14,6 +30,7 @@ public enum BcryptVersion: Equatable, Sendable { switch self { case .v2a: 0x61 case .v2b: 0x62 + case .v2y: 0x79 } } @@ -27,12 +44,14 @@ public enum BcryptVersion: Equatable, Sendable { guard identifier.count == 4 else { return nil } switch (identifier[0], identifier[1], identifier[2], identifier[3]) { case (0x24, 0x32, 0x61, 0x24): self = .v2a - case (0x24, 0x32, 0x62, 0x24), (0x24, 0x32, 0x79, 0x24): self = .v2b // 2y is an alias for 2b + case (0x24, 0x32, 0x62, 0x24): self = .v2b + case (0x24, 0x32, 0x79, 0x24): self = .v2y default: return nil } } } extension UInt8 { + @usableFromInline static let separator: UInt8 = 0x24 // $ } diff --git a/Sources/Bcrypt/Blowfish+InitialState.swift b/Sources/Bcrypt/Blowfish+InitialState.swift index 6bade41..b34192b 100644 --- a/Sources/Bcrypt/Blowfish+InitialState.swift +++ b/Sources/Bcrypt/Blowfish+InitialState.swift @@ -1,3 +1,7 @@ +// Ported from OpenBSD's Blowfish implementation (lib/libc/crypt/blowfish.c, include/blf.h). +// Copyright 1997 Niels Provos . All rights reserved. +// Redistributed under the BSD-3-Clause license; the full notice is reproduced in LICENSE. + extension EksBlowfish { @usableFromInline @inline(__always) diff --git a/Sources/Bcrypt/EksBlowfish.swift b/Sources/Bcrypt/EksBlowfish.swift index 559b6f4..36611cd 100644 --- a/Sources/Bcrypt/EksBlowfish.swift +++ b/Sources/Bcrypt/EksBlowfish.swift @@ -1,8 +1,12 @@ +// Ported from OpenBSD's Blowfish implementation (lib/libc/crypt/blowfish.c, include/blf.h). +// Copyright 1997 Niels Provos . All rights reserved. +// Redistributed under the BSD-3-Clause license; the full notice is reproduced in LICENSE. + /// EksBlowfish (Expensive key schedule Blowfish) is a block cipher based on Blowfish. /// /// This work is based on /// 1. Applied Cryptography, Second Edition by Bruce Schneier, section 14 and the corresponding code in Part V. -/// 2. The OpenBSD implementation of bcrypt at https://github.com/openbsd/src/blob/master/lib/libc/crypt/bcrypt.c. +/// 2. The OpenBSD implementation of Blowfish at https://github.com/openbsd/src/blob/master/lib/libc/crypt/blowfish.c. /// The function names and variable names are kept the same as in the OpenBSD implementation. @usableFromInline enum EksBlowfish { @usableFromInline static let N = 16 // Cipher Rounds @@ -21,7 +25,7 @@ expandState(password: password, salt: salt, p: &pSpan, s: &sSpan) - var i = 1 &<< cost + var i: UInt32 = 1 &<< cost while i > 0 { expand0State(key: password, nulTerminated: true, p: &pSpan, s: &sSpan) diff --git a/Sources/Bcrypt/Hasher.swift b/Sources/Bcrypt/Hasher.swift index 526dc79..b69d753 100644 --- a/Sources/Bcrypt/Hasher.swift +++ b/Sources/Bcrypt/Hasher.swift @@ -1,3 +1,7 @@ +// Ported from OpenBSD's bcrypt implementation (lib/libc/crypt/bcrypt.c). +// Copyright (c) 2014 Ted Unangst , Copyright (c) 1997 Niels Provos . +// Redistributed under the ISC license; the full notice is reproduced in LICENSE. + extension Bcrypt { /// "OrpheanBeholderScryDoubt" as six big-endian words; the block that bcrypt encrypts 64 times with the derived key. @usableFromInline static let cipherText: InlineArray<6, UInt32> = [ @@ -8,6 +12,7 @@ extension Bcrypt { @usableFromInline static let saltSpace = 22 @usableFromInline static let words = 6 @usableFromInline static let hashSpace = 60 + @usableFromInline static let maxPasswordLength = 72 /// Hashes a password using the bcrypt algorithm. /// - Parameters: @@ -119,8 +124,8 @@ extension Bcrypt { switch version { case .v2a: break - case .v2b: - guard key.count <= 72 else { + case .v2b, .v2y: + guard key.count <= Self.maxPasswordLength else { throw BcryptError.passwordTooLong } } @@ -130,10 +135,13 @@ extension Bcrypt { } var (p, s) = EksBlowfish.setup(password: key, salt: cSalt.span, cost: cost) - // these aren't actually being mutated but having them as Span instead would require - // us to have two separate encipher methods - let pSpan = p.mutableSpan - let sSpan = s.mutableSpan + var pSpan = p.mutableSpan + var sSpan = s.mutableSpan + + defer { + pSpan.zeroize() + sSpan.zeroize() + } var cData = Self.cipherText @@ -173,9 +181,9 @@ extension Bcrypt { output.append(36) - for index in salt.indices { - output.append(salt[index]) - } + // Re-encode the decoded salt rather than copying the input, so that a non-canonical final salt + // character (only its top two bits carry data) is normalised in the output, as OpenBSD does. + Base64.encode(cSalt.span, count: Self.maxSalt, into: &output) Base64.encode(cipherBytes.span, count: 4 * Self.words - 1, into: &output) } diff --git a/Sources/Bcrypt/MutableSpan+zeroize.swift b/Sources/Bcrypt/MutableSpan+zeroize.swift new file mode 100644 index 0000000..b032ffa --- /dev/null +++ b/Sources/Bcrypt/MutableSpan+zeroize.swift @@ -0,0 +1,12 @@ +extension MutableSpan { + /// Overwrites `buffer` with zeros in a way the optimizer cannot elide. + @_optimize(none) @inline(never) + @usableFromInline + mutating func zeroize() { + var i = 0 + while i < self.count { + unsafe self[unchecked: i] = 0 + i &+= 1 + } + } +} diff --git a/Sources/Bcrypt/Verifier.swift b/Sources/Bcrypt/Verifier.swift index fc2f64e..36965d6 100644 --- a/Sources/Bcrypt/Verifier.swift +++ b/Sources/Bcrypt/Verifier.swift @@ -1,3 +1,7 @@ +// Ported from OpenBSD's bcrypt implementation (lib/libc/crypt/bcrypt.c). +// Copyright (c) 2014 Ted Unangst , Copyright (c) 1997 Niels Provos . +// Redistributed under the ISC license; the full notice is reproduced in LICENSE. + extension Bcrypt { /// Verifies a password against a hash. /// - Parameters: @@ -48,8 +52,14 @@ extension Bcrypt { } let cost = tens * 10 + ones + guard hash[6] == UInt8.separator else { + throw BcryptError.invalidHash + } + + let key = password.count > Bcrypt.maxPasswordLength ? password.extracting(.. { outputSpan throws(BcryptError) in - try Bcrypt.hash(password: password, cost: cost, salt: hash.extracting(7..<29), version: version, into: &outputSpan) + try Bcrypt.hash(password: key, cost: cost, salt: hash.extracting(7..<29), version: version, into: &outputSpan) } return constantTimeEquals(newHash.span, hash) diff --git a/Tests/BcryptTests/BcryptTests.swift b/Tests/BcryptTests/BcryptTests.swift index db593ed..c400206 100644 --- a/Tests/BcryptTests/BcryptTests.swift +++ b/Tests/BcryptTests/BcryptTests.swift @@ -123,6 +123,36 @@ struct BcryptTests { #expect(throws: BcryptError.invalidVersion) { try Bcrypt.verify(password: "test", against: "$2z$10$" + String(repeating: "A", count: 53)) } + + #expect(throws: BcryptError.invalidHash) { + try Bcrypt.verify(password: "test", against: "$2a$10x" + String(repeating: "A", count: 53)) + } + } + + @Test("Verify $2y$ hash") + func verify2y() throws { + let hash = "$2y$12$3cVe95jlT26PkfwkJ1Jl4uHBWGEFfdI3L95clNilo3p82rLvh6GwK" + #expect(try Bcrypt.verify(password: "test", against: hash)) + #expect(try !Bcrypt.verify(password: "wrong", against: hash)) + #expect(try Bcrypt.hash(password: "test", cost: 4, version: .v2y).hasPrefix("$2y$04$")) + } + + @Test("Verify legacy hash of a password longer than 72 bytes") + func verifyLegacyLongPassword() throws { + let hash = "$2y$04$NpsZn6lJmcKCKlJWJMvLuuH/volE4xvrPM5Z0uMURrn3kPAgNiLvG" + #expect(try Bcrypt.verify(password: String(repeating: "a", count: 73), against: hash)) + #expect(try Bcrypt.verify(password: String(repeating: "a", count: 72), against: hash)) + #expect(try !Bcrypt.verify(password: String(repeating: "a", count: 71), against: hash)) + } + + @Test("Non-canonical salt is normalised in the output") + func nonCanonicalSalt() throws { + let canonical = "abcdefghijklmnopqrstue" // 'e' = 0b100000 + let nonCanonical = "abcdefghijklmnopqrstuf" // 'f' = 0b100001 + let h1 = try Bcrypt.hash(password: Array("x".utf8), cost: 4, salt: Array(canonical.utf8)) + let h2 = try Bcrypt.hash(password: Array("x".utf8), cost: 4, salt: Array(nonCanonical.utf8)) + #expect(h1 == h2) + #expect(String(decoding: h1, as: UTF8.self).hasPrefix("$2b$04$" + canonical)) } @Test("Property: Any valid password should hash and verify", arguments: 1...100)