File: hokey.hs

package info (click to toggle)
haskell-hopenpgp-tools 0.21.3-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 652 kB
  • sloc: haskell: 3,454; yacc: 192; makefile: 8
file content (443 lines) | stat: -rw-r--r-- 24,669 bytes parent folder | download
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
-- hokey.hs: hOpenPGP key tool
-- Copyright © 2013-2019  Clint Adams
--
-- vim: softtabstop=4:shiftwidth=4:expandtab
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Affero General Public License as
-- published by the Free Software Foundation, either version 3 of the
-- License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.

{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}

import HOpenPGP.Tools.Common (banner, versioner, warranty)
import HOpenPGP.Tools.HKP (fetchKeys, FetchValidationMethod(..), rearmorKeys)
import HOpenPGP.Tools.TKUtils (processTK)
import Codec.Encryption.OpenPGP.Expirations (getKeyExpirationTimesFromSignature)
import Codec.Encryption.OpenPGP.Fingerprint (fingerprint, eightOctetKeyID)
import Codec.Encryption.OpenPGP.KeyInfo (pubkeySize, pkalgoAbbrev)
import Codec.Encryption.OpenPGP.KeySelection (parseFingerprint)
import Codec.Encryption.OpenPGP.Ontology (isCertRevocationSig, isCT, isKUF, isPHA, isPKBindingSig, isSKBindingSig)
import Codec.Encryption.OpenPGP.Serialize ()
import Codec.Encryption.OpenPGP.Types
import Control.Arrow ((***))
import Control.Error.Util (hush)
import Control.Lens ((^.), (&), _1, _2, mapped, over)
import Control.Monad.Trans.Except (runExceptT)
import Control.Monad.Trans.Writer.Lazy (execWriter, tell)
import qualified Crypto.Hash.SHA3 as SHA3
import qualified Data.Aeson as A
import Data.Binary (get, put)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC8
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Base16 as Base16
import Data.Conduit ((.|), runConduitRes)
import qualified Data.Conduit.Binary as CB
import Data.Conduit.Serialization.Binary (conduitGet, conduitPut)
import qualified Data.Conduit.List as CL
import Data.Conduit.OpenPGP.Keyring (conduitToTKsDropping)
import Data.Foldable (find)
import Data.List (elemIndex, findIndex, nub, sort, sortOn, intercalate)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe, mapMaybe, listToMaybe)
#if !MIN_VERSION_base(4,9,0)
import Data.Monoid ((<>))
#else
import Data.Semigroup ((<>), Semigroup)
#endif
import Data.Ord (Down(..))
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Clock.POSIX (getPOSIXTime, posixSecondsToUTCTime, POSIXTime)
import Data.Time.Format (formatTime)
import qualified Data.Yaml as Y
import GHC.Generics

import Options.Applicative.Builder (argument, auto, command, eitherReader, footerDoc, headerDoc, help, helpDoc, info, long, metavar, prefs, progDesc, showDefault, showHelpOnError, option, str, value)
import Options.Applicative.Extra (customExecParser, helper, hsubparser)
import Options.Applicative.Types (Parser)

import System.IO (Handle, hFlush, hPutStrLn, stderr, stdin, stdout, hSetBuffering, BufferMode(..))
import Data.Time.Locale.Compat (defaultTimeLocale)

import Data.Text.Prettyprint.Doc (annotate, colon, flatAlt, hardline, indent, line, list, pretty, (<+>), Doc)
import qualified Data.Text.Prettyprint.Doc.Render.Terminal as PPA
import Data.Text.Prettyprint.Convert.AnsiWlPprint (toAnsiWlPprint)

linebreak = flatAlt line mempty
green = annotate (PPA.color PPA.Green)
yellow = annotate (PPA.color PPA.Yellow)
red = annotate (PPA.color PPA.Red)

data KAS = KAS {
    pubkeyalgo :: Colored PubKeyAlgorithm
  , pubkeysize :: Colored (Maybe Int)
  , stringrep :: String
} deriving Generic

data Color = Green | Yellow | Red
  deriving (Eq, Generic, Ord)

