File
Blob: tun/server/waf_rpc.go
| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/hex" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "net/http" |
| 11 | "time" |
| 12 | |
| 13 | "go.miragespace.co/specter/spec/protocol" |
| 14 | "go.miragespace.co/specter/spec/tun" |
| 15 | "go.miragespace.co/specter/waf" |
| 16 | |
| 17 | "github.com/go-chi/chi/v5/middleware" |
| 18 | "github.com/twitchtv/twirp" |
| 19 | "go.uber.org/zap" |
| 20 | ) |
| 21 | |
| 22 | const maxHostWAFBytes = 64 << 10 |
| 23 | |
| 24 | var errHostWAFUnavailable = errors.New("WAF policy lookup unavailable") |
| 25 | |
| 26 | func limitClientRPCBody(next http.Handler) http.Handler { |
| 27 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 28 | limit := int64(1 << 10) |
| 29 | switch r.URL.Path { |
| 30 | case protocol.TunnelServicePathPrefix + "GetHostWAF", protocol.TunnelServicePathPrefix + "SetHostWAF": |
| 31 | limit = maxHostWAFBytes |
| 32 | } |
| 33 | r.Body = http.MaxBytesReader(w, r.Body, limit) |
| 34 | next.ServeHTTP(w, r) |
| 35 | }) |
| 36 | } |
| 37 | |
| 38 | func normalizeWAFHostname(hostname string) (string, error) { |
| 39 | if hostname == "" || len(hostname) > 253 { |
| 40 | return "", twirp.InvalidArgument.Error("hostname is required and must fit a DNS name") |
| 41 | } |
| 42 | hostname, err := normalizeDelegationHostname(hostname) |
| 43 | if err != nil { |
| 44 | return "", twirp.InvalidArgument.Error(err.Error()) |
| 45 | } |
| 46 | return hostname, nil |
| 47 | } |
| 48 | |
| 49 | func hostWAFVersion(hostname string, data []byte) string { |
| 50 | if len(data) == 0 { |
| 51 | return "" |
| 52 | } |
| 53 | sum := sha256.Sum256(append([]byte(hostname+"\x00"), data...)) |
| 54 | return hex.EncodeToString(sum[:]) |
| 55 | } |
| 56 | |
| 57 | func (s *Server) readHostWAF(ctx context.Context, hostname string) (*protocol.HostWAFRecord, string, error) { |
| 58 | data, err := s.Chord.Get(ctx, []byte(tun.HostWAFKey(hostname))) |
| 59 | if err != nil { |
| 60 | return nil, "", fmt.Errorf("%w: %w", errHostWAFUnavailable, err) |
| 61 | } |
| 62 | if len(data) == 0 { |
| 63 | return nil, "", nil |
| 64 | } |
| 65 | if len(data) > maxHostWAFBytes { |
| 66 | return nil, "", fmt.Errorf("saved WAF policy exceeds size limit") |
| 67 | } |
| 68 | var record protocol.HostWAFRecord |
| 69 | if err := waf.DecodeJSON(bytes.NewReader(data), &record); err != nil { |
| 70 | return nil, "", fmt.Errorf("invalid saved WAF policy: %w", err) |
| 71 | } |
| 72 | if record.Schema != 1 || len(record.Owner) == 0 { |
| 73 | return nil, "", fmt.Errorf("unsupported saved WAF policy") |
| 74 | } |
| 75 | policy, err := waf.ValidatePolicy(record.Policy) |
| 76 | if err != nil { |
| 77 | return nil, "", fmt.Errorf("invalid saved WAF policy: %w", err) |
| 78 | } |
| 79 | record.Policy = policy |
| 80 | return &record, hostWAFVersion(hostname, data), nil |
| 81 | } |
| 82 | |
| 83 | func (s *Server) requireWAFHostname(ctx context.Context, owner *protocol.ClientToken, hostname string) error { |
| 84 | owned, err := s.ownsHostname(ctx, owner, hostname) |
| 85 | if err != nil { |
| 86 | return twirp.Unavailable.Errorf("could not verify hostname ownership: %v", err) |
| 87 | } |
| 88 | if !owned { |
| 89 | return twirp.PermissionDenied.Error("hostname is not registered to this client") |
| 90 | } |
| 91 | return nil |
| 92 | } |
| 93 | |
| 94 | func hostWAFResponse(hostname, version string, record *protocol.HostWAFRecord) *protocol.HostWAFResponse { |
| 95 | policy := waf.DefaultPolicy() |
| 96 | if record != nil { |
| 97 | policy = record.Policy |
| 98 | } |
| 99 | return &protocol.HostWAFResponse{Hostname: hostname, Version: version, Policy: policy} |
| 100 | } |
| 101 | |
| 102 | func (s *Server) GetHostWAF(ctx context.Context, req *protocol.GetHostWAFRequest) (*protocol.HostWAFResponse, error) { |
| 103 | owner, _, err := extractAuthenticated(ctx) |
| 104 | if err != nil { |
| 105 | return nil, err |
| 106 | } |
| 107 | hostname, err := normalizeWAFHostname(req.GetHostname()) |
| 108 | if err != nil { |
| 109 | return nil, err |
| 110 | } |
| 111 | ctx, cancel := context.WithTimeout(ctx, lookupTimeout) |
| 112 | defer cancel() |
| 113 | if err := s.requireWAFHostname(ctx, owner, hostname); err != nil { |
| 114 | return nil, err |
| 115 | } |
| 116 | record, version, err := s.readHostWAF(ctx, hostname) |
| 117 | if err != nil { |
| 118 | return nil, twirp.Unavailable.Error(err.Error()) |
| 119 | } |
| 120 | if record != nil && !bytes.Equal(record.Owner, owner.GetToken()) { |
| 121 | record, version = nil, "" |
| 122 | } |
| 123 | return hostWAFResponse(hostname, version, record), nil |
| 124 | } |
| 125 | |
| 126 | func (s *Server) SetHostWAF(ctx context.Context, req *protocol.SetHostWAFRequest) (*protocol.HostWAFResponse, error) { |
| 127 | owner, _, err := extractAuthenticated(ctx) |
| 128 | if err != nil { |
| 129 | return nil, err |
| 130 | } |
| 131 | hostname, err := normalizeWAFHostname(req.GetHostname()) |
| 132 | if err != nil { |
| 133 | return nil, err |
| 134 | } |
| 135 | input := req.GetPolicy() |
| 136 | if input == nil { |
| 137 | return nil, twirp.InvalidArgument.Error("policy is required") |
| 138 | } |
| 139 | policy, err := waf.ValidatePolicy(input) |
| 140 | if err != nil { |
| 141 | return nil, twirp.InvalidArgument.Error(err.Error()) |
| 142 | } |
| 143 | record := &protocol.HostWAFRecord{Schema: 1, Owner: owner.GetToken(), Policy: policy} |
| 144 | data, err := waf.MarshalJSON(record) |
| 145 | if err != nil || len(data) > maxHostWAFBytes { |
| 146 | return nil, twirp.InvalidArgument.Error("WAF policy exceeds size limit") |
| 147 | } |
| 148 | |
| 149 | // Policy writes and hostname release share the existing owner's lease. Keep |
| 150 | // validation outside it, and bound the read/check/write well below its TTL. |
| 151 | ctx, cancel := context.WithTimeout(ctx, lookupTimeout) |
| 152 | defer cancel() |
| 153 | leaseKey := []byte(tun.ClientLeaseKey(owner)) |
| 154 | lease, err := s.Chord.Acquire(ctx, leaseKey, 30*time.Second) |
| 155 | if err != nil { |
| 156 | return nil, twirp.Unavailable.Errorf("could not acquire owner lease: %v", err) |
| 157 | } |
| 158 | defer s.Chord.Release(ctx, leaseKey, lease) |
| 159 | if err := s.requireWAFHostname(ctx, owner, hostname); err != nil { |
| 160 | return nil, err |
| 161 | } |
| 162 | previous, version, err := s.readHostWAF(ctx, hostname) |
| 163 | if err != nil { |
| 164 | return nil, twirp.Unavailable.Error(err.Error()) |
| 165 | } |
| 166 | if previous != nil && !bytes.Equal(previous.Owner, owner.GetToken()) { |
| 167 | version = "" |
| 168 | } |
| 169 | if version != req.GetExpectedVersion() { |
| 170 | return nil, twirp.FailedPrecondition.Error("WAF settings changed; refresh before saving again") |
| 171 | } |
| 172 | err = s.Chord.Put(ctx, []byte(tun.HostWAFKey(hostname)), data) |
| 173 | s.hostWAFCache.Delete(hostname) |
| 174 | if err != nil { |
| 175 | return nil, twirp.Unavailable.Errorf("WAF save result is uncertain; refresh to review saved settings: %v", err) |
| 176 | } |
| 177 | return hostWAFResponse(hostname, hostWAFVersion(hostname, data), record), nil |
| 178 | } |
| 179 | |
| 180 | // WAFPolicy returns immutable policy data. Only that data is cached; ownership |
| 181 | // of an override is checked for every request. Unavailable lookups inherit the |
| 182 | // operator default without caching that fallback. |
| 183 | func (s *Server) WAFPolicy(ctx context.Context, hostname string) (*protocol.WAFPolicy, error) { |
| 184 | policy := waf.DefaultPolicy() |
| 185 | if err := ctx.Err(); err != nil { |
| 186 | return policy, err |
| 187 | } |
| 188 | if _, _, ephemeral := tun.ParseEphemeralLabel(hostname); ephemeral { |
| 189 | return policy, nil |
| 190 | } |
| 191 | lookupCtx, cancel := context.WithTimeout(ctx, lookupTimeout) |
| 192 | defer cancel() |
| 193 | record, err := s.readCachedHostWAF(lookupCtx, hostname) |
| 194 | if err == nil && record != nil && (record.Policy.Mode != protocol.WAFPolicy_INHERIT || len(record.Policy.Exclusions) != 0) { |
| 195 | var owned bool |
| 196 | owned, err = s.ownsHostname(lookupCtx, &protocol.ClientToken{Token: record.Owner}, hostname) |
| 197 | if err != nil { |
| 198 | err = fmt.Errorf("%w: %w", errHostWAFUnavailable, err) |
| 199 | } else if owned { |
| 200 | policy = record.Policy |
| 201 | } |
| 202 | } |
| 203 | if !errors.Is(err, errHostWAFUnavailable) && !errors.Is(err, context.DeadlineExceeded) { |
| 204 | return policy, err |
| 205 | } |
| 206 | if err := ctx.Err(); err != nil { |
| 207 | return policy, err |
| 208 | } |
| 209 | if err := s.ParentContext.Err(); err != nil { |
| 210 | return policy, err |
| 211 | } |
| 212 | s.Logger.Warn("WAF policy unavailable; inheriting operator default", |
| 213 | zap.String("hostname", hostname), zap.String("request_id", middleware.GetReqID(ctx))) |
| 214 | return policy, nil |
| 215 | } |
| 216 | |
| 217 | func (s *Server) clearHostWAF(ctx context.Context, owner *protocol.ClientToken, hostname string) error { |
| 218 | defer s.hostWAFCache.Delete(hostname) |
| 219 | record, _, err := s.readHostWAF(ctx, hostname) |
| 220 | if err != nil || record == nil || !bytes.Equal(record.Owner, owner.GetToken()) { |
| 221 | return err |
| 222 | } |
| 223 | return s.Chord.Delete(ctx, []byte(tun.HostWAFKey(hostname))) |
| 224 | } |