71 lines
2.0 KiB
Go
71 lines
2.0 KiB
Go
// Package publicnet keeps outbound requests that a user or org aims on the
|
|
// public internet. Archie sends them from inside the instance's network, so a
|
|
// URL must not reach the instance's own host, its LAN or other infrastructure.
|
|
package publicnet
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
// Public reports whether ip is on the public internet.
|
|
func Public(ip net.IP) bool {
|
|
switch {
|
|
case ip.IsLoopback(), ip.IsPrivate(), ip.IsUnspecified(),
|
|
ip.IsLinkLocalUnicast(), ip.IsLinkLocalMulticast(),
|
|
ip.IsInterfaceLocalMulticast(), ip.IsMulticast():
|
|
return false
|
|
}
|
|
for _, block := range reserved {
|
|
if block.Contains(ip) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// Client reaches public addresses only and follows no redirect. The address
|
|
// is checked as the socket connects, after resolution, so a hostname that
|
|
// resolves to a private address is refused too.
|
|
func Client(dialTimeout, timeout time.Duration) *http.Client {
|
|
dialer := &net.Dialer{
|
|
Timeout: dialTimeout,
|
|
Control: func(_, address string, _ syscall.RawConn) error {
|
|
host, _, err := net.SplitHostPort(address)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if ip := net.ParseIP(host); ip == nil || !Public(ip) {
|
|
return fmt.Errorf("address %s is not public", host)
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
return &http.Client{
|
|
Timeout: timeout,
|
|
Transport: &http.Transport{DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
return dialer.DialContext(ctx, network, addr)
|
|
}},
|
|
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
|
}
|
|
}
|
|
|
|
// reserved are ranges that are not the public internet: carrier-grade NAT,
|
|
// benchmarking, IETF protocol assignments and the NAT64 prefix, which can map
|
|
// to private IPv4 hosts.
|
|
var reserved = []*net.IPNet{
|
|
mustCIDR("100.64.0.0/10"), mustCIDR("198.18.0.0/15"), mustCIDR("192.0.0.0/24"), mustCIDR("64:ff9b::/96"),
|
|
}
|
|
|
|
func mustCIDR(text string) *net.IPNet {
|
|
_, block, err := net.ParseCIDR(text)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return block
|
|
}
|