fe61503e6had a Remote magpie whose address didn't dial look for it on the old address's /24 and this computer's private /24s, and sent GET /v1/models, signed with the provider's gateway key (Authorization, x-api-key and the provider's own headers), to every address that took the connection at the port. On a café's or hotel's network, or with the other computer off, anything listening there got the key in clear and, by answering {"data":[]}, became the provider: the failed request and every later one went to it.18a9a2d88turned the look off. Now an address that takes the connection is first asked to prove it holds the key, with nothing keyed sent: - B POSTs {"nonce": 32 random bytes hex, "key_id": sha256(key) hex} to /v1/magpie/prove (provider.RemoteProvePath), no key, no provider headers, no proxy, no redirects (proves in remote_moved.go). - A (gateway's remote_prove.go) finds the enabled gateway key with that sha256 (access.ProveSecret: constant-time compares over every key, the legacy settings sharing key too, then Check, so an off, expired or orphaned issued key has none) and answers HMAC-SHA256(key, "magpie-prove-v1\n" nonce "\n" address), the address being the one the connection reached it at (http.LocalAddrContextKey); 404 when no key matches. A host that relays B's nonce to A elsewhere gets a proof for A's address, which B, checking against the address it dialled with hmac.Equal, refuses. - Only after that does isRemote ask /v1/models with the key, as before. - The route goes through lanGuard like OIDC's trade (proveAsked: POST, exact path, no gateway key): from another machine only while shared, past the allow list and rebinding check; corsGuard still judges its Origin, the handler refuses anything fromBrowser, and an unknown id from another machine counts against tooManyAuthFails. readOnlyRoutes lists it (it carries no key and answers none). seekAt is lanNeighbours again: the old /24 and this computer's own private /24s, both behind the proof. Not found, and so safe: a remote magpie from before this route (404), one not shared (403), one reached through a port forward, NAT or a Docker port (it sees another local address than the one dialled), and one behind a proxy that needs the provider's headers. Each fails as beforefe61503e6and the user types the new address. Tests (local httptest servers only): - TestRemoteMagpieKeyGoesToNoNeighbour, rewritten from 18a9a2d88's "no address looked at": four impostors that list 200 for anything (no proof route; a well-formed proof under another key; a garbled proof; one relaying B's ask to the real magpie and handing back its proof) are asked only the proof, never see the key or the provider's custom header, and aren't saved; then the real magpie, last in the list, is found and saved. - TestRemoteProof: another key, nonce, address or port is another proof; an IPv4-mapped IPv6 address is the same address. - TestRemoteProveAnswersOnlyTheKeysHolder (gateway): from another machine while shared, the key's holder answers the right HMAC and never the key; an unknown id and a key turned off get 404; Origin, a Mozilla User-Agent and Sec-Fetch-Mode are refused; not shared, 403. - TestRemoteMagpieMovedIsFound now uses a real gateway key on A. Run on mote at this tree (base18a9a2d88): - gofmt -l internal cmd: clean - go vet ./internal/provider ./internal/gateway ./internal/access (darwin, with and without -tags nogui), GOOS=windows go vet, GOOS=linux go vet -tags nogui: ok - go test -tags nogui -count=1 -timeout 45m ./internal/provider ./internal/gateway ./internal/access: provider ok (206s), access ok, gateway FAIL on TestUnroutedHeldReportSaved only ("(under way)"), the open #4300, a file this change doesn't touch; it passes alone with -count=3 on mote. Rebased onto2000ae439(its gateway.go change, the Antigravity format check in models(), sits beside this one's route line). Rerun on mote at the rebased head: gofmt clean; the same four vets ok; go test -tags nogui -count=1 -run 'RemoteMagpie|RemoteProof|RemoteProve|LANNeighbours| Dialable|ReadOnlyKeyEveryRoute|OIDCToken|Antigravity|KeyPage' over the three packages: ok. The full suite was not run again. Broken by hand, each red: - isRemote without the proves check: the impostor with no proof route is sent the key and the header, is saved, and the real magpie is never reached. - RemoteProof without the address: the relaying impostor passes, is sent the key and saved; TestRemoteProof red too. Not tried: a real look across two computers on a LAN (A on mote, B in WSL asfe61503e6did); a real Windows A; IPv6 link-local addresses (not looked at). Residual: a user-chosen weak gateway key (8+ characters) can be guessed offline by an impostor from its sha256; magpie's own keys are 24 random bytes. Push rejected once; rebased ontof4068ccc2(proc only, none of this change's files). Rerun on mote there: gofmt, the same vets and the -run tests above: ok.
80 lines
3.0 KiB
Go
80 lines
3.0 KiB
Go
package gateway
|
|
|
|
import (
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"io"
|
|
"log"
|
|
"net"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/yetone/magpie/internal/access"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// A magpie looking for its Remote magpie at a new address (provider's
|
|
// remote_moved.go) asks each address that takes the connection to prove,
|
|
// before anything keyed is sent there, that it holds the provider's
|
|
// gateway key: it POSTs a nonce of its own and the key's sha256
|
|
// (provider.RemoteKeyID) to provider.RemoteProvePath, with no key. This
|
|
// gateway answers the HMAC of the nonce and the address it was reached at
|
|
// (provider.RemoteProof) under its enabled gateway key of that id, or 404
|
|
// when it has none.
|
|
//
|
|
// The route carries no key, so lanGuard lets it through to here
|
|
// (proveAsked) the way it does a CI job's OIDC trade: from another
|
|
// machine only while magpie is shared, past the allow list. A web page is
|
|
// refused (fromBrowser): only a magpie asks this. An ask for a key this
|
|
// gateway doesn't have counts against the failed authentications another
|
|
// machine may make (tooManyAuthFails), as a wrong key does, and costs one
|
|
// sha256 per key. The answer tells a caller nothing it didn't know: only
|
|
// one that already has the key's sha256 gets a proof, and the proof is
|
|
// for a nonce and an address of the asker's choosing, under a key it
|
|
// doesn't have.
|
|
|
|
// proveAsked: r is a magpie's ask for a proof, which carries no key.
|
|
func proveAsked(r *http.Request) bool {
|
|
return r.Method == http.MethodPost && r.URL.Path == provider.RemoteProvePath && r.URL.RawPath == "" && !managedKey(r)
|
|
}
|
|
|
|
// isHex: s is hex of between least and most characters.
|
|
func isHex(s string, least, most int) bool {
|
|
if len(s) < least || len(s) > most {
|
|
return false
|
|
}
|
|
_, err := hex.DecodeString(s)
|
|
return err == nil
|
|
}
|
|
|
|
func (s *Server) prove(w http.ResponseWriter, r *http.Request) {
|
|
if fromBrowser(r) {
|
|
log.Printf("refused %s %s from %s: a browser asked for a proof", r.Method, r.URL.Path, r.RemoteAddr)
|
|
writeError(w, provider.Chat, http.StatusForbidden, "only a magpie asks this")
|
|
return
|
|
}
|
|
var in struct {
|
|
Nonce string `json:"nonce"`
|
|
KeyID string `json:"key_id"`
|
|
}
|
|
b, _ := io.ReadAll(io.LimitReader(r.Body, 4<<10))
|
|
if json.Unmarshal(b, &in) != nil || !isHex(in.Nonce, 32, 128) || !isHex(in.KeyID, 64, 64) {
|
|
writeError(w, provider.Chat, http.StatusBadRequest, `send {"nonce": hex, "key_id": hex sha256 of the key}`)
|
|
return
|
|
}
|
|
at, _ := r.Context().Value(http.LocalAddrContextKey).(net.Addr)
|
|
key, ok := access.ProveSecret(in.KeyID)
|
|
if !ok || at == nil {
|
|
if !local(r) {
|
|
if over, retry := tooManyAuthFails(); over {
|
|
w.Header().Set("Retry-After", strconv.Itoa(int(retry.Seconds())+1))
|
|
writeError(w, provider.Chat, http.StatusTooManyRequests, "too many failed authentications; slow down")
|
|
return
|
|
}
|
|
}
|
|
writeError(w, provider.Chat, http.StatusNotFound, "no enabled gateway key here has that id")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]string{"proof": hex.EncodeToString(provider.RemoteProof(key, in.Nonce, at.String()))})
|
|
}
|