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) EnsureChunk() error {
  104. for {
  105. err := v.NextChunk()
  106. if err == nil {
  107. return nil
  108. }
  109. if err == errInsufficientBuffer {
  110. if !v.buffer.IsEmpty() {
  111. leftover := v.buffer.Bytes()
  112. v.buffer.SetBytesFunc(func(b []byte) int {
  113. return copy(b, leftover)
  114. })
  115. }
  116. _, err = v.buffer.FillFrom(v.reader)
  117. }
  118. return err
  119. }
  120. }
  121. func (v *AuthenticationReader) Read(b []byte) (int, error) {
  122. if len(v.chunk) > 0 {
  123. nBytes := v.CopyChunk(b)
  124. return nBytes, nil
  125. }
  126. err := v.EnsureChunk()
  127. if err != nil {
  128. return 0, err
  129. }
  130. nBytes := v.CopyChunk(b)
  131. return nBytes, nil
  132. }
  133. type AuthenticationWriter struct {
  134. auth Authenticator
  135. buffer []byte
  136. writer io.Writer
  137. ivGen BytesGenerator
  138. extraGen BytesGenerator
  139. }
  140. func NewAuthenticationWriter(auth Authenticator, writer io.Writer) *AuthenticationWriter {
  141. return &AuthenticationWriter{
  142. auth: auth,
  143. buffer: make([]byte, 32*1024),
  144. writer: writer,
  145. }
  146. }
  147. func (v *AuthenticationWriter) Write(b []byte) (int, error) {
  148. cipherChunk, err := v.auth.Seal(v.buffer[2:], b)
  149. if err != nil {
  150. return 0, err
  151. }
  152. serial.Uint16ToBytes(uint16(len(cipherChunk)), b[:0])
  153. _, err = v.writer.Write(v.buffer[:2+len(cipherChunk)])
  154. return len(b), err
  155. }