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