config.go 5.7 KB

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