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