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