config.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. package shadowsocks
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/md5"
  7. "crypto/sha1"
  8. "io"
  9. "github.com/xtls/xray-core/common"
  10. "github.com/xtls/xray-core/common/antireplay"
  11. "github.com/xtls/xray-core/common/buf"
  12. "github.com/xtls/xray-core/common/crypto"
  13. "github.com/xtls/xray-core/common/protocol"
  14. "golang.org/x/crypto/chacha20poly1305"
  15. "golang.org/x/crypto/hkdf"
  16. )
  17. // MemoryAccount is an account type converted from Account.
  18. type MemoryAccount struct {
  19. Cipher Cipher
  20. Key []byte
  21. replayFilter antireplay.GeneralizedReplayFilter
  22. }
  23. var ErrIVNotUnique = newError("IV is not unique")
  24. // Equals implements protocol.Account.Equals().
  25. func (a *MemoryAccount) Equals(another protocol.Account) bool {
  26. if account, ok := another.(*MemoryAccount); ok {
  27. return bytes.Equal(a.Key, account.Key)
  28. }
  29. return false
  30. }
  31. func (a *MemoryAccount) CheckIV(iv []byte) error {
  32. if a.replayFilter == nil {
  33. return nil
  34. }
  35. if a.replayFilter.Check(iv) {
  36. return nil
  37. }
  38. return ErrIVNotUnique
  39. }
  40. func createAesGcm(key []byte) cipher.AEAD {
  41. block, err := aes.NewCipher(key)
  42. common.Must(err)
  43. gcm, err := cipher.NewGCM(block)
  44. common.Must(err)
  45. return gcm
  46. }
  47. func createChaCha20Poly1305(key []byte) cipher.AEAD {
  48. ChaChaPoly1305, err := chacha20poly1305.New(key)
  49. common.Must(err)
  50. return ChaChaPoly1305
  51. }
  52. func createXChaCha20Poly1305(key []byte) cipher.AEAD {
  53. XChaChaPoly1305, err := chacha20poly1305.NewX(key)
  54. common.Must(err)
  55. return XChaChaPoly1305
  56. }
  57. func (a *Account) getCipher() (Cipher, error) {
  58. switch a.CipherType {
  59. case CipherType_AES_128_GCM:
  60. return &AEADCipher{
  61. KeyBytes: 16,
  62. IVBytes: 16,
  63. AEADAuthCreator: createAesGcm,
  64. }, nil
  65. case CipherType_AES_256_GCM:
  66. return &AEADCipher{
  67. KeyBytes: 32,
  68. IVBytes: 32,
  69. AEADAuthCreator: createAesGcm,
  70. }, nil
  71. case CipherType_CHACHA20_POLY1305:
  72. return &AEADCipher{
  73. KeyBytes: 32,
  74. IVBytes: 32,
  75. AEADAuthCreator: createChaCha20Poly1305,
  76. }, nil
  77. case CipherType_XCHACHA20_POLY1305:
  78. return &AEADCipher{
  79. KeyBytes: 32,
  80. IVBytes: 32,
  81. AEADAuthCreator: createXChaCha20Poly1305,
  82. }, nil
  83. case CipherType_NONE:
  84. return NoneCipher{}, nil
  85. default:
  86. return nil, newError("Unsupported cipher.")
  87. }
  88. }
  89. // AsAccount implements protocol.AsAccount.
  90. func (a *Account) AsAccount() (protocol.Account, error) {
  91. Cipher, err := a.getCipher()
  92. if err != nil {
  93. return nil, newError("failed to get cipher").Base(err)
  94. }
  95. return &MemoryAccount{
  96. Cipher: Cipher,
  97. Key: passwordToCipherKey([]byte(a.Password), Cipher.KeySize()),
  98. replayFilter: func() antireplay.GeneralizedReplayFilter {
  99. if a.IvCheck {
  100. return antireplay.NewBloomRing()
  101. }
  102. return nil
  103. }(),
  104. }, nil
  105. }
  106. // Cipher is an interface for all Shadowsocks ciphers.
  107. type Cipher interface {
  108. KeySize() int32
  109. IVSize() int32
  110. NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error)
  111. NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error)
  112. IsAEAD() bool
  113. EncodePacket(key []byte, b *buf.Buffer) error
  114. DecodePacket(key []byte, b *buf.Buffer) error
  115. }
  116. type AEADCipher struct {
  117. KeyBytes int32
  118. IVBytes int32
  119. AEADAuthCreator func(key []byte) cipher.AEAD
  120. }
  121. func (*AEADCipher) IsAEAD() bool {
  122. return true
  123. }
  124. func (c *AEADCipher) KeySize() int32 {
  125. return c.KeyBytes
  126. }
  127. func (c *AEADCipher) IVSize() int32 {
  128. return c.IVBytes
  129. }
  130. func (c *AEADCipher) createAuthenticator(key []byte, iv []byte) *crypto.AEADAuthenticator {
  131. subkey := make([]byte, c.KeyBytes)
  132. hkdfSHA1(key, iv, subkey)
  133. aead := c.AEADAuthCreator(subkey)
  134. nonce := crypto.GenerateAEADNonceWithSize(aead.NonceSize())
  135. return &crypto.AEADAuthenticator{
  136. AEAD: aead,
  137. NonceGenerator: nonce,
  138. }
  139. }
  140. func (c *AEADCipher) NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error) {
  141. auth := c.createAuthenticator(key, iv)
  142. return crypto.NewAuthenticationWriter(auth, &crypto.AEADChunkSizeParser{
  143. Auth: auth,
  144. }, writer, protocol.TransferTypeStream, nil), nil
  145. }
  146. func (c *AEADCipher) NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error) {
  147. auth := c.createAuthenticator(key, iv)
  148. return crypto.NewAuthenticationReader(auth, &crypto.AEADChunkSizeParser{
  149. Auth: auth,
  150. }, reader, protocol.TransferTypeStream, nil), nil
  151. }
  152. func (c *AEADCipher) EncodePacket(key []byte, b *buf.Buffer) error {
  153. ivLen := c.IVSize()
  154. payloadLen := b.Len()
  155. auth := c.createAuthenticator(key, b.BytesTo(ivLen))
  156. b.Extend(int32(auth.Overhead()))
  157. _, err := auth.Seal(b.BytesTo(ivLen), b.BytesRange(ivLen, payloadLen))
  158. return err
  159. }
  160. func (c *AEADCipher) DecodePacket(key []byte, b *buf.Buffer) error {
  161. if b.Len() <= c.IVSize() {
  162. return newError("insufficient data: ", b.Len())
  163. }
  164. ivLen := c.IVSize()
  165. payloadLen := b.Len()
  166. auth := c.createAuthenticator(key, b.BytesTo(ivLen))
  167. bbb, err := auth.Open(b.BytesTo(ivLen), b.BytesRange(ivLen, payloadLen))
  168. if err != nil {
  169. return err
  170. }
  171. b.Resize(ivLen, int32(len(bbb)))
  172. return nil
  173. }
  174. type NoneCipher struct{}
  175. func (NoneCipher) KeySize() int32 { return 0 }
  176. func (NoneCipher) IVSize() int32 { return 0 }
  177. func (NoneCipher) IsAEAD() bool {
  178. return false
  179. }
  180. func (NoneCipher) NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error) {
  181. return buf.NewReader(reader), nil
  182. }
  183. func (NoneCipher) NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error) {
  184. return buf.NewWriter(writer), nil
  185. }
  186. func (NoneCipher) EncodePacket(key []byte, b *buf.Buffer) error {
  187. return nil
  188. }
  189. func (NoneCipher) DecodePacket(key []byte, b *buf.Buffer) error {
  190. return nil
  191. }
  192. func passwordToCipherKey(password []byte, keySize int32) []byte {
  193. key := make([]byte, 0, keySize)
  194. md5Sum := md5.Sum(password)
  195. key = append(key, md5Sum[:]...)
  196. for int32(len(key)) < keySize {
  197. md5Hash := md5.New()
  198. common.Must2(md5Hash.Write(md5Sum[:]))
  199. common.Must2(md5Hash.Write(password))
  200. md5Hash.Sum(md5Sum[:0])
  201. key = append(key, md5Sum[:]...)
  202. }
  203. return key
  204. }
  205. func hkdfSHA1(secret, salt, outKey []byte) {
  206. r := hkdf.New(sha1.New, secret, salt, []byte("ss-subkey"))
  207. common.Must2(io.ReadFull(r, outKey))
  208. }