1 # Copyright 2015 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 """Utility library to add SSL support to the RPC server."""
12 #pylint: disable=relative-import
15 import SimpleJSONRPCServer
18 class Error(Exception):
23 """Creates an SSL keyfile and returns the path."""
24 keyfile
= tempfile
.mkstemp()[1]
35 def CreateCsrFile(keyfile
):
36 """Creates an SSL CSR file and returns the path."""
37 csrfile
= tempfile
.mkstemp()[1]
44 '-subj', '/C=NA/ST=NA/L=NA/O=Chromium/OU=Test/CN=chromium.org'
50 def CreateCrtFile(keyfile
, csrfile
):
51 """Creates an SSL CRT file and returns the path."""
52 crtfile
= tempfile
.mkstemp()[1]
67 """Creates an SSL PEM file and returns the path."""
68 keyfile
= CreateKeyFile()
69 csrfile
= CreateCsrFile(keyfile
)
70 crtfile
= CreateCrtFile(keyfile
, csrfile
)
71 pemfile
= tempfile
.mkstemp()[1]
72 with
open(keyfile
) as k
:
73 with
open(crtfile
) as c
:
74 with
open(pemfile
, 'wb') as p
:
75 p
.write('%s\n%s' % (k
.read(), c
.read()))
81 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
83 raise Error('Failed to run %s: %s' % (' '.join(cmd
), e
))
84 out
, err
= p
.communicate()
90 class SslRpcServer(SimpleJSONRPCServer
.SimpleJSONRPCServer
):
91 """Class to add SSL support to the RPC server."""
93 def __init__(self
, *args
, **kwargs
):
94 SimpleJSONRPCServer
.SimpleJSONRPCServer
.__init
__(self
, *args
, **kwargs
)
95 self
.socket
= ssl
.wrap_socket(self
.socket
, certfile
=CreatePemFile(),
99 def Connect(server
, port
=common_lib
.SERVER_PORT
):
100 """Creates and returns a connection to an SSL RPC server."""
101 addr
= 'https://%s:%d' % (server
, port
)
102 logging
.debug('Connecting to RPC server at %s', addr
)
103 return jsonrpclib
.ServerProxy(addr
, allow_none
=True)