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