[feature] reactor-based authenticator
[leap_pycommon.git] / src / leap / common / events / zmq_components.py
1 # -*- coding: utf-8 -*-
2 # zmq.py
3 # Copyright (C) 2015, 2016 LEAP
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 """
18 The server for the events mechanism.
19 """
20 import os
21 import logging
22 import txzmq
23 import re
24
25 from abc import ABCMeta
26
27 try:
28     import zmq.auth
29     from leap.common.events.auth import TxAuthenticator
30     from leap.common.events.auth import TxAuthenticationRequest
31 except ImportError:
32     pass
33
34 from txzmq.connection import ZmqEndpoint, ZmqEndpointType
35
36 from leap.common.config import flags, get_path_prefix
37 from leap.common.zmq_utils import zmq_has_curve
38 from leap.common.zmq_utils import maybe_create_and_get_certificates
39 from leap.common.zmq_utils import PUBLIC_KEYS_PREFIX
40
41 logger = logging.getLogger(__name__)
42
43 ADDRESS_RE = re.compile("^([a-z]+)://([^:]+):?(\d+)?$")
44
45 LOCALHOST_ALLOWED = '127.0.0.1'
46
47
48 class TxZmqComponent(object):
49     """
50     A twisted-powered zmq events component.
51     """
52     _factory = txzmq.ZmqFactory()
53     _factory.registerForShutdown()
54     _auth = None
55
56     __metaclass__ = ABCMeta
57
58     _component_type = None
59
60     def __init__(self, path_prefix=None, enable_curve=True):
61         """
62         Initialize the txzmq component.
63         """
64         if path_prefix is None:
65             path_prefix = get_path_prefix(flags.STANDALONE)
66         self._config_prefix = os.path.join(path_prefix, "leap", "events")
67         self._connections = []
68         if enable_curve:
69             self.use_curve = zmq_has_curve()
70         else:
71             self.use_curve = False
72
73     @property
74     def component_type(self):
75         if not self._component_type:
76             raise Exception(
77                 "Make sure implementations of TxZmqComponent"
78                 "define a self._component_type!")
79         return self._component_type
80
81     def _zmq_connect(self, connClass, address):
82         """
83         Connect to an address.
84
85         :param connClass: The connection class to be used.
86         :type connClass: txzmq.ZmqConnection
87         :param address: The address to connect to.
88         :type address: str
89
90         :return: The binded connection.
91         :rtype: txzmq.ZmqConnection
92         """
93         endpoint = ZmqEndpoint(ZmqEndpointType.connect, address)
94         connection = connClass(self._factory)
95
96         if self.use_curve:
97             socket = connection.socket
98             public, secret = maybe_create_and_get_certificates(
99                 self._config_prefix, self.component_type)
100             server_public_file = os.path.join(
101                 self._config_prefix, PUBLIC_KEYS_PREFIX, "server.key")
102
103             server_public, _ = zmq.auth.load_certificate(server_public_file)
104             socket.curve_publickey = public
105             socket.curve_secretkey = secret
106             socket.curve_serverkey = server_public
107
108         connection.addEndpoints([endpoint])
109         return connection
110
111     def _zmq_bind(self, connClass, address):
112         """
113         Bind to an address.
114
115         :param connClass: The connection class to be used.
116         :type connClass: txzmq.ZmqConnection
117         :param address: The address to bind to.
118         :type address: str
119
120         :return: The binded connection and port.
121         :rtype: (txzmq.ZmqConnection, int)
122         """
123         proto, addr, port = ADDRESS_RE.search(address).groups()
124
125         endpoint = ZmqEndpoint(ZmqEndpointType.bind, address)
126         connection = connClass(self._factory)
127
128         if self.use_curve:
129             socket = connection.socket
130
131             public, secret = maybe_create_and_get_certificates(
132                 self._config_prefix, self.component_type)
133             socket.curve_publickey = public
134             socket.curve_secretkey = secret
135             self._start_authentication(connection.socket)
136
137         connection.addEndpoints([endpoint])
138         return connection, port
139
140     def _start_authentication(self, socket):
141
142         if not TxZmqComponent._auth:
143             TxZmqComponent._auth = TxAuthenticator(self._factory)
144             TxZmqComponent._auth.start()
145
146         auth_req = TxAuthenticationRequest(self._factory)
147         auth_req.start()
148         auth_req.allow(LOCALHOST_ALLOWED)
149
150         # tell authenticator to use the certificate in a directory
151         public_keys_dir = os.path.join(self._config_prefix, PUBLIC_KEYS_PREFIX)
152         auth_req.configure_curve(domain="*", location=public_keys_dir)
153
154         # This has to be set before binding the socket, that's why this method
155         # has to be called before addEndpoints()
156         socket.curve_server = True
157
158
159 class TxZmqServerComponent(TxZmqComponent):
160     """
161     A txZMQ server component.
162     """
163
164     _component_type = "server"
165
166
167 class TxZmqClientComponent(TxZmqComponent):
168     """
169     A txZMQ client component.
170     """
171
172     _component_type = "client"