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