config.go 6.5 KB

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