Packet.swift, Framing.swift, MagicHash.swift, CipherStream.swift in MWBCore, each constant cited to the Windows source.
114 lines
4.7 KiB
Swift
114 lines
4.7 KiB
Swift
// Everything derived from the security key string itself: the magic number
|
|
// that frames every packet, and the key's validity, generation and display
|
|
// rules. See docs/protocol.md §2.1 and §2.4.
|
|
//
|
|
// Ported from App/Core/Encryption.cs.
|
|
|
|
import CryptoKit
|
|
import Foundation
|
|
|
|
/// The 32-bit magic number derived from the security key.
|
|
///
|
|
/// Only its top 16 bits go on the wire (`Framing`), but the whole value is
|
|
/// what a peer compares against, so it must be reproduced bit for bit.
|
|
public enum MagicHash {
|
|
/// Number of times the SHA-512 digest is re-hashed after the first pass
|
|
/// (`Encryption.cs:192`); 50 001 digests in total.
|
|
private static let rehashRounds = 50_000
|
|
|
|
/// `Get24BitHash(key)` (`Encryption.cs:173-200`).
|
|
///
|
|
/// The key is written into a fixed 32-byte zero buffer, one byte per
|
|
/// UTF-16 code unit **truncated to eight bits** (`Encryption.cs:185`), so
|
|
/// a non-ASCII key hashes to whatever the low bytes of its code units are —
|
|
/// matching Windows rather than being correct.
|
|
public static func magicNumber(for key: String) -> UInt32 {
|
|
guard !key.isEmpty else { return 0 } // Encryption.cs:175-178
|
|
|
|
var buffer = [UInt8](repeating: 0, count: packageSize) // Encryption.cs:180
|
|
for (i, unit) in key.utf16.enumerated() {
|
|
guard i < packageSize else { break } // Encryption.cs:181-183
|
|
buffer[i] = UInt8(truncatingIfNeeded: unit)
|
|
}
|
|
|
|
var digest = [UInt8](SHA512.hash(data: buffer))
|
|
for _ in 0..<rehashRounds {
|
|
digest = [UInt8](SHA512.hash(data: digest))
|
|
}
|
|
|
|
// Encryption.cs:199. `hashValue[0] << 23`, not << 24: the first two
|
|
// terms overlap at bit 23 and the sum carries. The C# expression is
|
|
// `int` arithmetic in an unchecked context and does overflow, so the
|
|
// additions wrap; `&+` on UInt32 gives the same 32 bits.
|
|
let high = UInt32(digest[0]) << 23
|
|
let mid = UInt32(digest[1]) << 16
|
|
let last = UInt32(digest[digest.count - 1]) << 8 // hashValue[^1], i.e. byte 63
|
|
return high &+ mid &+ last &+ UInt32(digest[2])
|
|
}
|
|
}
|
|
|
|
/// The rules the security key itself has to follow: length, generation and
|
|
/// the grouped form shown to the user (`Encryption.cs:65-79, 202-242`).
|
|
public enum SecurityKey {
|
|
/// Minimum key length in characters (`Encryption.cs:237`, `PW_LENGTH`
|
|
/// at `Encryption.cs:207`).
|
|
public static let minimumLength = 16
|
|
|
|
/// The four character sets a generated key draws from, in order
|
|
/// (`Encryption.cs:212`). `"` `'` `` ` `` `O` `0` and `&` are left out
|
|
/// because they confuse users.
|
|
private static let charsets = [
|
|
"abcdefghjkmnpqrstuvxyz",
|
|
"ABCDEFGHJKMNPQRSTUVXYZ",
|
|
"123456789",
|
|
"~!@#$%^*()_-+=:;<,>.?/\\|[]",
|
|
]
|
|
|
|
/// Whether a key may be used; validation is length-only, as on Windows
|
|
/// (`Encryption.cs:235-242`). There is no weak-key or charset check there
|
|
/// and adding one here would reject keys a Windows peer accepts.
|
|
public static func isValid(_ key: String) -> Bool {
|
|
key.count >= minimumLength
|
|
}
|
|
|
|
/// A key as typed by the user, with all whitespace discarded
|
|
/// (`Form/Settings/SetupPage2a.cs:92`) — the same normalisation that makes
|
|
/// the grouped `displayText` form safe to copy between machines.
|
|
public static func normalize(_ typed: String) -> String {
|
|
typed.filter { !$0.isWhitespace }
|
|
}
|
|
|
|
/// A fresh 16-character key, one character taken round-robin from each of
|
|
/// the four sets (`Encryption.cs:209-233`).
|
|
///
|
|
/// Windows takes a random byte and reduces it modulo the set size, which is
|
|
/// slightly biased; `randomElement()` over `SystemRandomNumberGenerator` is
|
|
/// not, and nothing on the wire depends on how the key was chosen.
|
|
public static func random() -> String {
|
|
var key = ""
|
|
while key.count < minimumLength {
|
|
for set in charsets {
|
|
guard let c = set.randomElement() else { continue }
|
|
key.append(c)
|
|
if key.count >= minimumLength { break } // Encryption.cs:224-227
|
|
}
|
|
}
|
|
return key
|
|
}
|
|
|
|
/// The key in groups of four separated by two spaces, as the Windows UI
|
|
/// shows it (`KeyDisplayedText`, `Encryption.cs:65-79`). `normalize`
|
|
/// reverses it.
|
|
public static func displayText(_ key: String) -> String {
|
|
let chars = Array(key)
|
|
var out = ""
|
|
var i = 0
|
|
repeat {
|
|
let end = min(i + 4, chars.count)
|
|
out += String(chars[i..<end]) + " "
|
|
i += 4
|
|
} while i < chars.count - 1 // Encryption.cs:76
|
|
return out.trimmingCharacters(in: .whitespaces)
|
|
}
|
|
}
|