auth.go 3.7 KB

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