{-# LANGUAGE DoAndIfThenElse #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE CPP #-} module Main ( main ) where import Control.Applicative import Control.Monad import Control.Monad.Fix import Data.ASN1.BinaryEncoding import Data.ASN1.Encoding import Data.ASN1.Types import Data.Binary import Data.Bits import Data.Char import Data.IORef import Data.Int import Data.List import Data.Maybe import Data.OpenPGP import Data.Ord import Data.Text.Encoding import System.Posix.User import System.Posix.Files import System.Posix.Types import System.FilePath.Posix import Foreign.C.Types (CTime(..)) import System.Directory import System.Environment import System.Exit import System.IO (hPutStrLn,stderr) import qualified Codec.Binary.Base64 as Base64 import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar #if !defined(VERSION_cryptonite) import qualified Crypto.Hash.RIPEMD160 as RIPEMD160 import qualified Crypto.Hash.SHA256 as SHA256 #else import Crypto.Hash.Algorithms (RIPEMD160(..)) import Crypto.Hash import Data.ByteArray (convert) #endif import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Char8 as Char8 import qualified Data.Map as Map import Control.Arrow (first,second) import Data.Monoid ( (<>) ) import Data.Binary.Put import Data.OpenPGP.Util (verify,fingerprint,generateKey, GenerateKeyParams(..)) import ScanningParser import PEM import DotLock import KeyRing import Base58 import qualified CryptoCoins -- import Chroot import ProcessUtils import qualified SSHKey as SSH import Text.Printf import qualified DNSKey as DNS import Data.Time.Clock.POSIX ( posixSecondsToUTCTime ) import Kiki import Debug.Trace -- {-# ANN module ("HLint: ignore Eta reduce"::String) #-} -- {-# ANN module ("HLint: ignore Use camelCase"::String) #-} {- - - accBindings :: forall t a a1 a2. Bits t => [(t, (Packet, Packet), [a], [a1], [a2])] -> [(t, (Packet, Packet), [a], [a1], [a2])] bitcoinAddress :: Word8 -> Packet -> String cannonical_eckey :: forall b b1. (Integral b1, Integral b) => b -> b1 -> [Word8] commands :: [(String, String)] decode_sshrsa :: Char8.ByteString -> Maybe RSAPublicKey disjoint_fp :: [Packet] -> [[Packet]] doAutosign :: forall t. t -> KeyData -> [PacketUpdate] fpmatch :: Maybe [Char] -> Packet -> Bool getBindings :: [Packet] -> ([([Packet], [SignatureOver])], [(Word8, (Packet, Packet), [String], [SignatureSubpacket], [Packet])]) isCertificationSig :: SignatureOver -> Bool isSubkeySignature :: SignatureOver -> Bool kiki :: forall a. (Eq a, Data.String.IsString a) => a -> [[Char]] -> IO () kiki_sync_help :: IO () listKeys :: [Packet] -> [Char] listKeysFiltered :: [[Char]] -> [Packet] -> [Char] :Main.main :: IO () main :: IO () partitionStaticArguments :: forall a. Ord a => [(a, Int)] -> [a] -> ([[a]], [a]) readPublicKey :: Char8.ByteString -> RSAPublicKey show_all :: KeyDB -> IO () show_id :: forall t. String -> t -> Map.Map KeyRing.KeyKey KeyData -> IO () show_pem :: String -> String -> KeyDB -> IO () show_ssh :: String -> String -> KeyDB -> IO () show_whose_key :: Maybe RSAPublicKey -> KeyDB -> IO () show_wip :: String -> String -> KeyDB -> IO () show_wk :: FilePath -> Maybe [Char] -> Map.Map KeyRing.KeyKey KeyData -> IO () smallpr :: Packet -> [Char] sshrsa :: Integer -> Integer -> Char8.ByteString toLast :: forall x. (x -> x) -> [x] -> [x] verifyBindings :: [Packet] -> [Packet] -> ([SignatureOver], [SignatureOver]) warn :: String -> IO () whoseKey :: RSAPublicKey -> KeyDB -> [KeyData] - - -} isCertificationSig (CertificationSignature {}) = True isCertificationSig _ = True fpmatch grip key = (==) Nothing (fmap (backend (fingerprint key)) grip >>= guard . not) where backend xs ys = and $ zipWith (==) (reverse xs) (reverse ys) listKeys pkts = listKeysFiltered [] pkts -- | listKeysFiltered -- @grips fingerprints of keys to show -- @pkts list of pgp packets -- Build the display output -- Operates in List Monad... -- returns all output as a single string listKeysFiltered grips pkts = do let masterkeys = filter (\k -> isKey k && not (is_subkey k)) pkts (certs,bs) = getBindings pkts as = accBindings bs defaultkind (k:_) hs = k defaultkind [] hs = fromMaybe "subkey" ( listToMaybe . mapMaybe (fmap usageString . keyflags) $ hs) kinds = map (\(_,_,k,h,_)->defaultkind k h) as kindwidth = maximum $ map length kinds kindcol = min 20 kindwidth code (c,(m,s),_,_,_) = (fingerprint_material m,-c) ownerkey (_,(a,_),_,_,_) = a sameMaster (ownerkey->a) (ownerkey->b) = fingerprint_material a==fingerprint_material b matchgrip _ | null grips = True matchgrip ((code,(top,sub), kind, hashed,claimants):_) | any (flip fpmatch top . Just) grips = True matchgrip _ = False gs = filter matchgrip $ groupBy sameMaster (sortBy (comparing code) as) singles = filter (\k -> fingerprint k `notElem` map fingerprint parents) masterkeys -- \\ parents where parents = do subs@((_,(top,_),_,_,_):_) <- gs return top showsigs claimants = map (\k -> " " ++ "^ signed: " ++ fingerprint k) claimants subs0 <- map Left gs ++ map Right singles let (top,subs) = case subs0 of Left subs1@((_,(top0,_),_,_,_):_) -> (top0,subs1) Right top0 -> (top0,[]) let subkeys = do (code,(top,sub), kind, hashed,claimants) <- subs let ar = case code of 0 -> " ??? " 1 -> " --> " 2 -> " <-- " 3 -> " <-> " formkind = take kindcol $ defaultkind kind hashed ++ repeat ' ' -- torhash = fromMaybe "" $ derToBase32 <$> derRSA sub (netid,kind') = maybe (0x0,"bitcoin") (\n->(CryptoCoins.publicByteFromName n,n)) $ listToMaybe kind unlines $ concat [ " " -- , grip top , ar , formkind , " " , fingerprint sub -- , " " ++ (torhash sub) -- , " " ++ (concatMap (printf "%02X") $ S.unpack (ecc_curve sub)) ] -- ++ ppShow hashed : if isCryptoCoinKey sub -- then (" " ++ "B⃦ " ++ bitcoinAddress sub) : showsigs claimants -- then (" " ++ "BTC " ++ bitcoinAddress sub) : showsigs claimants then (" " ++ "¢ "++kind'++":" ++ bitcoinAddress netid sub) : showsigs claimants else showsigs claimants torkeys = do (code,(top,sub), kind, hashed,claimants) <- subs guard ("tor" `elem` kind) guard (code .&. 0x2 /= 0) maybeToList $ derToBase32 <$> derRSA sub uid = {- fromMaybe "" . listToMaybe $ -} do (keys,sigs) <- certs sig <- sigs guard (isCertificationSig sig) guard (topkey sig == top) let issuers = do sig_over <- signatures_over sig i <- maybeToList $ signature_issuer sig_over maybeToList $ find_key (matchpr i) (Message keys) (reverse (take 16 (reverse i))) (primary,secondary) = partition (==top) issuers -- trace ("PRIMARY: "++show (map fingerprint primary)) $ return () -- trace ("SECONDARY: "++show (map fingerprint secondary)) $ return () guard (not (null primary)) let UserIDPacket uid = user_id sig parsed = parseUID uid ar = maybe " --> " (const " <-> ") $ do guard (uid_topdomain parsed == "onion" ) guard ( uid_realname parsed `elem` ["","Anonymous"]) guard ( uid_user parsed == "root" ) let subdom0 = L.fromChunks [encodeUtf8 (uid_subdomain parsed)] len = L.length subdom0 subdom = Char8.unpack subdom0 match = (==subdom) . take (fromIntegral len) guard (len >= 16) listToMaybe $ filter match torkeys unlines $ (" " ++ ar ++ "@" ++ " " ++ uid_full parsed) : showsigs secondary -- (_,sigs) = unzip certs "master-key " ++ fingerprint top ++ "\n" ++ uid ++" ...\n" ++ subkeys ++ "\n" {- - modify a UID to test the verify function properly - fails modifyUID (UserIDPacket str) = UserIDPacket str' where (fstname,rst) = break (==' ') str str' = mod fstname ++ rst mod "Bob" = "Bob Slacking" mod x = x modifyUID other = other -} readPublicKey :: Char8.ByteString -> RSAPublicKey readPublicKey bs = RSAKey (MPI n) (MPI e) where (n,e) = fromMaybe (error "Unsupported key format") $ SSH.blobkey bs -- | Returns the given list with its last element modified. toLast :: (x -> x) -> [x] -> [x] toLast f [] = [] toLast f [x] = [f x] toLast f (x:xs) = x : toLast f xs -- partitionStaticArguments :: Ord a => [(a, Int)] -> [a] -> ([[a]], [a]) partitionStaticArguments specs args = psa args where smap = Map.fromList specs psa [] = ([],[]) psa (a:as) = case Map.lookup a smap of Nothing | (k,'=':v) <- break (=='=') a , Just 1 <- Map.lookup k smap -> first ([k,v]:) $ psa as Nothing -> second (a:) $ psa as Just n -> first ((a:take n as):) $ psa (drop n as) show_wk secring_file grip db = do -- printf "show_wk(%s,%s,%s)\n" (show secring_file) (show grip) (show db) let sec_db = Map.filter gripmatch db gripmatch (KeyData p _ _ _) = Map.member secring_file (locations p) || Map.member "&secret" (locations p) Message sec = flattenKeys False sec_db putStrLn $ listKeysFiltered (maybeToList grip) sec show_all db = do let Message packets = flattenKeys True db putStrLn $ listKeys packets show_whose_key input_key db = flip (maybe $ return ()) input_key $ \input_key -> do let ks = whoseKey input_key db case ks of [KeyData k _ uids _] -> do putStrLn $ fingerprint (packet k) mapM_ putStrLn $ Map.keys uids (_:_) -> error "ambiguous" [] -> return () show_dns keyspec wkgrip db = either warn putStrLn $ show_pem' keyspec wkgrip db dnsPresentationFromPacket dnsPresentationFromPacket k = do let RSAKey (MPI n) (MPI e) = fromJust $ rsaKeyFromPacket k dnskey = DNS.RSA n e bin = runPut (DNS.putRSA dnskey) qq = Base64.encode (L.unpack bin) ttl = 24*60*60 -- 24 hours in seconds flags = 256 -- (ZONE-key = bit7) TODO: is this a zone key or a key-signing key? algo = 8 -- RSASHA256 -- TODO: support other algorithm return $ unwords ["." ,show ttl ,"IN" ,"DNSKEY" ,show flags ,"3" -- protocol MUST be 3 (RFC 4034) ,show algo ,qq ] show_id keyspec wkgrip db = do let s = parseSpec "" keyspec let ps = do (_,k) <- filterMatches (fst s) (Map.toList db) mp <- flattenTop "" True k return $ packet mp -- putStrLn $ "show key " ++ show s putStrLn $ listKeys ps show_wip keyspec wkgrip db = do let s = parseSpec wkgrip keyspec flip (maybe $ void (warn (keyspec ++ ": not found"))) (selectSecretKey s db) $ \k -> do let nwb = maybe 0x80 CryptoCoins.secretByteFromName $ snd s putStrLn $ walletImportFormat nwb k show_torhash pubkey _ = do bs <- Char8.readFile pubkey let parsekey f dta = do let mdta = L.pack <$> Base64.decode (Char8.unpack dta) e <- decodeASN1 DER <$> mdta asn1 <- either (const Nothing) (Just) e k <- either (const Nothing) (Just . fst) (fromASN1 asn1) return $ f (packetFromPublicRSAKey undefined) k addy :: String -> String addy hsh = take 16 hsh ++ ".onion " ++ hsh pkcs1 = fmap ( parsekey (\f (RSAKey n e) -> f n e) . pemBlob ) $ pemParser (Just "RSA PUBLIC KEY") pkcs8 = fmap ( parsekey (\f (RSAKey8 n e) -> f n e) . pemBlob ) $ pemParser (Just "PUBLIC KEY") cert = fmap (fmap pcertKey . parseCertBlob False . pemBlob) $ pemParser (Just "CERTIFICATE") keys = catMaybes $ scanAndParse (pkcs1 <> pkcs8 <> cert) $ Char8.lines bs mapM_ (putStrLn . addy . torhash) keys show_cert keyspec wkgrip db = do let s = parseSpec wkgrip keyspec case selectPublicKeyAndSigs s db of [] -> void $ warn (keyspec ++ ": not found") [(_,k,sigs)] -> do {- let rsa = pkcs8 . fromJust $ rsaKeyFromPacket k der = encodeASN1 DER (toASN1 rsa []) qq = Base64.encode (L.unpack der) putStrLn $ writePEM "PUBLIC KEY (TODO: CERT)" qq -- ("TODO "++show keyspec) -} let cs = mapMaybe x509cert $ (sigs >>= hashed_subpackets) ds = map decodeBlob $ map (ParsedCert k (posixSecondsToUTCTime $ fromIntegral $ timestamp k)) cs qqs = map (Base64.encode . L.unpack) ds pems = map (writePEM "CERTIFICATE") qqs forM_ pems putStrLn _ -> void $ warn (keyspec ++ ": ambiguous") {- show_cert certfile _ = do bs <- Char8.readFile certfile let dta = scanAndParse (fmap pemBlob $ pemParser $ Just "CERTIFICATE") $ Char8.lines bs mdta = do dta <- listToMaybe dta L.pack <$> Base64.decode (Char8.unpack dta) let c = mdta >>= parseCertBlob True d = mdta >>= parseCertBlob False -- e = mdta >>= parseCertBlob 2 -- b64 = Base64.encode . S.unpack b64L = Base64.encode . L.unpack -- hex = Base16.encode . S.unpack hexL = Base16.encode . L.unpack putStrLn $ maybe "" (fingerprint . pcertKey) c putStrLn $ maybe "" (torhash . pcertKey) c putStrLn "" putStrLn "" putStrLn $ maybe "" (("key = " ++) . show . pcertKey) c putStrLn "" putStrLn $ maybe "" (("small blob length = " ++) . show . L.length . pcertBlob) c putStrLn $ maybe "" (("small blob = " ++) . b64L . pcertBlob) c putStrLn $ maybe "" ((" decoded = " ++) . b64L . decodeBlob) c putStrLn "" putStrLn $ maybe "" ((" big blob length = " ++) . show . L.length . pcertBlob) d putStrLn $ maybe "" ((" big blob = " ++) . b64L . pcertBlob) d putStrLn $ maybe "" ((" decoded = " ++) . b64L . decodeBlob) d {- putStrLn "" putStrLn $ maybe "" ((" gzip blob length = " ++) . show . L.length . pcertBlob) e putStrLn "" putStrLn $ maybe "" ((" gzip blob = " ++) . b64L . pcertBlob) e -} -- ASN1 starts: -- 1 2 3 4 5 6 7 8 -- cl....pc.tag.......... -- Start Sequence tag = 0x10 -- Start Sequence cl = 0 let v = encodeASN1 DER [Start Sequence] putStrLn "" putStrLn $ "prefix = " ++ hexL v return () -} cannonical_eckey x y = 0x4:pad32(numToBytes x) ++ pad32(numToBytes y) :: [Word8] where numToBytes n = reverse $ unfoldr getbyte n where getbyte d = do guard (d/=0) let (q,b) = d `divMod` 256 return (fromIntegral b,q) pad32 xs = replicate zlen 0 ++ xs where zlen = 32 - length xs bitcoinAddress network_id k = address where Just (MPI x) = lookup 'x' (key k) Just (MPI y) = lookup 'y' (key k) pub = cannonical_eckey x y #if !defined(VERSION_cryptonite) hsh = S.cons network_id . RIPEMD160.hash . SHA256.hash . S.pack $ pub #else hsh = S.cons network_id . ripemd160 . sha256 . S.pack $ pub sha256 x = convert (Crypto.Hash.hash x :: Digest SHA256) :: S.ByteString ripemd160 x = convert (Crypto.Hash.hash x :: Digest RIPEMD160) :: S.ByteString #endif address = base58_encode hsh whoseKey :: RSAPublicKey -> KeyDB -> [KeyData] whoseKey rsakey db = filter matchkey (Map.elems db) where matchkey (KeyData k _ _ subs) = any (ismatch k) $ Map.elems subs ismatch k (SubKey mp sigs) = Just rsakey == rsaKeyFromPacket (packet mp) && any (check (packet k) (packet mp)) sigs check k sub (sig,_) = not . null $ do s <- signatures . Message $ [k,sub,packet sig] fw <- signatures_over $ verify (Message [k]) s subsig <- mapMaybe backsig (unhashed_subpackets $ packet sig) subsig_so <- signatures (Message [k,sub,subsig]) guard ( isSubkeySignature subsig_so && isSameKey (topkey subsig_so) k && isSameKey (subkey subsig_so) sub ) s2 <- signatures . Message $ [k,sub,subsig] signatures_over $ verify (Message [sub]) s2 isSameKey a b = sort (key apub) == sort (key bpub) where apub = secretToPublic a bpub = secretToPublic b kiki_usage :: Bool -> Bool -> Bool -> String -> IO () kiki_usage bExport bImport bSecret cmd = putStr $ case cmd of "show" -> unlines $ ["kiki show [options...]" ,"" ," show displays information about keys stored in the data files which resides in" ," the home directory (see --homedir)." ,"" ," The files pubring.gpg and subring.gpg in the directory specified by the " ," --homedir option are implicitly included in the keyring set." ,"" ,"Options: " ] ++ commonOptions ++ [" --working" ," Show fingerprints for the working key (which will be used to" ," make signatures) and all its subkeys and UID. This action is" ," inferred when no options are supplied." ,"" ," --key SPEC" ," Show fingerprints for the specified key and all its subkeys" ," and UID. (See 'kiki help spec' for more information.)" ,"" ," --all Show fingerprints and UIDs and usage tags for all known keys." ,"" ," --whose-key" ," Shows the fingerprint and UIDs of the key that owns the one that" ," is input on stdin in ssh-rsa format." ,"" ," --dns SPEC" ," Outputs the DNSKEY presentation format (RFC4034) of the public key" ," corresponding to SPEC." ," (See 'kiki help spec' for more information.)" ,"" ," --pem SPEC" ," Outputs the PKCS #8 public key corresponding to SPEC." ," (See 'kiki help spec' for more information.)" ,"" ," --cert SPEC" ," Outputs X509 certificates associated with the key SPEC." ," (See 'kiki help spec' for more information.)" ,"" ," --ssh SPEC" ," Outputs the ssh-rsa blob for the specified public key." ," (See 'kiki help spec' for more information.)" ,"" ," --wip SPEC" ," Outputs the secret crypto-coin key in Wallet Input Format." ," (See 'kiki help spec' for more information.)" ,"" ," --torhash FILE" ," Outputs tor address and base32 hash of the PEM-format key in" ," the given file." ,"" ," --help Shows this help screen." ,"" ] "sync-secret" -> unlines $ ["kiki sync-secret [KEYSPEC ...]" ,"kiki sync-secret FLAGS [--pems KEYSPEC ...] [--keyrings FILE ...] [--hosts FILE ...]" ," [--wallets FILE ...]" ,"" ," sync-secret syncs the information inside your OpenGPG keyring with information" ," in other files. Information flows both in and out of your keyring. This one command" ," is powerful enough to impliment all the functionality of kiki commands in the import-*," ," export-*, and sync-* families. Those other commands are mainly added to facilitate" ," a redundant safe gaurd which restricts the flow of information in such a way that is" ," theoretically less error prone." ,"" ," sync-secret works by first creating a combined database containing all information" ," and then updating all files (including OpenGPG files, as well as files specified as" ," arguments to the options --keyrings, --wallets, and --hosts) with information from" ," from that combined database." ,"" ," Master keys in keyring files are fleshed out with all known subkeys" ," in any file in which they appear. Ordinarily, if a file does not contain the master key" ," already, it will not be added. However, in the case of --import or --import-if-authentic" ," new master keys may be added to your OpenGPG keyring." ,"" ," Cryptocoin keys in wallet files are fleshed out with all CryptoCoin subkeys of the working" ," key. The working key is updated with new CryptoCoin subkeys from all specified wallets." ," Ordinarily, only one wallet is specified on the command line. If multiple wallets are" ," specified, they will all have the same keys after the the operation completes." ,"" ," The --hosts option is experimental and may be removed in the future. Any files given" ," as arguments to this option will be assumed to be in the format of /etc/hosts, and will" ," be updated with any hostname information currently stored within your OpenGPG keyring." ," Additionally, if the file has hostnames for the ip corresponding to a master key, then" ," then the masterkey is updated with unsigned annotations recording the additional hostnames." ," Warning: this effects all master keys, regardless of whether they have secret key" ," information, hence the annotations being unsigned." ,"" ," The files pubring.gpg and secring.gpg in the directory specified by the" ," --homedir option are implicitly included in the keyring set even if they" ," are not included after the --keyrings option." ,"" ," If KEYSPEC arguments appear prior to any of --keyrings, --wallets, or --hosts," ," then they are interpretted as if arguments to --pems." ,"" ] ++ syncflags ++ specifyingFiles "sync-public" -> unlines $ ["kiki sync-public [options...]" ,"" ," sync-public merges a set of key files into a combined database and then" ," uses the database to update all the input files, those inside and outside of" ," of the home directory (see --homedir), to have the most complete information." ,"" ," The files pubring.gpg and secring.gpg in the directory specified by the " ," --homedir option are implicitly included in the keyring set. However, the" ," difference betwen this command and sync-secret is that no secret keys are" ," modified by this command regardless of input. Export of secret keys is" ," possible using this command, but will only occur if the secret master key" ," is already in the external file. (TODO, remove this capacity entirely)" ,"" ," Subkeys that are imported with kiki are given an annotation \"usage@\" which" ," indicates what the key is for. This tag can be used as a SPEC to select a" ," particular key. Master keys may be specified by using fingerprints or by" ," specifying a substring of an associated UID." ,"" ," (See 'kiki help spec' for more information.)" ] ++ syncflags ++ specifyingFiles "import-secret" -> unlines $ ["kiki import-secret [options...]" ,"" ," import-secret uses a set of key files to update your keyring. It does not" ," alter any files outside of the home directory (see --homedir)." ,"" ," The files pubring.gpg and secring.gpg in the directory specified by the " ," --homedir option are implicitly included in the keyring set. Unlike the" ," sync-secret command, information will flow into these files, but not out" ," of them." ,"" ," Subkeys that are imported with kiki are given an annotation \"usage@\" which" ," indicates what the key is for. This tag can be used as a SPEC to select a" ," particular key. Master keys may be specified by using fingerprints or by" ," specifying a substring of an associated UID." ,"" ," (See 'kiki help spec' for more information.)" ] ++ syncflags ++ specifyingFiles "import-public" -> unlines $ ["kiki import-public [options...]" ,"" ," import-public uses a set of key files to update your keyring. It does not" ," alter any files outside of the home directory (see --homedir). Nor does it" ," alter your secring.gpg file." ,"" ," The files pubring.gpg and secring.gpg in the directory specified by the " ," --homedir option are implicitly included in the keyring set. However, the" ," difference betwen this command and import-secret is that no secret keys are" ," modified by this command regardless of input. Export of secret keys is" ," possible using this command, but will only occur if the secret master key" ," is already in the external file. (TODO, remove this capacity entirely)" ,"" ," Subkeys that are imported with kiki are given an annotation \"usage@\" which" ," indicates what the key is for. This tag can be used as a SPEC to select a" ," particular key. Master keys may be specified by using fingerprints or by" ," specifying a substring of an associated UID." ,"" ," (See 'kiki help spec' for more information.)" ] ++ syncflags ++ specifyingFiles "export-secret" -> unlines $ ["kiki export-secret [options...]" ,"" ," export-secret updates a set of key files using information from your keyring." ,"" ," The files pubring.gpg and secring.gpg in the directory specified by the" ," --homedir option are implicitly included in the keyring set. Unlike with the" ," sync-secret command, information only flows out of these files and not in to" ," them. Barring this however, the usage and behavior of export-secret is similar" ," to that of sync-secret." ,"" ," (See 'kiki help spec' for more information.)" ,"" ] ++ syncflags ++ specifyingFiles "export-public" -> unlines $ ["kiki export-public [options...]" ,"" ," export-public updates a set of key files using information from your keyring." ,"" ," The files pubring.gpg and secring.gpg in the directory specified by the " ," --homedir option are implicitly included in the keyring set. However, the" ," difference betwen this command and export-secret is that no secret keys are" ," exported by this command regardless of input." ,"" ," (See 'kiki help spec' for more information.)" ,"" ] ++ syncflags ++ specifyingFiles "spec" -> unlines keyspec where commonOptions :: [String] commonOptions = [" --help" ," Gives usage information" ,"" ] ++ documentHomeDir ++ [""] ++ documentPassphraseFDFlag bExport bImport bSecret showwk :: [String] showwk = [" --show-wk" ," After the operation completes, output the possibly modified" ," working key identity information." ,"" ] syncflags :: [String] syncflags = ["" ,"Flags:"] ++ commonOptions ++ showwk ++ documentImportFlag bExport bImport bSecret ++ documentImportIfAuthenticFlag bExport bImport bSecret ++ documentAutoSignFlag bExport bImport bSecret specifyingFiles :: [String] specifyingFiles = ["SPECIFYING FILES:" ] ++ documentKeyPairsOption bExport bImport bSecret ++ documentKeyRingsOption bExport bImport bSecret ++ documentWalletsOption bExport bImport bSecret ++ documentHostsOption bExport bImport bSecret keyspec :: [String] keyspec = -- unlines $ ["Specifying keys on the kiki command line:" ,"" ," SPEC ::= MASTER/SUBKEY" ,"" ," SPEC indicates a specific key in the keyring, in it's longest incarnation," ," it is of the form MASTER/SUBKEY where MASTER and SUBKEY are documented below." ," If kiki can infer the key unambiguously, either via the command in question or" ," the contents of the keyring, then it is permissable to ommit either MASTER or" ," SUBKEY, in which case the slash may also be ommitted unless it is used via its" ," position to indicate whether a SUBKEY or MASTER is intended." ,"" ," MASTER may be any of" ," * The tail end of a fingerprint prefixed by 'fp:'" ," * A sub-string of a user id (without slashes) prefixed by 'u:'" ," * 40 characters of hexidecimal (kiki will assume this to be a fingerprint)" ," * A sub-string of a user id (without slashes, the prefix 'u:' is optional)" ,"" ," SUBKEY may be any of" ," * The tail end of a fingerprint prefixed by 'fp:'" ," * An exact match of a usage tag prefixed by 't:'" ," * 40 characters of hexidecimal (kiki will assume this to be a fingerprint)" ," * An exact match of a usage tag (The prefix 't:' is optional)" ,"" ," In parsing the spec, kiki will attempt to match the string to one of the" ," above formats, in the order presented." ,"" ," Examples of valid SPEC strings:" ,"" ," fp:4A39F/tor" ," u:joe/tor" ," u:joe/t:tor" ," u:joe/fp:4abf30" ," joe/tor" ," 5E24CD442AA6965D2012E62A905C24185D5379C2" ] documentHomeDir :: [String] documentHomeDir = [" --homedir DIR" ," Where to find the files secring.gpg and pubring.gpg. The" ," default location is taken from the environment variable" ," GNUPGHOME. If this environment variable is not set and no" ," directory is specified using this option then a hardcoded" ," default of ~/.gnupg is assumed. " ,"" ," WARNING: Confusingly, this is *not* your home directory as" ," given by the HOME environment variable. The option is named" ," or rather misnamed in a fashion similar to the gpg option with" ," exactly the same functionality." ] documentPassphraseFDFlag bExport bImport bSecret = if bSecret then [" --passphrase-fd FD" ," The file descripter from which to read a passphrase. If FD is" ," 0, then the passphrase is inputted via stdin. Note that this" ," requires the user to issue CTRL-D to send EOF, so that kiki" ," knows to continue." ,""] else [] documentImportFlag bExport bImport bSecret = if bImport then [" --import Add master keys to pubring.gpg. Without this option, only UID" ," and subkey data is updated. " ,""] else [] documentImportIfAuthenticFlag bExport bImport bSecret = if bImport then [" --import-if-authentic" ," Add signed master keys to pubring.gpg. Like --import except that" ," only keys with signatures from the working key (--show-wk) are" ," imported." ,""] else [] documentAutoSignFlag bExport bImport bSecret = [" --autosign Sign all cross-certified tor-style UIDs." ," A tor-style UID is of the form:" ," Anonymous " ," It is considered cross certified if there exists a cross-certified" ," 'tor' subkey corresponding to the address HOSTNAME.onion." ,""] documentKeyPairsOption :: Bool -> Bool -> Bool -> [String] documentKeyPairsOption bExport bImport bSecret = [" --pems [KEYSPEC ...]" ] ++ case (bExport,bImport,bSecret) of (True,True,True) -> -- sync-secret [" This option specifies the paths of such private PEM files which" ," either currently contain keys to be imported, or lack keys to" ," be exported. If your working key has no subkey with the given" ," tag, and the file is empty or does not exist, and a shell" ," command is specified in braces, then the shell command will be" ," executed in a modified environment with the expectation of" ," creating the PEM file for import." ,"" ] ++ afterSecond (True,True,False) -> -- sync-public NOT-IMPLEMENTED [" This option specifies the paths of PEM files, of both the" ," public and private variety, which either currently contain" ," public keys to be imported, or lack public keys to be exported." ," If your working key has no subkey with the given tag, and the" ," file is empty or does not exist, and a shell command is" ," specified in braces, then the shell command will be executed in" ," a modified environment with the expectation of creating the PEM" ," file for import. Unlike the sync-secret command, this command" ," leaves no possibility of secret key information leaking from" ," your OpenGPG keyring into specified files." ,"" ] ++ afterSecond (False,True,True) -> -- import-secret [" This option specifies the paths of such private PEM files which" ," contain keys to be imported. If your working key has no subkey" ," with the given tag, and the file is empty or does not exist," ," and a shell command is specified in braces, then the shell" ," command will be executed in a modified environment with the" ," expectation of creating the PEM file for import. Files external" ," to your OpenGPG keyring will not be modified by this command." ,"" ] ++ afterSecond (False,True,False) -> -- import-public NOT-IMPLEMENTED [" This option specifies the paths of PEM files, of both the" ," public and private variety, which currently contain keys to" ," be imported. If your working key has no subkey with the" ," given tag, and the file is empty or does not exist, and a" ," shell command is specified in braces, then the shell command" ," will be executed in a modified environment with the" ," expectation of creating the PEM file for import. Files" ," external to your OpenGPG keyring will not be modified by" ," this command. Unlike the import-secret command, this" ," command leaves no possibility of secret key information" ," leaking from your OpenGPG keyring. " ,"" ] ++ afterSecond (True,False,True) -> -- export-secret [" This option specifies the paths of PEM files, of the private or" ," public variety, which lack information to be exported. Note that" ," files currently in the public format may be overwritten to update" ," them to the private format which holds both public and private" ," key information." ,"" ] ++ afterSecond (True,False,False) -> -- export-public [" This option specifies the paths of PEM files, of the private or" ," public variety, which lack public keys to be exported. Unlike" ," the export-secret command, this command leaves no possibility" ," of secret key information leaking from your OpenGPG keyring" ," into the specified files." ,"" ] ++ afterSecond _ -> afterSecond where afterSecond = [" Subkeys that are imported with kiki are given an annotation" ," \"usage@\" which indicates what the key is for. This tag can" ] ++ if bImport then n000Import else n000Export n000Import = [" be used as a SPEC to select a particular key. If a specifed PEM" ," file contains a novel key for an existing tag, it will imported," ," and you will have multiple keys with the same tag." ,"" ," Each KEYSPEC specifies that a key should match the content and" ," timestamp of an external file which is in the PKCS #1 private" ," RSA key format." -- " or in the PKCS #8 public key format." ] ++ n0 n000Export = [" be used as a SPEC to select a particular key." ,"" ," (TODO: check) Each KEYSPEC specifies that a key should match the content and" ," timestamp of an indicated external file which is either in PKCS #1" ," private RSA key format or in PKCS #8 public key format (provided" ," that the file already exists). If the file does not exist, it" ] ++ (if bSecret then n00Secret else n00Public) ++ n0 n00Secret = [" will be created and have PKCS #1 Private RSA Key format." ] n00Public = [" will be created and have PKCS #8 Public Key format." ] n0 = ["" ," If there is only one master key in your keyring and only one" ," key is used for each purpose, then it is possible for SPEC in" ," this case to merely be a tag which offers information about" ," what this key is used for, for example, any of `tor'," ," `ssh-client', `ssh-host', or `strongswan' will do." ,"" ," KEYSPEC ::= tag '=' file" ] ++ if bImport then " | tag '=' file '{' '}'":next else next next = ["" ," Or in more complicated cases," ,"" ," KEYSPEC ::= SPEC '=' file" ] ++ if bImport then " | SPEC '=' file '{' '}'":next' else next' next' = ["" ," where the format of SPEC is documented in 'kiki help spec'." ] ++ next'' next'' = if bImport then timeStamps ++ next''' else next''' timeStamps = ["" ," Your OpenGPG keyring contains time stamps for each subkey." ," Timestamps of newly imported keys will reflect the mtimes of" ," the files from which they were imported. In the case that the" ," key already exists in your OpenGPG keyring as well as in one of" ," the specified files, the timestamp in your OpenGPG keyring is" ," not updated."] next'''= ["" ," Note that this option is implicit if no options documented in" ," this section were specified. See 'kiki help spec' for more" ," information." ,"" ," (See 'kiki help spec' for more information.)" ,"" ] documentKeyRingsOption :: Bool -> Bool -> Bool -> [String] documentKeyRingsOption bExport bImport bSecret = [" --keyrings [FILE ...]" ," These files are PGP keyring files. The format is similar to" ," that of the GNU GPG state files: pubring.gpg and secring.gpg." ," Those files needn't be specified here as they are included" ," implicitly." ,"" ] documentWalletsOption :: Bool -> Bool -> Bool -> [String] documentWalletsOption bExport bImport False = [] documentWalletsOption bExport bImport True = [" --wallets [FILE ...]" ," Provide wallet files with secret crypto-coin keys in Wallet" ," Import Format. The keys will be treated as subkeys of your" ," current working key (the one shown by --show-wk)." ,""] documentHostsOption :: Bool -> Bool -> Bool -> [String] documentHostsOption bExport bImport bSecret = [" --hosts [FILE ...]" ," EXPERIMENTAL! May be removed in the future. This option" ," specifies files from which to read or write hostname aliases." ," The format is the same as /etc/hosts on unix systems. WARNING:" ," hostname aliases may be imported into the gpg keyring files," ," but they are currently NOT signed and may be altered in" ," transit." ,""] -- | -- Arguments: -- -- * option-count pairs - List of option names paired with number of expected values to follow them. -- -- * polyvariadic options - List of option names that can take any number of arguments. -- -- * default polyvariadic - Implicit polyvariadic option if no other option is specified. -- -- * arguments - list of arguments to be parsed. -- -- Returns: -- -- * (non-variadic only) options and corresponding arguemnts in list of lists form. -- -- * (variadic only) map of option name to argument lists. -- processArgs :: [(String,Int)] -> [String] -> String -> [String] -> ([[String]],Map.Map String [String]) processArgs sargspec polyVariadicArgs defaultPoly args_raw = (sargs,margs) where (args,trail1) = break (=="--") args_raw trail = drop 1 trail1 commonArgSpec = [ ("--homedir",1) , ("--passphrase-fd",1) , ("--help",0) ] sargspec' = commonArgSpec ++ sargspec (sargs,margs) = (sargs, foldl' (\m (k:xs)->Map.alter (appendArgs k xs) k m) Map.empty gargs) where (sargs,vargs) = partitionStaticArguments sargspec' args argspec = map fst sargspec' ++ polyVariadicArgs args' = if null defaultPoly || map (take 1) (take 1 vargs) == ["-"] then vargs else defaultPoly:vargs -- grouped args gargs = (sargs ++) . toLast (++trail) . groupBy (\_ s-> take 1 s /= "-") $ args' appendArgs k xs opt = if k `elem` argspec then Just . maybe xs (++xs) $ opt else error . unlines $ [ "unrecognized option "++k , "Use --help for usage." ] parseCommonArgs margs = CommonArgsParsed { cap_homespec = homespec, cap_passfd = passfd } where passphrase_fd = concat <$> Map.lookup "--passphrase-fd" margs homespec = join . take 1 <$> Map.lookup "--homedir" margs passfd = fmap (FileDesc . read) passphrase_fd parseKeySpecs = map $ \specfile -> do let (spec,efilecmd) = break (=='=') specfile guard $ take 1 efilecmd=="=" let filecmd = drop 1 efilecmd let (file,bcmdb0) = break (=='{') filecmd bcmdb = if null bcmdb0 then "{}" else bcmdb0 guard $ take 1 bcmdb=="{" let bdmcb = (dropWhile isSpace . reverse) bcmdb guard $ take 1 bdmcb == "}" let cmd = (drop 1 . reverse . drop 1) bdmcb Just (spec,file,cmd) buildStreamInfo :: KeyFilter -> FileType -> StreamInfo buildStreamInfo rtyp ftyp = StreamInfo { typ = ftyp , fill = rtyp , spill = KF_All , access = AutoAccess , initializer =NoCreate , transforms = [] } -- Flag-specific options -- bSecret: --pems and --wallets -- bImport: --import and --import-if-authentic sync :: Bool -> Bool -> Bool -> String -> [String] -> IO () sync bExport bImport bSecret cmdarg args_raw = do let (sargs,margs) = processArgs sargspec polyVariadicArgs "--pems" args_raw sargspec = [ ("--show-wk",0) , ("--autosign",0) {-, ("--show-all",0) , ("--show-whose-key",0) , ("--show-key",1) , ("--show-pem",1) , ("--show-ssh",1) , ("--show-wip",1) -} ] ++ do guard bImport [ ("--import",0), ("--import-if-authentic",0) ] polyVariadicArgs = ["--keyrings" ,"--hosts" ,"--pems"] ++ do guard bSecret [ "--wallets" ] -- putStrLn $ "margs = " ++ show (Map.assocs margs) unkeysRef <- newIORef Map.empty pwRef <- newIORef Nothing let keypairs0 = parseKeySpecs specs specs = fromMaybe [] $ Map.lookup "--pems" margs keyrings_ = fromMaybe [] $ Map.lookup "--keyrings" margs wallets = fromMaybe [] $ Map.lookup "--wallets" margs passphrase_fd = concat <$> Map.lookup "--passphrase-fd" margs forM_ (take 1 $ filter (isNothing . fst) $ zip keypairs0 specs ) $ \(_,badspec) -> do warn $ "Syntax error in key pair specification " ++ show badspec exitFailure input_key <- maybe (return Nothing) (const $ fmap (Just . readPublicKey) Char8.getContents) $ Map.lookup "--show-whose-key" margs let keypairs = catMaybes keypairs0 homespec = join . take 1 <$> Map.lookup "--homedir" margs passfd = fmap (FileDesc . read) passphrase_fd reftyp = if bExport then KF_Subkeys else KF_None pems = flip map keypairs $ \(usage,path,cmd) -> let cmd' = mfilter (not . null) (Just cmd) in if bExport then (ArgFile path, StreamInfo { fill = KF_Match usage , spill = KF_Match usage , typ = if "dns-" `isPrefixOf` usage then DNSPresentation else PEMFile , access = if bSecret then Sec else Pub , initializer = maybe NoCreate External cmd' , transforms = [] } ) else if isNothing cmd' then ( ArgFile path , (buildStreamInfo KF_None PEMFile) { spill = KF_Match usage }) else error "Unexpected PEM file initializer." walts = map (\fname -> ( ArgFile fname , (buildStreamInfo reftyp WalletFile) { access = Sec })) wallets rings = map (\fname -> ( ArgFile fname , buildStreamInfo reftyp KeyRingFile )) keyrings_ hosts = maybe [] (map decorate) $ Map.lookup "--hosts" margs where decorate fname = (ArgFile fname, buildStreamInfo reftyp Hosts) pubfill = maybe KF_Subkeys id $ mplus import_f importifauth_f where import_f = fmap (const KF_All) $ Map.lookup "--import" margs importifauth_f = fmap (const KF_Authentic) $ Map.lookup "--import-if-authentic" margs kikiOp = KeyRingOperation { opFiles = Map.fromList $ [ ( HomeSec, buildStreamInfo (if bSecret && bImport then KF_All else KF_None) KeyRingFile ) , ( HomePub, buildStreamInfo (if bImport then pubfill else KF_None) KeyRingFile ) ] ++ rings ++ pems ++ if bSecret then walts else [] ++ hosts , opPassphrases = do pfile <- maybeToList passfd return $ PassphraseSpec Nothing Nothing pfile , opTransforms = maybe [] (const [Autosign]) $ Map.lookup "--autosign" margs , opHome = homespec } (\f -> maybe f (const $ kiki_usage bExport bImport bSecret cmdarg) $ Map.lookup "--help" margs) $ do KikiResult rt report <- runKeyRing kikiOp case rt of KikiSuccess rt -> do -- interpret --show-* commands. let grip = rtGrip rt let shspec = Map.fromList [("--show-wk", const $ show_wk (rtSecring rt) grip) {-,("--show-all",const show_all) ,("--show-whose-key", const $ show_whose_key input_key) ,("--show-key",\[x] -> show_id x $ fromMaybe "" grip) ,("--show-pem",\[x] -> show_pem x $ fromMaybe "" grip) ,("--show-ssh",\[x] -> show_ssh x $ fromMaybe "" grip) ,("--show-wip",\[x] -> show_wip x $ fromMaybe "" grip)-} ] shargs = mapMaybe (\(x:xs) -> (,xs) <$> Map.lookup x shspec) sargs forM_ shargs $ \(cmd,args) -> cmd args (rtKeyDB rt) err -> putStrLn $ errorString err forM_ report $ \(fname,act) -> do putStrLn $ fname ++ ": " ++ reportString act kiki :: String -> [String] -> IO () kiki "sync-secret" args_raw = sync True True True "sync-secret" args_raw kiki "sync-public" args_raw = sync True True False "sync-public" args_raw kiki "import-secret" args_raw = sync False True True "import-secret" args_raw kiki "import-public" args_raw = sync False True False "import-public" args_raw kiki "export-secret" args_raw = sync True False True "export-secret" args_raw kiki "export-public" args_raw = sync True False False "export-public" args_raw -- Generic help kiki "help" [] = do putStrLn "Valid commands are:" let longest = maximum $ map (length . fst) commands pad cmd = take (longest+3) $ cmd ++ repeat ' ' forM commands $ \(cmd,help) -> do putStrLn $ " " ++ pad cmd ++ help putStr . unlines $ ["" ,"See 'kiki help ' for more information on a specific command." ,"Or see 'kiki help spec' for kiki's notation for specifying keys." ] return () kiki "help" args = forM_ args $ \arg -> case lookup arg commands of Nothing | arg == "spec" -> kiki_usage False False False arg Nothing | arg == "SPEC" -> kiki_usage False False False arg Nothing -> putStrLn $ "No help available for commmand '" ++ arg ++ "'." _ -> kiki arg ["--help"] kiki "show" [] = kiki "show" ["--working"] kiki "show" args = do let (sargs,margs) = processArgs sargspec polyVariadicArgs "--show" args sargspec = [ ("--working",0) --("--show-wk",0) , ("--all",0) --("--show-all",0) , ("--whose-key",0) , ("--key",1) , ("--pem",1) , ("--dns",1) , ("--ssh",1) , ("--wip",1) , ("--cert",1) , ("--torhash",1) ] polyVariadicArgs = ["--show"] let cap = parseCommonArgs margs homespec = cap_homespec cap passfd = cap_passfd cap pems = [] rings = [] hosts = [] walts = [] streaminfo = StreamInfo { fill = KF_None , typ = KeyRingFile , spill = KF_All , initializer = NoCreate , access = AutoAccess , transforms = [] } kikiOp = KeyRingOperation { opFiles = Map.fromList $ [ ( HomeSec, streaminfo { access = Sec }) , ( HomePub, streaminfo { access = Pub }) ] ++ rings ++ pems ++ walts ++ hosts , opPassphrases = do pfile <- maybeToList passfd return $ PassphraseSpec Nothing Nothing pfile , opTransforms = [] , opHome = homespec } (\f -> maybe f (const $ kiki_usage False False False "show") $ Map.lookup "--help" margs) $ do KikiResult rt report <- runKeyRing kikiOp input_key <- maybe (return Nothing) (const $ fmap (Just . readPublicKey) Char8.getContents) $ Map.lookup "--whose-key" margs case rt of KikiSuccess rt -> do -- interpret --show-* commands. let grip = rtGrip rt let shspec = Map.fromList [("--working", const $ show_wk (rtSecring rt) grip) ,("--all",const show_all) ,("--whose-key", const $ show_whose_key input_key) ,("--key",\[x] -> show_id x $ fromMaybe "" grip) ,("--pem",\[x] -> show_pem x $ fromMaybe "" grip) ,("--dns",\[x] -> show_dns x $ fromMaybe "" grip) ,("--ssh",\[x] -> show_ssh x $ fromMaybe "" grip) ,("--wip",\[x] -> show_wip x $ fromMaybe "" grip) ,("--cert",\[x] -> show_cert x $ fromMaybe "" grip) ,("--torhash",\[x] -> show_torhash x) ] shargs = mapMaybe (\(x:xs) -> (,xs) <$> Map.lookup x shspec) sargs forM_ shargs $ \(cmd,args) -> cmd args (rtKeyDB rt) err -> putStrLn $ errorString err forM_ report $ \(fname,act) -> do putStrLn $ fname ++ ": " ++ reportString act kiki "merge" [] = do putStr . unlines $ [ "kiki merge [ --passphrase-fd=FD ... ]" , " ( --home[=HOMEDIR]" , " | --type=(keyring|pem|wallet|hosts|dns)" , " | --access=[auto|secret|public]" , " | --flow=(fill|spill|sync)[,(subkeys|match=SPEC)]" , " | --create=CMD" , " | --autosign[=no]" , " | --delete=FINGERPRINT" , " | --" , " | FILE ) ..."] kiki "merge" args | "--help" `elem` args = do kiki "merge" [] -- TODO: more help kiki "merge" args = do hPutStrLn stderr $ show op KikiResult rt report <- runKeyRing op case rt of KikiSuccess rt -> return () err -> putStrLn $ errorString err forM_ report $ \(fname,act) -> do putStrLn $ fname ++ ": " ++ reportString act where (_,(_,op)) = foldl' buildOp (True,(flow,noop)) args noop = KeyRingOperation { opFiles = Map.empty , opTransforms = [] , opHome = Nothing , opPassphrases = [] } flow = StreamInfo { access = AutoAccess , typ = KeyRingFile , spill = KF_None , fill = KF_None , initializer = NoCreate , transforms = [] } updateFlow fil spil mtch flow = spill' $ fill' $ flow where fill' flow = flow { fill = if fil then val else KF_None } spill' flow = flow { spill = if spil then val else KF_None } val = either (\subkeys -> if subkeys then KF_Subkeys else KF_All) KF_Match mtch parseFlow :: String -> Maybe ((Bool,Bool),Either Bool String) parseFlow spec = if null bads then Just ( ( "spill" `elem` goods || "sync" `elem` goods , "fill" `elem` goods || "sync" `elem` goods ) , maybe (Left $ "subkeys" `elem` goods) Right match ) else Nothing where ws = case groupBy (\_ c->c/=',') spec of w:xs -> w:map (drop 1) xs [] -> [] (goods,bads) = partition acceptable ws acceptable :: String -> Bool acceptable "spill" = True acceptable "fill" = True acceptable "sync" = True acceptable "subkeys" = True acceptable s | "match=" `isPrefixOf` s = True acceptable _ = False match = listToMaybe $ do m <- filter ("match=" `isPrefixOf`) goods return $ drop 6 m doFile :: StreamInfo -> KeyRingOperation -> FilePath -> (StreamInfo,KeyRingOperation) doFile flow op fname = ( flow , op { opFiles= Map.insert (ArgFile fname) flow (opFiles op) }) doDelete :: String -> StreamInfo -> KeyRingOperation -> (StreamInfo,KeyRingOperation) doDelete fp flow op = ( flow , op { opTransforms = opTransforms op ++ [DeleteSubkeyByFingerprint fp] } ) doAutosign :: Bool -> StreamInfo -> KeyRingOperation -> (StreamInfo,KeyRingOperation) doAutosign True flow op = if Map.null (opFiles op) then (flow, op { opTransforms = opTransforms op ++ [Autosign] }) else (flow { transforms = transforms flow ++ [Autosign] }, op) doAutosign False flow op = ( flow { transforms = filter (/=Autosign) (transforms flow) } , op { opTransforms = filter (/=Autosign) (opTransforms op) } ) doPassphrase :: StreamInfo -> KeyRingOperation -> String -> (StreamInfo,KeyRingOperation) doPassphrase flow op pass = if Map.null (opFiles op) then ( flow , op { opPassphrases = PassphraseSpec Nothing Nothing pfd : opPassphrases op } ) else error "passphrase-fd must come before any file arguments or --home" where pfd = FileDesc (read pass) buildOp (False,(flow,op)) fname = (False,doFile flow op fname) buildOp (True,(flow,op)) arg@(splitArg->parsed) = case parsed of Left ("",Nothing) -> (False,(flow,op)) _ -> (True,) dispatch where dispatch = case parsed of Right fname -> doFile flow op fname Left ("delete",Just fp) -> doDelete fp flow op Left ("autosign",Nothing) -> doAutosign True flow op Left ("autosign",Just "y") -> doAutosign True flow op Left ("autosign",Just "yes") -> doAutosign True flow op Left ("autosign",Just "true") -> doAutosign True flow op Left ("autosign",Just "n") -> doAutosign False flow op Left ("autosign",Just "no") -> doAutosign False flow op Left ("autosign",Just "false")-> doAutosign False flow op Left ("passphrase-fd",Just pass) -> doPassphrase flow op pass Left ("create",Just cmd) -> ( flow { initializer = if null cmd then NoCreate else External cmd } , op ) Left ("type",Just "keyring") -> ( flow { typ = KeyRingFile } , op ) Left ("type",Just "pem" ) -> ( flow { typ = PEMFile } , op ) Left ("type",Just "wallet" ) -> ( flow { typ = WalletFile } , op ) Left ("type",Just "hosts" ) -> ( flow { typ = Hosts } , op ) Left ("type",Just "dns" ) -> ( flow { typ = DNSPresentation } , op ) Left ("access",Just "public") -> ( flow { access = Pub }, op ) Left ("access",Just "secret") -> ( flow { access = Sec }, op ) Left ("access",Just "auto") -> ( flow { access = AutoAccess }, op ) Left ("home",mb) -> ( flow , op { opFiles = Map.insert HomePub (flow { typ=KeyRingFile , access=Pub }) $ Map.insert HomeSec (flow { typ=KeyRingFile , access=Sec }) $ opFiles op , opHome = opHome op `mplus` mb } ) Left ("flow",Just flowspec) -> case parseFlow flowspec of Just ( (spil,fil), mtch ) -> ( updateFlow fil spil mtch flow , op ) Nothing -> error "Valid flow words are: spill,fill,sync,subkeys or match=KEYSPEC" Left (option,_) -> error $ "Unrecognized option: " ++ option kiki "init" args | "--help" `elem` args = do putStr . unlines $ [ "kiki init [ --passphrase-fd=FD" , " | --homedir[=HOMEDIR]" , " | --chroot=ROOTDIR ] ..." , "" , "Initialize a GnuPG keyring for use with kiki. After completion, you" , "willl have a GnuPG master key with following specialized subkeys:" , "" , " tor - freshly generated tor hidden service key" , " ipsec - freshly generated VPN key" , " ssh-server - possibly read from /etc/ssh/*" , " ssh-client - possibly read from /root/.ssh/id_rsa" , "" , "OPTIONS" , "" , " --chroot=ROOTDIR" , " Use ROOTDIR for input of ssh keys and export files to" , " ROOTDIR/var/cache/kiki instead of the current system path." , " When this option is specified, the GNUPGHOME environment" , " variable is ignored and you must use --homedir to specify" , " a value other than /root/.gnupg." , "" ] ++ documentHomeDir ++ [""] ++ documentPassphraseFDFlag True True True kiki "init" args = run args $ importAndRefresh <$> ㄧchroot <*> ㄧhomedir kiki "delete" args | "--help" `elem` args = do putStr . unlines $ [ "kiki delete ..." , "" , " Delete the subkeys specified by the given fingerprints along" , " with all associated signatures and trust markers." ] return () kiki "delete" args = do let (sargs,margs) = processArgs sargspec polyVariadicArgs "--delete" args where sargspec = [] polyVariadicArgs = ["--delete"] passfd = fmap (FileDesc . read) passphrase_fd where passphrase_fd = concat <$> Map.lookup "--passphrase-fd" margs fps = fromMaybe [] $ Map.lookup "--delete" margs homespec = join . take 1 <$> Map.lookup "--homedir" margs kikiOp = KeyRingOperation { opFiles = Map.fromList $ [ ( HomeSec, buildStreamInfo KF_All KeyRingFile ) , ( HomePub, buildStreamInfo KF_All KeyRingFile ) ] , opPassphrases = do pfile <- maybeToList passfd return $ PassphraseSpec Nothing Nothing pfile , opTransforms = map DeleteSubkeyByFingerprint fps , opHome = homespec } KikiResult rt report <- runKeyRing kikiOp forM_ report $ \(fname,act) -> do putStrLn $ fname ++ ": " ++ reportString act kiki "tar" args | "--help" `elem` args = do putStr . unlines $ [ "kiki tar (-c|-t) [--secrets SPEC] [--passphrase-fd FD] [--homedir HOMEDIR]" , "" , "Import or export a tar archive containing key files in the proper" , "format for software configuration." , "" ," -c Generate tar archive on stdout." ,"" ," -t List filepaths that would be included in the (-c) output archive." ,"" ," --secrets SPEC" ," Include secret keys for the specified identity." ," Otherwise, only public keys are included." ,"" ," SPEC is matched against the following forms in order:" ,"" ," -" ," (current working identity)" ,"" ," fp:4A39F" ," (tail end of a fingerprint prefixed by 'fp:')" ,"" ," u:joe" ," (sub-string of a user id prefixed by 'u:')" ,"" ," 5E24CD442AA6965D2012E62A905C24185D5379C2" ," (fingerprint as 40 characters of hexidecimal)" ,"" ," joe" ," (sub-string of a user id without 'u:' prefix)" ] kiki "tar" args = do let parsed_args = processArgs sargspec [] "" args sargspec = [("-t",0),("-c",0),("--secrets",1)] ismode ("-t":_) = True ismode ("-c":_) = True ismode _ = False case filter ismode (fst parsed_args) of ["-t":_] -> tarT parsed_args ["-c":_] -> tarC parsed_args ["-A":_] -> putStrLn "unimplemented." -- import tar file? _ -> kiki "tar" ["--help"] tarContent rt spec pubpem knownhosts secpem = ipsecs ++ sshs ++ secrets "root" where ipsecs = do (kk,ipsec,sigs) <- selectPublicKeyAndSigs (KeyUidMatch "",Just "ipsec") (rtKeyDB rt) let kd = (rtKeyDB rt Map.! kk) k = packet $ keyMappedPacket kd (addr,(onames,ns)) = getHostnames kd oname <- onames return ("etc/ipsec.d/certs/" ++ Char8.unpack oname ++ ".pem", pubpem ns addr ipsec sigs) sshs = case selectPublicKeyAndSigs (KeyUidMatch "",Just "ssh-host") (rtKeyDB rt) of [] -> [] ssh_sel -> [("etc/ssh/ssh_known_hosts", knownhosts ssh_sel)] secrets_kd = case fst . parseSpec "" <$> (++"/") <$> spec of _ | spec == Just "-" || spec == Just "" -> maybeToList (rtWorkingKey rt) >>= return . (Map.!) (rtKeyDB rt) . keykey Just topspec -> map snd $ filterMatches topspec $ Map.toList $ rtKeyDB rt w -> [] lookupSecret tag kd = maybeToList $ selectSecretKey (KeyGrip "",Just tag) m where m = Map.singleton (keykey $ keyPacket kd) kd sshkeyname SecretKeyPacket { key_algorithm = RSA } = "id_rsa" dir :: FilePath -> FilePath dir d = d -- TODO: prepend prefix path? spem d k = (d, secpem k) secrets homedir = do kd <- secrets_kd let torkey = spem (dir "var/lib/tor/samizdat/private_key") <$> lookupSecret "tor" kd sshcli = do k <- lookupSecret "ssh-client" kd return $ spem (dir $ homedir ++ "/.ssh/" ++ sshkeyname k) k sshsvr = spem (dir "etc/ssh/ssh_host_rsa_key") <$> lookupSecret "ssh-host" kd ipseckey = do k <- lookupSecret "ipsec" kd oname <- fst . snd $ getHostnames kd return $ spem (dir $ "etc/ipsec.d/private/"++Char8.unpack oname++".pem") k torkey ++ sshcli ++ sshsvr ++ ipseckey tarT :: ([[String]],Map.Map String [String]) -> IO () tarT (sargs,margs) = do KikiResult rt report <- runKeyRing $ minimalOp $ parseCommonArgs margs case rt of KikiSuccess rt -> do let keyspec = concat . take 1 <$> Map.lookup "--secrets" margs nil = error "internal error!" fs = map fst $ tarContent rt keyspec nil nil nil mapM_ putStrLn fs err -> putStrLn $ errorString err tarC :: ([[String]],Map.Map String [String]) -> IO () tarC (sargs,margs) = do KikiResult rt report <- runKeyRing $ minimalOp $ parseCommonArgs margs case rt of KikiSuccess rt -> do CTime pubtime <- modificationTime <$> getFileStatus (rtPubring rt) let keyspec = concat . take 1 <$> Map.lookup "--secrets" margs fs = tarContent rt keyspec build_ipsec (build_ssh rt pubtime) (build_secret rt) es = do (n,(epoch_time_int64,ebs)) <- fs let mktar' = mktar n epoch_time_int64 return $ case ebs of Right bs -> return $ either (const Nothing) Just $ mktar' bs Left iombs -> do mbs <- iombs case mbs of Nothing -> return Nothing Just bs -> return $ either (const Nothing) Just $ mktar' bs tarbs <- Tar.write . mapMaybe id <$> sequence es L.putStr tarbs err -> putStrLn $ errorString err where build_ipsec ns addr ipsec sigs = ( fromIntegral $ timestamp ipsec , Right $ Char8.pack $ fromJust $ pemFromPacket ipsec) build_ssh rt timestamp sshs = (timestamp, Right $ Char8.unlines $ map knownhost sshs) where knownhost (kk,hostkey,sigs) = Char8.intercalate "," ns <> " " <> Char8.pack (sshblobFromPacket hostkey) where ns = onames ++ others (_,(onames,others)) = getHostnames $ rtKeyDB rt Map.! kk build_secret rt k = ( fromIntegral $ timestamp k , Left $ fmap Char8.pack . (>>= secretPemFromPacket) <$> decrypt rt k ) mktar n epoch_time_int64 bs = do torpath <- Tar.toTarPath False n Right $ (Tar.fileEntry torpath bs) { Tar.entryTime = epoch_time_int64 } decrypt :: KeyRingRuntime -> Packet -> IO (Maybe Packet) decrypt rt k@SecretKeyPacket { symmetric_algorithm = Unencrypted } = return $ Just k decrypt rt k = do r <- rtPassphrases rt (MappedPacket k Map.empty) case r of KikiSuccess p -> return $ Just p _ -> do hPutStrLn stderr $ "Failed to decrypt "++fingerprint k++"." return Nothing -- | -- -- no leading hyphen, returns Right (input string). -- -- single leading hyphen, quits program with "Unrecognized option" error -- -- Otherwise, Left (key-value pair) is returend by parsing -- a string of the form --key=value. splitArg :: String -> Either (String,Maybe String) String splitArg arg = case hyphens of "" -> Right name "-" -> error $ "Unrecognized option: " ++ arg _ -> Left $ parseLongOption name where (hyphens, name) = span (=='-') arg parseLongOption name = (key,val v) where (key,v) = break (=='=') name val ('=':vs) = Just vs val _ = Nothing commands :: [(String,String)] commands = [ ( "help", "display usage information" ) --, ( "sync", "update key files of various kinds by propogating information" ) , ( "show", "display information from your keyrings") , ( "sync-secret", "update key files of various kinds by propogating information (both secret and public)" ) , ( "sync-public", "update key files of various kinds by propogating public information" ) , ( "import-secret", "import (both public and secret) information into your keyring" ) , ( "import-public", "import (public) information into your keyring" ) , ( "export-secret", "export (both public and secret) information into your keyring" ) , ( "export-public", "import (public) information into your keyring" ) , ( "merge", "low level import/export operation" ) -- , ( "init-key", "initialize the samizdat key ring") , ( "init", "Initialize kiki") , ( "delete", "Delete a subkey and its associated signatures" ) , ( "tar", "import or export system key files in tar format" ) ] main = do dotlock_init args_raw <- getArgs case args_raw of [] -> kiki "show" ["--working"] cmd : args | cmd `elem` map fst commands -> kiki cmd args _ -> kiki "help" [] --args_raw