if authentication with the session fails try authenticating with hmac
[nodemanager.git] / plcapi.py
1 # $Id$
2
3 import safexmlrpc
4 import hmac, sha
5
6 class PLCAPI:
7     """
8     Wrapper around safexmlrpc.ServerProxy to automagically add an Auth
9     struct as the first argument to every XML-RPC call. Initialize
10     auth with either:
11
12     (node_id, key) => BootAuth
13     or
14     session => SessionAuth
15
16     To authenticate using the Boot Manager authentication method, or
17     the new session-based method.
18     """
19
20     def __init__(self, uri, cacert, auth, timeout = 90, **kwds):
21         self.uri = uri
22         self.cacert = cacert
23         self.timeout = timeout
24
25         if isinstance(auth, (tuple, list)):
26             (self.node_id, self.key) = auth
27             self.session = None
28         elif isinstance(auth, (str, unicode)):
29             self.node_id = self.key = None
30             self.session = auth
31         else:
32             self.node_id = self.key = self.session = None
33
34         self.server = safexmlrpc.ServerProxy(self.uri, self.cacert, self.timeout, allow_none = 1, **kwds)
35         
36         self.__check_authentication()
37
38
39     def __update_session(self, f="/usr/boot/plnode.txt"):
40         # try authenticatipopulate /etc.planetlab/session 
41         def plnode(key):
42             try:
43                 return [i[:-1].split('=') for i in open(f).readlines() if i.startswith(key)][0][1].strip('"')
44             except:
45                 return None
46
47         auth = (int(plnode("NODE_ID")), plnode("NODE_KEY"))
48         plc = PLCAPI(self.uri, self.cacert, auth, self.timeout)
49         open("/etc/planetlab/session", 'w').write(plc.GetSession().strip())
50         self.session = open("/etc/planetlab/session").read().strip()
51         
52     def __check_authentication(self):
53         # just a simple call to check authentication
54         def check():
55             if (self.node_id and self.key) or self.session:
56                 if self.AuthCheck() == 1: return True
57             return False
58         if not check():
59             if self.node_id and self.key:
60                 # if hmac fails, just make it fail
61                 raise Exception, "Unable to authenticate with hmac"
62             else:
63                 self.__update_session()
64                 if not check():
65                     raise Exception, "Unable to authenticate with session"
66     
67
68     def add_auth(self, function):
69         """
70         Returns a wrapper which adds an Auth struct as the first
71         argument when the function is called.
72         """
73
74         def canonicalize(args):
75             """
76             BootAuth canonicalization method. Parameter values are
77             collected, sorted, converted to strings, then hashed with
78             the node key.
79             """
80
81             values = []
82
83             for arg in args:
84                 if isinstance(arg, list) or isinstance(arg, tuple):
85                     # The old implementation did not recursively handle
86                     # lists of lists. But neither did the old API itself.
87                     values += canonicalize(arg)
88                 elif isinstance(arg, dict):
89                     # Yes, the comments in the old implementation are
90                     # misleading. Keys of dicts are not included in the
91                     # hash.
92                     values += canonicalize(arg.values())
93                 else:
94                     # We use unicode() instead of str().
95                     values.append(unicode(arg))
96
97             return values
98
99         def wrapper(*params):
100             """
101             Adds an Auth struct as the first argument when the
102             function is called.
103             """
104
105             if self.session is not None:
106                 # Use session authentication
107                 auth = {'AuthMethod': "session",
108                         'session': self.session}
109             else:
110                 # Yes, this is the "canonicalization" method used.
111                 args = canonicalize(params)
112                 args.sort()
113                 msg = "[" + "".join(args) + "]"
114
115                 # We encode in UTF-8 before calculating the HMAC, which is
116                 # an 8-bit algorithm.
117                 digest = hmac.new(self.key, msg.encode('utf-8'), sha).hexdigest()
118
119                 auth = {'AuthMethod': "hmac",
120                         'node_id': self.node_id,
121                         'value': digest}
122
123             # Automagically add auth struct to every call
124             params = (auth,) + params
125
126             return function(*params)
127
128         return wrapper
129
130     def __getattr__(self, methodname):
131         function = getattr(self.server, methodname)
132         return self.add_auth(function)