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