config.go 6.5 KB

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