config.go 6.1 KB

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