auth.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. package crypto
  2. import (
  3. "crypto/cipher"
  4. "errors"
  5. "io"
  6. "v2ray.com/core/common"
  7. "v2ray.com/core/common/buf"
  8. "v2ray.com/core/common/serial"
  9. )
  10. var (
  11. ErrAuthenticationFailed = errors.New("Authentication failed.")
  12. errInsufficientBuffer = errors.New("Insufficient buffer.")
  13. errInvalidNonce = errors.New("Invalid nonce.")
  14. errInvalidLength = errors.New("Invalid buffer size.")
  15. )
  16. type BytesGenerator interface {
  17. Next() []byte
  18. }
  19. type NoOpBytesGenerator struct {
  20. buffer [1]byte
  21. }
  22. func (v NoOpBytesGenerator) Next() []byte {
  23. return v.buffer[:0]
  24. }
  25. type StaticBytesGenerator struct {
  26. Content []byte
  27. }
  28. func (v StaticBytesGenerator) Next() []byte {
  29. return v.Content
  30. }
  31. type Authenticator interface {
  32. NonceSize() int
  33. Overhead() int
  34. Open(dst, cipherText []byte) ([]byte, error)
  35. Seal(dst, plainText []byte) ([]byte, error)
  36. }
  37. type AEADAuthenticator struct {
  38. cipher.AEAD
  39. NonceGenerator BytesGenerator
  40. AdditionalDataGenerator BytesGenerator
  41. }
  42. func (v *AEADAuthenticator) Open(dst, cipherText []byte) ([]byte, error) {
  43. iv := v.NonceGenerator.Next()
  44. if len(iv) != v.AEAD.NonceSize() {
  45. return nil, errInvalidNonce
  46. }
  47. additionalData := v.AdditionalDataGenerator.Next()
  48. return v.AEAD.Open(dst, iv, cipherText, additionalData)
  49. }
  50. func (v *AEADAuthenticator) Seal(dst, plainText []byte) ([]byte, error) {
  51. iv := v.NonceGenerator.Next()
  52. if len(iv) != v.AEAD.NonceSize() {
  53. return nil, errInvalidNonce
  54. }
  55. additionalData := v.AdditionalDataGenerator.Next()
  56. return v.AEAD.Seal(dst, iv, plainText, additionalData), nil
  57. }
  58. type AuthenticationReader struct {
  59. auth Authenticator
  60. buffer *buf.Buffer
  61. reader io.Reader
  62. chunk []byte
  63. }
  64. const (
  65. readerBufferSize = 32 * 1024
  66. )
  67. func NewAuthenticationReader(auth Authenticator, reader io.Reader) *AuthenticationReader {
  68. return &AuthenticationReader{
  69. auth: auth,
  70. buffer: buf.NewLocal(readerBufferSize),
  71. reader: reader,
  72. }
  73. }
  74. func (v *AuthenticationReader) NextChunk() error {
  75. if v.buffer.Len() < 2 {
  76. return errInsufficientBuffer
  77. }
  78. size := int(serial.BytesToUint16(v.buffer.BytesTo(2)))
  79. if size > v.buffer.Len()-2 {
  80. return errInsufficientBuffer
  81. }
  82. if size > readerBufferSize-2 {
  83. return errInvalidLength
  84. }
  85. if size == v.auth.Overhead() {
  86. return io.EOF
  87. }
  88. if size < v.auth.Overhead() {
  89. return errors.New("AuthenticationReader: invalid packet size.")
  90. }
  91. cipherChunk := v.buffer.BytesRange(2, size+2)
  92. plainChunk, err := v.auth.Open(cipherChunk[:0], cipherChunk)
  93. if err != nil {
  94. return err
  95. }
  96. v.chunk = plainChunk
  97. v.buffer.SliceFrom(size + 2)
  98. return nil
  99. }
  100. func (v *AuthenticationReader) CopyChunk(b []byte) int {
  101. if len(v.chunk) == 0 {
  102. return 0
  103. }
  104. nBytes := copy(b, v.chunk)
  105. if nBytes == len(v.chunk) {
  106. v.chunk = nil
  107. } else {
  108. v.chunk = v.chunk[nBytes:]
  109. }
  110. return nBytes
  111. }
  112. func (v *AuthenticationReader) EnsureChunk() error {
  113. for {
  114. err := v.NextChunk()
  115. if err == nil {
  116. return nil
  117. }
  118. if err == errInsufficientBuffer {
  119. if v.buffer.IsEmpty() {
  120. v.buffer.Clear()
  121. } else {
  122. leftover := v.buffer.Bytes()
  123. common.Must(v.buffer.Reset(func(b []byte) (int, error) {
  124. return copy(b, leftover), nil
  125. }))
  126. }
  127. err = v.buffer.AppendSupplier(buf.ReadFrom(v.reader))
  128. if err == nil {
  129. continue
  130. }
  131. }
  132. return err
  133. }
  134. }
  135. func (v *AuthenticationReader) Read(b []byte) (int, error) {
  136. if len(v.chunk) > 0 {
  137. nBytes := v.CopyChunk(b)
  138. return nBytes, nil
  139. }
  140. err := v.EnsureChunk()
  141. if err != nil {
  142. return 0, err
  143. }
  144. return v.CopyChunk(b), nil
  145. }
  146. type AuthenticationWriter struct {
  147. auth Authenticator
  148. buffer []byte
  149. writer io.Writer
  150. }
  151. func NewAuthenticationWriter(auth Authenticator, writer io.Writer) *AuthenticationWriter {
  152. return &AuthenticationWriter{
  153. auth: auth,
  154. buffer: make([]byte, 32*1024),
  155. writer: writer,
  156. }
  157. }
  158. func (v *AuthenticationWriter) Write(b []byte) (int, error) {
  159. cipherChunk, err := v.auth.Seal(v.buffer[2:2], b)
  160. if err != nil {
  161. return 0, err
  162. }
  163. serial.Uint16ToBytes(uint16(len(cipherChunk)), v.buffer[:0])
  164. _, err = v.writer.Write(v.buffer[:2+len(cipherChunk)])
  165. return len(b), err
  166. }