Skip to content

Allow validation of relay join requests by certificate - #7217

Merged
calmh merged 2 commits into
syncthing:mainfrom
nadiamoe:feature/relay-cert-validation
Dec 21, 2020
Merged

calmh merged 2 commits into
syncthing:mainfrom
nadiamoe:feature/relay-cert-validation

Conversation

@nadiamoe

@nadiamoe nadiamoe commented Dec 21, 2020 •

Copy link
Copy Markdown
Contributor

Purpose

As discussed in #7196, there might be some scenarios where a relay server might want to advertise itself from a different IP address from which it is actually listening on. This is currently not possible, as the relay pool server rejects join requests whose advertised remote address does not match the address used to make the join request.

This PR enables relay servers to send their TLS certificate in the join requests, provided the pool is contacted via https. The relay pool server will capture this certificate, generate the Device ID from it, and compare it to the advertised device ID. If they do not match, the request is rejected straight away.

This ensures that the agent sending the join request is indeed in possession of the key corresponding to the advertised device ID. This advertised device ID is later checked to be the same as the one behind the advertised IP address as a part of the original connection test by performHandshakeAndValidation on:

remoteID := syncthingprotocol.NewDeviceID(certs[0].Raw)
if remoteID != relayID {
return fmt.Errorf("relay id does not match. Expected %v got %v", relayID, remoteID)

While this check is only triggered if uri.Query().Get("id") != "", this is ensured by the mismatch check mentioned earlier.

Testing

Very basic tested was performed locally by building a relay server and a pool server with the changes, and checking that they were able to exchange and validate the certificates. Please comment if you think more testing (automated or not) is desired for this.

Screenshots

N/A

Documentation

If this is a user visible change (including API and protocol changes), add a link here to the corresponding pull request on https://github.com/syncthing/docs or describe the documentation changes necessary.

None done yet, please tell me if this is necessary.


Closes #7196

@calmh calmh left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks reasonable!

@calmh
calmh merged commit b5de499 into syncthing:main Dec 21, 2020
@calmh

calmh commented Dec 21, 2020

Copy link
Copy Markdown
Member

This is not trivially deployable in our actual infrastructure unfortunately because the relay pool server is behind a caddy reverse proxy that eats the HTTPS. We can forward the certificate in a header, like we do for discovery, but there it's behind nginx instead for historical reasons... I'll look into it. :/

calmh added a commit to calmh/syncthing that referenced this pull request Dec 21, 2020
* main: (27 commits)
  lib/fs: Correct wrapping order for meaningful log-caller (syncthing#7209)
  all: Handle errors opening db/creating file-set (ref syncthing#5907) (syncthing#7150)
  cmd/relaypoolsrv: Allow validation of relay join requests by certificate (fixes syncthing#7196) (syncthing#7217)
  lib: Close underlying conn in protocol (fixes syncthing#7165) (syncthing#7212)
  lib/db: Prevent IndexID creation race (syncthing#7211)
  gui: Reflect change in untrusted in sharing tab (syncthing#7201)
  lib/db: Remove index ids when dropping folder (syncthing#7200)
  lib/model: Fix flaky test and add some scanning debug (syncthing#7214)
  lib: Consistently set suture logging (syncthing#7202)
  lib/model: Unflake TestIgnoreDeleteUnignore (syncthing#7208)
  gui: Apply changes to untrusted (ref syncthing#6443) (syncthing#7206)
  lib/config: Remove deprecated pending entries from config (ref syncthing#6443) (syncthing#7204)
  all: Store pending devices and folders in database (fixes syncthing#7178) (syncthing#6443)
  gui, man, authors: Update docs, translations, and contributors
  gui: Sort folders and devices in advanced config modal (syncthing#7192)
  model: Actually print folder description in "Overriding" log message
  gui: version.tags is an array, which is truthy when empty
  build: Switch to gopsutil's v3 module (syncthing#7191)
  build: Update notify (fixes syncthing#7076) (syncthing#7189)
  lib/api: Returns tags in version as list (syncthing#7190)
  ...
@calmh calmh added this to the v1.13.0 milestone Dec 21, 2020
@nadiamoe

Copy link
Copy Markdown
Contributor Author

This is not trivially deployable in our actual infrastructure unfortunately because the relay pool server is behind a caddy reverse proxy that eats the HTTPS. We can forward the certificate in a header, like we do for discovery, but there it's behind nginx instead for historical reasons... I'll look into it. :/

Ouch, I've been there and it's a bit messy in that case.

If you're going to forward the cert through a header tho, some things might need to be changed. Im not sure if this would work, for example:

if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {

And this setting, which would need to be carried over to the reverse proxy:

ClientAuth: tls.RequestClientCert,

If it becomes a problem let me know so we can think about an alternative approach :)

@calmh

calmh commented Dec 21, 2020

Copy link
Copy Markdown
Member

We already have this in the discosrv:

func certificateBytes(req *http.Request) []byte {
if req.TLS != nil && len(req.TLS.PeerCertificates) > 0 {
return req.TLS.PeerCertificates[0].Raw
}
var bs []byte
if hdr := req.Header.Get("X-SSL-Cert"); hdr != "" {
if strings.Contains(hdr, "%") {
// Nginx using $ssl_client_escaped_cert
// The certificate is in PEM format with url encoding.
// We need to decode for the PEM decoder
hdr, err := url.QueryUnescape(hdr)
if err != nil {
// Decoding failed
return nil
}
bs = []byte(hdr)
} else {
// Nginx using $ssl_client_cert
// The certificate is in PEM format but with spaces for newlines. We
// need to reinstate the newlines for the PEM decoder. But we need to
// leave the spaces in the BEGIN and END lines - the first and last
// space - alone.
bs = []byte(hdr)
firstSpace := bytes.Index(bs, []byte(" "))
lastSpace := bytes.LastIndex(bs, []byte(" "))
for i := firstSpace + 1; i < lastSpace; i++ {
if bs[i] == ' ' {
bs[i] = '\n'
}
}
}
} else if hdr := req.Header.Get("X-Forwarded-Tls-Client-Cert"); hdr != "" {
// Traefik 2 passtlsclientcert
// The certificate is in PEM format with url encoding but without newlines
// and start/end statements. We need to decode, reinstate the newlines every 64
// character and add statements for the PEM decoder
hdr, err := url.QueryUnescape(hdr)
if err != nil {
// Decoding failed
return nil
}
for i := 64; i < len(hdr); i += 65 {
hdr = hdr[:i] + "\n" + hdr[i:]
}
hdr = "-----BEGIN CERTIFICATE-----\n" + hdr
hdr = hdr + "\n-----END CERTIFICATE-----\n"
bs = []byte(hdr)
}
if bs == nil {
return nil
}
block, _ := pem.Decode(bs)
if block == nil {
// Decoding failed
return nil
}
return block.Bytes
}

I think it's just a question of teaching Caddy to request & pass the client certificate and adding something similar to relaypoolsrv, so no big deal.

@AudriusButkevicius

Copy link
Copy Markdown
Member

Sooo I didn't submit my review :(

Comment thread cmd/strelaysrv/pool.go
},
},
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I am not mistaken, we might fiddle with the default client somewhere in init/main setting our custom dialer?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, there was an httpClient initialized in main.go:

https://github.com/syncthing/syncthing/blob/ad642cef8e6caa4e399f31268527e8127d43ac57/cmd/strelaysrv/main.go#L73-77

This is later modified with a few custom options. For some reason I misread that as the default client and changed it inadvertently. I have pushed a commit which reuses the pre-existing httpClient, however I'm not sure whether this is the correct approach, as the change made by poolHandler will propagate to other uses of the client.

return
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whats the rationale of this new check? I guess id might be empty at which point this would start failing?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is an attempt to do validation, but this is not what I have imagined. In the pool, there is code that tests the relay connectivity, the same code should check the certificate of the relay it got as it connected (to match the one it was given in post), checking for ids is fine I guess, but that doesn't prevent malicious advertisments.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, as @calmh pointed below, there was already another check in place for the presented cert to be equal to the id arg in the URI, so I leveraged that by checking it. Not the most clear approach in the world, but the id check was nested about 4 or 5 methods deep and I didn't want to break the signatures of all of them :(

@AudriusButkevicius

Copy link
Copy Markdown
Member

I suspect this actually might not do what it says on the tin, and permits to work around the check :( i don't see any certs check in the "test" phase of this.

@calmh

calmh commented Dec 21, 2020

Copy link
Copy Markdown
Member

I don't think this works around a check. We currently do two checks:

  1. That the announcer IP and the relay IP are the same
  2. That the relay device ID from certificate is the same as the announced ?id= parameter (this is deep in the relay client)

This adds an alternative to check number uno, namely that the announcer certificate matches the announced ?id= parameter. If it does, it then follows that the second check verifies that the announcer and the relay are identical (certificate wise).

@AudriusButkevicius

Copy link
Copy Markdown
Member

Ok, I guess I wasn't sure if the id in the uri is validated in any way, and browsing on mobile is painful.

@calmh

calmh commented Dec 30, 2020

Copy link
Copy Markdown
Member

So apparently Caddy can't do this in any version today, unless I'm misreading things. (caddyserver/caddy#3767 to resolve shortly, I expect)

@nadiamoe

Copy link
Copy Markdown
Contributor Author

So apparently Caddy can't do this in any version today, unless I'm misreading things. (caddyserver/caddy#3767 to resolve shortly, I expect)

Ouch, that sucks. Well, as a temporary workaround my relay is listening now on the external IP, so I guess I can leave it like that until caddy fixes that :)

hiqua pushed a commit to hiqua/syncthing that referenced this pull request Jan 11, 2021
@st-review st-review added the frozen-due-to-age Issues closed and untouched for a long time, together with being locked for discussion label Dec 22, 2021
@syncthing syncthing locked and limited conversation to collaborators Dec 22, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

frozen-due-to-age Issues closed and untouched for a long time, together with being locked for discussion

Projects

None yet

Development

Successfully merging this pull request may close these issues.

relaysrv: allow to listen for requests on an IP address different to the external address

4 participants