2 protocol_auth.c -- handle the meta-protocol, authentication
3 Copyright (C) 2014-2017 Guus Sliepen <guus@meshlink.io>
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.
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.
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.
23 #include "connection.h"
28 #include "meshlink_internal.h"
38 #include "ed25519/sha512.h"
42 extern bool node_write_devclass(meshlink_handle_t *mesh, node_t *n);
44 static bool send_proxyrequest(meshlink_handle_t *mesh, connection_t *c) {
45 switch(mesh->proxytype) {
50 sockaddr2str(&c->address, &host, &port);
51 send_request(mesh, c, NULL, "CONNECT %s:%s HTTP/1.1\r\n\r", host, port);
58 if(c->address.sa.sa_family != AF_INET) {
59 logger(mesh, MESHLINK_ERROR, "Cannot connect to an IPv6 host through a SOCKS 4 proxy!");
63 char s4req[9 + (mesh->proxyuser ? strlen(mesh->proxyuser) : 0)];
66 memcpy(s4req + 2, &c->address.in.sin_port, 2);
67 memcpy(s4req + 4, &c->address.in.sin_addr, 4);
70 memcpy(s4req + 8, mesh->proxyuser, strlen(mesh->proxyuser));
73 s4req[sizeof(s4req) - 1] = 0;
75 return send_meta(mesh, c, s4req, sizeof(s4req));
79 int len = 3 + 6 + (c->address.sa.sa_family == AF_INET ? 4 : 16);
83 len += 3 + strlen(mesh->proxyuser) + strlen(mesh->proxypass);
94 s5req[i++] = strlen(mesh->proxyuser);
95 memcpy(s5req + i, mesh->proxyuser, strlen(mesh->proxyuser));
96 i += strlen(mesh->proxyuser);
97 s5req[i++] = strlen(mesh->proxypass);
98 memcpy(s5req + i, mesh->proxypass, strlen(mesh->proxypass));
99 i += strlen(mesh->proxypass);
109 if(c->address.sa.sa_family == AF_INET) {
111 memcpy(s5req + i, &c->address.in.sin_addr, 4);
113 memcpy(s5req + i, &c->address.in.sin_port, 2);
116 } else if(c->address.sa.sa_family == AF_INET6) {
118 memcpy(s5req + i, &c->address.in6.sin6_addr, 16);
120 memcpy(s5req + i, &c->address.in6.sin6_port, 2);
124 logger(mesh, MESHLINK_ERROR, "Address family %hx not supported for SOCKS 5 proxies!", c->address.sa.sa_family);
132 return send_meta(mesh, c, s5req, sizeof(s5req));
136 logger(mesh, MESHLINK_ERROR, "Proxy type not implemented yet");
140 logger(mesh, MESHLINK_ERROR, "Unknown proxy type");
145 bool send_id(meshlink_handle_t *mesh, connection_t *c) {
147 int minor = mesh->self->connection->protocol_minor;
149 if(mesh->proxytype && c->outgoing)
150 if(!send_proxyrequest(mesh, c)) {
154 return send_request(mesh, c, NULL, "%d %s %d.%d %s", ID, mesh->self->connection->name, mesh->self->connection->protocol_major, minor, mesh->appname);
157 static bool finalize_invitation(meshlink_handle_t *mesh, connection_t *c, const void *data, uint16_t len) {
160 if(strchr(data, '\n')) {
161 logger(mesh, MESHLINK_ERROR, "Received invalid key from invited node %s!\n", c->name);
165 // Create a new host config file
166 char filename[PATH_MAX];
167 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, c->name);
169 if(!access(filename, F_OK)) {
170 logger(mesh, MESHLINK_ERROR, "Host config file for %s already exists!\n", c->name);
174 FILE *f = fopen(filename, "w");
177 logger(mesh, MESHLINK_ERROR, "Error trying to create %s: %s\n", filename, strerror(errno));
181 fprintf(f, "ECDSAPublicKey = %s\n", (const char *)data);
184 fprintf(f, "SubMesh = %s\n", c->submesh->name);
189 logger(mesh, MESHLINK_INFO, "Key succesfully received from %s", c->name);
191 //TODO: callback to application to inform of an accepted invitation
193 sptps_send_record(&c->sptps, 2, data, 0);
195 load_all_nodes(mesh);
200 static bool receive_invitation_sptps(void *handle, uint8_t type, const void *data, uint16_t len) {
201 connection_t *c = handle;
202 meshlink_handle_t *mesh = c->mesh;
208 if(type == 1 && c->status.invitation_used) {
209 return finalize_invitation(mesh, c, data, len);
212 if(type != 0 || len != 18 || c->status.invitation_used) {
216 // Recover the filename from the cookie and the key
217 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
219 char hashbuf[18 + strlen(fingerprint)];
221 memcpy(hashbuf, data, 18);
222 memcpy(hashbuf + 18, fingerprint, sizeof(hashbuf) - 18);
223 sha512(hashbuf, sizeof(hashbuf), hash);
224 b64encode_urlsafe(hash, cookie, 18);
227 char filename[PATH_MAX], usedname[PATH_MAX];
228 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookie);
229 snprintf(usedname, sizeof(usedname), "%s" SLASH "invitations" SLASH "%s.used", mesh->confbase, cookie);
231 // Atomically rename the invitation file
232 if(rename(filename, usedname)) {
233 if(errno == ENOENT) {
234 logger(mesh, MESHLINK_ERROR, "Peer %s tried to use non-existing invitation %s\n", c->name, cookie);
236 logger(mesh, MESHLINK_ERROR, "Error trying to rename invitation %s\n", cookie);
242 // Open the renamed file
243 FILE *f = fopen(usedname, "r");
246 logger(mesh, MESHLINK_ERROR, "Error trying to open invitation %s\n", cookie);
251 // Check the timestamp
254 if(fstat(fileno(f), &st)) {
255 logger(mesh, MESHLINK_ERROR, "Could not stat invitation file %s\n", usedname);
261 if(time(NULL) > st.st_mtime + mesh->invitation_timeout) {
262 logger(mesh, MESHLINK_ERROR, "Peer %s tried to use an outdated invitation file %s\n", c->name, usedname);
268 // Read the new node's Name from the file
270 fgets(buf, sizeof(buf), f);
273 buf[strlen(buf) - 1] = 0;
276 len = strcspn(buf, " \t=");
277 char *name = buf + len;
278 name += strspn(name, " \t");
282 name += strspn(name, " \t");
287 if(!*buf || !*name || strcasecmp(buf, "Name") || !check_id(name)) {
288 logger(mesh, MESHLINK_ERROR, "Invalid invitation file %s\n", cookie);
294 c->name = xstrdup(name);
296 // Check if the file contains Sub-Mesh information
298 fgets(buf, sizeof(buf), f);
301 buf[strlen(buf) - 1] = 0;
304 if(!strncmp(buf, "SubMesh", 7)) {
305 len = strcspn(buf, " \t=");
306 char *submesh_name = buf + len;
307 submesh_name += strspn(submesh_name, " \t");
309 if(*submesh_name == '=') {
311 submesh_name += strspn(submesh_name, " \t");
314 if(!check_id(submesh_name)) {
315 logger(mesh, MESHLINK_ERROR, "Invalid invitation file %s\n", cookie);
321 c->submesh = lookup_or_create_submesh(mesh, submesh_name);
328 // Send the node the contents of the invitation file
332 while((result = fread(buf, 1, sizeof(buf), f))) {
333 sptps_send_record(&c->sptps, 0, buf, result);
336 sptps_send_record(&c->sptps, 1, buf, 0);
340 c->status.invitation_used = true;
342 logger(mesh, MESHLINK_INFO, "Invitation %s succesfully sent to %s", cookie, c->name);
346 bool id_h(meshlink_handle_t *mesh, connection_t *c, const char *request) {
347 char name[MAX_STRING_SIZE];
349 if(sscanf(request, "%*d " MAX_STRING " %d.%d", name, &c->protocol_major, &c->protocol_minor) < 2) {
350 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s", "ID", c->name);
354 /* Check if this is an invitation */
357 if(!mesh->invitation_key) {
358 logger(mesh, MESHLINK_ERROR, "Got invitation from %s but we don't have an invitation key", c->name);
362 c->ecdsa = ecdsa_set_base64_public_key(name + 1);
365 logger(mesh, MESHLINK_ERROR, "Got bad invitation from %s", c->name);
369 c->status.invitation = true;
370 char *mykey = ecdsa_get_base64_public_key(mesh->invitation_key);
376 if(!send_request(mesh, c, NULL, "%d %s", ACK, mykey)) {
382 c->protocol_minor = 2;
383 c->allow_request = 1;
385 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);
388 /* Check if identity is a valid name */
390 if(!check_id(name)) {
391 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s: %s", "ID", c->name, "invalid name");
395 /* If this is an outgoing connection, make sure we are connected to the right host */
398 if(strcmp(c->name, name)) {
399 logger(mesh, MESHLINK_ERROR, "Peer is %s instead of %s", name, c->name);
407 c->name = xstrdup(name);
410 /* Check if version matches */
412 if(c->protocol_major != mesh->self->connection->protocol_major) {
413 logger(mesh, MESHLINK_ERROR, "Peer %s uses incompatible version %d.%d",
414 c->name, c->protocol_major, c->protocol_minor);
418 if(!c->config_tree) {
419 init_configuration(&c->config_tree);
421 if(!read_host_config(mesh, c->config_tree, c->name)) {
422 logger(mesh, MESHLINK_ERROR, "Peer %s has unknown identity", c->name);
427 bool blacklisted = false;
428 get_config_bool(lookup_config(c->config_tree, "blacklisted"), &blacklisted);
431 logger(mesh, MESHLINK_EPEER, "Peer %s is blacklisted", c->name);
435 read_ecdsa_public_key(mesh, c);
437 if(!ecdsa_active(c->ecdsa)) {
438 logger(mesh, MESHLINK_ERROR, "No key known for peer %s", c->name);
440 node_t *n = lookup_node(mesh, c->name);
442 if(n && n->status.reachable && !n->status.waitingforkey) {
443 logger(mesh, MESHLINK_INFO, "Requesting key from peer %s", c->name);
444 send_req_key(mesh, n);
450 /* Forbid version rollback for nodes whose ECDSA key we know */
452 if(ecdsa_active(c->ecdsa) && c->protocol_minor < 2) {
453 logger(mesh, MESHLINK_ERROR, "Peer %s tries to roll back protocol version to %d.%d",
454 c->name, c->protocol_major, c->protocol_minor);
458 c->allow_request = ACK;
459 char label[sizeof(meshlink_tcp_label) + strlen(mesh->self->name) + strlen(c->name) + 2];
462 snprintf(label, sizeof(label), "%s %s %s", meshlink_tcp_label, mesh->self->name, c->name);
464 snprintf(label, sizeof(label), "%s %s %s", meshlink_tcp_label, c->name, mesh->self->name);
467 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);
470 bool send_ack(meshlink_handle_t *mesh, connection_t *c) {
472 /* Check some options */
474 if(mesh->self->options & OPTION_PMTU_DISCOVERY) {
475 c->options |= OPTION_PMTU_DISCOVERY;
478 return send_request(mesh, c, NULL, "%d %s %d %x", ACK, mesh->myport, mesh->devclass, (c->options & 0xffffff) | (PROT_MINOR << 24));
481 static void send_everything(meshlink_handle_t *mesh, connection_t *c) {
482 /* Send all known subnets and edges */
484 for splay_each(node_t, n, mesh->nodes) {
485 for splay_each(edge_t, e, n->edge_tree) {
486 send_add_edge(mesh, c, e, 0);
491 bool ack_h(meshlink_handle_t *mesh, connection_t *c, const char *request) {
492 char hisport[MAX_STRING_SIZE];
498 if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &devclass, &options) != 3) {
499 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s", "ACK", c->name);
503 if(devclass < 0 || devclass > _DEV_CLASS_MAX) {
504 logger(mesh, MESHLINK_ERROR, "Got bad %s from %s: %s", "ACK", c->name, "devclass invalid");
508 /* Check if we already have a node_t for him */
510 n = lookup_node(mesh, c->name);
514 n->name = xstrdup(c->name);
518 /* Oh dear, we already have a connection to this node. */
519 logger(mesh, MESHLINK_DEBUG, "Established a second connection with %s, closing old connection", n->connection->name);
521 if(n->connection->outgoing) {
523 logger(mesh, MESHLINK_WARNING, "Two outgoing connections to the same node!");
525 c->outgoing = n->connection->outgoing;
528 n->connection->outgoing = NULL;
531 terminate_connection(mesh, n->connection, false);
532 /* Run graph algorithm to keep things in sync */
537 n->devclass = devclass;
538 node_write_devclass(mesh, n);
540 n->last_successfull_connection = time(NULL);
545 if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
546 c->options &= ~OPTION_PMTU_DISCOVERY;
547 options &= ~OPTION_PMTU_DISCOVERY;
550 c->options |= options;
552 /* Activate this connection */
554 c->allow_request = ALL;
555 c->status.active = true;
557 logger(mesh, MESHLINK_INFO, "Connection with %s activated", c->name);
559 /* Send him everything we know */
561 send_everything(mesh, c);
563 /* Create an edge_t for this connection */
565 assert(devclass >= 0 && devclass <= _DEV_CLASS_MAX);
567 c->edge = new_edge();
568 c->edge->from = mesh->self;
570 sockaddr2str(&c->address, &hisaddress, NULL);
571 c->edge->address = str2sockaddr(hisaddress, hisport);
573 c->edge->weight = dev_class_traits[devclass].edge_weight;
574 c->edge->connection = c;
575 c->edge->options = c->options;
577 edge_add(mesh, c->edge);
579 /* Notify everyone of the new edge */
581 send_add_edge(mesh, mesh->everyone, c->edge, 0);
583 /* Run MST and SSSP algorithms */