]> git.meshlink.io Git - meshlink/blob - src/protocol_auth.c
Merge branch 'channels'
[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                         }
94                         s5req[i++] = 5;
95                         s5req[i++] = 1;
96                         s5req[i++] = 0;
97                         if(c->address.sa.sa_family == AF_INET) {
98                                 s5req[i++] = 1;
99                                 memcpy(s5req + i, &c->address.in.sin_addr, 4);
100                                 i += 4;
101                                 memcpy(s5req + i, &c->address.in.sin_port, 2);
102                                 i += 2;
103                                 c->tcplen += 10;
104                         } else if(c->address.sa.sa_family == AF_INET6) {
105                                 s5req[i++] = 3;
106                                 memcpy(s5req + i, &c->address.in6.sin6_addr, 16);
107                                 i += 16;
108                                 memcpy(s5req + i, &c->address.in6.sin6_port, 2);
109                                 i += 2;
110                                 c->tcplen += 22;
111                         } else {
112                                 logger(mesh, MESHLINK_ERROR, "Address family %hx not supported for SOCKS 5 proxies!", c->address.sa.sa_family);
113                                 return false;
114                         }
115                         if(i > len)
116                                 abort();
117                         return send_meta(mesh, c, s5req, sizeof s5req);
118                 }
119                 case PROXY_SOCKS4A:
120                         logger(mesh, MESHLINK_ERROR, "Proxy type not implemented yet");
121                         return false;
122                 case PROXY_EXEC:
123                         return true;
124                 default:
125                         logger(mesh, MESHLINK_ERROR, "Unknown proxy type");
126                         return false;
127         }
128 }
129
130 bool send_id(meshlink_handle_t *mesh, connection_t *c) {
131         
132         int minor = mesh->self->connection->protocol_minor;
133
134         if(mesh->proxytype && c->outgoing)
135                 if(!send_proxyrequest(mesh, c))
136                         return false;
137
138         return send_request(mesh, c, "%d %s %d.%d", ID, mesh->self->connection->name, mesh->self->connection->protocol_major, minor);
139 }
140
141 static bool finalize_invitation(meshlink_handle_t *mesh, connection_t *c, const void *data, uint16_t len) {
142         if(strchr(data, '\n')) {
143                 logger(mesh, MESHLINK_ERROR, "Received invalid key from invited node %s (%s)!\n", c->name, c->hostname);
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 (%s) already exists!\n", c->name, c->hostname);
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 (%s)", c->name, c->hostname);
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->hostname, 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 (%s)", cookie, c->name, c->hostname);
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 (%s)", "ID", c->name,
263                            c->hostname);
264                 return false;
265         }
266
267         /* Check if this is an invitation  */
268
269         if(name[0] == '?') {
270                 if(!mesh->invitation_key) {
271                         logger(mesh, MESHLINK_ERROR, "Got invitation from %s but we don't have an invitation key", c->hostname);
272                         return false;
273                 }
274
275                 c->ecdsa = ecdsa_set_base64_public_key(name + 1);
276                 if(!c->ecdsa) {
277                         logger(mesh, MESHLINK_ERROR, "Got bad invitation from %s", c->hostname);
278                         return false;
279                 }
280
281                 c->status.invitation = true;
282                 char *mykey = ecdsa_get_base64_public_key(mesh->invitation_key);
283                 if(!mykey)
284                         return false;
285                 if(!send_request(mesh, c, "%d %s", ACK, mykey))
286                         return false;
287                 free(mykey);
288
289                 c->protocol_minor = 2;
290                 c->allow_request = 1;
291
292                 return sptps_start(&c->sptps, c, false, false, mesh->invitation_key, c->ecdsa, "meshlink invitation", 15, send_meta_sptps, receive_invitation_sptps);
293         }
294
295         /* Check if identity is a valid name */
296
297         if(!check_id(name)) {
298                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s (%s): %s", "ID", c->name,
299                            c->hostname, "invalid name");
300                 return false;
301         }
302
303         /* If this is an outgoing connection, make sure we are connected to the right host */
304
305         if(c->outgoing) {
306                 if(strcmp(c->name, name)) {
307                         logger(mesh, MESHLINK_ERROR, "Peer %s is %s instead of %s", c->hostname, name,
308                                    c->name);
309                         return false;
310                 }
311         } else {
312                 if(c->name)
313                         free(c->name);
314                 c->name = xstrdup(name);
315         }
316
317         /* Check if version matches */
318
319         if(c->protocol_major != mesh->self->connection->protocol_major) {
320                 logger(mesh, MESHLINK_ERROR, "Peer %s (%s) uses incompatible version %d.%d",
321                         c->name, c->hostname, c->protocol_major, c->protocol_minor);
322                 return false;
323         }
324
325         if(!c->config_tree) {
326                 init_configuration(&c->config_tree);
327
328                 if(!read_host_config(mesh, c->config_tree, c->name)) {
329                         logger(mesh, MESHLINK_ERROR, "Peer %s had unknown identity (%s)", c->hostname, c->name);
330                         return false;
331                 }
332         }
333
334         read_ecdsa_public_key(mesh, c);
335
336         if(!ecdsa_active(c->ecdsa)) {
337                 logger(mesh, MESHLINK_ERROR, "No key known for peer %s (%s)", c->name, c->hostname);
338
339                 node_t *n = lookup_node(mesh, c->name);
340                 if(n && !n->status.waitingforkey) {
341                         logger(mesh, MESHLINK_INFO, "Requesting key from peer %s (%s)", c->name, c->hostname);
342                         send_req_key(mesh, n);
343                 }
344
345                 return false;
346         }
347
348         /* Forbid version rollback for nodes whose ECDSA key we know */
349
350         if(ecdsa_active(c->ecdsa) && c->protocol_minor < 2) {
351                 logger(mesh, MESHLINK_ERROR, "Peer %s (%s) tries to roll back protocol version to %d.%d",
352                         c->name, c->hostname, c->protocol_major, c->protocol_minor);
353                 return false;
354         }
355
356         c->allow_request = ACK;
357         char label[25 + strlen(mesh->self->name) + strlen(c->name)];
358
359         if(c->outgoing)
360                 snprintf(label, sizeof label, "meshlink TCP key expansion %s %s", mesh->self->name, c->name);
361         else
362                 snprintf(label, sizeof label, "meshlink TCP key expansion %s %s", c->name, mesh->self->name);
363
364         return sptps_start(&c->sptps, c, c->outgoing, false, mesh->self->connection->ecdsa, c->ecdsa, label, sizeof label, send_meta_sptps, receive_meta_sptps);
365 }
366
367 bool send_ack(meshlink_handle_t *mesh, connection_t *c) {
368
369         /* Check some options */
370
371         if(mesh->self->options & OPTION_PMTU_DISCOVERY)
372                 c->options |= OPTION_PMTU_DISCOVERY;
373
374         return send_request(mesh, c, "%d %s %d %x", ACK, mesh->myport, mesh->devclass, (c->options & 0xffffff) | (PROT_MINOR << 24));
375 }
376
377 static void send_everything(meshlink_handle_t *mesh, connection_t *c) {
378         /* Send all known subnets and edges */
379
380         for splay_each(node_t, n, mesh->nodes) {
381                 for splay_each(edge_t, e, n->edge_tree)
382                         send_add_edge(mesh, c, e);
383         }
384 }
385
386 bool ack_h(meshlink_handle_t *mesh, connection_t *c, const char *request) {
387         char hisport[MAX_STRING_SIZE];
388         char *hisaddress;
389         int devclass;
390         uint32_t options;
391         node_t *n;
392
393         if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &devclass, &options) != 3) {
394                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s (%s)", "ACK", c->name,
395                            c->hostname);
396                 return false;
397         }
398
399         if(devclass < 0 || devclass > _DEV_CLASS_MAX) {
400                 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s (%s): %s", "ACK", c->name,
401                            c->hostname, "devclass invalid");
402                 return false;
403         }
404
405         /* Check if we already have a node_t for him */
406
407         n = lookup_node(mesh, c->name);
408
409         if(!n) {
410                 n = new_node();
411                 n->name = xstrdup(c->name);
412                 node_add(mesh, n);
413         } else {
414                 if(n->connection) {
415                         /* Oh dear, we already have a connection to this node. */
416                         logger(mesh, MESHLINK_DEBUG, "Established a second connection with %s (%s), closing old connection", n->connection->name, n->connection->hostname);
417
418                         if(n->connection->outgoing) {
419                                 if(c->outgoing)
420                                         logger(mesh, MESHLINK_WARNING, "Two outgoing connections to the same node!");
421                                 else
422                                         c->outgoing = n->connection->outgoing;
423
424                                 n->connection->outgoing = NULL;
425                         }
426
427                         terminate_connection(mesh, n->connection, false);
428                         /* Run graph algorithm to keep things in sync */
429                         graph(mesh);
430                 }
431         }
432
433         n->devclass = devclass;
434         node_write_devclass(mesh, n);
435
436         n->last_successfull_connection = time(NULL);
437
438         n->connection = c;
439         c->node = n;
440         if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
441                 c->options &= ~OPTION_PMTU_DISCOVERY;
442                 options &= ~OPTION_PMTU_DISCOVERY;
443         }
444         c->options |= options;
445
446         /* Activate this connection */
447
448         c->allow_request = ALL;
449         c->status.active = true;
450
451         logger(mesh, MESHLINK_INFO, "Connection with %s (%s) activated", c->name,
452                            c->hostname);
453
454         /* Send him everything we know */
455
456         send_everything(mesh, c);
457
458         /* Create an edge_t for this connection */
459
460         assert(devclass >= 0 && devclass <= _DEV_CLASS_MAX);
461
462         c->edge = new_edge();
463         c->edge->from = mesh->self;
464         c->edge->to = n;
465         sockaddr2str(&c->address, &hisaddress, NULL);
466         c->edge->address = str2sockaddr(hisaddress, hisport);
467         free(hisaddress);
468         c->edge->weight = dev_class_traits[devclass].edge_weight;
469         c->edge->connection = c;
470         c->edge->options = c->options;
471
472         edge_add(mesh, c->edge);
473
474         /* Notify everyone of the new edge */
475
476         send_add_edge(mesh, mesh->everyone, c->edge);
477
478         /* Run MST and SSSP algorithms */
479
480         graph(mesh);
481
482         return true;
483 }