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