Statistics
| Branch: | Tag: | Revision:

root / htools / Ganeti / Confd / Utils.hs @ 26d62e4c

History | View | Annotate | Download (2.5 kB)

1
{-| Implementation of the Ganeti confd utilities.
2

    
3
This holds a few utility functions that could be useful in both
4
clients and servers.
5

    
6
-}
7

    
8
{-
9

    
10
Copyright (C) 2011, 2012 Google Inc.
11

    
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.
16

    
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.
21

    
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
25
02110-1301, USA.
26

    
27
-}
28

    
29
module Ganeti.Confd.Utils
30
  ( getClusterHmac
31
  , parseRequest
32
  , parseMessage
33
  , signMessage
34
  ) where
35

    
36
import qualified Data.ByteString as B
37
import qualified Text.JSON as J
38

    
39
import Ganeti.BasicTypes
40
import Ganeti.Confd
41
import Ganeti.Hash
42
import qualified Ganeti.Constants as C
43
import qualified Ganeti.Path as Path
44
import Ganeti.JSON
45
import Ganeti.Utils
46

    
47
-- | Returns the HMAC key.
48
getClusterHmac :: IO HashKey
49
getClusterHmac = fmap B.unpack $ B.readFile Path.confdHmacKey
50

    
51
-- | Parses a signed request.
52
parseRequest :: HashKey -> String -> Result (String, String, ConfdRequest)
53
parseRequest key str = do
54
  (SignedMessage hmac msg salt) <- fromJResult "parsing request" $ J.decode str
55
  req <- if verifyMac key (Just salt) msg hmac
56
           then fromJResult "parsing message" $ J.decode msg
57
           else Bad "HMAC verification failed"
58
  return (salt, msg, req)
59

    
60
-- | Mesage parsing. This can either result in a good, valid message,
61
-- or fail in the Result monad.
62
parseMessage :: HashKey -> String -> Integer
63
             -> Result (String, ConfdRequest)
64
parseMessage hmac msg curtime = do
65
  (salt, origmsg, request) <- parseRequest hmac msg
66
  ts <- tryRead "Parsing timestamp" salt::Result Integer
67
  if abs (ts - curtime) > fromIntegral C.confdMaxClockSkew
68
    then fail "Too old/too new timestamp or clock skew"
69
    else return (origmsg, request)
70

    
71
-- | Signs a message with a given key and salt.
72
signMessage :: HashKey -> String -> String -> SignedMessage
73
signMessage key salt msg =
74
  SignedMessage { signedMsgMsg  = msg
75
                , signedMsgSalt = salt
76
                , signedMsgHmac = hmac
77
                }
78
    where hmac = computeMac key (Just salt) msg