]> git.meshlink.io Git - meshlink/blob - src/protocol_auth.c
f88aaf4b9e7bf430c08cffb02542fe1b9170dbc6
[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 "ecdsa.h"
25 #include "edge.h"
26 #include "graph.h"
27 #include "logger.h"
28 #include "meshlink_internal.h"
29 #include "meta.h"
30 #include "net.h"
31 #include "netutl.h"
32 #include "node.h"
33 #include "prf.h"
34 #include "protocol.h"
35 #include "sptps.h"
36 #include "utils.h"
37 #include "xalloc.h"
38 #include "ed25519/sha512.h"
39
40 #include <assert.h>
41
42 extern bool node_write_devclass(meshlink_handle_t *mesh, node_t *n);
43
44 static bool send_proxyrequest(meshlink_handle_t *mesh, connection_t *c) {
45         switch(mesh->proxytype) {
46         case PROXY_HTTP: {
47                 char *host;
48                 char *port;
49
50                 sockaddr2str(&c->address, &host, &port);
51                 send_request(mesh, c, NULL, "CONNECT %s:%s HTTP/1.1\r\n\r", host, port);
52                 free(host);
53                 free(port);
54                 return true;
55         }
56
57         case PROXY_SOCKS4: {
58                 if(c->address.sa.sa_family != AF_INET) {
59                         logger(mesh, MESHLINK_ERROR, "Cannot connect to an IPv6 host through a SOCKS 4 proxy!");
60                         return false;
61                 }
62
63                 char s4req[9 + (mesh->proxyuser ? strlen(mesh->proxyuser) : 0)];
64                 s4req[0] = 4;
65                 s4req[1] = 1;
66                 memcpy(s4req + 2, &c->address.in.sin_port, 2);
67                 memcpy(s4req + 4, &c->address.in.sin_addr, 4);
68
69                 if(mesh->proxyuser) {
70                         memcpy(s4req + 8, mesh->proxyuser, strlen(mesh->proxyuser));
71                 }
72
73                 s4req[sizeof(s4req) - 1] = 0;
74                 c->tcplen = 8;
75                 return send_meta(mesh, c, s4req, sizeof(s4req));
76         }
77
78         case PROXY_SOCKS5: {
79                 int len = 3 + 6 + (c->address.sa.sa_family == AF_INET ? 4 : 16);
80                 c->tcplen = 2;
81
82                 if(mesh->proxypass) {
83                         len += 3 + strlen(mesh->proxyuser) + strlen(mesh->proxypass);
84                 }
85
86                 char s5req[len];
87                 int i = 0;
88                 s5req[i++] = 5;
89                 s5req[i++] = 1;
90
91                 if(mesh->proxypass) {
92                         s5req[i++] = 2;
93                         s5req[i++] = 1;
94                         s5req[i++] = strlen(mesh->proxyuser);
95                         memcpy(s5req + i, mesh->proxyuser, strlen(mesh->proxyuser));
96                         i += strlen(mesh->proxyuser);
97                         s5req[i++] = strlen(mesh->proxypass);
98                         memcpy(s5req + i, mesh->proxypass, strlen(mesh->proxypass));
99                         i += strlen(mesh->proxypass);
100                         c->tcplen += 2;
101                 } else {
102                         s5req[i++] = 0;
103                 }
104
105                 s5req[i++] = 5;
106                 s5req[i++] = 1;
107                 s5req[i++] = 0;
108
109                 if(c->address.sa.sa_family == AF_INET) {
110                         s5req[i++] = 1;
111                         memcpy(s5req + i, &c->address.in.sin_addr, 4);
112                         i += 4;
113                         memcpy(s5req + i, &c->address.in.sin_port, 2);
114                         i += 2;
115                         c->tcplen += 10;
116                 } else if(c->address.sa.sa_family == AF_INET6) {
117                         s5req[i++] = 3;
118                         memcpy(s5req + i, &c->address.in6.sin6_addr, 16);
119                         i += 16;
120                         memcpy(s5req + i, &c->address.in6.sin6_port, 2);
121                         i += 2;
122                         c->tcplen += 22;
123                 } else {
124                         logger(mesh, MESHLINK_ERROR, "Address family %hx not supported for SOCKS 5 proxies!", c->address.sa.sa_family);
125                         return false;
126                 }
127
128                 if(i > len) {
129                         abort();
130                 }
131
132                 return send_meta(mesh, c, s5req, sizeof(s5req));
133         }
134
135         case PROXY_SOCKS4A:
136                 logger(mesh, MESHLINK_ERROR, "Proxy type not implemented yet");
137                 return false;
138
139         default:
140                 logger(mesh, MESHLINK_ERROR, "Unknown proxy type");
141                 return false;
142         }
143 }
144
145 bool send_id(meshlink_handle_t *mesh, connection_t *c) {
146
147         int minor = mesh->self->connection->protocol_minor;
148
149         if(mesh->proxytype && c->outgoing)
150                 if(!send_proxyrequest(mesh, c)) {
151                         return false;
152                 }
153
154         return send_request(mesh, c, NULL, "%d %s %d.%d %s", ID, mesh->self->connection->name, mesh->self->connection->protocol_major, minor, mesh->appname);
155 }
156
157 static bool finalize_invitation(meshlink_handle_t *mesh, connection_t *c, const void *data, uint16_t len) {
158         (void)len;
159
160         if(strchr(data, '\n')) {
161                 logger(mesh, MESHLINK_ERROR, "Received invalid key from invited node %s!\n", c->name);
162                 return false;
163         }
164
165         // Create a new host config file
166         char filename[PATH_MAX];
167         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, c->name);
168
169         if(!access(filename, F_OK)) {
170                 logger(mesh, MESHLINK_ERROR, "Host config file for %s already exists!\n", c->name);
171                 return false;
172         }
173
174         FILE *f = fopen(filename, "w");
175
176         if(!f) {
177                 logger(mesh, MESHLINK_ERROR, "Error trying to create %s: %s\n", filename, strerror(errno));
178                 return false;
179         }
180
181         fprintf(f, "ECDSAPublicKey = %s\n", (const char *)data);
182
183         if(c->submesh) {
184                 fprintf(f, "SubMesh = %s\n", c->submesh->name);
185         }
186
187         fclose(f);
188
189         logger(mesh, MESHLINK_INFO, "Key successfully received from %s", c->name);
190
191         //TODO: callback to application to inform of an accepted invitation
192
193         sptps_send_record(&c->sptps, 2, data, 0);
194
195         load_all_nodes(mesh);
196
197         return true;
198 }
199
200 static bool receive_invitation_sptps(void *handle, uint8_t type, const void *data, uint16_t len) {
201         connection_t *c = handle;
202         meshlink_handle_t *mesh = c->mesh;
203
204         if(type == 128) {
205                 return true;
206         }
207
208         if(type == 1 && c->status.invitation_used) {
209                 return finalize_invitation(mesh, c, data, len);
210         }
211
212         if(type != 0 || len != 18 || c->status.invitation_used) {
213                 return false;
214         }
215
216         // Recover the filename from the cookie and the key
217         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
218         char hash[64];
219         char hashbuf[18 + strlen(fingerprint)];
220         char cookie[25];
221         memcpy(hashbuf, data, 18);
222         memcpy(hashbuf + 18, fingerprint, sizeof(hashbuf) - 18);
223         sha512(hashbuf, sizeof(hashbuf), hash);
224         b64encode_urlsafe(hash, cookie, 18);
225         free(fingerprint);
226
227         char filename[PATH_MAX], usedname[PATH_MAX];
228         snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookie);
229         snprintf(usedname, sizeof(usedname), "%s" SLASH "invitations" SLASH "%s.used", mesh->confbase, cookie);
230
231         // Atomically rename the invitation file
232         if(rename(filename, usedname)) {
233                 if(errno == ENOENT) {
234                         logger(mesh, MESHLINK_ERROR, "Peer %s tried to use non-existing invitation %s\n", c->name, cookie);
235                 } else {
236                         logger(mesh, MESHLINK_ERROR, "Error trying to rename invitation %s\n", cookie);
237                 }
238
239                 return false;
240         }
241
242         // Open the renamed file
243         FILE *f = fopen(usedname, "r");
244
245         if(!f) {
246                 logger(mesh, MESHLINK_ERROR, "Error trying to open invitation %s\n", cookie);
247                 unlink(usedname);
248                 return false;
249         }
250
251         // Check the timestamp
252         struct stat st;
253
254         if(fstat(fileno(f), &st)) {
255                 logger(mesh, MESHLINK_ERROR, "Could not stat invitation file %s\n", usedname);
256                 fclose(f);
257                 unlink(usedname);
258                 return false;
259         }
260
261         if(time(NULL) > st.st_mtime + mesh->invitation_timeout) {
262                 logger(mesh, MESHLINK_ERROR, "Peer %s tried to use an outdated invitation file %s\n", c->name, usedname);
263                 fclose(f);
264                 unlink(usedname);
265                 return false;
266         }
267
268         // Read the new node's Name from the file
269         char buf[1024];
270         fgets(buf, sizeof(buf), f);
271
272         if(*buf) {
273                 buf[strlen(buf) - 1] = 0;
274         }
275
276         len = strcspn(buf, " \t=");
277         char *name = buf + len;
278         name += strspn(name, " \t");
279
280         if(*name == '=') {
281                 name++;
282                 name += strspn(name, " \t");
283         }
284
285         buf[len] = 0;
286
287         if(!*buf || !*name || strcasecmp(buf, "Name") || !check_id(name)) {
288                 logger(mesh, MESHLINK_ERROR, "Invalid invitation file %s\n", cookie);
289                 fclose(f);
290                 return false;
291         }
292
293         free(c->name);
294         c->name = xstrdup(name);
295
296         // Check if the file contains Sub-Mesh information
297         buf[0] = 0;
298         fgets(buf, sizeof(buf), f);
299
300         if(*buf) {
301                 buf[strlen(buf) - 1] = 0;
302         }
303
304         if(!strncmp(buf, "SubMesh", 7)) {
305                 len = strcspn(buf, " \t=");
306                 char *submesh_name = buf + len;
307                 submesh_name += strspn(submesh_name, " \t");
308
309                 if(*submesh_name == '=') {
310                         submesh_name++;
311                         submesh_name += strspn(submesh_name, " \t");
312                 }
313
314                 if(!check_id(submesh_name)) {
315                         logger(mesh, MESHLINK_ERROR, "Invalid invitation file %s\n", cookie);
316                         fclose(f);
317                         return false;
318                 }
319
320                 c->submesh = NULL;
321                 c->submesh = lookup_or_create_submesh(mesh, submesh_name);
322
323                 if(!c->submesh) {
324                         return false;
325                 }
326         }
327
328         // Send the node the contents of the invitation file
329         rewind(f);
330         size_t result;
331
332         while((result = fread(buf, 1, sizeof(buf), f))) {
333                 sptps_send_record(&c->sptps, 0, buf, result);
334         }
335
336         sptps_send_record(&c->sptps, 1, buf, 0);
337         fclose(f);
338         unlink(usedname);
339
340         c->status.invitation_used = true;
341
342         logger(mesh, MESHLINK_INFO, "Invitation %s successfully sent to %s", cookie, c->name);
343         return true;
344 }
345
346 bool id_h(meshlink_handle_t *mesh, connection_t *c, const char *request) {
347         char name[MAX_STRING_SIZE];
348
349         if(sscanf(request, "%*d " MAX_STRING " %d.%d", name, &c->protocol_major, &c->protocol_minor) < 2) {
350                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s", "ID", c->name);
351                 return false;
352         }
353
354         /* Check if this is an invitation  */
355
356         if(name[0] == '?') {
357                 if(!mesh->invitation_key) {
358                         logger(mesh, MESHLINK_ERROR, "Got invitation from %s but we don't have an invitation key", c->name);
359                         return false;
360                 }
361
362                 c->ecdsa = ecdsa_set_base64_public_key(name + 1);
363
364                 if(!c->ecdsa) {
365                         logger(mesh, MESHLINK_ERROR, "Got bad invitation from %s", c->name);
366                         return false;
367                 }
368
369                 c->status.invitation = true;
370                 char *mykey = ecdsa_get_base64_public_key(mesh->invitation_key);
371
372                 if(!mykey) {
373                         return false;
374                 }
375
376                 if(!send_request(mesh, c, NULL, "%d %s", ACK, mykey)) {
377                         return false;
378                 }
379
380                 free(mykey);
381
382                 c->protocol_minor = 2;
383                 c->allow_request = 1;
384
385                 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);
386         }
387
388         /* Check if identity is a valid name */
389
390         if(!check_id(name)) {
391                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s: %s", "ID", c->name, "invalid name");
392                 return false;
393         }
394
395         /* If this is an outgoing connection, make sure we are connected to the right host */
396
397         if(c->outgoing) {
398                 if(strcmp(c->name, name)) {
399                         logger(mesh, MESHLINK_ERROR, "Peer is %s instead of %s", name, c->name);
400                         return false;
401                 }
402         } else {
403                 if(c->name) {
404                         free(c->name);
405                 }
406
407                 c->name = xstrdup(name);
408         }
409
410         /* Check if version matches */
411
412         if(c->protocol_major != mesh->self->connection->protocol_major) {
413                 logger(mesh, MESHLINK_ERROR, "Peer %s uses incompatible version %d.%d",
414                        c->name, c->protocol_major, c->protocol_minor);
415                 return false;
416         }
417
418         if(!c->config_tree) {
419                 init_configuration(&c->config_tree);
420
421                 if(!read_host_config(mesh, c->config_tree, c->name)) {
422                         logger(mesh, MESHLINK_ERROR, "Peer %s has unknown identity", c->name);
423                         return false;
424                 }
425         }
426
427         bool blacklisted = false;
428         get_config_bool(lookup_config(c->config_tree, "blacklisted"), &blacklisted);
429
430         if(blacklisted) {
431                 logger(mesh, MESHLINK_EPEER, "Peer %s is blacklisted", c->name);
432                 return false;
433         }
434
435         read_ecdsa_public_key(mesh, c);
436
437         if(!ecdsa_active(c->ecdsa)) {
438                 logger(mesh, MESHLINK_ERROR, "No key known for peer %s", c->name);
439
440                 node_t *n = lookup_node(mesh, c->name);
441
442                 if(n && n->status.reachable && !n->status.waitingforkey) {
443                         logger(mesh, MESHLINK_INFO, "Requesting key from peer %s", c->name);
444                         send_req_key(mesh, n);
445                 }
446
447                 return false;
448         }
449
450         /* Forbid version rollback for nodes whose ECDSA key we know */
451
452         if(ecdsa_active(c->ecdsa) && c->protocol_minor < 2) {
453                 logger(mesh, MESHLINK_ERROR, "Peer %s tries to roll back protocol version to %d.%d",
454                        c->name, c->protocol_major, c->protocol_minor);
455                 return false;
456         }
457
458         c->allow_request = ACK;
459         char label[sizeof(meshlink_tcp_label) + strlen(mesh->self->name) + strlen(c->name) + 2];
460
461         if(c->outgoing) {
462                 snprintf(label, sizeof(label), "%s %s %s", meshlink_tcp_label, mesh->self->name, c->name);
463         } else {
464                 snprintf(label, sizeof(label), "%s %s %s", meshlink_tcp_label, c->name, mesh->self->name);
465         }
466
467         return sptps_start(&c->sptps, c, c->outgoing, false, mesh->self->connection->ecdsa, c->ecdsa, label, sizeof(label) - 1, send_meta_sptps, receive_meta_sptps);
468 }
469
470 bool send_ack(meshlink_handle_t *mesh, connection_t *c) {
471
472         /* Check some options */
473
474         if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
475                 c->options |= OPTION_PMTU_DISCOVERY;
476         }
477
478         return send_request(mesh, c, NULL, "%d %s %d %x", ACK, mesh->myport, mesh->devclass, (c->options & 0xffffff) | (PROT_MINOR << 24));
479 }
480
481 static void send_everything(meshlink_handle_t *mesh, connection_t *c) {
482         /* Send all known subnets and edges */
483
484         for splay_each(node_t, n, mesh->nodes) {
485                 for splay_each(edge_t, e, n->edge_tree) {
486                         send_add_edge(mesh, c, e, 0);
487                 }
488         }
489 }
490
491 bool ack_h(meshlink_handle_t *mesh, connection_t *c, const char *request) {
492         char hisport[MAX_STRING_SIZE];
493         char *hisaddress;
494         int devclass;
495         uint32_t options;
496         node_t *n;
497
498         if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &devclass, &options) != 3) {
499                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s", "ACK", c->name);
500                 return false;
501         }
502
503         if(devclass < 0 || devclass > _DEV_CLASS_MAX) {
504                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s: %s", "ACK", c->name, "devclass invalid");
505                 return false;
506         }
507
508         /* Check if we already have a node_t for him */
509
510         n = lookup_node(mesh, c->name);
511
512         if(!n) {
513                 n = new_node();
514                 n->name = xstrdup(c->name);
515                 node_add(mesh, n);
516         } else {
517                 if(n->connection) {
518                         /* Oh dear, we already have a connection to this node. */
519                         logger(mesh, MESHLINK_DEBUG, "Established a second connection with %s, closing old connection", n->connection->name);
520
521                         if(n->connection->outgoing) {
522                                 if(c->outgoing) {
523                                         logger(mesh, MESHLINK_WARNING, "Two outgoing connections to the same node!");
524                                 } else {
525                                         c->outgoing = n->connection->outgoing;
526                                 }
527
528                                 n->connection->outgoing = NULL;
529                         }
530
531                         terminate_connection(mesh, n->connection, false);
532                         /* Run graph algorithm to keep things in sync */
533                         graph(mesh);
534                 }
535         }
536
537         n->devclass = devclass;
538         node_write_devclass(mesh, n);
539
540         n->last_successfull_connection = time(NULL);
541
542         n->connection = c;
543         c->node = n;
544
545         if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
546                 c->options &= ~OPTION_PMTU_DISCOVERY;
547                 options &= ~OPTION_PMTU_DISCOVERY;
548         }
549
550         c->options |= options;
551
552         /* Activate this connection */
553
554         c->allow_request = ALL;
555         c->status.active = true;
556
557         logger(mesh, MESHLINK_INFO, "Connection with %s activated", c->name);
558
559         /* Send him everything we know */
560
561         send_everything(mesh, c);
562
563         /* Create an edge_t for this connection */
564
565         assert(devclass >= 0 && devclass <= _DEV_CLASS_MAX);
566
567         c->edge = new_edge();
568         c->edge->from = mesh->self;
569         c->edge->to = n;
570         sockaddr2str(&c->address, &hisaddress, NULL);
571         c->edge->address = str2sockaddr(hisaddress, hisport);
572         free(hisaddress);
573         c->edge->weight = dev_class_traits[devclass].edge_weight;
574         c->edge->connection = c;
575         c->edge->options = c->options;
576
577         edge_add(mesh, c->edge);
578
579         /* Notify everyone of the new edge */
580
581         send_add_edge(mesh, mesh->everyone, c->edge, 0);
582
583         /* Run MST and SSSP algorithms */
584
585         graph(mesh);
586
587         return true;
588 }