-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Stop reusing hosts after idle leftovers #7679
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Mzack9999
wants to merge
1
commit into
dev
Choose a base branch
from
idle-conn-quarantine
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+762
−4
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| package protocolstate | ||
|
|
||
| import ( | ||
| "slices" | ||
| "sync" | ||
| "sync/atomic" | ||
| "time" | ||
| ) | ||
|
|
||
| // ExpiringSet is a lock-free-read set of string keys with per-entry expiry. | ||
| // Cleanup is amortized across writes and also performed by Keys. | ||
| type ExpiringSet struct { | ||
| values sync.Map // string -> expiry UnixNano | ||
| cleanupInterval time.Duration | ||
| lastCleanup atomic.Int64 | ||
| } | ||
|
|
||
| func NewExpiringSet(cleanupInterval time.Duration) *ExpiringSet { | ||
| set := &ExpiringSet{cleanupInterval: cleanupInterval} | ||
| set.lastCleanup.Store(time.Now().UnixNano()) | ||
| return set | ||
| } | ||
|
|
||
| func (s *ExpiringSet) Store(key string, ttl time.Duration) { | ||
| s.StoreUntil(key, time.Now().Add(ttl)) | ||
| } | ||
|
|
||
| func (s *ExpiringSet) StoreUntil(key string, expiry time.Time) { | ||
| if s == nil || key == "" { | ||
| return | ||
| } | ||
| s.values.Store(key, expiry.UnixNano()) | ||
| s.maybeCleanup(time.Now()) | ||
| } | ||
|
|
||
| func (s *ExpiringSet) Contains(key string) bool { | ||
| return s.containsAt(key, time.Now()) | ||
| } | ||
|
|
||
| func (s *ExpiringSet) containsAt(key string, now time.Time) bool { | ||
| if s == nil || key == "" { | ||
| return false | ||
| } | ||
| value, ok := s.values.Load(key) | ||
| if !ok { | ||
| return false | ||
| } | ||
| expiresAt, ok := value.(int64) | ||
| if !ok || now.UnixNano() >= expiresAt { | ||
| s.values.CompareAndDelete(key, value) | ||
| return false | ||
| } | ||
| return true | ||
| } | ||
|
|
||
| func (s *ExpiringSet) Keys() []string { | ||
| return s.keysAt(time.Now()) | ||
| } | ||
|
|
||
| func (s *ExpiringSet) keysAt(now time.Time) []string { | ||
| if s == nil { | ||
| return nil | ||
| } | ||
| var keys []string | ||
| s.values.Range(func(key, value any) bool { | ||
| name, keyOK := key.(string) | ||
| expiresAt, expiryOK := value.(int64) | ||
| if keyOK && expiryOK && now.UnixNano() < expiresAt { | ||
| keys = append(keys, name) | ||
| } else { | ||
| s.values.CompareAndDelete(key, value) | ||
| } | ||
| return true | ||
| }) | ||
| slices.Sort(keys) | ||
| return keys | ||
| } | ||
|
|
||
| func (s *ExpiringSet) maybeCleanup(now time.Time) { | ||
| if s.cleanupInterval <= 0 { | ||
| return | ||
| } | ||
| last := s.lastCleanup.Load() | ||
| if now.UnixNano()-last < s.cleanupInterval.Nanoseconds() || | ||
| !s.lastCleanup.CompareAndSwap(last, now.UnixNano()) { | ||
| return | ||
| } | ||
| s.keysAt(now) | ||
| } |
102 changes: 102 additions & 0 deletions
102
pkg/protocols/common/protocolstate/expiring_set_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| package protocolstate | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "strconv" | ||
| "sync/atomic" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestExpiringSetContainsAndExpires(t *testing.T) { | ||
| set := NewExpiringSet(time.Minute) | ||
| now := time.Now() | ||
| set.StoreUntil("active", now.Add(time.Minute)) | ||
| set.StoreUntil("expired", now.Add(-time.Second)) | ||
|
|
||
| require.True(t, set.containsAt("active", now)) | ||
| require.False(t, set.containsAt("expired", now)) | ||
| _, exists := set.values.Load("expired") | ||
| require.False(t, exists) | ||
| } | ||
|
|
||
| func TestExpiringSetKeysSortsAndCleans(t *testing.T) { | ||
| set := NewExpiringSet(time.Minute) | ||
| now := time.Now() | ||
| set.StoreUntil("b", now.Add(time.Minute)) | ||
| set.StoreUntil("a", now.Add(time.Minute)) | ||
| set.StoreUntil("expired", now.Add(-time.Second)) | ||
|
|
||
| require.Equal(t, []string{"a", "b"}, set.keysAt(now)) | ||
| _, exists := set.values.Load("expired") | ||
| require.False(t, exists) | ||
| } | ||
|
|
||
| func TestExpiringSetRefreshesTTL(t *testing.T) { | ||
| set := NewExpiringSet(time.Minute) | ||
| now := time.Now() | ||
| set.StoreUntil("host", now.Add(time.Minute)) | ||
| set.StoreUntil("host", now.Add(2*time.Minute)) | ||
|
|
||
| require.True(t, set.containsAt("host", now.Add(90*time.Second))) | ||
| require.False(t, set.containsAt("host", now.Add(3*time.Minute))) | ||
| } | ||
|
|
||
| func TestExpiringSetEmptyAndNil(t *testing.T) { | ||
| var nilSet *ExpiringSet | ||
| require.False(t, nilSet.Contains("host")) | ||
| require.Empty(t, nilSet.Keys()) | ||
|
|
||
| set := NewExpiringSet(time.Minute) | ||
| set.Store("", time.Minute) | ||
| require.False(t, set.Contains("")) | ||
| require.Empty(t, set.Keys()) | ||
| } | ||
|
|
||
| func TestExpiringSetConcurrentAccess(t *testing.T) { | ||
| set := NewExpiringSet(time.Minute) | ||
| var done atomic.Int64 | ||
|
|
||
| t.Run("parallel", func(t *testing.T) { | ||
| for i := range 100 { | ||
| i := i | ||
| t.Run(strconv.Itoa(i), func(t *testing.T) { | ||
| t.Parallel() | ||
| key := fmt.Sprintf("host-%d", i%10) | ||
| set.Store(key, time.Minute) | ||
| require.True(t, set.Contains(key)) | ||
| done.Add(1) | ||
| }) | ||
| } | ||
| }) | ||
| require.Equal(t, int64(100), done.Load()) | ||
| } | ||
|
|
||
| func TestExpiringSetConcurrentRefreshSurvivesExpiredCleanup(t *testing.T) { | ||
| for range 1000 { | ||
| set := NewExpiringSet(time.Minute) | ||
| now := time.Now() | ||
| set.StoreUntil("host", now.Add(-time.Second)) | ||
|
|
||
| start := make(chan struct{}) | ||
| done := make(chan struct{}, 2) | ||
| go func() { | ||
| <-start | ||
| _ = set.containsAt("host", now) | ||
| done <- struct{}{} | ||
| }() | ||
| go func() { | ||
| <-start | ||
| set.StoreUntil("host", now.Add(time.Minute)) | ||
| done <- struct{}{} | ||
| }() | ||
| close(start) | ||
| <-done | ||
| <-done | ||
|
|
||
| require.True(t, set.containsAt("host", now), | ||
| "cleanup of the expired value must not delete a concurrent refresh") | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| package httpclientpool | ||
|
|
||
| import ( | ||
| "crypto/tls" | ||
| "net" | ||
| "sync" | ||
| "sync/atomic" | ||
| ) | ||
|
|
||
| // desyncConn watches for bytes that arrive from a server while the connection is | ||
| // not serving any request. A server has nothing to answer at that point, so | ||
| // whatever it sends belongs to an earlier exchange. | ||
| // | ||
| // Idleness comes from net/http: GotConn fires when a request takes the | ||
| // connection and PutIdleConn fires when it returns to the pool. Bytes in that | ||
| // window are unsolicited by the same criterion net/http uses internally. The | ||
| // check is one atomic load in Read, identical over plaintext and TLS because | ||
| // the wrapper sits above the handshake. | ||
| // | ||
| // net/http already closes a connection when it notices this, but only logs it. | ||
| // Observing it here is what lets the pool stop reusing connections to that host. | ||
| // A leftover that arrives while a request is outstanding is indistinguishable | ||
| // from that request's real reply, so this cannot save the first wrong response. | ||
| // Closing and quarantining only stops the host from doing it again. | ||
| type desyncConn struct { | ||
| net.Conn | ||
| host string | ||
| onPoison func(host string) | ||
| idle atomic.Bool | ||
| poisoned atomic.Bool | ||
| closeOnce sync.Once | ||
| } | ||
|
|
||
| func newDesyncConn(conn net.Conn, addr string, onPoison func(host string)) net.Conn { | ||
| if conn == nil || negotiatedHTTP2(conn) { | ||
| return conn | ||
| } | ||
| return &desyncConn{ | ||
| Conn: conn, | ||
| host: desyncedHostKey(addr), | ||
| onPoison: onPoison, | ||
| } | ||
| } | ||
|
|
||
| func (c *desyncConn) Read(b []byte) (int, error) { | ||
| n, err := c.Conn.Read(b) | ||
| if n > 0 && c.idle.Load() { | ||
| c.poison() | ||
| } | ||
| return n, err | ||
| } | ||
|
|
||
| func (c *desyncConn) markBusy() { | ||
| c.idle.Store(false) | ||
| } | ||
|
|
||
| func (c *desyncConn) markIdle() { | ||
| c.idle.Store(true) | ||
| } | ||
|
|
||
| func (c *desyncConn) Close() error { | ||
| c.idle.Store(false) | ||
| return c.Conn.Close() | ||
| } | ||
|
|
||
| func (c *desyncConn) poison() { | ||
| if !c.poisoned.CompareAndSwap(false, true) { | ||
| return | ||
| } | ||
| c.idle.Store(false) | ||
| if c.onPoison != nil { | ||
| c.onPoison(c.host) | ||
| } | ||
| c.closeOnce.Do(func() { _ = c.Conn.Close() }) | ||
| } | ||
|
|
||
| func negotiatedHTTP2(conn net.Conn) bool { | ||
| handshaked, ok := conn.(interface{ ConnectionState() tls.ConnectionState }) | ||
| if !ok { | ||
| return false | ||
| } | ||
| return handshaked.ConnectionState().NegotiatedProtocol == "h2" | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
Repository: projectdiscovery/nuclei
Length of output: 161
🌐 Web query:
Go net/http Transport DialTLSContext custom dialer Response.TLS nil requires *tls.Conn type assertion💡 Result:
When using a custom DialTLSContext in net/http.Transport, the net/http package specifically checks if the returned net.Conn is of type *tls.Conn to populate the Response.TLS field [1]. If the connection is wrapped (for example, by a logging or statistics wrapper) and fails this type assertion, Response.TLS will be nil [1]. The underlying implementation performs a type assertion (e.g., conn.(*tls.Conn)) to extract the TLS connection state [2][3][1]. If this assertion fails, the transport cannot access the TLS metadata, resulting in the following consequences: 1. Response.TLS is nil: The metadata required for TLS inspection is lost because the transport cannot reach the *tls.Conn object [1]. 2. HTTP/2 Negotiation Failures: If you attempt to use HTTP/2, the transport often silently falls back to HTTP/1.1 because it cannot confirm the ALPN protocol negotiation (which is tied to the TLS state) [2][3]. To resolve this issue while maintaining custom wrappers around your connection, you must ensure that your custom net.Conn implementation preserves access to the TLS connection state. The best practice is to ensure that your wrapper type implements the ConnectionState method [2][4]. The net/http package (and the bundled HTTP/2 implementation) will use this method if it exists, allowing it to populate Response.TLS and perform correct protocol negotiation even when the connection is not a literal *tls.Conn [2][5][4]. Alternatively, you can restructure your code so that the TLS dialer remains the outermost layer [1]. By applying your wrappers to the underlying TCP connection before passing it to the TLS dialer (or using a wrapper that preserves the *tls.Conn type assertion), you ensure that the Transport receives the concrete *tls.Conn it expects [1].
Citations:
🏁 Script executed:
Repository: projectdiscovery/nuclei
Length of output: 37158
🏁 Script executed:
Repository: projectdiscovery/nuclei
Length of output: 10202
Do not wrap TLS connections returned by
DialTLSContextFor direct HTTP/1.1 HTTPS connections,
trackDesyncwraps the*tls.Connreturned byDialTLSContextindesyncConn.http.Transportonly records the TLS state in this custom TLS path after a*tls.Connassertion, soResponse.TLSbecomes nil.enrichEventWithTLSMetadatathen omits the TLS version, cipher, SNI, and certificate metadata. ApplytrackDesynconly toDialContext, or preserve the required*tls.Connhandling.🤖 Prompt for AI Agents
Source: Linters/SAST tools