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