Explorar el Código

Rework antireplay

tags/1.0^2
9seconds hace 6 años
padre
commit
d44474012a
Se han modificado 3 ficheros con 41 adiciones y 25 borrados
  1. 8
    23
      antireplay/cache.go
  2. 31
    0
      antireplay/init.go
  3. 2
    2
      obfuscated2/client_protocol.go

+ 8
- 23
antireplay/cache.go Ver fichero

@@ -1,31 +1,16 @@
1 1
 package antireplay
2 2
 
3
-import (
4
-	"github.com/allegro/bigcache"
3
+import "github.com/allegro/bigcache"
5 4
 
6
-	"github.com/9seconds/mtg/config"
7
-)
8
-
9
-var cache *bigcache.BigCache
10
-
11
-func Add(data []byte) {
12
-	cache.Set(string(data), nil) // nolint: errcheck
5
+type cache struct {
6
+	cache *bigcache.BigCache
13 7
 }
14 8
 
15
-func Has(data []byte) bool {
16
-	_, err := cache.Get(string(data))
17
-	return err == nil
9
+func (c *cache) Add(data []byte) {
10
+	c.cache.Set(string(data), nil) // nolint: errcheck
18 11
 }
19 12
 
20
-func Init() {
21
-	c, err := bigcache.NewBigCache(bigcache.Config{
22
-		Shards:           1024,
23
-		LifeWindow:       config.C.AntiReplay.EvictionTime,
24
-		Hasher:           hasher{},
25
-		HardMaxCacheSize: config.C.AntiReplay.MaxSize,
26
-	})
27
-	if err != nil {
28
-		panic(err)
29
-	}
30
-	cache = c
13
+func (c *cache) Has(data []byte) bool {
14
+	_, err := c.cache.Get(string(data))
15
+	return err == nil
31 16
 }

+ 31
- 0
antireplay/init.go Ver fichero

@@ -0,0 +1,31 @@
1
+package antireplay
2
+
3
+import (
4
+	"sync"
5
+
6
+	"github.com/9seconds/mtg/config"
7
+	"github.com/allegro/bigcache"
8
+)
9
+
10
+var (
11
+	Cache    *cache
12
+	initOnce sync.Once
13
+)
14
+
15
+func Init() {
16
+	initOnce.Do(func() {
17
+		c, err := bigcache.NewBigCache(bigcache.Config{
18
+			Shards:           1024,
19
+			LifeWindow:       config.C.AntiReplay.EvictionTime,
20
+			Hasher:           hasher{},
21
+			HardMaxCacheSize: config.C.AntiReplay.MaxSize,
22
+		})
23
+		if err != nil {
24
+			panic(err)
25
+		}
26
+
27
+		Cache = &cache{
28
+			cache: c,
29
+		}
30
+	})
31
+}

+ 2
- 2
obfuscated2/client_protocol.go Ver fichero

@@ -80,10 +80,10 @@ func (c *ClientProtocol) Handshake(socket conntypes.StreamReadWriteCloser) (conn
80 80
 	}
81 81
 
82 82
 	antiReplayKey := decryptedFrame.Unique()
83
-	if antireplay.Has(antiReplayKey) {
83
+	if antireplay.Cache.Has(antiReplayKey) {
84 84
 		return nil, errors.New("Replay attack is detected")
85 85
 	}
86
-	antireplay.Add(antiReplayKey)
86
+	antireplay.Cache.Add(antiReplayKey)
87 87
 
88 88
 	return wrappers.NewObfuscated2(socket, encryptor, decryptor), nil
89 89
 }

Loading…
Cancelar
Guardar