config.go 6.3 KB

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