]> git.meshlink.io Git - meshlink/blob - src/protocol_auth.c
Clean up after tests.
[meshlink] / src / protocol_auth.c
1 /*
2     protocol_auth.c -- handle the meta-protocol, authentication
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 "conf.h"
23 #include "connection.h"
24 #include "devtools.h"
25 #include "ecdsa.h"
26 #include "edge.h"
27 #include "graph.h"
28 #include "logger.h"
29 #include "meshlink_internal.h"
30 #include "meta.h"
31 #include "net.h"
32 #include "netutl.h"
33 #include "node.h"
34 #include "packmsg.h"
35 #include "prf.h"
36 #include "protocol.h"
37 #include "sptps.h"
38 #include "utils.h"
39 #include "xalloc.h"
40 #include "ed25519/sha512.h"
41
42 #include <assert.h>
43
44 extern bool node_write_devclass(meshlink_handle_t *mesh, node_t *n);
45
46 bool send_id(meshlink_handle_t *mesh, connection_t *c) {
47         return send_request(mesh, c, NULL, "%d %s %d.%d %s %u", ID, mesh->self->name, PROT_MAJOR, PROT_MINOR, mesh->appname, 0);
48 }
49
50 static bool commit_invitation(meshlink_handle_t *mesh, connection_t *c, const void *data) {
51         // Check if the node is known
52         node_t *n = lookup_node(mesh, c->name);
53
54         if(n) {
55                 if(n->status.blacklisted) {
56                         logger(mesh, MESHLINK_ERROR, "Invitee %s is blacklisted", c->name);
57                 } else {
58                         logger(mesh, MESHLINK_ERROR, "Invitee %s already known", c->name);
59                 }
60
61                 return false;
62         }
63
64         // Create a new node
65         n = new_node();
66         n->name = xstrdup(c->name);
67         n->devclass = DEV_CLASS_UNKNOWN;
68         n->ecdsa = ecdsa_set_public_key(data);
69         n->submesh = c->submesh;
70
71         // Remember its current address
72         node_add_recent_address(mesh, n, &c->address);
73
74         if(!node_write_config(mesh, n, true)) {
75                 logger(mesh, MESHLINK_ERROR, "Error writing configuration file for invited node %s!\n", c->name);
76                 free_node(n);
77                 return false;
78
79         }
80
81         node_add(mesh, n);
82
83         logger(mesh, MESHLINK_INFO, "Key successfully received from %s", c->name);
84
85         //TODO: callback to application to inform of an accepted invitation
86
87         sptps_send_record(&c->sptps, 1, "", 0);
88
89         return true;
90 }
91
92 static bool process_invitation(meshlink_handle_t *mesh, connection_t *c, const void *data) {
93         // Recover the filename from the cookie and the key
94         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
95         char hash[64];
96         char hashbuf[18 + strlen(fingerprint)];
97         char cookie[25];
98         memcpy(hashbuf, data, 18);
99         memcpy(hashbuf + 18, fingerprint, sizeof(hashbuf) - 18);
100         sha512(hashbuf, sizeof(hashbuf), hash);
101         b64encode_urlsafe(hash, cookie, 18);
102         free(fingerprint);
103
104         config_t config;
105
106         if(!invitation_read(mesh, cookie, &config)) {
107                 logger(mesh, MESHLINK_ERROR, "Error while trying to read invitation file\n");
108                 return false;
109         }
110
111         // Read the new node's Name from the file
112         packmsg_input_t in = {config.buf, config.len};
113         uint32_t version = packmsg_get_uint32(&in);
114
115         if(version != MESHLINK_INVITATION_VERSION) {
116                 logger(mesh, MESHLINK_ERROR, "Invalid invitation file\n");
117                 config_free(&config);
118                 return false;
119         }
120
121         int64_t timestamp = packmsg_get_int64(&in);
122
123         if(time(NULL) >= timestamp + mesh->invitation_timeout) {
124                 logger(mesh, MESHLINK_ERROR, "Peer tried to use an outdated invitation file %s\n", cookie);
125                 config_free(&config);
126                 return false;
127         }
128
129         char *name = packmsg_get_str_dup(&in);
130
131         if(!check_id(name)) {
132                 logger(mesh, MESHLINK_ERROR, "Invalid invitation file %s\n", cookie);
133                 free(name);
134                 config_free(&config);
135                 return false;
136         }
137
138         free(c->name);
139         c->name = name;
140
141         // Check if the file contains Sub-Mesh information
142         char *submesh_name = packmsg_get_str_dup(&in);
143
144         if(!strcmp(submesh_name, CORE_MESH)) {
145                 free(submesh_name);
146                 c->submesh = NULL;
147         } else {
148                 if(!check_id(submesh_name)) {
149                         logger(mesh, MESHLINK_ERROR, "Invalid invitation file %s\n", cookie);
150                         free(submesh_name);
151                         config_free(&config);
152                         return false;
153                 }
154
155                 c->submesh = lookup_or_create_submesh(mesh, submesh_name);
156                 free(submesh_name);
157
158                 if(!c->submesh) {
159                         logger(mesh, MESHLINK_ERROR, "Unknown submesh in invitation file %s\n", cookie);
160                         config_free(&config);
161                         return false;
162                 }
163         }
164
165         if(mesh->inviter_commits_first && !commit_invitation(mesh, c, (const char *)data + 18)) {
166                 config_free(&config);
167                 return false;
168         }
169
170         if(mesh->inviter_commits_first) {
171                 devtool_set_inviter_commits_first(true);
172         }
173
174         // Send the node the contents of the invitation file
175         sptps_send_record(&c->sptps, 0, config.buf, config.len);
176
177         config_free(&config);
178
179         c->status.invitation_used = true;
180
181         logger(mesh, MESHLINK_INFO, "Invitation %s successfully sent to %s", cookie, c->name);
182         return true;
183 }
184
185 static bool receive_invitation_sptps(void *handle, uint8_t type, const void *data, uint16_t len) {
186         connection_t *c = handle;
187         meshlink_handle_t *mesh = c->mesh;
188
189         // Extend the time for the invitation exchange upon receiving a valid message
190         c->last_ping_time = mesh->loop.now.tv_sec;
191
192         if(type == SPTPS_HANDSHAKE) {
193                 // The peer should send its cookie first.
194                 return true;
195         }
196
197         if(mesh->inviter_commits_first) {
198                 if(type == 2 && len == 18 + 32 && !c->status.invitation_used) {
199                         return process_invitation(mesh, c, data);
200                 }
201         } else {
202                 if(type == 0 && len == 18 && !c->status.invitation_used) {
203                         return process_invitation(mesh, c, data);
204                 } else if(type == 1 && len == 32 && c->status.invitation_used) {
205                         return commit_invitation(mesh, c, data);
206                 }
207         }
208
209         return false;
210 }
211
212 bool id_h(meshlink_handle_t *mesh, connection_t *c, const char *request) {
213         assert(request);
214         assert(*request);
215
216         char name[MAX_STRING_SIZE];
217
218         if(sscanf(request, "%*d " MAX_STRING " %d.%d %*s %u", name, &c->protocol_major, &c->protocol_minor, &c->flags) < 2) {
219                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s", "ID", c->name);
220                 return false;
221         }
222
223         /* Check if this is an invitation  */
224
225         if(name[0] == '?') {
226                 if(!mesh->invitation_key) {
227                         logger(mesh, MESHLINK_ERROR, "Got invitation from %s but we don't have an invitation key", c->name);
228                         return false;
229                 }
230
231                 c->ecdsa = ecdsa_set_base64_public_key(name + 1);
232
233                 if(!c->ecdsa) {
234                         logger(mesh, MESHLINK_ERROR, "Got bad invitation from %s", c->name);
235                         return false;
236                 }
237
238                 c->status.invitation = true;
239                 char *mykey = ecdsa_get_base64_public_key(mesh->invitation_key);
240
241                 if(!mykey) {
242                         return false;
243                 }
244
245                 if(!send_request(mesh, c, NULL, "%d %s", ACK, mykey)) {
246                         return false;
247                 }
248
249                 free(mykey);
250
251                 c->protocol_minor = 2;
252                 c->allow_request = 1;
253                 c->last_ping_time = mesh->loop.now.tv_sec;
254
255                 return sptps_start(&c->sptps, c, false, false, mesh->invitation_key, c->ecdsa, meshlink_invitation_label, sizeof(meshlink_invitation_label), send_meta_sptps, receive_invitation_sptps);
256         }
257
258         /* Check if identity is a valid name */
259
260         if(!check_id(name)) {
261                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s: %s", "ID", c->name, "invalid name");
262                 return false;
263         }
264
265         /* If this is an outgoing connection, make sure we are connected to the right host */
266
267         if(c->outgoing) {
268                 if(strcmp(c->name, name)) {
269                         logger(mesh, MESHLINK_ERROR, "Peer is %s instead of %s", name, c->name);
270                         return false;
271                 }
272         } else {
273                 if(c->name) {
274                         free(c->name);
275                 }
276
277                 c->name = xstrdup(name);
278         }
279
280         /* Check if version matches */
281
282         if(c->protocol_major != PROT_MAJOR) {
283                 logger(mesh, MESHLINK_ERROR, "Peer %s uses incompatible version %d.%d",
284                        c->name, c->protocol_major, c->protocol_minor);
285                 return false;
286         }
287
288         /* Check if we know this node */
289
290         node_t *n = lookup_node(mesh, c->name);
291
292         if(!n) {
293                 logger(mesh, MESHLINK_ERROR, "Peer %s has unknown identity", c->name);
294                 return false;
295         }
296
297         if(!node_read_public_key(mesh, n)) {
298                 logger(mesh, MESHLINK_ERROR, "No key known for peer %s", c->name);
299
300                 if(n->status.reachable && !n->status.waitingforkey) {
301                         logger(mesh, MESHLINK_INFO, "Requesting key from peer %s", c->name);
302                         send_req_key(mesh, n);
303                 }
304
305                 return false;
306         }
307
308         /* Forbid version rollback for nodes whose ECDSA key we know */
309
310         if(ecdsa_active(c->ecdsa) && c->protocol_minor < 2) {
311                 logger(mesh, MESHLINK_ERROR, "Peer %s tries to roll back protocol version to %d.%d",
312                        c->name, c->protocol_major, c->protocol_minor);
313                 return false;
314         }
315
316         c->allow_request = ACK;
317         c->last_ping_time = mesh->loop.now.tv_sec;
318         char label[sizeof(meshlink_tcp_label) + strlen(mesh->self->name) + strlen(c->name) + 2];
319
320         if(c->outgoing) {
321                 snprintf(label, sizeof(label), "%s %s %s", meshlink_tcp_label, mesh->self->name, c->name);
322         } else {
323                 snprintf(label, sizeof(label), "%s %s %s", meshlink_tcp_label, c->name, mesh->self->name);
324         }
325
326         if(mesh->log_level <= MESHLINK_DEBUG) {
327                 char buf1[1024], buf2[1024];
328                 bin2hex((uint8_t *)mesh->private_key + 64, buf1, 32);
329                 bin2hex((uint8_t *)n->ecdsa + 64, buf2, 32);
330                 logger(mesh, MESHLINK_DEBUG, "Connection to %s mykey %s hiskey %s", c->name, buf1, buf2);
331         }
332
333         return sptps_start(&c->sptps, c, c->outgoing, false, mesh->private_key, n->ecdsa, label, sizeof(label) - 1, send_meta_sptps, receive_meta_sptps);
334 }
335
336 bool send_ack(meshlink_handle_t *mesh, connection_t *c) {
337         node_t *n = lookup_node(mesh, c->name);
338
339         if(n && n->status.blacklisted) {
340                 logger(mesh, MESHLINK_WARNING, "Peer %s is blacklisted", c->name);
341                 return send_error(mesh, c, BLACKLISTED, "blacklisted");
342         }
343
344         c->last_ping_time = mesh->loop.now.tv_sec;
345         return send_request(mesh, c, NULL, "%d %s %d %x", ACK, mesh->myport, mesh->devclass, OPTION_PMTU_DISCOVERY | (PROT_MINOR << 24));
346 }
347
348 static void send_everything(meshlink_handle_t *mesh, connection_t *c) {
349         /* Send all known subnets and edges */
350
351         for splay_each(node_t, n, mesh->nodes) {
352                 for inner_splay_each(edge_t, e, n->edge_tree) {
353                         send_add_edge(mesh, c, e, 0);
354                 }
355         }
356 }
357
358 bool ack_h(meshlink_handle_t *mesh, connection_t *c, const char *request) {
359         assert(request);
360         assert(*request);
361
362         char hisport[MAX_STRING_SIZE];
363         int devclass;
364         uint32_t options;
365         node_t *n;
366
367         if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &devclass, &options) != 3) {
368                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s", "ACK", c->name);
369                 return false;
370         }
371
372         if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
373                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s: %s", "ACK", c->name, "devclass invalid");
374                 return false;
375         }
376
377         /* Check if we already have a node_t for him */
378
379         n = lookup_node(mesh, c->name);
380
381         if(!n) {
382                 n = new_node();
383                 n->name = xstrdup(c->name);
384                 node_add(mesh, n);
385         } else {
386                 if(n->connection) {
387                         /* Oh dear, we already have a connection to this node. */
388                         logger(mesh, MESHLINK_INFO, "Established a second connection with %s, closing old connection", n->connection->name);
389
390                         if(n->connection->outgoing) {
391                                 if(c->outgoing) {
392                                         logger(mesh, MESHLINK_WARNING, "Two outgoing connections to the same node!");
393                                 } else {
394                                         c->outgoing = n->connection->outgoing;
395                                 }
396
397                                 n->connection->outgoing = NULL;
398                         }
399
400                         /* Remove the edge before terminating the connection, to prevent a graph update. */
401                         edge_del(mesh, n->connection->edge);
402                         n->connection->edge = NULL;
403
404                         terminate_connection(mesh, n->connection, false);
405                 }
406         }
407
408         n->devclass = devclass;
409         n->status.dirty = true;
410         n->status.tiny = c->flags & PROTOCOL_TINY;
411
412         n->last_successfull_connection = mesh->loop.now.tv_sec;
413
414         n->connection = c;
415         n->nexthop = n;
416         c->node = n;
417
418         /* Activate this connection */
419
420         c->allow_request = ALL;
421         c->last_key_renewal = mesh->loop.now.tv_sec;
422         c->status.active = true;
423
424         logger(mesh, MESHLINK_INFO, "Connection with %s activated", c->name);
425
426         if(mesh->meta_status_cb) {
427                 mesh->meta_status_cb(mesh, (meshlink_node_t *)n, true);
428         }
429
430         /*  Terminate any connections to this node that are not activated yet */
431
432         for list_each(connection_t, other, mesh->connections) {
433                 if(!other->status.active && !strcmp(other->name, c->name)) {
434                         if(other->outgoing) {
435                                 if(c->outgoing) {
436                                         logger(mesh, MESHLINK_WARNING, "Two outgoing connections to the same node!");
437                                 } else {
438                                         c->outgoing = other->outgoing;
439                                 }
440
441                                 other->outgoing = NULL;
442                         }
443
444                         logger(mesh, MESHLINK_DEBUG, "Terminating pending second connection with %s", n->name);
445                         terminate_connection(mesh, other, false);
446                 }
447         }
448
449         /* Send him everything we know */
450
451         if(!(c->flags & PROTOCOL_TINY)) {
452                 send_everything(mesh, c);
453         }
454
455         /* Create an edge_t for this connection */
456
457         assert(devclass >= 0 && devclass < DEV_CLASS_COUNT);
458
459         c->edge = new_edge();
460         c->edge->from = mesh->self;
461         c->edge->to = n;
462         sockaddrcpy_setport(&c->edge->address, &c->address, atoi(hisport));
463         c->edge->weight = mesh->dev_class_traits[devclass].edge_weight;
464         c->edge->connection = c;
465
466         node_add_recent_address(mesh, n, &c->address);
467         edge_add(mesh, c->edge);
468
469         /* Notify everyone of the new edge */
470
471         send_add_edge(mesh, mesh->everyone, c->edge, 0);
472
473         /* Run MST and SSSP algorithms */
474
475         graph(mesh);
476
477         /* Request a session key to jump start UDP traffic */
478
479         if(c->status.initiator) {
480                 send_req_key(mesh, n);
481         }
482
483         return true;
484 }