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. "io"
  9. "reflect"
  10. "strconv"
  11. "golang.org/x/crypto/chacha20poly1305"
  12. "golang.org/x/crypto/hkdf"
  13. "github.com/xtls/xray-core/common"
  14. "github.com/xtls/xray-core/common/buf"
  15. "github.com/xtls/xray-core/common/crypto"
  16. "github.com/xtls/xray-core/common/protocol"
  17. )
  18. // MemoryAccount is an account type converted from Account.
  19. type MemoryAccount struct {
  20. Cipher Cipher
  21. Key []byte
  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) GetCipherName() string {
  31. switch a.Cipher.(type) {
  32. case *AEADCipher:
  33. switch reflect.ValueOf(a.Cipher.(*AEADCipher).AEADAuthCreator).Pointer() {
  34. case reflect.ValueOf(createAesGcm).Pointer():
  35. keyBytes := a.Cipher.(*AEADCipher).KeyBytes
  36. return "AES_" + strconv.FormatInt(int64(keyBytes*8), 10) + "_GCM"
  37. case reflect.ValueOf(createChaCha20Poly1305).Pointer():
  38. return "CHACHA20_POLY1305"
  39. }
  40. case *NoneCipher:
  41. return "NONE"
  42. }
  43. return ""
  44. }
  45. func createAesGcm(key []byte) cipher.AEAD {
  46. block, err := aes.NewCipher(key)
  47. common.Must(err)
  48. gcm, err := cipher.NewGCM(block)
  49. common.Must(err)
  50. return gcm
  51. }
  52. func createChaCha20Poly1305(key []byte) cipher.AEAD {
  53. ChaChaPoly1305, err := chacha20poly1305.New(key)
  54. common.Must(err)
  55. return ChaChaPoly1305
  56. }
  57. func (a *Account) getCipher() (Cipher, error) {
  58. switch a.CipherType {
  59. case CipherType_AES_128_GCM:
  60. return &AEADCipher{
  61. KeyBytes: 16,
  62. IVBytes: 16,
  63. AEADAuthCreator: createAesGcm,
  64. }, nil
  65. case CipherType_AES_256_GCM:
  66. return &AEADCipher{
  67. KeyBytes: 32,
  68. IVBytes: 32,
  69. AEADAuthCreator: createAesGcm,
  70. }, nil
  71. case CipherType_CHACHA20_POLY1305:
  72. return &AEADCipher{
  73. KeyBytes: 32,
  74. IVBytes: 32,
  75. AEADAuthCreator: createChaCha20Poly1305,
  76. }, nil
  77. case CipherType_NONE:
  78. return NoneCipher{}, nil
  79. default:
  80. return nil, newError("Unsupported cipher.")
  81. }
  82. }
  83. // AsAccount implements protocol.AsAccount.
  84. func (a *Account) AsAccount() (protocol.Account, error) {
  85. Cipher, err := a.getCipher()
  86. if err != nil {
  87. return nil, newError("failed to get cipher").Base(err)
  88. }
  89. return &MemoryAccount{
  90. Cipher: Cipher,
  91. Key: passwordToCipherKey([]byte(a.Password), Cipher.KeySize()),
  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. }