ota.go 2.3 KB

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