1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
|
"""RPKI "publication" protocol.
$Id$
Copyright (C) 2007--2008 American Registry for Internet Numbers ("ARIN")
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND ARIN DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL ARIN BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
"""
import base64, os
import rpki.resource_set, rpki.x509, rpki.sql, rpki.exceptions, rpki.xml_utils
import rpki.https, rpki.up_down, rpki.relaxng, rpki.sundial, rpki.log, rpki.roa
class publication_namespace(object):
"""XML namespace parameters for publication protocol."""
xmlns = "http://www.hactrn.net/uris/rpki/publication-spec/"
nsmap = { None : xmlns }
class control_elt(rpki.xml_utils.data_elt, rpki.sql.sql_persistant, publication_namespace):
"""Virtual class for control channel objects."""
def serve_dispatch(self, r_msg, cb):
"""Action dispatch handler. This needs special handling because
we need to make sure that this PDU arrived via the control channel.
"""
if self.client is not None:
raise rpki.exceptions.BadQuery, "Control query received on client channel"
rpki.xml_utils.data_elt.serve_dispatch(self, r_msg, cb)
class config_elt(control_elt):
"""<config/> element. This is a little weird because there should
never be more than one row in the SQL config table, but we have to
put the BPKI CRL somewhere and SQL is the least bad place available.
So we reuse a lot of the SQL machinery, but we nail config_id at 1,
we don't expose it in the XML protocol, and we only support the get
and set actions.
"""
attributes = ("action", "tag")
element_name = "config"
elements = ("bpki_crl",)
sql_template = rpki.sql.template("config", "config_id", ("bpki_crl", rpki.x509.CRL))
wired_in_config_id = 1
def startElement(self, stack, name, attrs):
"""StartElement() handler for config object. This requires
special handling because of the weird way we treat config_id.
"""
control_elt.startElement(self, stack, name, attrs)
self.config_id = self.wired_in_config_id
@classmethod
def fetch(cls, gctx):
"""Fetch the config object from SQL. This requires special
handling because of the weird way we treat config_id.
"""
return cls.sql_fetch(gctx, cls.wired_in_config_id)
def serve_set(self, r_msg, cb):
"""Handle a set action. This requires special handling because
config doesn't support the create method.
"""
if self.sql_fetch(self.gctx, self.config_id) is None:
control_elt.serve_create(self, r_msg, cb)
else:
control_elt.serve_set(self, r_msg, cb)
def serve_fetch_one(self):
"""Find the config object on which a get or set method should
operate.
"""
r = self.sql_fetch(self.gctx, self.config_id)
if r is None:
raise rpki.exceptions.NotFound
return r
class client_elt(control_elt):
"""<client/> element."""
element_name = "client"
attributes = ("action", "tag", "client_id", "base_uri")
elements = ("bpki_cert", "bpki_glue")
sql_template = rpki.sql.template("client", "client_id", "base_uri", ("bpki_cert", rpki.x509.X509), ("bpki_glue", rpki.x509.X509))
base_uri = None
bpki_cert = None
bpki_glue = None
clear_https_ta_cache = False
def endElement(self, stack, name, text):
"""Handle subelements of <client/> element. These require special
handling because modifying them invalidates the HTTPS trust anchor
cache.
"""
control_elt.endElement(self, stack, name, text)
if name in self.elements:
self.clear_https_ta_cache = True
def serve_post_save_hook(self, q_pdu, r_pdu, cb):
"""Extra server actions for client_elt."""
if self.clear_https_ta_cache:
self.gctx.clear_https_ta_cache()
self.clear_https_ta_cache = False
cb()
def serve_fetch_one(self):
"""Find the client object on which a get, set, or destroy method
should operate.
"""
r = self.sql_fetch(self.gctx, self.client_id)
if r is None:
raise rpki.exceptions.NotFound
return r
def serve_fetch_all(self):
"""Find client objects on which a list method should operate."""
return self.sql_fetch_all(self.gctx)
def check_allowed_uri(self, uri):
if not uri.startswith(self.base_uri):
raise rpki.exceptions.ForbiddenURI
class publication_object_elt(rpki.xml_utils.base_elt, publication_namespace):
"""Virtual class for publishable objects. These have very similar
syntax, differences lie in underlying datatype and methods. XML
methods are a little different from the pattern used for objects
that support the create/set/get/list/destroy actions, but
publishable objects don't go in SQL either so these classes would be
different in any case.
"""
attributes = ("action", "tag", "client_id", "uri")
payload = None
def endElement(self, stack, name, text):
"""Handle a publishable element element."""
assert name == self.element_name, "Unexpected name %s, stack %s" % (name, stack)
if text:
self.payload = self.payload_type(Base64 = text)
stack.pop()
def toXML(self):
"""Generate XML element for publishable object."""
elt = self.make_elt()
if self.payload:
elt.text = base64.b64encode(self.payload.get_DER())
return elt
def serve_dispatch(self, r_msg, cb):
"""Action dispatch handler."""
if self.client is None:
raise rpki.exceptions.BadQuery, "Client query received on control channel"
dispatch = { "publish" : self.serve_publish,
"withdraw" : self.serve_withdraw }
if self.action not in dispatch:
raise rpki.exceptions.BadQuery, "Unexpected query: action %s" % self.action
self.client.check_allowed_uri(self.uri)
dispatch[self.action]()
r_pdu = self.__class__()
r_pdu.action = self.action
r_pdu.tag = self.tag
r_pdu.uri = self.uri
r_msg.append(r_pdu)
cb()
def serve_publish(self):
"""Publish an object."""
rpki.log.info("Publishing %s as %s" % (repr(self.payload), repr(self.uri)))
filename = self.uri_to_filename()
dirname = os.path.dirname(filename)
if not os.path.isdir(dirname):
os.makedirs(dirname)
f = open(filename, "wb")
f.write(self.payload.get_DER())
f.close()
def serve_withdraw(self):
"""Withdraw an object."""
rpki.log.info("Withdrawing %s" % repr(self.uri))
os.remove(self.uri_to_filename())
def uri_to_filename(self):
"""Convert a URI to a local filename."""
if not self.uri.startswith("rsync://"):
raise rpki.exceptions.BadURISyntax
filename = self.gctx.publication_base + self.uri[len("rsync://"):]
if filename.find("//") >= 0 or filename.find("/../") >= 0 or filename.endswith("/.."):
raise rpki.exceptions.BadURISyntax
return filename
class certificate_elt(publication_object_elt):
"""<certificate/> element."""
element_name = "certificate"
payload_type = rpki.x509.X509
class crl_elt(publication_object_elt):
"""<crl/> element."""
element_name = "crl"
payload_type = rpki.x509.CRL
class manifest_elt(publication_object_elt):
"""<manifest/> element."""
element_name = "manifest"
payload_type = rpki.x509.SignedManifest
class roa_elt(publication_object_elt):
"""<roa/> element."""
element_name = "roa"
payload_type = rpki.x509.ROA
## @var obj2elt
# Map of data types to publication element wrapper types
obj2elt = dict((e.payload_type, e) for e in (certificate_elt, crl_elt, manifest_elt, roa_elt))
class report_error_elt(rpki.xml_utils.base_elt, publication_namespace):
"""<report_error/> element."""
element_name = "report_error"
attributes = ("tag", "error_code")
@classmethod
def from_exception(cls, exc):
"""Generate a <report_error/> element from an exception."""
self = cls()
self.error_code = exc.__class__.__name__
return self
class msg(rpki.xml_utils.msg, publication_namespace):
"""Publication PDU."""
## @var version
# Protocol version
version = 1
## @var pdus
# Dispatch table of PDUs for this protocol.
pdus = dict((x.element_name, x)
for x in (config_elt, client_elt, certificate_elt, crl_elt, manifest_elt, roa_elt, report_error_elt))
def serve_top_level(self, gctx, client, cb):
"""Serve one msg PDU."""
if self.type != "query":
raise rpki.exceptions.BadQuery, "Message type is not query"
r_msg = self.__class__()
r_msg.type = "reply"
def loop(iterator, q_pdu):
q_pdu.gctx = gctx
q_pdu.client = client
q_pdu.serve_dispatch(r_msg, iterator)
def done():
cb(r_msg)
rpki.async.iterator(self, loop, done)
class sax_handler(rpki.xml_utils.sax_handler):
"""SAX handler for publication protocol."""
pdu = msg
name = "msg"
version = "1"
class cms_msg(rpki.x509.XML_CMS_object):
"""Class to hold a CMS-signed publication PDU."""
encoding = "us-ascii"
schema = rpki.relaxng.publication
saxify = sax_handler.saxify
|