2 protocol_auth.c -- handle the meta-protocol, authentication
3 Copyright (C) 2014 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"
40 static bool send_proxyrequest(meshlink_handle_t *mesh, connection_t *c) {
41 switch(mesh->proxytype) {
46 sockaddr2str(&c->address, &host, &port);
47 send_request(mesh, c, "CONNECT %s:%s HTTP/1.1\r\n\r", host, port);
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!");
57 char s4req[9 + (mesh->proxyuser ? strlen(mesh->proxyuser) : 0)];
60 memcpy(s4req + 2, &c->address.in.sin_port, 2);
61 memcpy(s4req + 4, &c->address.in.sin_addr, 4);
63 memcpy(s4req + 8, mesh->proxyuser, strlen(mesh->proxyuser));
64 s4req[sizeof s4req - 1] = 0;
66 return send_meta(mesh, c, s4req, sizeof s4req);
69 int len = 3 + 6 + (c->address.sa.sa_family == AF_INET ? 4 : 16);
72 len += 3 + strlen(mesh->proxyuser) + strlen(mesh->proxypass);
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);
93 if(c->address.sa.sa_family == AF_INET) {
95 memcpy(s5req + i, &c->address.in.sin_addr, 4);
97 memcpy(s5req + i, &c->address.in.sin_port, 2);
100 } else if(c->address.sa.sa_family == AF_INET6) {
102 memcpy(s5req + i, &c->address.in6.sin6_addr, 16);
104 memcpy(s5req + i, &c->address.in6.sin6_port, 2);
108 logger(DEBUG_ALWAYS, LOG_ERR, "Address family %hx not supported for SOCKS 5 proxies!", c->address.sa.sa_family);
113 return send_meta(mesh, c, s5req, sizeof s5req);
116 logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type not implemented yet");
121 logger(DEBUG_ALWAYS, LOG_ERR, "Unknown proxy type");
126 bool send_id(meshlink_handle_t *mesh, connection_t *c) {
127 gettimeofday(&c->start, NULL);
129 int minor = mesh->self->connection->protocol_minor;
131 if(mesh->proxytype && c->outgoing)
132 if(!send_proxyrequest(mesh, c))
135 return send_request(mesh, c, "%d %s %d.%d", ID, mesh->self->connection->name, mesh->self->connection->protocol_major, minor);
138 static bool finalize_invitation(meshlink_handle_t *mesh, connection_t *c, const void *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);
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);
152 FILE *f = fopen(filename, "w");
154 logger(DEBUG_ALWAYS, LOG_ERR, "Error trying to create %s: %s\n", filename, strerror(errno));
158 fprintf(f, "ECDSAPublicKey = %s\n", (const char *)data);
161 logger(DEBUG_CONNECTIONS, LOG_INFO, "Key succesfully received from %s (%s)", c->name, c->hostname);
163 //TODO: callback to application to inform of an accepted invitation
165 sptps_send_record(&c->sptps, 2, data, 0);
167 load_all_nodes(mesh);
172 static bool receive_invitation_sptps(void *handle, uint8_t type, const void *data, uint16_t len) {
173 connection_t *c = handle;
174 meshlink_handle_t *mesh = c->mesh;
179 if(type == 1 && c->status.invitation_used)
180 return finalize_invitation(mesh, c, data, len);
182 if(type != 0 || len != 18 || c->status.invitation_used)
185 // Recover the filename from the cookie and the key
186 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
188 char hashbuf[18 + strlen(fingerprint)];
190 memcpy(hashbuf, data, 18);
191 memcpy(hashbuf + 18, fingerprint, sizeof hashbuf - 18);
192 sha512(hashbuf, sizeof hashbuf, hash);
193 b64encode_urlsafe(hash, cookie, 18);
196 char filename[PATH_MAX], usedname[PATH_MAX];
197 snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookie);
198 snprintf(usedname, sizeof usedname, "%s" SLASH "invitations" SLASH "%s.used", mesh->confbase, cookie);
200 // Atomically rename the invitation file
201 if(rename(filename, usedname)) {
203 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s tried to use non-existing invitation %s\n", c->hostname, cookie);
205 logger(DEBUG_ALWAYS, LOG_ERR, "Error trying to rename invitation %s\n", cookie);
209 // Open the renamed file
210 FILE *f = fopen(usedname, "r");
212 logger(DEBUG_ALWAYS, LOG_ERR, "Error trying to open invitation %s\n", cookie);
216 // Read the new node's Name from the file
218 fgets(buf, sizeof buf, f);
220 buf[strlen(buf) - 1] = 0;
222 len = strcspn(buf, " \t=");
223 char *name = buf + len;
224 name += strspn(name, " \t");
227 name += strspn(name, " \t");
231 if(!*buf || !*name || strcasecmp(buf, "Name") || !check_id(name)) {
232 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid invitation file %s\n", cookie);
238 c->name = xstrdup(name);
240 // Send the node the contents of the invitation file
243 while((result = fread(buf, 1, sizeof buf, f)))
244 sptps_send_record(&c->sptps, 0, buf, result);
245 sptps_send_record(&c->sptps, 1, buf, 0);
249 c->status.invitation_used = true;
251 logger(DEBUG_CONNECTIONS, LOG_INFO, "Invitation %s succesfully sent to %s (%s)", cookie, c->name, c->hostname);
255 bool id_h(meshlink_handle_t *mesh, connection_t *c, const char *request) {
256 char name[MAX_STRING_SIZE];
258 if(sscanf(request, "%*d " MAX_STRING " %d.%d", name, &c->protocol_major, &c->protocol_minor) < 2) {
259 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
264 /* Check if this is an invitation */
267 if(!mesh->invitation_key) {
268 logger(DEBUG_ALWAYS, LOG_ERR, "Got invitation from %s but we don't have an invitation key", c->hostname);
272 c->ecdsa = ecdsa_set_base64_public_key(name + 1);
274 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad invitation from %s", c->hostname);
278 c->status.invitation = true;
279 char *mykey = ecdsa_get_base64_public_key(mesh->invitation_key);
282 if(!send_request(mesh, c, "%d %s", ACK, mykey))
286 c->protocol_minor = 2;
287 c->allow_request = 1;
289 return sptps_start(&c->sptps, c, false, false, mesh->invitation_key, c->ecdsa, "meshlink invitation", 15, send_meta_sptps, receive_invitation_sptps);
292 /* Check if identity is a valid name */
294 if(!check_id(name)) {
295 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
296 c->hostname, "invalid name");
300 /* If this is an outgoing connection, make sure we are connected to the right host */
303 if(strcmp(c->name, name)) {
304 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
311 c->name = xstrdup(name);
314 /* Check if version matches */
316 if(c->protocol_major != mesh->self->connection->protocol_major) {
317 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s (%s) uses incompatible version %d.%d",
318 c->name, c->hostname, c->protocol_major, c->protocol_minor);
322 if(!c->config_tree) {
323 init_configuration(&c->config_tree);
325 if(!read_host_config(mesh, c->config_tree, c->name)) {
326 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname, c->name);
330 read_ecdsa_public_key(mesh, c);
332 if(c->protocol_minor && !ecdsa_active(c->ecdsa))
333 c->protocol_minor = 1;
336 /* Forbid version rollback for nodes whose ECDSA key we know */
338 if(ecdsa_active(c->ecdsa) && c->protocol_minor < 2) {
339 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s (%s) tries to roll back protocol version to %d.%d",
340 c->name, c->hostname, c->protocol_major, c->protocol_minor);
344 c->allow_request = ACK;
345 char label[25 + strlen(mesh->self->name) + strlen(c->name)];
348 snprintf(label, sizeof label, "meshlink TCP key expansion %s %s", mesh->self->name, c->name);
350 snprintf(label, sizeof label, "meshlink TCP key expansion %s %s", c->name, mesh->self->name);
352 return sptps_start(&c->sptps, c, c->outgoing, false, mesh->self->connection->ecdsa, c->ecdsa, label, sizeof label, send_meta_sptps, receive_meta_sptps);
355 bool send_ack(meshlink_handle_t *mesh, connection_t *c) {
356 /* ACK message contains rest of the information the other end needs
357 to create node_t and edge_t structures. */
361 /* Estimate weight */
363 gettimeofday(&now, NULL);
364 c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
366 /* Check some options */
368 if(mesh->self->options & OPTION_PMTU_DISCOVERY)
369 c->options |= OPTION_PMTU_DISCOVERY;
371 return send_request(mesh, c, "%d %s %d %x", ACK, mesh->myport, c->estimated_weight, (c->options & 0xffffff) | (PROT_MINOR << 24));
374 static void send_everything(meshlink_handle_t *mesh, connection_t *c) {
375 /* Send all known subnets and edges */
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);
383 bool ack_h(meshlink_handle_t *mesh, connection_t *c, const char *request) {
384 char hisport[MAX_STRING_SIZE];
390 if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
391 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
396 /* Check if we already have a node_t for him */
398 n = lookup_node(mesh, c->name);
402 n->name = xstrdup(c->name);
406 /* Oh dear, we already have a connection to this node. */
407 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Established a second connection with %s (%s), closing old connection", n->connection->name, n->connection->hostname);
409 if(n->connection->outgoing) {
411 logger(DEBUG_ALWAYS, LOG_WARNING, "Two outgoing connections to the same node!");
413 c->outgoing = n->connection->outgoing;
415 n->connection->outgoing = NULL;
418 terminate_connection(mesh, n->connection, false);
419 /* Run graph algorithm to keep things in sync */
426 if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
427 c->options &= ~OPTION_PMTU_DISCOVERY;
428 options &= ~OPTION_PMTU_DISCOVERY;
430 c->options |= options;
432 /* Activate this connection */
434 c->allow_request = ALL;
435 c->status.active = true;
437 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection with %s (%s) activated", c->name,
440 /* Send him everything we know */
442 send_everything(mesh, c);
444 /* Create an edge_t for this connection */
446 c->edge = new_edge();
447 c->edge->from = mesh->self;
449 sockaddr2str(&c->address, &hisaddress, NULL);
450 c->edge->address = str2sockaddr(hisaddress, hisport);
452 c->edge->weight = (weight + c->estimated_weight) / 2;
453 c->edge->connection = c;
454 c->edge->options = c->options;
456 edge_add(mesh, c->edge);
458 /* Notify everyone of the new edge */
460 send_add_edge(mesh, mesh->everyone, c->edge);
462 /* Run MST and SSSP algorithms */