فهرست منبع

Fix unsafe math rand usage

Shelikhoo 1 سال پیش
والد
کامیت
04275b6991
3فایلهای تغییر یافته به همراه18 افزوده شده و 3 حذف شده
  1. 15 0
      common/dice/dice.go
  2. 2 2
      proxy/shadowsocks2022/encoding.go
  3. 1 1
      proxy/vmess/encoding/client.go

+ 15 - 0
common/dice/dice.go

@@ -3,6 +3,10 @@
 package dice
 
 import (
+	crand "crypto/rand"
+	"github.com/v2fly/v2ray-core/v5/common"
+	"io"
+	"math/big"
 	"math/rand"
 	"time"
 )
@@ -15,6 +19,17 @@ func Roll(n int) int {
 	return rand.Intn(n)
 }
 
+// RollWith returns a non-negative number between 0 (inclusive) and n (exclusive).
+// Use random as the random source, if read fails, it panics.
+func RollWith(n int, random io.Reader) int {
+	if n == 1 {
+		return 0
+	}
+	mrand, err := crand.Int(random, big.NewInt(int64(n)))
+	common.Must(err)
+	return int(mrand.Int64())
+}
+
 // Roll returns a non-negative number between 0 (inclusive) and n (exclusive).
 func RollDeterministic(n int, seed int64) int {
 	if n == 1 {

+ 2 - 2
proxy/shadowsocks2022/encoding.go

@@ -5,8 +5,8 @@ import (
 	"crypto/cipher"
 	cryptoRand "crypto/rand"
 	"encoding/binary"
+	"github.com/v2fly/v2ray-core/v5/common/dice"
 	"io"
-	"math/rand"
 	"time"
 
 	"github.com/v2fly/v2ray-core/v5/common"
@@ -62,7 +62,7 @@ func (t *TCPRequest) EncodeTCPRequestHeader(effectivePsk []byte,
 	paddingLength := TCPMinPaddingLength
 	if initialPayload == nil {
 		initialPayload = []byte{}
-		paddingLength += 1 + rand.Intn(TCPMaxPaddingLength) // TODO INSECURE RANDOM USED
+		paddingLength += 1 + dice.RollWith(TCPMaxPaddingLength, cryptoRand.Reader)
 	}
 
 	variableLengthHeader := &TCPRequestHeader3VariableLength{

+ 1 - 1
proxy/vmess/encoding/client.go

@@ -101,7 +101,7 @@ func (c *ClientSession) EncodeRequestHeader(header *protocol.RequestHeader, writ
 	common.Must(buffer.WriteByte(c.responseHeader))
 	common.Must(buffer.WriteByte(byte(header.Option)))
 
-	paddingLen := dice.Roll(16)
+	paddingLen := dice.RollWith(16, rand.Reader)
 	security := byte(paddingLen<<4) | byte(header.Security)
 	common.Must2(buffer.Write([]byte{security, byte(0), byte(header.Command)}))