-
Notifications
You must be signed in to change notification settings - Fork 40
/
Class.hs
585 lines (492 loc) · 17.9 KB
/
Class.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
-- | Abstract key evolving signatures.
module Cardano.Crypto.KES.Class
(
-- * KES algorithm class
KESAlgorithm (..)
, genKeyKES
, updateKES
, forgetSignKeyKES
, Period
, OptimizedKESAlgorithm (..)
, verifyOptimizedKES
-- * 'SignKeyWithPeriodKES' wrapper
, SignKeyWithPeriodKES (..)
, updateKESWithPeriod
-- * 'SignedKES' wrapper
, SignedKES (..)
, signedKES
, verifySignedKES
-- * CBOR encoding and decoding
, encodeVerKeyKES
, decodeVerKeyKES
, encodeSigKES
, decodeSigKES
, encodeSignedKES
, decodeSignedKES
-- * Encoded 'Size' expressions
, encodedVerKeyKESSizeExpr
, encodedSignKeyKESSizeExpr
, encodedSigKESSizeExpr
-- * Raw sizes
, sizeVerKeyKES
, sizeSigKES
, sizeSignKeyKES
, seedSizeKES
-- * Unsound APIs
, UnsoundKESAlgorithm (..)
, encodeSignKeyKES
, decodeSignKeyKES
, rawDeserialiseSignKeyKES
, UnsoundPureKESAlgorithm (..)
, unsoundPureSignedKES
, encodeUnsoundPureSignKeyKES
, decodeUnsoundPureSignKeyKES
-- * Utility functions
-- These are used between multiple KES implementations. User code will
-- most likely not need these, but they are required for recursive
-- definitions of the SumKES algorithms, and can be expressed entirely in
-- terms of the KES, DSIGN and Hash typeclasses, so we keep them here for
-- convenience.
, hashPairOfVKeys
, mungeName
)
where
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Kind (Type)
import Data.Proxy (Proxy(..))
import Data.Typeable (Typeable)
import GHC.Exts (Constraint)
import GHC.Generics (Generic)
import GHC.Stack
import GHC.TypeLits (Nat, KnownNat, natVal, TypeError, ErrorMessage (..))
import NoThunks.Class (NoThunks)
import Control.Monad.Class.MonadST (MonadST)
import Control.Monad.Class.MonadThrow (MonadThrow)
import Control.Monad.Trans.Maybe (MaybeT (..), runMaybeT)
import Cardano.Binary (Decoder, decodeBytes, Encoding, encodeBytes, Size, withWordSize)
import Cardano.Crypto.Util (Empty)
import Cardano.Crypto.Libsodium.MLockedSeed
import Cardano.Crypto.Libsodium (MLockedAllocator, mlockedMalloc)
import Cardano.Crypto.Hash.Class (HashAlgorithm, Hash, hashWith)
import Cardano.Crypto.DSIGN.Class (failSizeCheck)
import Cardano.Crypto.Seed
class ( Typeable v
, Show (VerKeyKES v)
, Eq (VerKeyKES v)
, Show (SigKES v)
, Eq (SigKES v)
, NoThunks (SigKES v)
, NoThunks (SignKeyKES v)
, NoThunks (VerKeyKES v)
, KnownNat (SeedSizeKES v)
, KnownNat (SizeVerKeyKES v)
, KnownNat (SizeSignKeyKES v)
, KnownNat (SizeSigKES v)
)
=> KESAlgorithm v where
--
-- Key and signature types
--
data VerKeyKES v :: Type
data SigKES v :: Type
data SignKeyKES v :: Type
type SeedSizeKES v :: Nat
type SizeVerKeyKES v :: Nat
type SizeSignKeyKES v :: Nat
type SizeSigKES v :: Nat
--
-- Metadata and basic key operations
--
algorithmNameKES :: proxy v -> String
hashVerKeyKES :: HashAlgorithm h => VerKeyKES v -> Hash h (VerKeyKES v)
hashVerKeyKES = hashWith rawSerialiseVerKeyKES
-- | Context required to run the KES algorithm
--
-- Unit by default (no context required)
type ContextKES v :: Type
type ContextKES v = ()
type Signable v :: Type -> Constraint
type Signable v = Empty
--
-- Core algorithm operations
--
-- | Full KES verification. This method checks that the signature itself
-- checks out (as per 'verifySigKES'), and also makes sure that it matches
-- the provided VerKey.
verifyKES
:: (Signable v a, HasCallStack)
=> ContextKES v
-> VerKeyKES v
-> Period -- ^ The /current/ period for the key
-> a
-> SigKES v
-> Either String ()
-- | Return the total number of KES periods supported by this algorithm. The
-- KES algorithm is assumed to support a fixed maximum number of periods, not
-- a variable number.
--
-- Do note that this is the total number of /periods/ not the total number of
-- evolutions. The difference is off-by-one. For example if there are 2
-- periods (period 0 and 1) then there is only one evolution.
--
totalPeriodsKES
:: proxy v -> Word
--
-- Serialisation/(de)serialisation in fixed-size raw format
--
rawSerialiseVerKeyKES :: VerKeyKES v -> ByteString
rawSerialiseSigKES :: SigKES v -> ByteString
rawDeserialiseVerKeyKES :: ByteString -> Maybe (VerKeyKES v)
rawDeserialiseSigKES :: ByteString -> Maybe (SigKES v)
deriveVerKeyKES :: (MonadST m, MonadThrow m) => SignKeyKES v -> m (VerKeyKES v)
--
-- Core algorithm operations
--
signKES
:: forall a m. (Signable v a, MonadST m, MonadThrow m)
=> ContextKES v
-> Period -- ^ The /current/ period for the key
-> a
-> SignKeyKES v
-> m (SigKES v)
updateKESWith
:: (MonadST m, MonadThrow m)
=> MLockedAllocator m
-> ContextKES v
-> SignKeyKES v
-> Period -- ^ The /current/ period for the key, not the target period.
-> m (Maybe (SignKeyKES v))
genKeyKESWith
:: (MonadST m, MonadThrow m)
=> MLockedAllocator m
-> MLockedSeed (SeedSizeKES v)
-> m (SignKeyKES v)
--
-- Secure forgetting
--
-- | Forget a signing key synchronously, rather than waiting for GC. In some
-- non-mock instances this provides a guarantee that the signing key is no
-- longer in memory.
--
-- The precondition is that this key value will not be used again.
--
forgetSignKeyKESWith
:: (MonadST m, MonadThrow m)
=> MLockedAllocator m
-> SignKeyKES v
-> m ()
sizeVerKeyKES :: forall v proxy. KESAlgorithm v => proxy v -> Word
sizeVerKeyKES _ = fromInteger (natVal (Proxy @(SizeVerKeyKES v)))
sizeSigKES :: forall v proxy. KESAlgorithm v => proxy v -> Word
sizeSigKES _ = fromInteger (natVal (Proxy @(SizeSigKES v)))
sizeSignKeyKES :: forall v proxy. KESAlgorithm v => proxy v -> Word
sizeSignKeyKES _ = fromInteger (natVal (Proxy @(SizeSignKeyKES v)))
-- | The upper bound on the 'Seed' size needed by 'genKeyKES'
seedSizeKES :: forall v proxy. KESAlgorithm v => proxy v -> Word
seedSizeKES _ = fromInteger (natVal (Proxy @(SeedSizeKES v)))
-- | Forget a signing key synchronously, rather than waiting for GC. In some
-- non-mock instances this provides a guarantee that the signing key is no
-- longer in memory.
--
-- The precondition is that this key value will not be used again.
--
forgetSignKeyKES
:: (KESAlgorithm v, MonadST m, MonadThrow m)
=> SignKeyKES v
-> m ()
forgetSignKeyKES = forgetSignKeyKESWith mlockedMalloc
-- | Key generation
--
genKeyKES
:: forall v m. (KESAlgorithm v, MonadST m, MonadThrow m)
=> MLockedSeed (SeedSizeKES v)
-> m (SignKeyKES v)
genKeyKES = genKeyKESWith mlockedMalloc
-- | Update the KES signature key to the /next/ period, given the /current/
-- period.
--
-- It returns 'Nothing' if the cannot be evolved any further.
--
-- The precondition (to get a 'Just' result) is that the current KES period
-- of the input key is not the last period. The given period must be the
-- current KES period of the input key (not the next or target).
--
-- The postcondition is that in case a key is returned, its current KES
-- period is incremented by one compared to before.
--
-- Note that you must track the current period separately, and to skip to a
-- later period requires repeated use of this function, since it only
-- increments one period at once.
--
updateKES
:: forall v m. (KESAlgorithm v, MonadST m, MonadThrow m)
=> ContextKES v
-> SignKeyKES v
-> Period -- ^ The /current/ period for the key, not the target period.
-> m (Maybe (SignKeyKES v))
updateKES = updateKESWith mlockedMalloc
-- | Pure implementations of the core KES operations. These are unsound, because
-- proper handling of KES secrets (seeds, sign keys) requires mlocking and
-- deterministic erasure (\"secure forgetting\"), which is not possible in pure
-- code.
-- This API is only provided for testing purposes; it must not be used to
-- generate or use real KES keys.
class KESAlgorithm v => UnsoundPureKESAlgorithm v where
data UnsoundPureSignKeyKES v :: Type
unsoundPureSignKES
:: forall a. (Signable v a)
=> ContextKES v
-> Period -- ^ The /current/ period for the key
-> a
-> UnsoundPureSignKeyKES v
-> SigKES v
unsoundPureUpdateKES
:: ContextKES v
-> UnsoundPureSignKeyKES v
-> Period -- ^ The /current/ period for the key, not the target period.
-> Maybe (UnsoundPureSignKeyKES v)
unsoundPureGenKeyKES
:: Seed
-> UnsoundPureSignKeyKES v
unsoundPureDeriveVerKeyKES
:: UnsoundPureSignKeyKES v
-> VerKeyKES v
unsoundPureSignKeyKESToSoundSignKeyKES
:: (MonadST m, MonadThrow m)
=> UnsoundPureSignKeyKES v
-> m (SignKeyKES v)
rawSerialiseUnsoundPureSignKeyKES :: UnsoundPureSignKeyKES v -> ByteString
rawDeserialiseUnsoundPureSignKeyKES :: ByteString -> Maybe (UnsoundPureSignKeyKES v)
-- | Unsound operations on KES sign keys. These operations violate secure
-- forgetting constraints by leaking secrets to unprotected memory. Consider
-- using the 'DirectSerialise' / 'DirectDeserialise' APIs instead.
class KESAlgorithm v => UnsoundKESAlgorithm v where
rawDeserialiseSignKeyKESWith :: (MonadST m, MonadThrow m)
=> MLockedAllocator m
-> ByteString
-> m (Maybe (SignKeyKES v))
rawSerialiseSignKeyKES :: (MonadST m, MonadThrow m) => SignKeyKES v -> m ByteString
rawDeserialiseSignKeyKES ::
(UnsoundKESAlgorithm v, MonadST m, MonadThrow m)
=> ByteString
-> m (Maybe (SignKeyKES v))
rawDeserialiseSignKeyKES = rawDeserialiseSignKeyKESWith mlockedMalloc
-- | Subclass for KES algorithms that embed a copy of the VerKey into the
-- signature itself, rather than relying on the externally supplied VerKey
-- alone. Some optimizations made in the 'Cardano.Crypto.KES.CompactSingleKES'
-- and 'Cardano.Crypto.KES.CompactSumKES' implementations require this
-- additional interface in order to avoid redundant computations.
class KESAlgorithm v => OptimizedKESAlgorithm v where
-- | Partial verification: this method only verifies the signature itself,
-- but it does not check it against any externally-provided VerKey. Use
-- 'verifyKES' for full KES verification.
verifySigKES
:: (Signable v a, HasCallStack)
=> ContextKES v
-> Period -- ^ The /current/ period for the key
-> a
-> SigKES v
-> Either String ()
-- | Extract a VerKey from a SigKES. Note that a VerKey embedded in or
-- derived from a SigKES is effectively user-supplied, so it is not enough
-- to validate a SigKES against this VerKey (like 'verifySigKES' does); you
-- must also compare the VerKey against an externally-provided key that you
-- want to verify against (see 'verifyKES').
verKeyFromSigKES
:: ContextKES v
-> Period
-> SigKES v
-> VerKeyKES v
verifyOptimizedKES :: (OptimizedKESAlgorithm v, Signable v a, HasCallStack)
=> ContextKES v
-> VerKeyKES v
-> Period
-> a
-> SigKES v
-> Either String ()
verifyOptimizedKES ctx vk t a sig = do
verifySigKES ctx t a sig
let vk' = verKeyFromSigKES ctx t sig
if vk' == vk then
return ()
else
Left "KES verification failed"
--
-- Do not provide Ord instances for keys, see #38
--
instance ( TypeError ('Text "Ord not supported for signing keys, use the hash instead")
, Eq (SignKeyKES v)
)
=> Ord (SignKeyKES v) where
compare = error "unsupported"
instance ( TypeError ('Text "Ord not supported for verification keys, use the hash instead")
, KESAlgorithm v
)
=> Ord (VerKeyKES v) where
compare = error "unsupported"
--
-- Convenient CBOR encoding/decoding
--
-- Implementations in terms of the raw (de)serialise
--
encodeVerKeyKES :: KESAlgorithm v => VerKeyKES v -> Encoding
encodeVerKeyKES = encodeBytes . rawSerialiseVerKeyKES
encodeUnsoundPureSignKeyKES :: UnsoundPureKESAlgorithm v => UnsoundPureSignKeyKES v -> Encoding
encodeUnsoundPureSignKeyKES = encodeBytes . rawSerialiseUnsoundPureSignKeyKES
encodeSigKES :: KESAlgorithm v => SigKES v -> Encoding
encodeSigKES = encodeBytes . rawSerialiseSigKES
encodeSignKeyKES ::
forall v m. (UnsoundKESAlgorithm v, MonadST m, MonadThrow m)
=> SignKeyKES v
-> m Encoding
encodeSignKeyKES = fmap encodeBytes . rawSerialiseSignKeyKES
decodeVerKeyKES :: forall v s. KESAlgorithm v => Decoder s (VerKeyKES v)
decodeVerKeyKES = do
bs <- decodeBytes
case rawDeserialiseVerKeyKES bs of
Just vk -> return vk
Nothing -> failSizeCheck "decodeVerKeyKES" "key" bs (sizeVerKeyKES (Proxy :: Proxy v))
{-# INLINE decodeVerKeyKES #-}
decodeUnsoundPureSignKeyKES :: forall v s. UnsoundPureKESAlgorithm v => Decoder s (UnsoundPureSignKeyKES v)
decodeUnsoundPureSignKeyKES = do
bs <- decodeBytes
case rawDeserialiseUnsoundPureSignKeyKES bs of
Just vk -> return vk
Nothing -> failSizeCheck "decodeUnsoundPureSignKeyKES" "key" bs (sizeSignKeyKES (Proxy :: Proxy v))
{-# INLINE decodeUnsoundPureSignKeyKES #-}
decodeSigKES :: forall v s. KESAlgorithm v => Decoder s (SigKES v)
decodeSigKES = do
bs <- decodeBytes
case rawDeserialiseSigKES bs of
Just sig -> return sig
Nothing -> failSizeCheck "decodeSigKES" "signature" bs (sizeSigKES (Proxy :: Proxy v))
{-# INLINE decodeSigKES #-}
decodeSignKeyKES ::
forall v s m. (UnsoundKESAlgorithm v, MonadST m, MonadThrow m)
=> Decoder s (m (Maybe (SignKeyKES v)))
decodeSignKeyKES = do
bs <- decodeBytes
let expected = fromIntegral (sizeSignKeyKES (Proxy @v))
actual = BS.length bs
if actual /= expected then
fail ("decodeSignKeyKES: wrong length, expected " ++
show expected ++ " bytes but got " ++ show actual)
else
return $ rawDeserialiseSignKeyKES bs
-- | The KES period. Periods are enumerated from zero.
--
-- Be careful of fencepost errors: if there are 2 periods (period 0 and 1)
-- then there is only one key evolution.
--
type Period = Word
newtype SignedKES v a = SignedKES {getSig :: SigKES v}
deriving Generic
deriving instance KESAlgorithm v => Show (SignedKES v a)
deriving instance KESAlgorithm v => Eq (SignedKES v a)
instance KESAlgorithm v => NoThunks (SignedKES v a)
-- use generic instance
signedKES
:: (KESAlgorithm v, Signable v a, MonadST m, MonadThrow m)
=> ContextKES v
-> Period
-> a
-> SignKeyKES v
-> m (SignedKES v a)
signedKES ctxt time a key = SignedKES <$> signKES ctxt time a key
verifySignedKES
:: (KESAlgorithm v, Signable v a)
=> ContextKES v
-> VerKeyKES v
-> Period
-> a
-> SignedKES v a
-> Either String ()
verifySignedKES ctxt vk j a (SignedKES sig) = verifyKES ctxt vk j a sig
unsoundPureSignedKES
:: (UnsoundPureKESAlgorithm v, Signable v a)
=> ContextKES v
-> Period
-> a
-> UnsoundPureSignKeyKES v
-> SignedKES v a
unsoundPureSignedKES ctxt time a key = SignedKES $ unsoundPureSignKES ctxt time a key
encodeSignedKES :: KESAlgorithm v => SignedKES v a -> Encoding
encodeSignedKES (SignedKES s) = encodeSigKES s
decodeSignedKES :: KESAlgorithm v => Decoder s (SignedKES v a)
decodeSignedKES = SignedKES <$> decodeSigKES
{-# INLINE decodeSignedKES #-}
-- | A sign key bundled with its associated period.
data SignKeyWithPeriodKES v =
SignKeyWithPeriodKES
{ skWithoutPeriodKES :: !(SignKeyKES v)
, periodKES :: !Period
}
deriving (Generic)
deriving instance (KESAlgorithm v, Eq (SignKeyKES v)) => Eq (SignKeyWithPeriodKES v)
deriving instance (KESAlgorithm v, Show (SignKeyKES v)) => Show (SignKeyWithPeriodKES v)
instance KESAlgorithm v => NoThunks (SignKeyWithPeriodKES v)
-- use generic instance
updateKESWithPeriod
:: (KESAlgorithm v, MonadST m, MonadThrow m)
=> ContextKES v
-> SignKeyWithPeriodKES v
-> m (Maybe (SignKeyWithPeriodKES v))
updateKESWithPeriod c (SignKeyWithPeriodKES sk t) = runMaybeT $ do
sk' <- MaybeT $ updateKES c sk t
return $ SignKeyWithPeriodKES sk' (succ t)
--
-- 'Size' expressions for 'ToCBOR' instances.
--
-- | 'Size' expression for 'VerKeyKES' which is using 'sizeVerKeyKES' encoded
-- as 'Size'.
--
encodedVerKeyKESSizeExpr :: forall v. KESAlgorithm v => Proxy (VerKeyKES v) -> Size
encodedVerKeyKESSizeExpr _proxy =
-- 'encodeBytes' envelope
fromIntegral ((withWordSize :: Word -> Integer) (sizeVerKeyKES (Proxy :: Proxy v)))
-- payload
+ fromIntegral (sizeVerKeyKES (Proxy :: Proxy v))
-- | 'Size' expression for 'SignKeyKES' which is using 'sizeSignKeyKES' encoded
-- as 'Size'.
--
encodedSignKeyKESSizeExpr :: forall v. KESAlgorithm v => Proxy (SignKeyKES v) -> Size
encodedSignKeyKESSizeExpr _proxy =
-- 'encodeBytes' envelope
fromIntegral ((withWordSize :: Word -> Integer) (sizeSignKeyKES (Proxy @v)))
-- payload
+ fromIntegral (sizeSignKeyKES (Proxy :: Proxy v))
-- | 'Size' expression for 'SigKES' which is using 'sizeSigKES' encoded as
-- 'Size'.
--
encodedSigKESSizeExpr :: forall v. KESAlgorithm v => Proxy (SigKES v) -> Size
encodedSigKESSizeExpr _proxy =
-- 'encodeBytes' envelope
fromIntegral ((withWordSize :: Word -> Integer) (sizeSigKES (Proxy :: Proxy v)))
-- payload
+ fromIntegral (sizeSigKES (Proxy :: Proxy v))
hashPairOfVKeys :: (KESAlgorithm d, HashAlgorithm h)
=> (VerKeyKES d, VerKeyKES d)
-> Hash h (VerKeyKES d, VerKeyKES d)
hashPairOfVKeys =
hashWith $ \(a,b) ->
rawSerialiseVerKeyKES a <> rawSerialiseVerKeyKES b
mungeName :: String -> String
mungeName basename
| (name, '^':nstr) <- span (/= '^') basename
, [(n, "")] <- reads nstr
= name ++ '^' : show (n+1 :: Word)
| otherwise
= basename ++ "_2^1"