cb6e6867f38158c164bdee0b838b0923a821ebb9
[sfa.git] / sfa / trust / abac_credential.py
1 #----------------------------------------------------------------------
2 # Copyright (c) 2014 Raytheon BBN Technologies
3 #
4 # Permission is hereby granted, free of charge, to any person obtaining
5 # a copy of this software and/or hardware specification (the "Work") to
6 # deal in the Work without restriction, including without limitation the
7 # rights to use, copy, modify, merge, publish, distribute, sublicense,
8 # and/or sell copies of the Work, and to permit persons to whom the Work
9 # is furnished to do so, subject to the following conditions:
10 #
11 # The above copyright notice and this permission notice shall be
12 # included in all copies or substantial portions of the Work.
13 #
14 # THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
18 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
19 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
21 # IN THE WORK.
22 #----------------------------------------------------------------------
23
24 from __future__ import print_function
25
26 from sfa.trust.credential import Credential, append_sub, DEFAULT_CREDENTIAL_LIFETIME
27 from sfa.util.sfalogging import logger
28 from sfa.util.sfatime import SFATIME_FORMAT
29
30 from xml.dom.minidom import Document, parseString
31
32 from sfa.util.py23 import StringIO
33
34 HAVELXML = False
35 try:
36     from lxml import etree
37     HAVELXML = True
38 except:
39     pass
40
41 # This module defines a subtype of sfa.trust,credential.Credential
42 # called an ABACCredential. An ABAC credential is a signed statement
43 # asserting a role representing the relationship between a subject and target
44 # or between a subject and a class of targets (all those satisfying a role).
45 #
46 # An ABAC credential is like a normal SFA credential in that it has
47 # a validated signature block and is checked for expiration. 
48 # It does not, however, have 'privileges'. Rather it contains a 'head' and
49 # list of 'tails' of elements, each of which represents a principal and
50 # role.
51
52 # A special case of an ABAC credential is a speaks_for credential. Such
53 # a credential is simply an ABAC credential in form, but has a single 
54 # tail and fixed role 'speaks_for'. In ABAC notation, it asserts
55 # AGENT.speaks_for(AGENT)<-CLIENT, or "AGENT asserts that CLIENT may speak
56 # for AGENT". The AGENT in this case is the head and the CLIENT is the
57 # tail and 'speaks_for_AGENT' is the role on the head. These speaks-for
58 # Credentials are used to allow a tool to 'speak as' itself but be recognized
59 # as speaking for an individual and be authorized to the rights of that
60 # individual and not to the rights of the tool itself.
61
62 # For more detail on the semantics and syntax and expected usage patterns
63 # of ABAC credentials, see http://groups.geni.net/geni/wiki/TIEDABACCredential.
64
65
66 # An ABAC element contains a principal (keyid and optional mnemonic)
67 # and optional role and linking_role element
68 class ABACElement:
69     def __init__(self, principal_keyid, principal_mnemonic=None, \
70                      role=None, linking_role=None):
71         self._principal_keyid = principal_keyid
72         self._principal_mnemonic = principal_mnemonic
73         self._role = role
74         self._linking_role = linking_role
75
76     def get_principal_keyid(self): return self._principal_keyid
77     def get_principal_mnemonic(self): return self._principal_mnemonic
78     def get_role(self): return self._role
79     def get_linking_role(self): return self._linking_role
80
81     def __str__(self):
82         ret = self._principal_keyid
83         if self._principal_mnemonic:
84             ret = "%s (%s)" % (self._principal_mnemonic, self._principal_keyid)
85         if self._linking_role:
86             ret += ".%s" % self._linking_role
87         if self._role:
88             ret += ".%s" % self._role
89         return ret
90
91 # Subclass of Credential for handling ABAC credentials
92 # They have a different cred_type (geni_abac vs. geni_sfa)
93 # and they have a head and tail and role (as opposed to privileges)
94 class ABACCredential(Credential):
95
96     ABAC_CREDENTIAL_TYPE = 'geni_abac'
97
98     def __init__(self, create=False, subject=None, 
99                  string=None, filename=None):
100         self.head = None # An ABACElemenet
101         self.tails = [] # List of ABACElements
102         super(ABACCredential, self).__init__(create=create, 
103                                              subject=subject, 
104                                              string=string, 
105                                              filename=filename)
106         self.cred_type = ABACCredential.ABAC_CREDENTIAL_TYPE
107
108     def get_head(self) : 
109         if not self.head: 
110             self.decode()
111         return self.head
112
113     def get_tails(self) : 
114         if len(self.tails) == 0:
115             self.decode()
116         return self.tails
117
118     def decode(self):
119         super(ABACCredential, self).decode()
120         # Pull out the ABAC-specific info
121         doc = parseString(self.xml)
122         rt0s = doc.getElementsByTagName('rt0')
123         if len(rt0s) != 1:
124             raise CredentialNotVerifiable("ABAC credential had no rt0 element")
125         rt0_root = rt0s[0]
126         heads = self._get_abac_elements(rt0_root, 'head')
127         if len(heads) != 1:
128             raise CredentialNotVerifiable("ABAC credential should have exactly 1 head element, had %d" % len(heads))
129
130         self.head = heads[0]
131         self.tails = self._get_abac_elements(rt0_root, 'tail')
132
133     def _get_abac_elements(self, root, label):
134         abac_elements = []
135         elements = root.getElementsByTagName(label)
136         for elt in elements:
137             keyids = elt.getElementsByTagName('keyid')
138             if len(keyids) != 1:
139                 raise CredentialNotVerifiable("ABAC credential element '%s' should have exactly 1 keyid, had %d." % (label, len(keyids)))
140             keyid_elt = keyids[0]
141             keyid = keyid_elt.childNodes[0].nodeValue.strip()
142
143             mnemonic = None
144             mnemonic_elts = elt.getElementsByTagName('mnemonic')
145             if len(mnemonic_elts) > 0:
146                 mnemonic = mnemonic_elts[0].childNodes[0].nodeValue.strip()
147
148             role = None
149             role_elts = elt.getElementsByTagName('role')
150             if len(role_elts) > 0:
151                 role = role_elts[0].childNodes[0].nodeValue.strip()
152
153             linking_role = None
154             linking_role_elts = elt.getElementsByTagName('linking_role')
155             if len(linking_role_elts) > 0:
156                 linking_role = linking_role_elts[0].childNodes[0].nodeValue.strip()
157
158             abac_element = ABACElement(keyid, mnemonic, role, linking_role)
159             abac_elements.append(abac_element)
160
161         return abac_elements
162
163     def dump_string(self, dump_parents=False, show_xml=False):
164         result = "ABAC Credential\n"
165         filename=self.get_filename()
166         if filename: result += "Filename %s\n"%filename
167         if self.expiration:
168             result +=  "\texpiration: %s \n" % self.expiration.strftime(SFATIME_FORMAT)
169
170         result += "\tHead: %s\n" % self.get_head() 
171         for tail in self.get_tails():
172             result += "\tTail: %s\n" % tail
173         if self.get_signature():
174             result += "  gidIssuer:\n"
175             result += self.get_signature().get_issuer_gid().dump_string(8, dump_parents)
176         if show_xml and HAVELXML:
177             try:
178                 tree = etree.parse(StringIO(self.xml))
179                 aside = etree.tostring(tree, pretty_print=True)
180                 result += "\nXML:\n\n"
181                 result += aside
182                 result += "\nEnd XML\n"
183             except:
184                 import traceback
185                 print("exc. Credential.dump_string / XML")
186                 traceback.print_exc()
187         return result
188
189     # sounds like this should be __repr__ instead ??
190     # Produce the ABAC assertion. Something like [ABAC cred: Me.role<-You] or similar
191     def pretty_cred(self):
192         result = "[ABAC cred: " + str(self.get_head())
193         for tail in self.get_tails():
194             result += "<-%s" % str(tail)
195         result += "]"
196         return result
197
198     def createABACElement(self, doc, tagName, abacObj):
199         kid = abacObj.get_principal_keyid()
200         mnem = abacObj.get_principal_mnemonic() # may be None
201         role = abacObj.get_role() # may be None
202         link = abacObj.get_linking_role() # may be None
203         ele = doc.createElement(tagName)
204         prin = doc.createElement('ABACprincipal')
205         ele.appendChild(prin)
206         append_sub(doc, prin, "keyid", kid)
207         if mnem:
208             append_sub(doc, prin, "mnemonic", mnem)
209         if role:
210             append_sub(doc, ele, "role", role)
211         if link:
212             append_sub(doc, ele, "linking_role", link)
213         return ele
214
215     ##
216     # Encode the attributes of the credential into an XML string
217     # This should be done immediately before signing the credential.
218     # WARNING:
219     # In general, a signed credential obtained externally should
220     # not be changed else the signature is no longer valid.  So, once
221     # you have loaded an existing signed credential, do not call encode() or sign() on it.
222
223     def encode(self):
224         # Create the XML document
225         doc = Document()
226         signed_cred = doc.createElement("signed-credential")
227
228 # Declare namespaces
229 # Note that credential/policy.xsd are really the PG schemas
230 # in a PL namespace.
231 # Note that delegation of credentials between the 2 only really works
232 # cause those schemas are identical.
233 # Also note these PG schemas talk about PG tickets and CM policies.
234         signed_cred.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
235         signed_cred.setAttribute("xsi:noNamespaceSchemaLocation", "http://www.geni.net/resources/credential/2/credential.xsd")
236         signed_cred.setAttribute("xsi:schemaLocation", "http://www.planet-lab.org/resources/sfa/ext/policy/1 http://www.planet-lab.org/resources/sfa/ext/policy/1/policy.xsd")
237
238 # PG says for those last 2:
239 #        signed_cred.setAttribute("xsi:noNamespaceSchemaLocation", "http://www.protogeni.net/resources/credential/credential.xsd")
240 #        signed_cred.setAttribute("xsi:schemaLocation", "http://www.protogeni.net/resources/credential/ext/policy/1 http://www.protogeni.net/resources/credential/ext/policy/1/policy.xsd")
241
242         doc.appendChild(signed_cred)
243
244         # Fill in the <credential> bit
245         cred = doc.createElement("credential")
246         cred.setAttribute("xml:id", self.get_refid())
247         signed_cred.appendChild(cred)
248         append_sub(doc, cred, "type", "abac")
249
250         # Stub fields
251         append_sub(doc, cred, "serial", "8")
252         append_sub(doc, cred, "owner_gid", '')
253         append_sub(doc, cred, "owner_urn", '')
254         append_sub(doc, cred, "target_gid", '')
255         append_sub(doc, cred, "target_urn", '')
256         append_sub(doc, cred, "uuid", "")
257
258         if not self.expiration:
259             self.set_expiration(datetime.datetime.utcnow() + datetime.timedelta(seconds=DEFAULT_CREDENTIAL_LIFETIME))
260         self.expiration = self.expiration.replace(microsecond=0)
261         if self.expiration.tzinfo is not None and self.expiration.tzinfo.utcoffset(self.expiration) is not None:
262             # TZ aware. Make sure it is UTC
263             self.expiration = self.expiration.astimezone(tz.tzutc())
264         append_sub(doc, cred, "expires", self.expiration.strftime(SFATIME_FORMAT)) # RFC3339
265
266         abac = doc.createElement("abac")
267         rt0 = doc.createElement("rt0")
268         abac.appendChild(rt0)
269         cred.appendChild(abac)
270         append_sub(doc, rt0, "version", "1.1")
271         head = self.createABACElement(doc, "head", self.get_head())
272         rt0.appendChild(head)
273         for tail in self.get_tails():
274             tailEle = self.createABACElement(doc, "tail", tail)
275             rt0.appendChild(tailEle)
276
277         # Create the <signatures> tag
278         signatures = doc.createElement("signatures")
279         signed_cred.appendChild(signatures)
280
281         # Get the finished product
282         self.xml = doc.toxml("utf-8")