config.go 6.4 KB

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