ota.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package shadowsocks
  2. import (
  3. "bytes"
  4. "crypto/hmac"
  5. "crypto/sha1"
  6. "io"
  7. "github.com/v2ray/v2ray-core/common/alloc"
  8. "github.com/v2ray/v2ray-core/common/log"
  9. "github.com/v2ray/v2ray-core/common/serial"
  10. "github.com/v2ray/v2ray-core/transport"
  11. )
  12. const (
  13. AuthSize = 10
  14. )
  15. type KeyGenerator func() []byte
  16. type Authenticator struct {
  17. key KeyGenerator
  18. }
  19. func NewAuthenticator(keygen KeyGenerator) *Authenticator {
  20. return &Authenticator{
  21. key: keygen,
  22. }
  23. }
  24. func (this *Authenticator) Authenticate(auth []byte, data []byte) []byte {
  25. hasher := hmac.New(sha1.New, this.key())
  26. hasher.Write(data)
  27. res := hasher.Sum(nil)
  28. return append(auth, res[:AuthSize]...)
  29. }
  30. func HeaderKeyGenerator(key []byte, iv []byte) func() []byte {
  31. return func() []byte {
  32. newKey := make([]byte, 0, len(key)+len(iv))
  33. newKey = append(newKey, iv...)
  34. newKey = append(newKey, key...)
  35. return newKey
  36. }
  37. }
  38. func ChunkKeyGenerator(iv []byte) func() []byte {
  39. chunkId := 0
  40. return func() []byte {
  41. newKey := make([]byte, 0, len(iv)+4)
  42. newKey = append(newKey, iv...)
  43. serial.IntToBytes(chunkId, newKey)
  44. chunkId++
  45. return newKey
  46. }
  47. }
  48. type ChunkReader struct {
  49. reader io.Reader
  50. auth *Authenticator
  51. }
  52. func NewChunkReader(reader io.Reader, auth *Authenticator) *ChunkReader {
  53. return &ChunkReader{
  54. reader: reader,
  55. auth: auth,
  56. }
  57. }
  58. func (this *ChunkReader) Release() {
  59. this.reader = nil
  60. this.auth = nil
  61. }
  62. func (this *ChunkReader) Read() (*alloc.Buffer, error) {
  63. buffer := alloc.NewLargeBuffer()
  64. if _, err := io.ReadFull(this.reader, buffer.Value[:2]); err != nil {
  65. buffer.Release()
  66. return nil, err
  67. }
  68. // There is a potential buffer overflow here. Large buffer is 64K bytes,
  69. // while uin16 + 10 will be more than that
  70. length := serial.BytesToUint16(buffer.Value[:2]) + AuthSize
  71. if _, err := io.ReadFull(this.reader, buffer.Value[:length]); err != nil {
  72. buffer.Release()
  73. return nil, err
  74. }
  75. buffer.Slice(0, int(length))
  76. authBytes := buffer.Value[:AuthSize]
  77. payload := buffer.Value[AuthSize:]
  78. actualAuthBytes := this.auth.Authenticate(nil, payload)
  79. if !bytes.Equal(authBytes, actualAuthBytes) {
  80. buffer.Release()
  81. log.Debug("AuthenticationReader: Unexpected auth: ", authBytes)
  82. return nil, transport.ErrCorruptedPacket
  83. }
  84. buffer.Value = payload
  85. return buffer, nil
  86. }