]> git.meshlink.io Git - meshlink/blob - src/protocol_auth.c
Update astylerc and reformat the code.
[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, "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         case PROXY_EXEC:
140                 return true;
141
142         default:
143                 logger(mesh, MESHLINK_ERROR, "Unknown proxy type");
144                 return false;
145         }
146 }
147
148 bool send_id(meshlink_handle_t *mesh, connection_t *c) {
149
150         int minor = mesh->self->connection->protocol_minor;
151
152         if(mesh->proxytype && c->outgoing)
153                 if(!send_proxyrequest(mesh, c)) {
154                         return false;
155                 }
156
157         return send_request(mesh, c, "%d %s %d.%d", ID, mesh->self->connection->name, mesh->self->connection->protocol_major, minor);
158 }
159
160 static bool finalize_invitation(meshlink_handle_t *mesh, connection_t *c, const void *data, uint16_t len) {
161         (void)len;
162
163         if(strchr(data, '\n')) {
164                 logger(mesh, MESHLINK_ERROR, "Received invalid key from invited node %s!\n", c->name);
165                 return false;
166         }
167
168         // Create a new host config file
169         char filename[PATH_MAX];
170         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, c->name);
171
172         if(!access(filename, F_OK)) {
173                 logger(mesh, MESHLINK_ERROR, "Host config file for %s already exists!\n", c->name);
174                 return false;
175         }
176
177         FILE *f = fopen(filename, "w");
178
179         if(!f) {
180                 logger(mesh, MESHLINK_ERROR, "Error trying to create %s: %s\n", filename, strerror(errno));
181                 return false;
182         }
183
184         fprintf(f, "ECDSAPublicKey = %s\n", (const char *)data);
185         fclose(f);
186
187         logger(mesh, MESHLINK_INFO, "Key succesfully received from %s", c->name);
188
189         //TODO: callback to application to inform of an accepted invitation
190
191         sptps_send_record(&c->sptps, 2, data, 0);
192
193         load_all_nodes(mesh);
194
195         return true;
196 }
197
198 static bool receive_invitation_sptps(void *handle, uint8_t type, const void *data, uint16_t len) {
199         connection_t *c = handle;
200         meshlink_handle_t *mesh = c->mesh;
201
202         if(type == 128) {
203                 return true;
204         }
205
206         if(type == 1 && c->status.invitation_used) {
207                 return finalize_invitation(mesh, c, data, len);
208         }
209
210         if(type != 0 || len != 18 || c->status.invitation_used) {
211                 return false;
212         }
213
214         // Recover the filename from the cookie and the key
215         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
216         char hash[64];
217         char hashbuf[18 + strlen(fingerprint)];
218         char cookie[25];
219         memcpy(hashbuf, data, 18);
220         memcpy(hashbuf + 18, fingerprint, sizeof(hashbuf) - 18);
221         sha512(hashbuf, sizeof(hashbuf), hash);
222         b64encode_urlsafe(hash, cookie, 18);
223         free(fingerprint);
224
225         char filename[PATH_MAX], usedname[PATH_MAX];
226         snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookie);
227         snprintf(usedname, sizeof(usedname), "%s" SLASH "invitations" SLASH "%s.used", mesh->confbase, cookie);
228
229         // Atomically rename the invitation file
230         if(rename(filename, usedname)) {
231                 if(errno == ENOENT) {
232                         logger(mesh, MESHLINK_ERROR, "Peer %s tried to use non-existing invitation %s\n", c->name, cookie);
233                 } else {
234                         logger(mesh, MESHLINK_ERROR, "Error trying to rename invitation %s\n", cookie);
235                 }
236
237                 return false;
238         }
239
240         // Open the renamed file
241         FILE *f = fopen(usedname, "r");
242
243         if(!f) {
244                 logger(mesh, MESHLINK_ERROR, "Error trying to open invitation %s\n", cookie);
245                 return false;
246         }
247
248         // Read the new node's Name from the file
249         char buf[1024];
250         fgets(buf, sizeof(buf), f);
251
252         if(*buf) {
253                 buf[strlen(buf) - 1] = 0;
254         }
255
256         len = strcspn(buf, " \t=");
257         char *name = buf + len;
258         name += strspn(name, " \t");
259
260         if(*name == '=') {
261                 name++;
262                 name += strspn(name, " \t");
263         }
264
265         buf[len] = 0;
266
267         if(!*buf || !*name || strcasecmp(buf, "Name") || !check_id(name)) {
268                 logger(mesh, MESHLINK_ERROR, "Invalid invitation file %s\n", cookie);
269                 fclose(f);
270                 return false;
271         }
272
273         free(c->name);
274         c->name = xstrdup(name);
275
276         // Send the node the contents of the invitation file
277         rewind(f);
278         size_t result;
279
280         while((result = fread(buf, 1, sizeof(buf), f))) {
281                 sptps_send_record(&c->sptps, 0, buf, result);
282         }
283
284         sptps_send_record(&c->sptps, 1, buf, 0);
285         fclose(f);
286         unlink(usedname);
287
288         c->status.invitation_used = true;
289
290         logger(mesh, MESHLINK_INFO, "Invitation %s succesfully sent to %s", cookie, c->name);
291         return true;
292 }
293
294 bool id_h(meshlink_handle_t *mesh, connection_t *c, const char *request) {
295         char name[MAX_STRING_SIZE];
296
297         if(sscanf(request, "%*d " MAX_STRING " %d.%d", name, &c->protocol_major, &c->protocol_minor) < 2) {
298                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s", "ID", c->name);
299                 return false;
300         }
301
302         /* Check if this is an invitation  */
303
304         if(name[0] == '?') {
305                 if(!mesh->invitation_key) {
306                         logger(mesh, MESHLINK_ERROR, "Got invitation from %s but we don't have an invitation key", c->name);
307                         return false;
308                 }
309
310                 c->ecdsa = ecdsa_set_base64_public_key(name + 1);
311
312                 if(!c->ecdsa) {
313                         logger(mesh, MESHLINK_ERROR, "Got bad invitation from %s", c->name);
314                         return false;
315                 }
316
317                 c->status.invitation = true;
318                 char *mykey = ecdsa_get_base64_public_key(mesh->invitation_key);
319
320                 if(!mykey) {
321                         return false;
322                 }
323
324                 if(!send_request(mesh, c, "%d %s", ACK, mykey)) {
325                         return false;
326                 }
327
328                 free(mykey);
329
330                 c->protocol_minor = 2;
331                 c->allow_request = 1;
332
333                 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);
334         }
335
336         /* Check if identity is a valid name */
337
338         if(!check_id(name)) {
339                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s: %s", "ID", c->name, "invalid name");
340                 return false;
341         }
342
343         /* If this is an outgoing connection, make sure we are connected to the right host */
344
345         if(c->outgoing) {
346                 if(strcmp(c->name, name)) {
347                         logger(mesh, MESHLINK_ERROR, "Peer is %s instead of %s", name, c->name);
348                         return false;
349                 }
350         } else {
351                 if(c->name) {
352                         free(c->name);
353                 }
354
355                 c->name = xstrdup(name);
356         }
357
358         /* Check if version matches */
359
360         if(c->protocol_major != mesh->self->connection->protocol_major) {
361                 logger(mesh, MESHLINK_ERROR, "Peer %s uses incompatible version %d.%d",
362                        c->name, c->protocol_major, c->protocol_minor);
363                 return false;
364         }
365
366         if(!c->config_tree) {
367                 init_configuration(&c->config_tree);
368
369                 if(!read_host_config(mesh, c->config_tree, c->name)) {
370                         logger(mesh, MESHLINK_ERROR, "Peer %s has unknown identity", c->name);
371                         return false;
372                 }
373         }
374
375         read_ecdsa_public_key(mesh, c);
376
377         if(!ecdsa_active(c->ecdsa)) {
378                 logger(mesh, MESHLINK_ERROR, "No key known for peer %s", c->name);
379
380                 node_t *n = lookup_node(mesh, c->name);
381
382                 if(n && !n->status.waitingforkey) {
383                         logger(mesh, MESHLINK_INFO, "Requesting key from peer %s", c->name);
384                         send_req_key(mesh, n);
385                 }
386
387                 return false;
388         }
389
390         /* Forbid version rollback for nodes whose ECDSA key we know */
391
392         if(ecdsa_active(c->ecdsa) && c->protocol_minor < 2) {
393                 logger(mesh, MESHLINK_ERROR, "Peer %s tries to roll back protocol version to %d.%d",
394                        c->name, c->protocol_major, c->protocol_minor);
395                 return false;
396         }
397
398         c->allow_request = ACK;
399         char label[sizeof(meshlink_tcp_label) + strlen(mesh->self->name) + strlen(c->name) + 2];
400
401         if(c->outgoing) {
402                 snprintf(label, sizeof(label), "%s %s %s", meshlink_tcp_label, mesh->self->name, c->name);
403         } else {
404                 snprintf(label, sizeof(label), "%s %s %s", meshlink_tcp_label, c->name, mesh->self->name);
405         }
406
407         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);
408 }
409
410 bool send_ack(meshlink_handle_t *mesh, connection_t *c) {
411
412         /* Check some options */
413
414         if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
415                 c->options |= OPTION_PMTU_DISCOVERY;
416         }
417
418         return send_request(mesh, c, "%d %s %d %x", ACK, mesh->myport, mesh->devclass, (c->options & 0xffffff) | (PROT_MINOR << 24));
419 }
420
421 static void send_everything(meshlink_handle_t *mesh, connection_t *c) {
422         /* Send all known subnets and edges */
423
424         for splay_each(node_t, n, mesh->nodes) {
425                 for splay_each(edge_t, e, n->edge_tree) {
426                         send_add_edge(mesh, c, e);
427                 }
428         }
429 }
430
431 bool ack_h(meshlink_handle_t *mesh, connection_t *c, const char *request) {
432         char hisport[MAX_STRING_SIZE];
433         char *hisaddress;
434         int devclass;
435         uint32_t options;
436         node_t *n;
437
438         if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &devclass, &options) != 3) {
439                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s", "ACK", c->name);
440                 return false;
441         }
442
443         if(devclass < 0 || devclass > _DEV_CLASS_MAX) {
444                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s: %s", "ACK", c->name, "devclass invalid");
445                 return false;
446         }
447
448         /* Check if we already have a node_t for him */
449
450         n = lookup_node(mesh, c->name);
451
452         if(!n) {
453                 n = new_node();
454                 n->name = xstrdup(c->name);
455                 node_add(mesh, n);
456         } else {
457                 if(n->connection) {
458                         /* Oh dear, we already have a connection to this node. */
459                         logger(mesh, MESHLINK_DEBUG, "Established a second connection with %s, closing old connection", n->connection->name);
460
461                         if(n->connection->outgoing) {
462                                 if(c->outgoing) {
463                                         logger(mesh, MESHLINK_WARNING, "Two outgoing connections to the same node!");
464                                 } else {
465                                         c->outgoing = n->connection->outgoing;
466                                 }
467
468                                 n->connection->outgoing = NULL;
469                         }
470
471                         terminate_connection(mesh, n->connection, false);
472                         /* Run graph algorithm to keep things in sync */
473                         graph(mesh);
474                 }
475         }
476
477         n->devclass = devclass;
478         node_write_devclass(mesh, n);
479
480         n->last_successfull_connection = time(NULL);
481
482         n->connection = c;
483         c->node = n;
484
485         if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
486                 c->options &= ~OPTION_PMTU_DISCOVERY;
487                 options &= ~OPTION_PMTU_DISCOVERY;
488         }
489
490         c->options |= options;
491
492         /* Activate this connection */
493
494         c->allow_request = ALL;
495         c->status.active = true;
496
497         logger(mesh, MESHLINK_INFO, "Connection with %s activated", c->name);
498
499         /* Send him everything we know */
500
501         send_everything(mesh, c);
502
503         /* Create an edge_t for this connection */
504
505         assert(devclass >= 0 && devclass <= _DEV_CLASS_MAX);
506
507         c->edge = new_edge();
508         c->edge->from = mesh->self;
509         c->edge->to = n;
510         sockaddr2str(&c->address, &hisaddress, NULL);
511         c->edge->address = str2sockaddr(hisaddress, hisport);
512         free(hisaddress);
513         c->edge->weight = dev_class_traits[devclass].edge_weight;
514         c->edge->connection = c;
515         c->edge->options = c->options;
516
517         edge_add(mesh, c->edge);
518
519         /* Notify everyone of the new edge */
520
521         send_add_edge(mesh, mesh->everyone, c->edge);
522
523         /* Run MST and SSSP algorithms */
524
525         graph(mesh);
526
527         return true;
528 }