diff --git a/README.md b/README.md index 50aed11..db8625f 100644 --- a/README.md +++ b/README.md @@ -179,8 +179,13 @@ or the [Telegram group](https://t.me/+6UwIu9F4gZQxNjM0). it with the server's addresses. It also lists the ports a firewall in front of the server (your provider's, or a router) has to let in for the components you've turned on: web and federation, Coturn, LiveKit for - Element Call and Matrix RTC, Jitsi and Postmoogle (`interzone check` - prints them too). Once you've deployed, it shows what + Element Call and Matrix RTC, Jitsi and Postmoogle, with the port numbers + your settings and extra vars give (`interzone check` prints them too). + It then connects to every TCP port from where interzone runs and says + which get through and which a firewall seems to drop (UDP can't be + tested this way), and once the server is installed it checks federation + the way a federation tester does: `/.well-known/matrix/server`, then the + server's signing keys over a trusted certificate. Once you've deployed, it shows what changes in `vars.yml` since the last successful deploy (`x` switches to the whole file). - **Checks after deploying.** The playbook's self-check runs at the end and diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 2d6d7f4..90bc445 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -185,7 +185,7 @@ func Check(args []string) error { fmt.Println() fmt.Println(head.Render("==> Ports to open in a firewall in front of the server")) for _, p := range c.Ports() { - fmt.Printf(" %-40s %s\n", p.Port, muted.Render(p.For)) + fmt.Printf(" %-40s %s\n", p.String(), muted.Render(p.For)) } if max(worst, deploy.Worst(fs2)) == deploy.Fail { return ErrFailed diff --git a/internal/config/hosts.go b/internal/config/hosts.go index a0f00e1..37394e5 100644 --- a/internal/config/hosts.go +++ b/internal/config/hosts.go @@ -1,6 +1,7 @@ package config import ( + "fmt" "maps" "os" "path/filepath" @@ -131,7 +132,12 @@ func (r hostResolver) value(name string, depth int) string { } var s string if v, ok := r.vars[name]; ok { - s, _ = v.(string) + switch v := v.(type) { + case string: + s = v + case int: + s = fmt.Sprint(v) // a port number + } } else if d, ok := r.defaults[name]; ok { s = strings.Trim(strings.TrimSpace(d), `"'`) } diff --git a/internal/config/ports.go b/internal/config/ports.go index a266752..5176c3c 100644 --- a/internal/config/ports.go +++ b/internal/config/ports.go @@ -1,36 +1,82 @@ package config -import "interzone/internal/catalog" +import ( + "fmt" + "strings" -// Port is a port (or range) the server must accept from the internet, and -// what for. -type Port struct{ Port, For string } + "interzone/internal/catalog" +) + +// Port is what a firewall in front of the server must let in for one +// component: TCP and UDP ports, each a number or a range "a-b". +type Port struct { + For string + TCP, UDP []string +} + +// String is "80, 443/tcp; 443/udp". +func (p Port) String() string { + var out []string + if len(p.TCP) > 0 { + out = append(out, strings.Join(p.TCP, ", ")+"/tcp") + } + if len(p.UDP) > 0 { + out = append(out, strings.Join(p.UDP, ", ")+"/udp") + } + return strings.Join(out, "; ") +} // Ports lists what a firewall in front of the server must let in, from the // playbook's docs (prerequisites.md and the pages of the components that -// need more). Docker opens them on the server itself. -// shortcut: the playbook's default port numbers; a port moved in extra vars isn't followed. +// need more), with the port numbers the playbook's variables give, as +// vars.yml, extra vars or the playbook's defaults set them. Docker opens +// them on the server itself. func (c *Config) Ports() []Port { on := func(id string) bool { comp, ok := catalog.ByID(id) return ok && c.Enabled(comp) } - out := []Port{{"80/tcp, 443/tcp+udp", "Web (HTTPS, certificates)"}} + r := c.hostResolver() + port := func(name, fallback string) string { return r.port(name, fallback) } + span := func(from, to, a, b string) string { return port(from, a) + "-" + port(to, b) } + + out := []Port{{For: "Web (HTTPS, certificates)", TCP: []string{"80", "443"}, UDP: []string{"443"}}} // UVS and Matrix RTC need the federation port even with federation off. - if fp := c.FederationPort(); fp != "443" && (c.Federation || on("uvs") || on("matrix-rtc") || on("element-call")) { - out = append(out, Port{fp + "/tcp+udp", "Federation"}) + if fp := port("matrix_federation_public_port", c.FederationPort()); fp != "443" && (c.Federation || on("uvs") || on("matrix-rtc") || on("element-call")) { + out = append(out, Port{For: "Federation", TCP: []string{fp}, UDP: []string{fp}}) } if on("coturn") { - out = append(out, Port{"3478, 5349/tcp+udp; 49152-49172/udp", "Coturn (TURN for calls)"}) + plain, tls := port("coturn_container_stun_plain_host_bind_port_tcp", "3478"), port("coturn_container_stun_tls_host_bind_port_tcp", "5349") + out = append(out, Port{For: "Coturn (TURN for calls)", TCP: []string{plain, tls}, + UDP: []string{plain, tls, span("coturn_turn_udp_min_port", "coturn_turn_udp_max_port", "49152", "49172")}}) } if on("matrix-rtc") || on("element-call") { - out = append(out, Port{"7881/tcp, 5350/tcp; 7882, 3479, 30000-30020/udp", "LiveKit (Element Call, Element X calls)"}) + out = append(out, Port{For: "LiveKit (Element Call, Element X calls)", + TCP: []string{port("livekit_server_config_rtc_tcp_port", "7881"), port("livekit_server_config_turn_tls_port", "5350")}, + UDP: []string{port("livekit_server_config_rtc_udp_port", "7882"), port("livekit_server_config_turn_udp_port", "3479"), + span("livekit_server_config_turn_relay_range_start", "livekit_server_config_turn_relay_range_end", "30000", "30020")}}) } if on("jitsi") { - out = append(out, Port{"4443/tcp, 10000/udp", "Jitsi media"}) + // 4443/tcp is the role's docs', with no variable behind it. + out = append(out, Port{For: "Jitsi media", TCP: []string{"4443"}, UDP: []string{port("jitsi_jvb_rtp_udp_port", "10000")}}) } if on("postmoogle") { - out = append(out, Port{"25/tcp, 587/tcp", "Postmoogle (receiving email)"}) + out = append(out, Port{For: "Postmoogle (receiving email)", + TCP: []string{port("matrix_bridge_postmoogle_smtp_host_bind_port", "25"), port("matrix_bridge_postmoogle_submission_host_bind_port", "587")}}) } return out } + +// port is the value of name when it's a port number, or else fallback +// (unset, or a Jinja expression). +func (r hostResolver) port(name, fallback string) string { + v := r.value(name, 0) + if i := strings.LastIndex(v, ":"); i >= 0 { // "0.0.0.0:3478" + v = v[i+1:] + } + var n int + if _, err := fmt.Sscanf(v, "%d", &n); err != nil || fmt.Sprint(n) != v || n < 1 || n > 65535 { + return fallback + } + return v +} diff --git a/internal/config/ports_test.go b/internal/config/ports_test.go index 3ca2b5d..6b2b614 100644 --- a/internal/config/ports_test.go +++ b/internal/config/ports_test.go @@ -9,23 +9,29 @@ func TestPorts(t *testing.T) { list := func(c *Config) string { var s []string for _, p := range c.Ports() { - s = append(s, p.Port) + s = append(s, p.String()) } return strings.Join(s, " | ") } c := Default() + c.PlaybookDir = t.TempDir() c.Homeserver, c.Federation = "synapse", false c.Components = map[string]bool{} - if got := list(c); got != "80/tcp, 443/tcp+udp" { + if got := list(c); got != "80, 443/tcp; 443/udp" { t.Errorf("bare server: %s", got) } c.Components = map[string]bool{"uvs": true, "coturn": true, "postmoogle": true} got := list(c) - for _, want := range []string{"8448/tcp+udp", "3478, 5349/tcp+udp", "49152-49172/udp", "25/tcp, 587/tcp"} { + for _, want := range []string{"8448/tcp; 8448/udp", "3478, 5349/tcp; 3478, 5349, 49152-49172/udp", "25, 587/tcp"} { if !strings.Contains(got, want) { t.Errorf("missing %s in %s", want, got) } } + // ports moved in extra vars are followed + c.ExtraYAML = "coturn_turn_udp_max_port: 49200\nmatrix_bridge_postmoogle_smtp_host_bind_port: '0.0.0.0:2525'\n" + if got := list(c); !strings.Contains(got, "49152-49200/udp") || !strings.Contains(got, "2525, 587/tcp") { + t.Errorf("moved ports not followed: %s", got) + } c.Homeserver, c.Federation = "conduit", true // federation on 443 if strings.Contains(list(c), "8448") { t.Errorf("conduit opens 8448: %s", list(c)) diff --git a/internal/deploy/reach.go b/internal/deploy/reach.go new file mode 100644 index 0000000..c934109 --- /dev/null +++ b/internal/deploy/reach.go @@ -0,0 +1,135 @@ +package deploy + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "os" + "strings" + "sync" + "syscall" + "time" + + "interzone/internal/config" +) + +// reachChecks looks at the server from here, as the internet would: whether +// the TCP ports the components need get through (UDP can't be told from +// silence), and whether other servers can federate with it. +func reachChecks(ctx context.Context, c *config.Config) []Finding { + if c.Domain == "" { + return nil + } + return append(portChecks(ctx, c), federationChecks(ctx, c)...) +} + +// portChecks connects to every TCP port Ports lists, at the homeserver's +// hostname. Refused means the port got through to a server with nothing +// listening on it; no answer at all usually means a firewall drops it. +func portChecks(ctx context.Context, c *config.Config) []Finding { + host := c.HostName() + if _, err := net.DefaultResolver.LookupHost(ctx, host); err != nil { + return nil // the DNS checks already say so + } + installed := c.Installed() + var out []Finding + for _, p := range c.Ports() { + for _, port := range p.TCP { + out = append(out, Finding{Group: "Ports", Name: port + "/tcp", Service: p.For}) + } + } + var wg sync.WaitGroup + for i := range out { + wg.Add(1) + go func(f *Finding) { + defer wg.Done() + f.Level, f.Detail = dialPort(ctx, host, strings.TrimSuffix(f.Name, "/tcp"), installed) + }(&out[i]) + } + wg.Wait() + return out +} + +// dialPort says whether a TCP connection to host:port gets through. +func dialPort(ctx context.Context, host, port string, installed bool) (Level, string) { + d := net.Dialer{Timeout: 6 * time.Second} + conn, err := d.DialContext(ctx, "tcp", net.JoinHostPort(host, port)) + switch { + case err == nil: + conn.Close() + return Pass, "open" + case errors.Is(err, syscall.ECONNREFUSED) && installed: + return Warn, "gets through, but nothing answers: is the service running?" + case errors.Is(err, syscall.ECONNREFUSED): + return Pass, "gets through; nothing listens until you deploy" + case os.IsTimeout(err) || errors.Is(err, context.DeadlineExceeded): + return Warn, "no answer: a firewall in front of the server probably drops it" + } + return Warn, netReason(err) +} + +// federationChecks does what a federation tester does: finds where other +// servers would reach this one (/.well-known/matrix/server, else port +// 8448 of the domain) and asks it for the server's signing keys. +func federationChecks(ctx context.Context, c *config.Config) []Finding { + if !c.Federation || !c.Installed() { + return nil + } + var out []Finding + add := func(name string, l Level, format string, a ...any) { + out = append(out, Finding{Group: "Federation", Name: name, Level: l, Detail: fmt.Sprintf(format, a...)}) + } + client := &http.Client{Timeout: 10 * time.Second, Transport: &http.Transport{Proxy: http.ProxyFromEnvironment}} + get := func(url string, v any) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return err + } + resp, err := client.Do(req) + if err != nil { + return errors.New(netReason(err)) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return errors.New("answered " + resp.Status) + } + if json.NewDecoder(resp.Body).Decode(v) != nil { + return errors.New("didn't answer JSON") + } + return nil + } + + // shortcut: SRV records aren't looked up; the playbook delegates with .well-known. + at := c.Domain + ":8448" + var wk struct { + Server string `json:"m.server"` + } + if err := get("https://"+c.Domain+"/.well-known/matrix/server", &wk); err != nil || wk.Server == "" { + if err == nil { + err = errors.New("has no m.server") + } + add("Delegation", Warn, "https://%s/.well-known/matrix/server %s; other servers will try %s", c.Domain, err, at) + } else { + at = wk.Server + if _, _, err := net.SplitHostPort(at); err != nil { + at += ":8448" + } + add("Delegation", Pass, "other servers are sent to %s", at) + } + + var keys struct { + Name string `json:"server_name"` + } + switch err := get("https://"+at+"/_matrix/key/v2/server", &keys); { + case err != nil: + add("Federation API", Fail, "https://%s %s; other servers can't reach this one", at, err) + case keys.Name != c.Domain: + add("Federation API", Fail, "%s answers as %q, not %s", at, keys.Name, c.Domain) + default: + add("Federation API", Pass, "%s answers as %s, with a trusted certificate", at, c.Domain) + } + return out +} diff --git a/internal/deploy/reach_test.go b/internal/deploy/reach_test.go new file mode 100644 index 0000000..75be415 --- /dev/null +++ b/internal/deploy/reach_test.go @@ -0,0 +1,27 @@ +package deploy + +import ( + "context" + "net" + "testing" +) + +func TestDialPort(t *testing.T) { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + _, open, _ := net.SplitHostPort(l.Addr().String()) + l.Close() // now refused + if lv, d := dialPort(context.Background(), "127.0.0.1", open, true); lv != Warn { + t.Errorf("closed port, installed: %v %s", lv, d) + } + if lv, d := dialPort(context.Background(), "127.0.0.1", open, false); lv != Pass { + t.Errorf("closed port, not installed: %v %s", lv, d) + } + l, _ = net.Listen("tcp", "127.0.0.1:"+open) + defer l.Close() + if lv, d := dialPort(context.Background(), "127.0.0.1", open, true); lv != Pass || d != "open" { + t.Errorf("open port: %v %s", lv, d) + } +} diff --git a/internal/deploy/server.go b/internal/deploy/server.go index 88410f8..6a2cbdd 100644 --- a/internal/deploy/server.go +++ b/internal/deploy/server.go @@ -25,9 +25,9 @@ const ( // Finding is the outcome of one pre-deploy check. type Finding struct { - Group string // "Server" or "DNS" + Group string // "Server", "DNS", "Ports" or "Federation" Name string - Service string // DNS: what the hostname serves + Service string // DNS: what the hostname serves; Ports: what the port is for Level Level Detail string } @@ -98,7 +98,7 @@ func probe(ctx context.Context, c *config.Config) (map[string]string, error) { // ServerChecks logs into the target and checks it can run the playbook, // then checks every DNS record points at it. func ServerChecks(c *config.Config) []Finding { - ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second) defer cancel() var out []Finding @@ -113,7 +113,7 @@ func ServerChecks(c *config.Config) []Finding { } if err != nil { add("Connect", Fail, "can't run commands on %s: %s", where, err) - return append(out, dnsChecks(ctx, c, nil)...) + return append(append(out, dnsChecks(ctx, c, nil)...), reachChecks(ctx, c)...) } add("Connect", Pass, "%s", where) @@ -202,7 +202,8 @@ func ServerChecks(c *config.Config) []Finding { } out = append(out, mirrorChecks(ctx, c, facts)...) - return append(out, dnsChecks(ctx, c, strings.Fields(facts["ips"]))...) + out = append(out, dnsChecks(ctx, c, strings.Fields(facts["ips"]))...) + return append(out, reachChecks(ctx, c)...) } // mirrorChecks makes sure the blackout mirrors carry this server's distro diff --git a/internal/ui/screens_deploy.go b/internal/ui/screens_deploy.go index ac508f0..4f1416d 100644 --- a/internal/ui/screens_deploy.go +++ b/internal/ui/screens_deploy.go @@ -320,17 +320,21 @@ func (s *reviewScreen) checksView(w int) []string { dnsW = max(dnsW, min(34, len(f.Name)+2)) } } - for _, g := range []string{"Server", "DNS"} { + collapsed := map[string]string{"Server": "%d server checks passed", "Ports": "%d ports get through", "Federation": "%d federation checks passed"} + for _, g := range []string{"Server", "DNS", "Ports", "Federation"} { passed := 0 var rows []string for _, f := range s.checks { if f.Group != g { continue } - if f.Level == deploy.Pass && !s.verbose && g == "Server" { + if f.Level == deploy.Pass && !s.verbose && collapsed[g] != "" { passed++ continue } + if f.Service != "" && g == "Ports" { + f.Detail = f.Service + ": " + f.Detail + } icon, style := sGood.Render("✓"), sMuted switch f.Level { case deploy.Warn: @@ -364,7 +368,7 @@ func (s *reviewScreen) checksView(w int) []string { rows = append(rows, " "+icon+" "+name+detail) } if passed > 0 { - rows = append([]string{" " + sGood.Render("✓") + " " + sMuted.Render(fmt.Sprintf("%d server checks passed", passed)) + sFaint.Render(" (v for details)")}, rows...) + rows = append([]string{" " + sGood.Render("✓") + " " + sMuted.Render(fmt.Sprintf(collapsed[g], passed)) + sFaint.Render(" (v for details)")}, rows...) } lines = append(lines, rows...) } @@ -376,16 +380,16 @@ func (s *reviewScreen) checksView(w int) []string { func portsView(c *config.Config, w int) []string { lines := []string{rule("Ports a firewall in front must let in", min(w, 72))} ports := c.Ports() - pw := 0 + fw, pw := 0, 0 for _, p := range ports { - pw = max(pw, len(p.Port)+2) + fw, pw = max(fw, len(p.For)+2), max(pw, len(p.String())) } for _, p := range ports { - if w < 60 || pw > w/2 { // the ports go under the name - lines = append(lines, " "+sTitle.Render(p.For), " "+sMuted.Render(p.Port)) + if w < 60 || 2+fw+pw > w { // the ports go under the name + lines = append(lines, " "+sTitle.Render(p.For), " "+sMuted.Render(p.String())) continue } - lines = append(lines, " "+lipgloss.NewStyle().Width(pw).Render(sMuted.Render(p.Port))+sTitle.Render(truncate(p.For, max(8, w-pw-2)))) + lines = append(lines, " "+lipgloss.NewStyle().Width(fw).Render(sTitle.Render(p.For))+sMuted.Render(p.String())) } return lines } diff --git a/internal/ui/testdata/layout/review-120x36.txt b/internal/ui/testdata/layout/review-120x36.txt index 38401d0..67e6337 100644 --- a/internal/ui/testdata/layout/review-120x36.txt +++ b/internal/ui/testdata/layout/review-120x36.txt @@ -23,9 +23,9 @@ │ ││ ○ Cinny cinny.example.org │ │ ││ │ │ ││ Ports a firewall in front must let in ────────────────────────────────── │ -│ ││ 80/tcp, 443/tcp+udp Web (HTTPS, certificates) │ -│ ││ 8448/tcp+udp Federation │ -│ ││ 3478, 5349/tcp+udp; 49152-49172/udp Coturn (TURN for calls) │ +│ ││ Web (HTTPS, certificates) 80, 443/tcp; 443/udp │ +│ ││ Federation 8448/tcp; 8448/udp │ +│ ││ Coturn (TURN for calls) 3478, 5349/tcp; 3478, 5349, 49152-49172/udp │ │ ││ │ │ ││ │ │ ││ │ diff --git a/internal/ui/testdata/layout/review-46x40.txt b/internal/ui/testdata/layout/review-46x40.txt index 3d2c0ad..4c4affe 100644 --- a/internal/ui/testdata/layout/review-46x40.txt +++ b/internal/ui/testdata/layout/review-46x40.txt @@ -26,11 +26,11 @@ Ports a firewall in front must let in ──── Web (HTTPS, certificates) - 80/tcp, 443/tcp+udp + 80, 443/tcp; 443/udp Federation - 8448/tcp+udp + 8448/tcp; 8448/udp Coturn (TURN for calls) - 3478, 5349/tcp+udp; 49152-49172/udp + 3478, 5349/tcp; 3478, 5349, 49152-49172/