data Colored a = Colored {
    color :: Maybe Color
  , explanation :: Maybe String
  , val :: a
} deriving (Functor, Generic)

newtype FakeMap a b = FakeMap { unFakeMap :: [(a, b)] }

data KeyReport = KeyReport {
    keyStatus :: String
  , keyFingerprint :: TwentyOctetFingerprint
  , keyVer :: Colored KeyVersion
  , keyCreationTime :: ThirtyTwoBitTimeStamp
  , keyAlgorithmAndSize :: KAS
  , keyUIDsAndUAts :: FakeMap Text (Colored UIDReport)
  , keyBestOf :: Maybe UIDReport
  , keySubkeys :: [SubkeyReport]
  , keyHasEncryptionCapableSubkey :: Colored Bool
} deriving Generic

data UIDReport = UIDReport {
    uidSelfSigHashAlgorithms :: [Colored HashAlgorithm]
  , uidPreferredHashAlgorithms :: [Colored [HashAlgorithm]]
  , uidKeyExpirationTimes :: [Colored [ThirtyTwoBitDuration]]
  , uidKeyUsageFlags :: [Colored (Set.Set KeyFlag)]
  , uidRevocationStatus :: [RevocationStatus]
} deriving Generic

data SubkeyReport = SubkeyReport {
    skFingerprint :: Colored TwentyOctetFingerprint
  , skVer :: Colored KeyVersion
  , skCreationTime :: ThirtyTwoBitTimeStamp
  , skAlgorithmAndSize :: KAS
  , skBindingSigHashAlgorithms :: [Colored HashAlgorithm]
  , skUsageFlags :: [Colored (Set.Set KeyFlag)]
  , skCrossCerts :: CrossCertReport
} deriving Generic

data CrossCertReport = CrossCertReport {
    ccPresent :: Colored Bool
  , ccHashAlgorithms :: [Colored HashAlgorithm]
} deriving Generic

data RevocationStatus = RevocationStatus {
    isRevoked :: Bool
  , revocationCode :: String
  , revocationReason :: Text
} deriving Generic

instance A.ToJSON KAS
instance A.ToJSON Color
instance (A.ToJSON a) => A.ToJSON (Colored a)
instance A.ToJSON KeyReport
instance A.ToJSON UIDReport
instance A.ToJSON SubkeyReport
instance A.ToJSON CrossCertReport
instance A.ToJSON b => A.ToJSON (FakeMap Text b) where
    toJSON = A.toJSON . Map.fromList . unFakeMap
instance A.ToJSON RevocationStatus

#if MIN_VERSION_base(4,9,0)
instance Semigroup UIDReport where
    (<>) (UIDReport a b c d e) (UIDReport a' b' c' d' e') = UIDReport (a <> a') (b <> b') (c <> c') (d <> d') (e <> e')
#endif

instance Monoid UIDReport where
    mempty = UIDReport [] [] [] [] []
#if !MIN_VERSION_base(4,9,0)
    mappend (UIDReport a b c d e) (UIDReport a' b' c' d' e') = UIDReport (a <> a') (b <> b') (c <> c') (d <> d') (e <> e')
#else
    mappend = (<>)
#endif

