aboutsummaryrefslogtreecommitdiff
path: root/scripts/Old/tls-server.py
blob: d3798a32a0da1308de7d10f7c2fb61b5ce53a3a7 (plain) (blame)
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
# $Id$

import socket, POW, time

key = POW.pemRead(POW.RSA_PRIVATE_KEY, open("Alice.key", "r").read())
cer = POW.pemRead(POW.X509_CERTIFICATE, open("Alice.cer", "r").read())
ta  = POW.pemRead(POW.X509_CERTIFICATE, open("Carol-TA.cer", "r").read())

listener = socket.socket()
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
listener.bind(('',6666))
listener.listen(5)

s, addr = listener.accept()
while not s:
  time.sleep(2)
  s, addr = listener.accept()

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)

print "Got connection %r from %r" % (s, addr)

ssl = POW.Ssl(POW.TLSV1_SERVER_METHOD)

ssl.useCertificate(cer)
ssl.useKey(key)
ssl.setVerifyMode(POW.SSL_VERIFY_PEER | POW.SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
ssl.trustCertificate(ta)

ssl.setFd(s.fileno())
ssl.accept()

peer = ssl.peerCertificate()
if peer is not None:
  print peer.pprint()

ssl.write("Hello, TLS")
print ssl.read(100)
Rob Austein <sra@hactrn.net> 2008-06-03 14:31:21 +0000 committer Rob Austein <sra@hactrn.net> 2008-06-03 14:31:21 +0000 Add pubd support (not yet tested)' href='/sra/rpki.net/commit/rpkid/irbe-cli.py?id=e6a77a4374ddecc9db3f0f287f4474c976ac5d24'>e6a77a43
aac95769

ce422aa2


e6a77a43
aac95769

ce422aa2


e6a77a43
aac95769
e6a77a43
a780a780


e6a77a43


a780a780


55769ccf
10ba9398

e6a77a43


c4be735c
eec99329
c4be735c

0077617b
c4be735c
7fe2be97
c4be735c
ac9ca8b4
c4be735c


eec99329
c4be735c


0077617b
c4be735c





eec99329
c4be735c

eec99329
c4be735c

eec99329
c4be735c

4ac35868
c4be735c

b01b3e3f
c4be735c




10ba9398
eec99329
4ac35868
2ecbf67b
eec99329
e6a77a43







c4be735c
e5e70443
c4be735c
e6a77a43
c4be735c




e6a77a43
c4be735c

e6a77a43
c4be735c




e6a77a43
c4be735c

e6a77a43
c4be735c

e6a77a43
c4be735c

10ba9398
c4be735c

a4ecc28f
e6a77a43
a4ecc28f


e6a77a43





0fed927b
e6a77a43
68cebf41
4ac35868
0077617b
e6a77a43
609b6464


e6a77a43


53f9a0f8
e6a77a43





0077617b
0fed927b
0077617b
eba8fc67
8f8a7ea8
860f2242
0077617b
dc6a8bf7
0077617b

dc6a8bf7
7c26e04d
4ac35868
437edf67
4ac35868
0077617b
437edf67
0077617b
e5538e6f
437edf67
e5538e6f
0077617b
4ac35868

e5538e6f

140ba275
0077617b

dc6a8bf7
8f8a7ea8
437edf67
da14517d

437edf67
0077617b
e6a77a43






0077617b



71eacd9f


















e6a77a43
38353d7e
da14517d



71eacd9f

d2847b67



94bad6e5
da14517d
71eacd9f



d2847b67
da14517d
38353d7e
da14517d
e6a77a43

38353d7e
da14517d



71eacd9f

d2847b67



94bad6e5
da14517d
71eacd9f



d2847b67
f370e831
38353d7e
da14517d
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385

                     






























                                                                                    
                                                            

   









                       
 

              
                                         


                                                          

                            


                                                   



                                                      
















                                                


                                                       
 

               

                                                                     
                   

               

                 


                                        
                                                                                                   


                                                    
         
                          
 
                                


                                 
                           
                                                                                                                                            









                                                        
               
 
                                        


                                           
                                                    
 
                                   


                                           
                                                    

                                            


                                               
                                                        

                                       


                                               
                                                        
 
                            


                                                       


                 


                                        
                                 

                                      


                    
                                                         
 

                                                          
 
                                                        
 
                                  
 


                                                         
 


                                                            
 





                                                                 
 

                                                              
 

                                                            
 

                                                                      
 

                                                                                              
 




                                                                                                             
 
                                 
                                                                                 
                                                                                                   
 







                                                          
                                                           
 
                                                               
 




                                                    
 

                                                               
 




                                                                         
 

                                                                   
 

                                                         
 

                                                                             
 

                                                                         
 
                                 


                                                                         





                                                            
 
       
 
                                                              
 
                    


                         


                              
                                                 





                                 
                
 
              
 
                         
 
                   
 

            
 
               
              
 
                                                     
                 
                                 
            
                               
                
                                
               

                              

                                
 

            
 
                                              
 

                      
 
           






                                           



                                      


















                                                                   
                    
 



                                 

                                                          



                                              
                                                        
                                   



                                        
                            
                           
 
                               

                     
 



                                  

                                                        



                                             
                                                       
                                    



                                        
                           
                           
 
                               
#!/usr/bin/env python

# $Id$
#
# Copyright (C) 2009--2013  Internet Systems Consortium ("ISC")
#
# 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 ISC DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS.  IN NO EVENT SHALL ISC 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.
#
# Portions 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.

__doc__ = """
Command line IR back-end control program for rpkid and pubd.
"""

import sys
import getopt
import textwrap
import rpki.left_right
import rpki.http
import rpki.x509
import rpki.config
import rpki.log
import rpki.publication
import rpki.async

pem_out = None

class UsageWrapper(textwrap.TextWrapper):
  """
  Call interface around Python textwrap.Textwrapper class.
  """

  def __call__(self, *args):
    """
    Format arguments, with TextWrapper indentation.
    """
    return self.fill(textwrap.dedent(" ".join(args)))

usage_fill = UsageWrapper(subsequent_indent = " " * 4)

class reply_elt_mixin(object):
  """
  Protocol mix-in for printout of reply PDUs.
  """

  is_cmd = False

  def client_reply_decode(self):
    pass

  def client_reply_show(self):
    print self.element_name
    for i in self.attributes + self.elements:
      if getattr(self, i) is not None:
        print "  %s: %s" % (i, getattr(self, i))

class cmd_elt_mixin(reply_elt_mixin):
  """
  Protocol mix-in for command line client element PDUs.
  """

  is_cmd = True

  ## @var excludes
  # XML attributes and elements that should not be allowed as command
  # line arguments.
  excludes = ()

  @classmethod
  def usage(cls):
    """
    Generate usage message for this PDU.
    """
    args = " ".join("--" + x + "=" for x in cls.attributes + cls.elements if x not in cls.excludes)
    bools = " ".join("--" + x for x in cls.booleans)
    if args and bools:
      return args + " " + bools
    else:
      return args or bools

  def client_getopt(self, argv):
    """
    Parse options for this class.
    """
    # pylint: disable=W0621
    opts, argv = getopt.getopt(argv, "", [x + "=" for x in self.attributes + self.elements if x not in self.excludes] + list(self.booleans))
    for o, a in opts:
      o = o[2:]
      handler = getattr(self, "client_query_" + o, None)
      if handler is not None:
        handler(a)
      elif o in self.booleans:
        setattr(self, o, True)
      else:
        assert o in self.attributes
        setattr(self, o, a)
    return argv

  def client_query_bpki_cert(self, arg):
    """
    Special handler for --bpki_cert option.
    """
    self.bpki_cert = rpki.x509.X509(Auto_file = arg)

  def client_query_glue(self, arg):
    """
    Special handler for --bpki_glue option.
    """
    self.bpki_glue = rpki.x509.X509(Auto_file = arg)

  def client_query_bpki_cms_cert(self, arg):
    """
    Special handler for --bpki_cms_cert option.
    """
    self.bpki_cms_cert = rpki.x509.X509(Auto_file = arg)

  def client_query_cms_glue(self, arg):
    """
    Special handler for --bpki_cms_glue option.
    """
    self.bpki_cms_glue = rpki.x509.X509(Auto_file = arg)

class cmd_msg_mixin(object):
  """
  Protocol mix-in for command line client message PDUs.
  """

  @classmethod
  def usage(cls):
    """
    Generate usage message for this PDU.
    """
    for k, v in cls.pdus.items():
      if v.is_cmd:
        print usage_fill(k, v.usage())

# left-right protcol

class left_right_msg(cmd_msg_mixin, rpki.left_right.msg):

  class self_elt(cmd_elt_mixin, rpki.left_right.self_elt):
    pass

  class bsc_elt(cmd_elt_mixin, rpki.left_right.bsc_elt):

    excludes = ("pkcs10_request",)

    def client_query_signing_cert(self, arg):
      """--signing_cert option."""
      self.signing_cert = rpki.x509.X509(Auto_file = arg)

    def client_query_signing_cert_crl(self, arg):
      """--signing_cert_crl option."""
      self.signing_cert_crl = rpki.x509.CRL(Auto_file = arg)

    def client_reply_decode(self):
      global pem_out
      if pem_out is not None and self.pkcs10_request is not None:
        if isinstance(pem_out, str):
          pem_out = open(pem_out, "w")
        pem_out.write(self.pkcs10_request.get_PEM())

  class parent_elt(cmd_elt_mixin, rpki.left_right.parent_elt):
    pass

  class child_elt(cmd_elt_mixin, rpki.left_right.child_elt):
    pass

  class repository_elt(cmd_elt_mixin, rpki.left_right.repository_elt):
    pass

  class list_published_objects_elt(cmd_elt_mixin, rpki.left_right.list_published_objects_elt):
    excludes = ("uri",)

  class list_received_resources_elt(cmd_elt_mixin, rpki.left_right.list_received_resources_elt):
    excludes = ("parent_handle", "notBefore", "notAfter", "uri", "sia_uri", "aia_uri", "asn", "ipv4", "ipv6")

  class report_error_elt(reply_elt_mixin, rpki.left_right.report_error_elt):
    pass

  pdus = dict((x.element_name, x)
              for x in (self_elt, bsc_elt, parent_elt, child_elt, repository_elt,
                        list_published_objects_elt, list_received_resources_elt, report_error_elt))

class left_right_sax_handler(rpki.left_right.sax_handler):
  pdu = left_right_msg

class left_right_cms_msg(rpki.left_right.cms_msg):
  saxify = left_right_sax_handler.saxify

# Publication protocol

class publication_msg(cmd_msg_mixin, rpki.publication.msg):

  class config_elt(cmd_elt_mixin, rpki.publication.config_elt):

    def client_query_bpki_crl(self, arg):
      """
      Special handler for --bpki_crl option.
      """
      self.bpki_crl = rpki.x509.CRL(Auto_file = arg)

  class client_elt(cmd_elt_mixin, rpki.publication.client_elt):
    pass

  class certificate_elt(cmd_elt_mixin, rpki.publication.certificate_elt):
    pass

  class crl_elt(cmd_elt_mixin, rpki.publication.crl_elt):
    pass

  class manifest_elt(cmd_elt_mixin, rpki.publication.manifest_elt):
    pass

  class roa_elt(cmd_elt_mixin, rpki.publication.roa_elt):
    pass

  class report_error_elt(reply_elt_mixin, rpki.publication.report_error_elt):
    pass

  class ghostbuster_elt(cmd_elt_mixin, rpki.publication.ghostbuster_elt):
    pass

  pdus = dict((x.element_name, x)
              for x in (config_elt, client_elt, certificate_elt, crl_elt,
                        manifest_elt, roa_elt, report_error_elt,
                        ghostbuster_elt))

class publication_sax_handler(rpki.publication.sax_handler):
  pdu = publication_msg

class publication_cms_msg(rpki.publication.cms_msg):
  saxify = publication_sax_handler.saxify

# Usage

top_opts = ["config=", "help", "pem_out=", "quiet", "verbose"]

def usage(code = 1):
  if __doc__ is not None:
    print __doc__.strip()
    print
  print "Usage:"
  print
  print "# Top-level options:"
  print usage_fill(*["--" + x for x in top_opts])
  print
  print "# left-right protocol:"
  left_right_msg.usage()
  print
  print "# publication protocol:"
  publication_msg.usage()
  sys.exit(code)

# Main program

rpki.log.init("irbe_cli")

argv = sys.argv[1:]

if not argv:
  usage(0)

cfg_file = None
verbose = True

opts, argv = getopt.getopt(argv, "c:hpqv?", top_opts)
for o, a in opts:
  if o in ("-?", "-h", "--help"):
    usage(0)
  elif o in ("-c", "--config"):
    cfg_file = a
  elif o in ("-p", "--pem_out"):
    pem_out = a
  elif o in ("-q", "--quiet"):
    verbose = False
  elif o in ("-v", "--verbose"):
    verbose = True

if not argv:
  usage(1)

cfg = rpki.config.parser(cfg_file, "irbe_cli")

q_msg_left_right  = []
q_msg_publication = []

while argv:
  if argv[0] in left_right_msg.pdus:
    q_pdu = left_right_msg.pdus[argv[0]]()
    q_msg = q_msg_left_right
  elif argv[0] in publication_msg.pdus:
    q_pdu = publication_msg.pdus[argv[0]]()
    q_msg = q_msg_publication
  else:
    usage(1)
  argv = q_pdu.client_getopt(argv[1:])
  q_msg.append(q_pdu)

from django.conf import settings

settings.configure(
  DATABASES = { "default" : {
    "ENGINE"   : "django.db.backends.mysql",
    "NAME"     : cfg.get("sql-database", section = "irdbd"),
    "USER"     : cfg.get("sql-username", section = "irdbd"),
    "PASSWORD" : cfg.get("sql-password", section = "irdbd"),
    "HOST"     : "",
    "PORT"     : "",
    "OPTIONS"  : { "init_command": "SET storage_engine=INNODB" }}},
  INSTALLED_APPS = ("rpki.irdb",),
)

import rpki.irdb

server_ca = rpki.irdb.ServerCA.objects.get()
irbe = server_ca.ee_certificates.get(purpose = "irbe")

if q_msg_left_right:

  class left_right_proto(object):
    cms_msg = left_right_cms_msg
    msg     = left_right_msg

  rpkid = server_ca.ee_certificates.get(purpose = "rpkid")

  rpkid_url = "http://%s:%s/left-right/" % (
    cfg.get("server-host", section = "rpkid"),
    cfg.get("server-port", section = "rpkid"))

  call_rpkid = rpki.async.sync_wrapper(rpki.http.caller(
    proto       = left_right_proto,
    client_key  = irbe.private_key,
    client_cert = irbe.certificate,
    server_ta   = server_ca.certificate,
    server_cert = rpkid.certificate,
    url         = rpkid_url,
    debug       = verbose))

  call_rpkid(*q_msg_left_right)

if q_msg_publication:

  class publication_proto(object):
    msg     = publication_msg
    cms_msg = publication_cms_msg

  pubd = server_ca.ee_certificates.get(purpose = "pubd")

  pubd_url = "http://%s:%s/control/" % (
    cfg.get("server-host", section = "pubd"),
    cfg.get("server-port", section = "pubd"))

  call_pubd = rpki.async.sync_wrapper(rpki.http.caller(
    proto       = publication_proto,
    client_key  = irbe.private_key,
    client_cert = irbe.certificate,
    server_ta   = server_ca.certificate,
    server_cert = pubd.certificate,
    url         = pubd_url,
    debug       = verbose))

  call_pubd(*q_msg_publication)