1 {-| Implementation of the Ganeti confd utilities.
3 This holds a few utility functions that could be useful in both
10 Copyright (C) 2011, 2012 Google Inc.
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 2 of the License, or
15 (at your option) any later version.
17 This program is distributed in the hope that it will be useful, but
18 WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
29 module Ganeti.Confd.Utils
37 import qualified Data.ByteString as B
38 import qualified Text.JSON as J
41 import Ganeti.BasicTypes
42 import Ganeti.Confd.Types
44 import qualified Ganeti.Constants as C
45 import qualified Ganeti.Path as Path
49 -- | Type-adjusted max clock skew constant.
50 maxClockSkew :: Integer
51 maxClockSkew = fromIntegral C.confdMaxClockSkew
53 -- | Returns the HMAC key.
54 getClusterHmac :: IO HashKey
55 getClusterHmac = Path.confdHmacKey >>= fmap B.unpack . B.readFile
57 -- | Parses a signed request.
58 parseRequest :: HashKey -> String -> Result (String, String, ConfdRequest)
59 parseRequest key str = do
60 (SignedMessage hmac msg salt) <- fromJResult "parsing request" $ J.decode str
61 req <- if verifyMac key (Just salt) msg hmac
62 then fromJResult "parsing message" $ J.decode msg
63 else Bad "HMAC verification failed"
64 return (salt, msg, req)
66 -- | Message parsing. This can either result in a good, valid message,
67 -- or fail in the Result monad.
68 parseMessage :: HashKey -> String -> Integer
69 -> Result (String, ConfdRequest)
70 parseMessage hmac msg curtime = do
71 (salt, origmsg, request) <- parseRequest hmac msg
72 ts <- tryRead "Parsing timestamp" salt::Result Integer
73 if abs (ts - curtime) > maxClockSkew
74 then fail "Too old/too new timestamp or clock skew"
75 else return (origmsg, request)
77 -- | Signs a message with a given key and salt.
78 signMessage :: HashKey -> String -> String -> SignedMessage
79 signMessage key salt msg =
80 SignedMessage { signedMsgMsg = msg
81 , signedMsgSalt = salt
82 , signedMsgHmac = hmac
84 where hmac = computeMac key (Just salt) msg
86 -- | Returns the current time.
87 getCurrentTime :: IO Integer
89 TOD ctime _ <- getClockTime