packages feed

nova-cache-0.14.0.1 / src / NovaCache / Signing.hs

-- | Ed25519 signing and verification for Nix binary cache.---- Nix signs narinfo fingerprints with Ed25519. Keys are stored as-- @name:base64@ pairs. The fingerprint is a semicolon-delimited string:---- @1;\<StorePath\>;\<NarHash\>;\<NarSize\>;\<comma-separated-refs\>@module NovaCache.Signing  ( SecretKey (..),    PublicKey (..),    parseSecretKey,    parsePublicKey,    normalizeKeyText,    toPublicKey,    renderPublicKey,    fingerprint,    sign,    verify,  )whereimport Crypto.Error (CryptoFailable (..))import qualified Crypto.PubKey.Ed25519 as Ed25519import Data.ByteArray (constEq, convert)import Data.ByteString (ByteString)import qualified Data.ByteString as BSimport qualified Data.ByteString.Base64 as B64import qualified Data.Set as Setimport Data.Text (Text)import qualified Data.Text as Timport qualified Data.Text.Encoding as TEimport NovaCache.NarInfo (NarInfo (..))-- ----------------------------------------------------------------------------- Types-- ----------------------------------------------------------------------------- | An Ed25519 secret key with its key name.data SecretKey = SecretKey  { skName :: !Text,    skBytes :: !ByteString  }-- | Renders the key NAME only.  The secret bytes must never be-- reachable through 'Show': any enclosing type deriving 'Show' (a-- config record, a debug trace, an error formatter) would otherwise-- render them.  Deliberately not read-back-able.instance Show SecretKey where  show (SecretKey keyName _) = "SecretKey " ++ show keyName ++ " <redacted>"-- | The name compares normally (it is public); the key bytes compare in-- constant time - equality over secret material must not be-- timing-dependent.instance Eq SecretKey where  SecretKey nameA bytesA == SecretKey nameB bytesB =    nameA == nameB && constEq bytesA bytesB-- | An Ed25519 public key with its key name.data PublicKey = PublicKey  { pkName :: !Text,    pkBytes :: !ByteString  }  deriving (Eq, Show)-- ----------------------------------------------------------------------------- Constants-- ----------------------------------------------------------------------------- | Size of an Ed25519 secret key: 32-byte seed + 32-byte public half.ed25519SecretKeySize :: Inted25519SecretKeySize = 64-- | Size of an Ed25519 public key.ed25519PublicKeySize :: Inted25519PublicKeySize = 32-- | Size of the Ed25519 seed (first half of the secret key).ed25519SeedSize :: Inted25519SeedSize = 32-- | Key separator in @name:base64@ format.keySeparator :: TextkeySeparator = ":"-- | Fingerprint version tag.fingerprintVersion :: TextfingerprintVersion = "1"-- | Fingerprint field separator.fingerprintSep :: TextfingerprintSep = ";"-- | Reference separator within a fingerprint.referenceSep :: TextreferenceSep = ","-- | The Unicode byte-order mark.  Windows tooling (PowerShell pipes and-- redirects in particular) prepends it to text in transit; it is never-- legal key material.bomChar :: CharbomChar = '\xFEFF'-- ----------------------------------------------------------------------------- Key parsing-- ----------------------------------------------------------------------------- | Normalize key text picked up from an environment variable or a file:-- drop byte-order marks and surrounding whitespace.  'T.strip' alone is not-- enough - a BOM is not whitespace, so it survives stripping and silently-- corrupts the key.  None of the dropped characters can be legitimate key-- material, so normalizing is always safe.normalizeKeyText :: Text -> TextnormalizeKeyText = T.strip . T.filter (/= bomChar)-- | Parse a @name:base64@ secret key string.parseSecretKey :: Text -> Either String SecretKeyparseSecretKey txt = do  (keyName, decoded) <- splitAndDecode txt "secret key"  expectSize ed25519SecretKeySize "secret key" decoded  pure SecretKey {skName = keyName, skBytes = decoded}-- | Parse a @name:base64@ public key string.parsePublicKey :: Text -> Either String PublicKeyparsePublicKey txt = do  (keyName, decoded) <- splitAndDecode txt "public key"  expectSize ed25519PublicKeySize "public key" decoded  pure PublicKey {pkName = keyName, pkBytes = decoded}-- | Derive the public key corresponding to a secret key, keeping the name.---- The 64-byte secret key carries the public half in its second half, but-- deriving from the seed through the crypto library validates the key-- material instead of trusting it.toPublicKey :: SecretKey -> Either String PublicKeytoPublicKey (SecretKey keyName secretBytes) = do  sk <- cryptoSecretKey (BS.take ed25519SeedSize secretBytes)  pure PublicKey {pkName = keyName, pkBytes = convert (Ed25519.toPublic sk)}-- | Render a public key in Nix's @name:base64@ trust-anchor format - the-- exact string a client puts in @trusted-public-keys@.renderPublicKey :: PublicKey -> TextrenderPublicKey (PublicKey keyName bytes) =  keyName <> keySeparator <> TE.decodeLatin1 (B64.encode bytes)-- | Split a @name:base64@ string and decode the base64 payload.-- An empty name or empty payload is corrupt, as upstream's Key-- constructor treats it: an empty-named key would sign every narinfo-- with @:sig@ lines no client's named trust anchor can ever match, so-- the misconfiguration must fail at key-load time, not as silent-- signature rejection downstream.splitAndDecode :: Text -> String -> Either String (Text, ByteString)splitAndDecode txt label = case T.breakOn keySeparator txt of  (keyName, rest)    | T.null rest -> Left (label ++ " missing ':' separator")    | T.null keyName -> Left (label ++ " has an empty name before ':'")    | T.null encoded -> Left (label ++ " has empty key material after ':'")    | otherwise -> do        decoded <- decodeBase64 encoded        pure (keyName, decoded)    where      encoded = T.drop 1 rest-- | Assert that decoded bytes have the expected size.expectSize :: Int -> String -> ByteString -> Either String ()expectSize expected label bs  | BS.length bs == expected = Right ()  | otherwise =      Left        ( "expected "            ++ show expected            ++ "-byte "            ++ label            ++ ", got "            ++ show (BS.length bs)        )-- ----------------------------------------------------------------------------- Fingerprint-- ----------------------------------------------------------------------------- | Construct the fingerprint string for a narinfo.---- Format: @1;\<StorePath\>;\<NarHash\>;\<NarSize\>;\<ref1,ref2,...\>@fingerprint :: NarInfo -> Textfingerprint ni =  T.intercalate    fingerprintSep    [ fingerprintVersion,      niStorePath ni,      niNarHash ni,      T.pack (show (niNarSize ni)),      T.intercalate referenceSep (map (storeDir <>) sortedReferences)    ]  where    -- References in a narinfo are basenames, but the fingerprint signs them as    -- full store paths (/nix/store/<hash>-<name>), matching C++ Nix.  The store    -- directory is the leading path of the (already absolute) niStorePath.    storeDir = T.dropWhileEnd (/= '/') (niStorePath ni)    -- C++ Nix fingerprints a StorePathSet - references sorted by basename,    -- deduplicated - so the narinfo's file order must not leak into the    -- signature: real Nix clients always verify against the sorted form.    sortedReferences = Set.toAscList (Set.fromList (niReferences ni))-- ----------------------------------------------------------------------------- Signing and verification-- ----------------------------------------------------------------------------- | Sign a narinfo, producing a @keyname:base64sig@ string.sign :: SecretKey -> NarInfo -> Either String Textsign (SecretKey keyName secretBytes) ni = do  sk <- cryptoSecretKey (BS.take ed25519SeedSize secretBytes)  let pk = Ed25519.toPublic sk      msg = TE.encodeUtf8 (fingerprint ni)      sig = Ed25519.sign sk pk msg      sigB64 = TE.decodeLatin1 (B64.encode (convert sig))  pure (keyName <> keySeparator <> sigB64)-- | Verify a @keyname:base64sig@ signature against a narinfo and public key.---- The signature's key name must match this key's name (Nix looks the public key-- up BY name) before the Ed25519 check runs.  Returns 'False' for any malformed-- or non-matching input rather than failing.verify :: PublicKey -> NarInfo -> Text -> Boolverify (PublicKey trustedName pubBytes) ni sigLine =  case T.breakOn keySeparator sigLine of    (sigName, sigRest)      | T.null sigRest || sigName /= trustedName -> False      | otherwise -> case extractSignaturePayload sigLine of          Nothing -> False          Just sigRaw -> verifyRaw pubBytes (TE.encodeUtf8 (fingerprint ni)) sigRaw-- | Extract the raw signature bytes from a @keyname:base64sig@ line.extractSignaturePayload :: Text -> Maybe ByteStringextractSignaturePayload sigLine = case T.breakOn keySeparator sigLine of  (_, rest)    | T.null rest -> Nothing    | otherwise -> either (const Nothing) Just (decodeBase64 (T.drop 1 rest))-- | Low-level Ed25519 verification of raw bytes.verifyRaw :: ByteString -> ByteString -> ByteString -> BoolverifyRaw pubBytes msg sigBytes =  case (cryptoPublicKey pubBytes, cryptoSignature sigBytes) of    (Right pk, Right sig) -> Ed25519.verify pk msg sig    _ -> False-- ----------------------------------------------------------------------------- Cryptographic primitives (thin wrappers over crypton)-- ----------------------------------------------------------------------------- | Decode base64 text to bytes.decodeBase64 :: Text -> Either String ByteStringdecodeBase64 = B64.decode . TE.encodeUtf8-- | Lift a 'CryptoFailable' to 'Either' with a descriptive label.liftCrypto :: String -> CryptoFailable a -> Either String aliftCrypto _ (CryptoPassed x) = Right xliftCrypto label (CryptoFailed err) = Left ("invalid " ++ label ++ ": " ++ show err)-- | Parse raw bytes as an Ed25519 secret key.cryptoSecretKey :: ByteString -> Either String Ed25519.SecretKeycryptoSecretKey = liftCrypto "Ed25519 secret key" . Ed25519.secretKey-- | Parse raw bytes as an Ed25519 public key.cryptoPublicKey :: ByteString -> Either String Ed25519.PublicKeycryptoPublicKey = liftCrypto "Ed25519 public key" . Ed25519.publicKey-- | Parse raw bytes as an Ed25519 signature.cryptoSignature :: ByteString -> Either String Ed25519.SignaturecryptoSignature = liftCrypto "Ed25519 signature" . Ed25519.signature