forked from riobard/go-shadowsocks2
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
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
Implement reuse detection for cipher #165
Merged
riobard
merged 2 commits into
shadowsocks:master
from
oif:implement-reuse-detection-filter
Feb 15, 2020
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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 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 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 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,67 @@ | ||
package internal | ||
|
||
import ( | ||
"hash/fnv" | ||
"sync" | ||
|
||
"github.com/riobard/go-bloom" | ||
) | ||
|
||
// simply use Double FNV here as our Bloom Filter hash | ||
func doubleFNV(b []byte) (uint64, uint64) { | ||
hx := fnv.New64() | ||
hx.Write(b) | ||
x := hx.Sum64() | ||
hy := fnv.New64a() | ||
hy.Write(b) | ||
y := hy.Sum64() | ||
return x, y | ||
} | ||
|
||
type BloomRing struct { | ||
slotCapacity int | ||
slotPosition int | ||
slotCount int | ||
entryCounter int | ||
slots []bloom.Filter | ||
mutex sync.RWMutex | ||
} | ||
|
||
func NewBloomRing(slot, capacity int, falsePositiveRate float64) *BloomRing { | ||
// Calculate entries for each slot | ||
r := &BloomRing{ | ||
slotCapacity: capacity / slot, | ||
slotCount: slot, | ||
slots: make([]bloom.Filter, slot), | ||
} | ||
for i := 0; i < slot; i++ { | ||
r.slots[i] = bloom.New(r.slotCapacity, falsePositiveRate, doubleFNV) | ||
} | ||
return r | ||
} | ||
|
||
func (r *BloomRing) Add(b []byte) { | ||
r.mutex.Lock() | ||
defer r.mutex.Unlock() | ||
slot := r.slots[r.slotPosition] | ||
if r.entryCounter > r.slotCapacity { | ||
// Move to next slot and reset | ||
r.slotPosition = (r.slotPosition + 1) % r.slotCount | ||
slot = r.slots[r.slotPosition] | ||
slot.Reset() | ||
r.entryCounter = 0 | ||
} | ||
r.entryCounter++ | ||
slot.Add(b) | ||
} | ||
|
||
func (r *BloomRing) Test(b []byte) bool { | ||
r.mutex.RLock() | ||
defer r.mutex.RUnlock() | ||
for _, s := range r.slots { | ||
if s.Test(b) { | ||
return true | ||
} | ||
} | ||
return false | ||
} |
This file contains 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,68 @@ | ||
package internal_test | ||
|
||
import ( | ||
"fmt" | ||
"os" | ||
"testing" | ||
|
||
"github.com/shadowsocks/go-shadowsocks2/internal" | ||
) | ||
|
||
var ( | ||
bloomRingInstance *internal.BloomRing | ||
) | ||
|
||
func TestMain(m *testing.M) { | ||
bloomRingInstance = internal.NewBloomRing(internal.DefaultSFSlot, int(internal.DefaultSFCapacity), | ||
internal.DefaultSFFPR) | ||
os.Exit(m.Run()) | ||
} | ||
|
||
func TestBloomRing_Add(t *testing.T) { | ||
defer func() { | ||
if any := recover(); any != nil { | ||
t.Fatalf("Should not got panic while adding item: %v", any) | ||
} | ||
}() | ||
bloomRingInstance.Add(make([]byte, 16)) | ||
} | ||
|
||
func TestBloomRing_Test(t *testing.T) { | ||
buf := []byte("shadowsocks") | ||
bloomRingInstance.Add(buf) | ||
if !bloomRingInstance.Test(buf) { | ||
t.Fatal("Test on filter missing") | ||
} | ||
} | ||
|
||
func BenchmarkBloomRing(b *testing.B) { | ||
// Generate test samples with different length | ||
samples := make([][]byte, internal.DefaultSFCapacity-internal.DefaultSFSlot) | ||
var checkPoints [][]byte | ||
for i := 0; i < len(samples); i++ { | ||
samples[i] = []byte(fmt.Sprint(i)) | ||
if i%1000 == 0 { | ||
checkPoints = append(checkPoints, samples[i]) | ||
} | ||
} | ||
b.Logf("Generated %d samples and %d check points", len(samples), len(checkPoints)) | ||
for i := 1; i < 16; i++ { | ||
b.Run(fmt.Sprintf("Slot%d", i), benchmarkBloomRing(samples, checkPoints, i)) | ||
} | ||
} | ||
|
||
func benchmarkBloomRing(samples, checkPoints [][]byte, slot int) func(*testing.B) { | ||
filter := internal.NewBloomRing(slot, int(internal.DefaultSFCapacity), internal.DefaultSFFPR) | ||
for _, sample := range samples { | ||
filter.Add(sample) | ||
} | ||
return func(b *testing.B) { | ||
b.ResetTimer() | ||
b.ReportAllocs() | ||
for i := 0; i < b.N; i++ { | ||
for _, cp := range checkPoints { | ||
filter.Test(cp) | ||
} | ||
} | ||
} | ||
} |
This file contains 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,80 @@ | ||
package internal | ||
|
||
import ( | ||
"fmt" | ||
"os" | ||
"strconv" | ||
) | ||
|
||
// Those suggest value are all set according to | ||
// https://github.com/shadowsocks/shadowsocks-org/issues/44#issuecomment-281021054 | ||
// Due to this package contains various internal implementation so const named with DefaultBR prefix | ||
const ( | ||
DefaultSFCapacity = 1e6 | ||
// FalsePositiveRate | ||
DefaultSFFPR = 1e-6 | ||
DefaultSFSlot = 10 | ||
) | ||
|
||
const EnvironmentPrefix = "SHADOWSOCKS_" | ||
|
||
// A shared instance used for checking salt repeat | ||
var saltfilter *BloomRing | ||
|
||
func init() { | ||
var ( | ||
finalCapacity = DefaultSFCapacity | ||
finalFPR = DefaultSFFPR | ||
finalSlot = float64(DefaultSFSlot) | ||
) | ||
for _, opt := range []struct { | ||
ENVName string | ||
Target *float64 | ||
}{ | ||
{ | ||
ENVName: "CAPACITY", | ||
Target: &finalCapacity, | ||
}, | ||
{ | ||
ENVName: "FPR", | ||
Target: &finalFPR, | ||
}, | ||
{ | ||
ENVName: "SLOT", | ||
Target: &finalSlot, | ||
}, | ||
} { | ||
envKey := EnvironmentPrefix + "SF_" + opt.ENVName | ||
env := os.Getenv(envKey) | ||
if env != "" { | ||
p, err := strconv.ParseFloat(env, 64) | ||
if err != nil { | ||
panic(fmt.Sprintf("Invalid envrionment `%s` setting in saltfilter: %s", envKey, env)) | ||
} | ||
*opt.Target = p | ||
} | ||
} | ||
// Support disable saltfilter by given a negative capacity | ||
if finalCapacity <= 0 { | ||
return | ||
} | ||
saltfilter = NewBloomRing(int(finalSlot), int(finalCapacity), finalFPR) | ||
} | ||
|
||
// TestSalt returns true if salt is repeated | ||
func TestSalt(b []byte) bool { | ||
// If nil means feature disabled, return false to bypass salt repeat detection | ||
if saltfilter == nil { | ||
return false | ||
} | ||
return saltfilter.Test(b) | ||
} | ||
|
||
// AddSalt salt to filter | ||
func AddSalt(b []byte) { | ||
// If nil means feature disabled | ||
if saltfilter == nil { | ||
return | ||
} | ||
saltfilter.Add(b) | ||
} |
This file contains 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 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 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 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 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 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
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.
Because this large allocation is done on
init()
, anyone depending on go-shadowsocks2 will have this allocation done, even client code on memory constrained devices. This caused an issue on the Outline iOS client, where the VpnExtension has a very tight memory limit.Instead, this could be done on main and injected into the code that needs it, or initialized on demand.
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.
Good point, client needs fewer capacity so maybe provide a manual initialization by giving two kind of capacity, slot and FPR which are identitified by running mode (client/server) to reduce large allocations is a good chooice.
What do you think? @riobard
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.
And on the other hand,
saltfilter
provide enough ENV to let caller or executor to controll related args while initializing, it's another way to controll allocation directly.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.
I sent #189 to fix it.
The ENV is not appropriate. Who sets it? Setting it on main leaks implementation details. Setting in a library is messy, since libraries can compete. For example, if client code disables it, we'll have a problem with an integration test that runs both the client and the server code.
The ideal solution would be to inject dependencies instead of using globals, but the code is not designed for injection (doesn't use classes). I implemented a compromise where I get a singleton object when needed. That can be injected later if wiring is made easier.
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.
I agree with @fortuna that the filter should be optional. It was an oversight that the filter is created in
init()
, causing problems for importing go-ss2 as a library.Please move to #189 for further discussion about the fix.