config.go 6.1 KB

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