]> git.meshlink.io Git - meshlink/blob - src/protocol_key.c
Never automatically try to bind to ports >= 32768.
[meshlink] / src / protocol_key.c
1 /*
2     protocol_key.c -- handle the meta-protocol, key exchange
3     Copyright (C) 2014-2017 Guus Sliepen <guus@meshlink.io>
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 2 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 along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include "connection.h"
23 #include "logger.h"
24 #include "meshlink_internal.h"
25 #include "net.h"
26 #include "netutl.h"
27 #include "node.h"
28 #include "prf.h"
29 #include "protocol.h"
30 #include "sptps.h"
31 #include "utils.h"
32 #include "xalloc.h"
33
34 static const int req_key_timeout = 2;
35
36 bool key_changed_h(meshlink_handle_t *mesh, connection_t *c, const char *request) {
37         assert(request);
38         assert(*request);
39
40         char name[MAX_STRING_SIZE];
41         node_t *n;
42
43         if(sscanf(request, "%*d %*x " MAX_STRING, name) != 1) {
44                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s", "KEY_CHANGED", c->name);
45                 return false;
46         }
47
48         if(seen_request(mesh, request)) {
49                 return true;
50         }
51
52         n = lookup_node(mesh, name);
53
54         if(!n) {
55                 logger(mesh, MESHLINK_ERROR, "Got %s from %s origin %s which does not exist", "KEY_CHANGED", c->name, name);
56                 return true;
57         }
58
59         /* Tell the others */
60
61         forward_request(mesh, c, NULL, request);
62
63         return true;
64 }
65
66 static bool send_initial_sptps_data(void *handle, uint8_t type, const void *data, size_t len) {
67         (void)type;
68
69         assert(data);
70         assert(len);
71
72         node_t *to = handle;
73         meshlink_handle_t *mesh = to->mesh;
74
75         if(!to->nexthop || !to->nexthop->connection) {
76                 logger(mesh, MESHLINK_WARNING, "Cannot send SPTPS data to %s via %s", to->name, to->nexthop ? to->nexthop->name : to->name);
77                 return false;
78         }
79
80         to->sptps.send_data = send_sptps_data;
81         char buf[len * 4 / 3 + 5];
82         b64encode(data, buf, len);
83         return send_request(mesh, to->nexthop->connection, NULL, "%d %s %s %d %s", REQ_KEY, mesh->self->name, to->name, REQ_KEY, buf);
84 }
85
86 bool send_canonical_address(meshlink_handle_t *mesh, node_t *to) {
87         if(!mesh->self->canonical_address) {
88                 return true;
89         }
90
91         return send_request(mesh, to->nexthop->connection, NULL, "%d %s %s %d %s", REQ_KEY, mesh->self->name, to->name, REQ_CANONICAL, mesh->self->canonical_address);
92 }
93
94 bool send_req_key(meshlink_handle_t *mesh, node_t *to) {
95         if(!node_read_public_key(mesh, to)) {
96                 logger(mesh, MESHLINK_DEBUG, "No ECDSA key known for %s", to->name);
97
98                 if(!to->nexthop || !to->nexthop->connection) {
99                         logger(mesh, MESHLINK_WARNING, "Cannot send REQ_PUBKEY to %s via %s", to->name, to->nexthop ? to->nexthop->name : to->name);
100                         return true;
101                 }
102
103                 char *pubkey = ecdsa_get_base64_public_key(mesh->private_key);
104                 send_request(mesh, to->nexthop->connection, NULL, "%d %s %s %d %s", REQ_KEY, mesh->self->name, to->name, REQ_PUBKEY, pubkey);
105                 free(pubkey);
106                 return true;
107         }
108
109         if(to->sptps.label) {
110                 logger(mesh, MESHLINK_DEBUG, "send_req_key(%s) called while sptps->label != NULL!", to->name);
111         }
112
113         /* Send our canonical address to help with UDP hole punching */
114         send_canonical_address(mesh, to);
115
116         char label[sizeof(meshlink_udp_label) + strlen(mesh->self->name) + strlen(to->name) + 2];
117         snprintf(label, sizeof(label), "%s %s %s", meshlink_udp_label, mesh->self->name, to->name);
118         sptps_stop(&to->sptps);
119         to->status.validkey = false;
120         to->status.waitingforkey = true;
121         to->last_req_key = mesh->loop.now.tv_sec;
122         return sptps_start(&to->sptps, to, true, true, mesh->private_key, to->ecdsa, label, sizeof(label) - 1, send_initial_sptps_data, receive_sptps_record);
123 }
124
125 /* REQ_KEY is overloaded to allow arbitrary requests to be routed between two nodes. */
126
127 static bool req_key_ext_h(meshlink_handle_t *mesh, connection_t *c, const char *request, node_t *from, int reqno) {
128         (void)c;
129
130         if(!from->nexthop || !from->nexthop->connection) {
131                 logger(mesh, MESHLINK_WARNING, "Cannot answer REQ_KEY from %s via %s", from->name, from->nexthop ? from->nexthop->name : from->name);
132                 return true;
133         }
134
135         switch(reqno) {
136         case REQ_PUBKEY: {
137                 char *pubkey = ecdsa_get_base64_public_key(mesh->private_key);
138
139                 if(!node_read_public_key(mesh, from)) {
140                         char hiskey[MAX_STRING_SIZE];
141
142                         if(sscanf(request, "%*d %*s %*s %*d " MAX_STRING, hiskey) == 1) {
143                                 from->ecdsa = ecdsa_set_base64_public_key(hiskey);
144
145                                 if(!from->ecdsa) {
146                                         logger(mesh, MESHLINK_ERROR, "Got bad %s from %s: %s", "REQ_PUBKEY", from->name, "invalid pubkey");
147                                         return true;
148                                 }
149
150                                 logger(mesh, MESHLINK_INFO, "Learned ECDSA public key from %s", from->name);
151                                 from->status.dirty = true;
152
153                                 if(!node_write_config(mesh, from, true)) {
154                                         // ignore
155                                 }
156                         }
157                 }
158
159                 send_request(mesh, from->nexthop->connection, NULL, "%d %s %s %d %s", REQ_KEY, mesh->self->name, from->name, ANS_PUBKEY, pubkey);
160                 free(pubkey);
161                 return true;
162         }
163
164         case ANS_PUBKEY: {
165                 if(node_read_public_key(mesh, from)) {
166                         logger(mesh, MESHLINK_WARNING, "Got ANS_PUBKEY from %s even though we already have his pubkey", from->name);
167                         return true;
168                 }
169
170                 char pubkey[MAX_STRING_SIZE];
171
172                 if(sscanf(request, "%*d %*s %*s %*d " MAX_STRING, pubkey) != 1 || !(from->ecdsa = ecdsa_set_base64_public_key(pubkey))) {
173                         logger(mesh, MESHLINK_ERROR, "Got bad %s from %s: %s", "ANS_PUBKEY", from->name, "invalid pubkey");
174                         return true;
175                 }
176
177                 logger(mesh, MESHLINK_INFO, "Learned ECDSA public key from %s", from->name);
178                 from->status.dirty = true;
179
180                 if(!node_write_config(mesh, from, true)) {
181                         // ignore
182                 }
183
184                 /* If we are trying to form an outgoing connection to this node, retry immediately */
185                 for list_each(outgoing_t, outgoing, mesh->outgoings) {
186                         if(outgoing->node == from && outgoing->ev.cb) {
187                                 outgoing->timeout = 0;
188                                 timeout_set(&mesh->loop, &outgoing->ev, &(struct timespec) {
189                                         0, 0
190                                 });
191                         }
192                 }
193
194                 /* Also reset any UTCP timers */
195                 utcp_reset_timers(from->utcp);
196
197                 return true;
198         }
199
200         case REQ_KEY: {
201                 if(!node_read_public_key(mesh, from)) {
202                         logger(mesh, MESHLINK_DEBUG, "No ECDSA key known for %s", from->name);
203                         send_request(mesh, from->nexthop->connection, NULL, "%d %s %s %d", REQ_KEY, mesh->self->name, from->name, REQ_PUBKEY);
204                         return true;
205                 }
206
207                 if(from->sptps.label) {
208                         logger(mesh, MESHLINK_DEBUG, "Got REQ_KEY from %s while we already started a SPTPS session!", from->name);
209
210                         if(mesh->loop.now.tv_sec < from->last_req_key + req_key_timeout && strcmp(mesh->self->name, from->name) < 0) {
211                                 logger(mesh, MESHLINK_DEBUG, "Ignoring REQ_KEY from %s.", from->name);
212                                 return true;
213                         }
214                 }
215
216                 char buf[MAX_STRING_SIZE];
217                 int len;
218
219                 if(sscanf(request, "%*d %*s %*s %*d " MAX_STRING, buf) != 1 || !(len = b64decode(buf, buf, strlen(buf)))) {
220                         logger(mesh, MESHLINK_ERROR, "Got bad %s from %s: %s", "REQ_SPTPS_START", from->name, "invalid SPTPS data");
221                         return true;
222                 }
223
224                 char label[sizeof(meshlink_udp_label) + strlen(from->name) + strlen(mesh->self->name) + 2];
225                 snprintf(label, sizeof(label), "%s %s %s", meshlink_udp_label, from->name, mesh->self->name);
226                 sptps_stop(&from->sptps);
227                 from->status.validkey = false;
228                 from->status.waitingforkey = true;
229                 from->last_req_key = mesh->loop.now.tv_sec;
230
231                 /* Send our canonical address to help with UDP hole punching */
232                 send_canonical_address(mesh, from);
233
234                 if(!sptps_start(&from->sptps, from, false, true, mesh->private_key, from->ecdsa, label, sizeof(label) - 1, send_sptps_data, receive_sptps_record)) {
235                         logger(mesh, MESHLINK_ERROR, "Could not start SPTPS session with %s: %s", from->name, strerror(errno));
236                         return true;
237                 }
238
239                 if(!sptps_receive_data(&from->sptps, buf, len)) {
240                         logger(mesh, MESHLINK_ERROR, "Could not process SPTPS data from %s: %s", from->name, strerror(errno));
241                         return true;
242                 }
243
244                 return true;
245         }
246
247         case REQ_SPTPS: {
248                 if(!from->status.validkey) {
249                         logger(mesh, MESHLINK_ERROR, "Got REQ_SPTPS from %s but we don't have a valid key yet", from->name);
250                         return true;
251                 }
252
253                 char buf[MAX_STRING_SIZE];
254                 int len;
255
256                 if(sscanf(request, "%*d %*s %*s %*d " MAX_STRING, buf) != 1 || !(len = b64decode(buf, buf, strlen(buf)))) {
257                         logger(mesh, MESHLINK_ERROR, "Got bad %s from %s: %s", "REQ_SPTPS", from->name, "invalid SPTPS data");
258                         return true;
259                 }
260
261                 if(!sptps_receive_data(&from->sptps, buf, len)) {
262                         logger(mesh, MESHLINK_ERROR, "Could not process SPTPS data from %s: %s", from->name, strerror(errno));
263                         return true;
264                 }
265
266                 return true;
267         }
268
269         case REQ_CANONICAL: {
270                 char host[MAX_STRING_SIZE];
271                 char port[MAX_STRING_SIZE];
272
273                 if(sscanf(request, "%*d %*s %*s %*d " MAX_STRING " " MAX_STRING, host, port) != 2) {
274                         logger(mesh, MESHLINK_ERROR, "Got bad %s from %s: %s", "REQ_CANONICAL", from->name, "invalid canonical address");
275                         return true;
276                 }
277
278                 char *canonical_address;
279                 xasprintf(&canonical_address, "%s %s", host, port);
280
281                 if(mesh->log_level <= MESHLINK_DEBUG && (!from->canonical_address || strcmp(from->canonical_address, canonical_address))) {
282                         logger(mesh, MESHLINK_DEBUG, "Updating canonical address of %s to %s", from->name, canonical_address);
283                 }
284
285                 free(from->canonical_address);
286                 from->canonical_address = canonical_address;
287                 return true;
288         }
289
290         default:
291                 logger(mesh, MESHLINK_ERROR, "Unknown extended REQ_KEY request from %s: %s", from->name, request);
292                 return true;
293         }
294 }
295
296 bool req_key_h(meshlink_handle_t *mesh, connection_t *c, const char *request) {
297         assert(request);
298         assert(*request);
299
300         char from_name[MAX_STRING_SIZE];
301         char to_name[MAX_STRING_SIZE];
302         node_t *from, *to;
303         int reqno = 0;
304
305         if(sscanf(request, "%*d " MAX_STRING " " MAX_STRING " %d", from_name, to_name, &reqno) < 2) {
306                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s", "REQ_KEY", c->name);
307                 return false;
308         }
309
310         if(!check_id(from_name) || !check_id(to_name)) {
311                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s: %s", "REQ_KEY", c->name, "invalid name");
312                 return false;
313         }
314
315         from = lookup_node(mesh, from_name);
316
317         if(!from) {
318                 logger(mesh, MESHLINK_ERROR, "Got %s from %s origin %s which does not exist in our connection list",
319                        "REQ_KEY", c->name, from_name);
320                 return true;
321         }
322
323         to = lookup_node(mesh, to_name);
324
325         if(!to) {
326                 logger(mesh, MESHLINK_ERROR, "Got %s from %s destination %s which does not exist in our connection list",
327                        "REQ_KEY", c->name, to_name);
328                 return true;
329         }
330
331         /* Check if this key request is for us */
332
333         if(to == mesh->self) {                      /* Yes */
334                 /* Is this an extended REQ_KEY message? */
335                 if(reqno) {
336                         return req_key_ext_h(mesh, c, request, from, reqno);
337                 }
338
339                 /* This should never happen. Ignore it, unless it came directly from the connected peer, in which case we disconnect. */
340                 return from->connection != c;
341         } else {
342                 if(!to->status.reachable || !to->nexthop || !to->nexthop->connection) {
343                         logger(mesh, MESHLINK_WARNING, "Got %s from %s destination %s which is not reachable",
344                                "REQ_KEY", c->name, to_name);
345                         return true;
346                 }
347
348                 size_t len = strlen(request);
349                 from->in_forward += len + SPTPS_OVERHEAD;
350                 to->out_forward += len + SPTPS_OVERHEAD;
351
352                 send_request(mesh, to->nexthop->connection, NULL, "%s", request);
353         }
354
355         return true;
356 }
357
358 bool ans_key_h(meshlink_handle_t *mesh, connection_t *c, const char *request) {
359         assert(request);
360         assert(*request);
361
362         char from_name[MAX_STRING_SIZE];
363         char to_name[MAX_STRING_SIZE];
364         char key[MAX_STRING_SIZE];
365         char address[MAX_STRING_SIZE] = "";
366         char port[MAX_STRING_SIZE] = "";
367         int cipher, digest, maclength, compression;
368         node_t *from, *to;
369
370         if(sscanf(request, "%*d "MAX_STRING" "MAX_STRING" "MAX_STRING" %d %d %d %d "MAX_STRING" "MAX_STRING,
371                         from_name, to_name, key, &cipher, &digest, &maclength,
372                         &compression, address, port) < 7) {
373                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s", "ANS_KEY", c->name);
374                 return false;
375         }
376
377         if(!check_id(from_name) || !check_id(to_name)) {
378                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s: %s", "ANS_KEY", c->name, "invalid name");
379                 return false;
380         }
381
382         from = lookup_node(mesh, from_name);
383
384         if(!from) {
385                 logger(mesh, MESHLINK_ERROR, "Got %s from %s origin %s which does not exist in our connection list",
386                        "ANS_KEY", c->name, from_name);
387                 return true;
388         }
389
390         to = lookup_node(mesh, to_name);
391
392         if(!to) {
393                 logger(mesh, MESHLINK_ERROR, "Got %s from %s destination %s which does not exist in our connection list",
394                        "ANS_KEY", c->name, to_name);
395                 return true;
396         }
397
398         /* Forward it if necessary */
399
400         if(to != mesh->self) {
401                 if(!to->status.reachable) {
402                         logger(mesh, MESHLINK_WARNING, "Got %s from %s destination %s which is not reachable",
403                                "ANS_KEY", c->name, to_name);
404                         return true;
405                 }
406
407                 if(from == to) {
408                         logger(mesh, MESHLINK_WARNING, "Got %s from %s from %s to %s",
409                                "ANS_KEY", c->name, from_name, to_name);
410                         return true;
411                 }
412
413                 if(!to->nexthop || !to->nexthop->connection) {
414                         logger(mesh, MESHLINK_WARNING, "Cannot forward ANS_KEY to %s via %s", to->name, to->nexthop ? to->nexthop->name : to->name);
415                         return false;
416                 }
417
418                 /* TODO: find a good way to avoid the use of strlen() */
419                 size_t len = strlen(request);
420                 from->in_forward += len + SPTPS_OVERHEAD;
421                 to->out_forward += len + SPTPS_OVERHEAD;
422
423                 /* Append the known UDP address of the from node, if we have a confirmed one */
424                 if(!*address && from->status.udp_confirmed && from->address.sa.sa_family != AF_UNSPEC) {
425                         char *reflexive_address, *reflexive_port;
426                         logger(mesh, MESHLINK_DEBUG, "Appending reflexive UDP address to ANS_KEY from %s to %s", from->name, to->name);
427                         sockaddr2str(&from->address, &reflexive_address, &reflexive_port);
428                         send_request(mesh, to->nexthop->connection, NULL, "%s %s %s", request, reflexive_address, reflexive_port);
429                         free(reflexive_address);
430                         free(reflexive_port);
431                         return true;
432                 }
433
434                 return send_request(mesh, to->nexthop->connection, NULL, "%s", request);
435         }
436
437         /* Is this an ANS_KEY informing us of our own reflexive UDP address? */
438
439         if(from == mesh->self) {
440                 if(*key == '.' && *address && *port) {
441                         logger(mesh, MESHLINK_DEBUG, "Learned our own reflexive UDP address from %s: %s port %s", c->name, address, port);
442
443                         /* Inform all other nodes we want to communicate with and which are reachable via this connection */
444                         for splay_each(node_t, n, mesh->nodes) {
445                                 if(n->nexthop != c->node) {
446                                         continue;
447                                 }
448
449                                 if(n->status.udp_confirmed) {
450                                         continue;
451                                 }
452
453                                 if(!n->status.waitingforkey && !n->status.validkey) {
454                                         continue;
455                                 }
456
457                                 if(!n->nexthop->connection) {
458                                         continue;
459                                 }
460
461                                 logger(mesh, MESHLINK_DEBUG, "Forwarding our own reflexive UDP address to %s", n->name);
462                                 send_request(mesh, c, NULL, "%d %s %s . -1 -1 -1 0 %s %s", ANS_KEY, mesh->self->name, n->name, address, port);
463                         }
464                 } else {
465                         logger(mesh, MESHLINK_WARNING, "Got %s from %s from %s to %s",
466                                "ANS_KEY", c->name, from_name, to_name);
467                 }
468
469                 return true;
470         }
471
472         /* Process SPTPS data if present */
473
474         if(*key != '.') {
475                 /* Don't use key material until every check has passed. */
476                 from->status.validkey = false;
477
478                 /* Compression is not supported. */
479                 if(compression != 0) {
480                         logger(mesh, MESHLINK_ERROR, "Node %s uses bogus compression level!", from->name);
481                         return true;
482                 }
483
484                 char buf[strlen(key)];
485                 int len = b64decode(key, buf, strlen(key));
486
487                 if(!len || !sptps_receive_data(&from->sptps, buf, len)) {
488                         logger(mesh, MESHLINK_ERROR, "Error processing SPTPS data from %s", from->name);
489                 }
490         }
491
492         if(from->status.validkey) {
493                 if(*address && *port) {
494                         logger(mesh, MESHLINK_DEBUG, "Using reflexive UDP address from %s: %s port %s", from->name, address, port);
495                         sockaddr_t sa = str2sockaddr(address, port);
496                         update_node_udp(mesh, from, &sa);
497                 }
498
499                 send_mtu_probe(mesh, from);
500         }
501
502         return true;
503 }