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