config.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. package shadowsocks
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/md5"
  7. "crypto/sha1"
  8. "io"
  9. "strings"
  10. "golang.org/x/crypto/chacha20poly1305"
  11. "golang.org/x/crypto/hkdf"
  12. "github.com/v2fly/v2ray-core/v5/common"
  13. "github.com/v2fly/v2ray-core/v5/common/antireplay"
  14. "github.com/v2fly/v2ray-core/v5/common/buf"
  15. "github.com/v2fly/v2ray-core/v5/common/crypto"
  16. "github.com/v2fly/v2ray-core/v5/common/protocol"
  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. ReducedIVEntropy bool
  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 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 (a *Account) getCipher() (Cipher, error) {
  54. switch a.CipherType {
  55. case CipherType_AES_128_GCM:
  56. return &AEADCipher{
  57. KeyBytes: 16,
  58. IVBytes: 16,
  59. AEADAuthCreator: createAesGcm,
  60. }, nil
  61. case CipherType_AES_256_GCM:
  62. return &AEADCipher{
  63. KeyBytes: 32,
  64. IVBytes: 32,
  65. AEADAuthCreator: createAesGcm,
  66. }, nil
  67. case CipherType_CHACHA20_POLY1305:
  68. return &AEADCipher{
  69. KeyBytes: 32,
  70. IVBytes: 32,
  71. AEADAuthCreator: createChaCha20Poly1305,
  72. }, nil
  73. case CipherType_NONE:
  74. return NoneCipher{}, nil
  75. default:
  76. return nil, newError("Unsupported cipher.")
  77. }
  78. }
  79. // AsAccount implements protocol.AsAccount.
  80. func (a *Account) AsAccount() (protocol.Account, error) {
  81. Cipher, err := a.getCipher()
  82. if err != nil {
  83. return nil, newError("failed to get cipher").Base(err)
  84. }
  85. return &MemoryAccount{
  86. Cipher: Cipher,
  87. Key: passwordToCipherKey([]byte(a.Password), Cipher.KeySize()),
  88. replayFilter: func() antireplay.GeneralizedReplayFilter {
  89. if a.IvCheck {
  90. return antireplay.NewBloomRing()
  91. }
  92. return nil
  93. }(),
  94. ReducedIVEntropy: a.ExperimentReducedIvHeadEntropy,
  95. }, nil
  96. }
  97. // Cipher is an interface for all Shadowsocks ciphers.
  98. type Cipher interface {
  99. KeySize() int32
  100. IVSize() int32
  101. NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error)
  102. NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error)
  103. IsAEAD() bool
  104. EncodePacket(key []byte, b *buf.Buffer) error
  105. DecodePacket(key []byte, b *buf.Buffer) error
  106. }
  107. type AEADCipher struct {
  108. KeyBytes int32
  109. IVBytes int32
  110. AEADAuthCreator func(key []byte) cipher.AEAD
  111. }
  112. func (*AEADCipher) IsAEAD() bool {
  113. return true
  114. }
  115. func (c *AEADCipher) KeySize() int32 {
  116. return c.KeyBytes
  117. }
  118. func (c *AEADCipher) IVSize() int32 {
  119. return c.IVBytes
  120. }
  121. func (c *AEADCipher) createAuthenticator(key []byte, iv []byte) *crypto.AEADAuthenticator {
  122. nonce := crypto.GenerateInitialAEADNonce()
  123. subkey := make([]byte, c.KeyBytes)
  124. hkdfSHA1(key, iv, subkey)
  125. return &crypto.AEADAuthenticator{
  126. AEAD: c.AEADAuthCreator(subkey),
  127. NonceGenerator: nonce,
  128. }
  129. }
  130. func (c *AEADCipher) NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error) {
  131. auth := c.createAuthenticator(key, iv)
  132. return crypto.NewAuthenticationWriter(auth, &crypto.AEADChunkSizeParser{
  133. Auth: auth,
  134. }, writer, protocol.TransferTypeStream, nil), nil
  135. }
  136. func (c *AEADCipher) NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error) {
  137. auth := c.createAuthenticator(key, iv)
  138. return crypto.NewAuthenticationReader(auth, &crypto.AEADChunkSizeParser{
  139. Auth: auth,
  140. }, reader, protocol.TransferTypeStream, nil), nil
  141. }
  142. func (c *AEADCipher) EncodePacket(key []byte, b *buf.Buffer) error {
  143. ivLen := c.IVSize()
  144. payloadLen := b.Len()
  145. auth := c.createAuthenticator(key, b.BytesTo(ivLen))
  146. b.Extend(int32(auth.Overhead()))
  147. _, err := auth.Seal(b.BytesTo(ivLen), b.BytesRange(ivLen, payloadLen))
  148. return err
  149. }
  150. func (c *AEADCipher) DecodePacket(key []byte, b *buf.Buffer) error {
  151. if b.Len() <= c.IVSize() {
  152. return newError("insufficient data: ", b.Len())
  153. }
  154. ivLen := c.IVSize()
  155. payloadLen := b.Len()
  156. auth := c.createAuthenticator(key, b.BytesTo(ivLen))
  157. bbb, err := auth.Open(b.BytesTo(ivLen), b.BytesRange(ivLen, payloadLen))
  158. if err != nil {
  159. return err
  160. }
  161. b.Resize(ivLen, int32(len(bbb)))
  162. return nil
  163. }
  164. type NoneCipher struct{}
  165. func (NoneCipher) KeySize() int32 { return 0 }
  166. func (NoneCipher) IVSize() int32 { return 0 }
  167. func (NoneCipher) IsAEAD() bool {
  168. return false
  169. }
  170. func (NoneCipher) NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error) {
  171. return buf.NewReader(reader), nil
  172. }
  173. func (NoneCipher) NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error) {
  174. return buf.NewWriter(writer), nil
  175. }
  176. func (NoneCipher) EncodePacket(key []byte, b *buf.Buffer) error {
  177. return nil
  178. }
  179. func (NoneCipher) DecodePacket(key []byte, b *buf.Buffer) error {
  180. return nil
  181. }
  182. func CipherFromString(c string) CipherType {
  183. switch strings.ToLower(c) {
  184. case "aes-128-gcm", "aes_128_gcm", "aead_aes_128_gcm":
  185. return CipherType_AES_128_GCM
  186. case "aes-256-gcm", "aes_256_gcm", "aead_aes_256_gcm":
  187. return CipherType_AES_256_GCM
  188. case "chacha20-poly1305", "chacha20_poly1305", "aead_chacha20_poly1305", "chacha20-ietf-poly1305":
  189. return CipherType_CHACHA20_POLY1305
  190. case "none", "plain":
  191. return CipherType_NONE
  192. default:
  193. return CipherType_UNKNOWN
  194. }
  195. }
  196. func passwordToCipherKey(password []byte, keySize int32) []byte {
  197. key := make([]byte, 0, keySize)
  198. md5Sum := md5.Sum(password)
  199. key = append(key, md5Sum[:]...)
  200. for int32(len(key)) < keySize {
  201. md5Hash := md5.New()
  202. common.Must2(md5Hash.Write(md5Sum[:]))
  203. common.Must2(md5Hash.Write(password))
  204. md5Hash.Sum(md5Sum[:0])
  205. key = append(key, md5Sum[:]...)
  206. }
  207. return key
  208. }
  209. func hkdfSHA1(secret, salt, outKey []byte) {
  210. r := hkdf.New(sha1.New, secret, salt, []byte("ss-subkey"))
  211. common.Must2(io.ReadFull(r, outKey))
  212. }