checkKey :: Maybe POSIXTime -> TK -> KeyReport
checkKey mpt key = (\x -> x { keyBestOf = populateBestOf x, keyHasEncryptionCapableSubkey = hasEncryptionCapableSubkey (concatMap skUsageFlags (keySubkeys x)) }) KeyReport {
    keyStatus = either id (const "good") processedTK
  , keyFingerprint = key^.tkKey._1 & fingerprint
  , keyVer = key^.tkKey._1.keyVersion & colorizeKV
  , keyCreationTime = key^.tkKey._1.timestamp
  , keyAlgorithmAndSize = kasIt (key^.tkKey._1)
  , keyUIDsAndUAts = FakeMap (map (\(x,y) -> (x, uidr (Just x) y)) (processedOrOrig^.tkUIDs) ++ map (uatspsToText *** uidr Nothing) (processedOrOrig^.tkUAts))
  , keyBestOf = Nothing
  , keySubkeys = map (checkSK (key^.tkKey._1 & fingerprint)) (key^.tkSubs)
  , keyHasEncryptionCapableSubkey = Colored Nothing Nothing False
}
    where
        processedOrOrig = either (const key) id processedTK
        processedTK = processTK mpt key
        kasIt :: PKPayload -> KAS
        kasIt pkp = KAS {
          pubkeyalgo = pkp^.pkalgo & colorizePKA
        , pubkeysize = pkp^.pubkey & colorizePKS . pubkeySize
        , stringrep = (pkp^.pubkey & either (const "unknown") show . pubkeySize) ++ (pkp^.pkalgo & pkalgoAbbrev)
        }
        colorizeKV kv = uncurry Colored (if kv == V4 then (Just Green, Nothing) else (Just Red, Just "not a V4 key")) kv
        colorizePKA pka = uncurry Colored (if pka == RSA then (Just Green, Nothing) else (Just Yellow, Just "not an RSA key")) pka
        colorizePKS pks = uncurry Colored (colorizePKS' pks) (hush pks)
        colorizePKS' (Right pks)
          | pks >= 3072 = (Just Green, Nothing)
          | pks >= 2048 = (Just Yellow, Just "Public key size between 2048 and 3072 bits")
          | otherwise = (Just Red, Just "Public key size under 2048 bits")
        colorizePKS' (Left _) = (Just Red, Just "public key algorithm not understood")
        colorizePHAs x = uncurry Colored (if fSHA2Family x < ei DeprecatedMD5 x && fSHA2Family x < ei SHA1 x then (Just Green, Nothing) else (Just Red, Just "weak hash with higher preference")) x
        fSHA2Family = fi (`elem` [SHA512,SHA384,SHA256,SHA224])
        ei x y = fromMaybe maxBound (elemIndex x y)
        fi x y = fromMaybe maxBound (findIndex x y)
        colorizeKETs ct ts kes
            | null kes  = Colored (Just Red) (Just "no expiration set") kes
            | any (\ke -> realToFrac ts + realToFrac ke < ct) kes = Colored (Just Red) (Just "expiration passed") kes
            | any (\ke -> realToFrac ts + realToFrac ke > ct + (5*31557600)) kes = Colored (Just Yellow) (Just "expiration too far in future") kes
            | otherwise = Colored (Just Green) Nothing kes
        eoki pkp
            | pkp^.keyVersion == V4 = hush . eightOctetKeyID $ pkp
            | pkp^.keyVersion == DeprecatedV3 && elem (pkp^.pkalgo) [RSA,DeprecatedRSASignOnly] = hush . eightOctetKeyID $ pkp
            | otherwise = Nothing
        phas (SigV4 _ _ _ xs _ _ _) = colorizePHAs . concatMap (\(SigSubPacket _ (PreferredHashAlgorithms x)) -> x) $ filter isPHA xs
        phas _ = Colored Nothing Nothing []
        has = map (colorizeHA . hashAlgo) . alleged
        colorizeHA ha = uncurry Colored (if ha `elem` [DeprecatedMD5, SHA1] then (Just Red, Just "weak hash algorithm") else (Nothing, Nothing)) ha
        sigcts (SigV4 _ _ _ xs _ _ _) = map (\(SigSubPacket _ (SigCreationTime x)) -> x) $ filter isCT xs
        alleged = filter (\x -> ((==) <$> sigissuer x <*> eoki (key^.tkKey._1)) == Just True)
        uatspsToText = T.pack . uatspsToString
        uatspsToString us = "<uat:[" ++ intercalate "," (map uaspToString us) ++ "]>"
        uaspToString (ImageAttribute hdr d) = hdrToString hdr ++ ':':show (BL.length d) ++ ':':BC8.unpack (Base16.encode (SHA3.hashlazy 48 d))
        uaspToString (OtherUASub t d) = "other-" ++ show t ++ ':':show (BL.length d) ++ ':':BC8.unpack (Base16.encode (SHA3.hashlazy 48 d))
        hdrToString (ImageHV1 JPEG) = "jpeg"
        hdrToString (ImageHV1 fmt) = "image-" ++ show (fromFVal fmt)
        uidr Nothing sps = Colored Nothing Nothing (UIDReport (has sps)
                                                              (map phas sps)
                                                              (map (colorizeKETs (fromMaybe 0 mpt) (key^.tkKey._1.timestamp & unThirtyTwoBitTimeStamp) . getKeyExpirationTimesFromSignature) sps) -- should that be 0?
                                                              (kufs False sps)
                                                              (findRevocationReason sps))
        uidr (Just u) sps = colorizeUID u (UIDReport (has sps)
                                                     (map phas sps)
                                                     (map (colorizeKETs (fromMaybe 0 mpt) (key^.tkKey._1.timestamp & unThirtyTwoBitTimeStamp) . getKeyExpirationTimesFromSignature) sps) -- should that be 0?
                                                     (kufs False sps)
                                                     (findRevocationReason sps))
        populateBestOf krep = Just (UIDReport <$> best . uidSelfSigHashAlgorithms <*> best . uidPreferredHashAlgorithms <*> best . uidKeyExpirationTimes <*> best . uidKeyUsageFlags <*> pure [] $ mconcat (justTheUIDRs krep))
        justTheUIDRs = map (decolorize . snd) . unFakeMap . keyUIDsAndUAts
        best = take 1 . sortOn color
        decolorize (Colored _ _ x) = x
        colorizeUID u
            | '(' `elem` T.unpack u = Colored (Just Yellow) (Just "parenthesis in uid")  -- FIXME: be more discerning
            | '<' `notElem` T.unpack u = Colored (Just Yellow) (Just "no left angle bracket in uid")  -- FIXME: be more discerning
            | otherwise = Colored Nothing Nothing
        findRevocationReason = concatMap grabReasons . filter isCertRevocationSig
        grabReasons (SigV4 CertRevocationSig _ _ has _ _ _) = mapMaybe (grabReasons' . _sspPayload) has
        grabReasons _ = []
        grabReasons' (ReasonForRevocation a b) = Just (RevocationStatus True (show a) b)
        grabReasons' _ = Nothing
        kufs s = map (colorizeKUFs s . (\(SigSubPacket _ (KeyFlags x)) -> x) . fromMaybe undefined . find isKUF . hasheds) . newestWith (any isKUF . hasheds)
        colorizeKUFs False x = uncurry Colored (if (Set.member EncryptStorageKey x || Set.member EncryptCommunicationsKey x) && (Set.member SignDataKey x || Set.member CertifyKeysKey x) then (Just Yellow, Just "both signing & encryption") else (Just Green, Nothing)) x
        colorizeKUFs True x = uncurry Colored (if Set.member CertifyKeysKey x then (Just Red, Just "certification-capable subkey") else (if (Set.member EncryptStorageKey x || Set.member EncryptCommunicationsKey x) && Set.member SignDataKey x then (Just Yellow, Just "both signing & encryption") else (Just Green, Nothing))) x
        newestWith p = take 1 . sortOn (Down . take 1 . sigcts) . filter p -- FIXME: this is terrible
        hasheds (SigV4 _ _ _ xs _ _ _) = xs
        hasheds _ = []
        checkSK :: TwentyOctetFingerprint -> (Pkt, [SignaturePayload]) -> SubkeyReport
        checkSK pf (PublicSubkeyPkt pkp, sigs) = checkSK' pf pkp sigs
        checkSK pf (SecretSubkeyPkt pkp _, sigs) = checkSK' pf pkp sigs
        checkSK' pf pkp sigs = (\x -> x { skCrossCerts = ccr (map decolorize (skUsageFlags x)) sigs }) SubkeyReport {
          skFingerprint = colorizeF pf (fingerprint pkp)
        , skVer = colorizeKV (pkp^.keyVersion)
        , skCreationTime = pkp^.timestamp
        , skAlgorithmAndSize = kasIt pkp
        , skBindingSigHashAlgorithms = has (filter isSKBindingSig sigs)
        , skUsageFlags = kufs True (filter isSKBindingSig sigs)
        , skCrossCerts = CrossCertReport (Colored Nothing Nothing False) []
        }
        hasEncryptionCapableSubkey skrs = if any ((\x -> Set.member EncryptStorageKey x || Set.member EncryptCommunicationsKey x) . decolorize) skrs then Colored (Just Green) Nothing True else Colored (Just Red) (Just "no encryption-capable subkey present") False
        embeddedSigs = filter isPKBindingSig . concatMap getEmbeds . filter isSKBindingSig
        getEmbeds (SigV4 _ _ _ _ xs _ _) = concatMap getEmbed xs
        getEmbeds _ = []
        getEmbed (SigSubPacket _ (EmbeddedSignature sp)) = [sp]
        getEmbed _ = []
        ccr kufs sigs = CrossCertReport (colorES kufs sigs) (map (colorizeHA . hashAlgo) sigs)
        colorES kufs sigs = case (null (embeddedSigs sigs), any (Set.member SignDataKey) kufs, any (Set.member AuthKey) kufs) of
                                (True, True, True) -> Colored (Just Red) (Just "signing- and auth-capable subkey without cross-cert") False
                                (True, True, False) -> Colored (Just Red) (Just "signing-capable subkey without cross-cert") False
                                (True, False, True) -> Colored (Just Yellow) (Just "auth-capable subkey without cross-cert") False
                                (False, True, True) -> Colored (Just Green) Nothing True
                                (False, True, False) -> Colored (Just Green) Nothing True
                                (False, False, True) -> Colored (Just Green) Nothing True
                                (False, False, False) -> Colored Nothing Nothing True
                                (True, _, _) -> Colored Nothing Nothing False
        colorizeF pf fp = uncurry Colored (if pf == fp then (Just Red, Just "subkey has same fingerprint as primary key") else (Just Green, Nothing)) fp

prettyKeyReport :: POSIXTime -> TK -> Doc PPA.AnsiStyle
prettyKeyReport cpt key = do
 let keyReport = checkKey (Just cpt) key
 execWriter $ tell
   ( linebreak <> pretty "Key has potential validity" <> colon <+> pretty (keyStatus keyReport)
  <> linebreak <> pretty "Key has fingerprint" <> colon <+> pretty (SpacedFingerprint (keyFingerprint keyReport))
  <> linebreak <> pretty "Checking to see if key is OpenPGPv4" <> colon <+> coloredToColor (pretty . show) (keyVer keyReport)
  <> linebreak <> (\kas -> pretty "Checking to see if key is RSA or DSA (>= 2048-bit)" <> colon <+> coloredToColor pretty (pubkeyalgo kas) <+> coloredToColor (maybe (pretty "unknown") pretty) (pubkeysize kas)) (keyAlgorithmAndSize keyReport)
  <> linebreak <> pretty "Checking user-ID- and user-attribute-related items" <> colon
  <> mconcat (map (uidtrip (keyCreationTime keyReport) . gottabeabetterway) (unFakeMap (keyUIDsAndUAts keyReport)))
  <> linebreak <> pretty "Checking subkeys" <> colon
  <> linebreak <> indent 2 (pretty "one of the subkeys is encryption-capable" <> colon <+> coloredToColor pretty (keyHasEncryptionCapableSubkey keyReport))
  <> mconcat (map subkeyrep (keySubkeys keyReport))
  <> linebreak
   )
    where
        coloredToColor f (Colored (Just Green) _ x) = green (f x)
        coloredToColor f (Colored (Just Yellow) _ x) = yellow (f x)
        coloredToColor f (Colored (Just Red) _ x) = red (f x)
        coloredToColor f (Colored Nothing _ x) = f x
        uidtrip ts (u, ur)
           | null (uidRevocationStatus ur) = linebreak <> indent 2 (coloredToColor pretty (fmap T.unpack u)) <> colon
          <> linebreak <> indent 4 (pretty "Self-sig hash algorithms" <> colon <+> (list . map (coloredToColor pretty) . uidSelfSigHashAlgorithms) ur)
          <> linebreak <> indent 4 (pretty "Preferred hash algorithms" <> colon <+> mconcat (map (coloredToColor pretty) (uidPreferredHashAlgorithms ur)))
          <> linebreak <> indent 4 (pretty "Key expiration times" <> colon <+> mconcat (map (coloredToColor list . fmap (map (pretty . keyExp ts))) (uidKeyExpirationTimes ur)))
          <> linebreak <> indent 4 (pretty "Key usage flags" <> colon <+> (list . map (coloredToColor (pretty . Set.toList))) (uidKeyUsageFlags ur))
           | otherwise = linebreak <> indent 2 (coloredToColor pretty (fmap T.unpack u)) <> colon <+> pretty "[revoked]"
          <> linebreak <> indent 4 (pretty "Revocation code" <> colon <+> list (map (pretty . revocationCode) (uidRevocationStatus ur)))
          <> linebreak <> indent 4 (pretty "Revocation reason" <> colon <+> list (map (pretty . T.unpack . revocationReason) (uidRevocationStatus ur)))
        keyExp ts ke = (show . pretty) ke ++ " = " ++ formatTime defaultTimeLocale "%c" (posixSecondsToUTCTime (realToFrac ts + realToFrac ke))
        gottabeabetterway (a, Colored x y z) = (Colored x y a, z)
        subkeyrep skr = linebreak <> indent 2 (pretty "fpr" <> colon <+> coloredToColor pretty (fmap SpacedFingerprint (skFingerprint skr)))
                     <> linebreak <> indent 4 (pretty "version" <> colon <+> coloredToColor pretty (skVer skr))
                     <> linebreak <> indent 4 (pretty "timestamp" <> colon <+> pretty (skCreationTime skr))
                     <> linebreak <> indent 4 ((\kas -> pretty "algo/size" <> colon <+> coloredToColor pretty (pubkeyalgo kas) <+> coloredToColor (maybe (pretty "unknown") pretty) (pubkeysize kas)) (skAlgorithmAndSize skr))
                     <> linebreak <> indent 4 (pretty "binding sig hash algorithms" <> colon <+> (list . map (coloredToColor pretty) . skBindingSigHashAlgorithms) skr)
                     <> linebreak <> indent 4 (pretty "usage flags" <> colon <+> (list . map (coloredToColor (pretty . Set.toList))) (skUsageFlags skr))
                     <> linebreak <> indent 4 (pretty "embedded cross-cert" <> colon <+> (coloredToColor pretty . ccPresent . skCrossCerts) skr)
                     <> linebreak <> indent 4 (pretty "cross-cert hash algorithms" <> colon <+> (list . map (coloredToColor pretty) . ccHashAlgorithms . skCrossCerts) skr)

jsonReport :: POSIXTime -> TK -> BL.ByteString
jsonReport ps = A.encode . checkKey (Just ps)

yamlReport :: POSIXTime -> TK -> B.ByteString
yamlReport ps = Y.encode . (:[]) . checkKey (Just ps)

data LintOutputFormat = Pretty | JSON | YAML
    deriving (Bounded, Enum, Eq, Read, Show)

data LintOptions = LintOptions {
    lintOutputFormat :: LintOutputFormat
}

data FetchOptions = FetchOptions {
    keyServer :: String
  , fetchValidation :: FetchValidationMethod
  , fetchQuery :: TwentyOctetFingerprint
}

data Command = CmdLint LintOptions | CmdCanonicalize | CmdFetch FetchOptions

lintO :: Parser LintOptions
lintO = LintOptions
    <$> option auto
        ( long "output-format"
       <> metavar "FORMAT"
       <> value Pretty
       <> showDefault
       <> ofHelp
        )
    where
        ofHelp = helpDoc . Just . toAnsiWlPprint $ pretty "output format" <> hardline <> list (map (pretty . show) ofchoices)
        ofchoices = [minBound..maxBound] :: [LintOutputFormat]

fetchO :: Parser FetchOptions
fetchO = FetchOptions
    <$> option str
        ( long "keyserver"
       <> metavar "URL"
       <> value "http://pool.sks-keyservers.net:11371"
       <> showDefault
       <> help "HKP server"
        )
    <*> option auto
        ( long "validation-method"
       <> metavar "METHOD"
       <> value MatchPrimaryKeyFingerprint
       <> showDefault
       <> vmHelp
        )
    <*> argument (eitherReader strToFP) ( metavar "FINGERPRINT" )
    where
        vmHelp = helpDoc . Just . toAnsiWlPprint $ pretty "validation method" <> hardline <> list (map (pretty . show) vmchoices)
        vmchoices = [minBound..maxBound] :: [FetchValidationMethod]
        strToFP = parseFingerprint . T.pack

dispatch :: Command -> IO ()
dispatch (CmdFetch o) = banner' stderr >> hFlush stderr >> doFetch o
dispatch (CmdLint o) = banner' stderr >> hFlush stderr >> doLint o
dispatch CmdCanonicalize = banner' stderr >> hFlush stderr >> doCanonicalize

main :: IO ()
main = do
    hSetBuffering stderr LineBuffering
    customExecParser (prefs showHelpOnError)
                     (info (helper <*> versioner "hokey" <*> cmd)
                           (headerDoc (Just (toAnsiWlPprint (banner "hokey")))
                         <> progDesc "hOpenPGP Key utility"
                         <> footerDoc (Just (toAnsiWlPprint (warranty "hokey"))))) >>= dispatch

cmd :: Parser Command
cmd = hsubparser
    ( command "canonicalize" (info ( pure CmdCanonicalize) ( progDesc "arrange key components in a canonical ordering" ))
   <> command "fetch" (info ( CmdFetch <$> fetchO) ( progDesc "fetch key(s) from keyserver" ))
   <> command "lint" (info ( CmdLint <$> lintO) ( progDesc "check key(s) for 'best practices'" ))
    )

doLint :: LintOptions -> IO ()
doLint o = do
    cpt <- getPOSIXTime
    keys <- runConduitRes $ CB.sourceHandle stdin .| conduitGet get .| conduitToTKsDropping .| CL.consume
    output (lintOutputFormat o) cpt keys
    where
        output Pretty cpt = mapM_ (PPA.putDoc . prettyKeyReport cpt)
        output JSON cpt = mapM_ (BL.putStr . flip BL.append (BL.singleton 0x0a) . jsonReport cpt)
        output YAML cpt = mapM_ (B.putStr . yamlReport cpt)

doCanonicalize :: IO ()
doCanonicalize = runConduitRes $ CB.sourceHandle stdin .| conduitGet get .|
                   conduitToTKsDropping .| CL.map canonicalize .|
                   CL.map put .| conduitPut .| CB.sinkHandle stdout
    where
        canonicalize (TK k r ui ua s) = TK k
                                           (sort r)
                                           (indepthsort ui)
                                           (indepthsort ua)
                                           (indepthsort s)
        indepthsort :: (Ord a, Ord b) => [(a,[b])] -> [(a,[b])]
        indepthsort = nub . sort . over (mapped._2) sort

doFetch :: FetchOptions -> IO ()
doFetch o = do
    ekeys <- runExceptT $ fetchKeys (keyServer o) (fetchValidation o) (fetchQuery o)
    case ekeys of
        Left e -> hPutStrLn stderr $ "error fetching keys: " ++ e
        Right ks -> B.putStr $ rearmorKeys ks

banner' :: Handle -> IO ()
banner' h = PPA.hPutDoc h (banner "hokey" <> hardline <> warranty "hokey" <> hardline)

sigissuer :: SignaturePayload -> Maybe EightOctetKeyId
getIssuer :: SigSubPacketPayload -> Maybe EightOctetKeyId
hashAlgo :: SignaturePayload -> HashAlgorithm

sigissuer (SigVOther 2 _) = Nothing
sigissuer SigV3{} = Nothing
sigissuer (SigV4 _ _ _ ys xs _ _) = listToMaybe . mapMaybe (getIssuer . _sspPayload) $ (ys++xs) -- FIXME: what should this be if there are multiple matches?
sigissuer (SigVOther _ _) = error "We're in the future." -- FIXME

getIssuer (Issuer i) = Just i
getIssuer _ = Nothing

hashAlgo (SigV4 _ _ x _ _ _ _) = x
hashAlgo _ = error "V3 sig not supported here"