config.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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 *AesCfb:
  33. keyBytes := a.Cipher.(*AesCfb).KeyBytes
  34. return "AES_" + strconv.FormatInt(int64(keyBytes*8), 10) + "_CFB"
  35. case *ChaCha20:
  36. if a.Cipher.(*ChaCha20).IVBytes == 8 {
  37. return "CHACHA20"
  38. }
  39. return "CHACHA20_IETF"
  40. case *AEADCipher:
  41. switch reflect.ValueOf(a.Cipher.(*AEADCipher).AEADAuthCreator).Pointer() {
  42. case reflect.ValueOf(createAesGcm).Pointer():
  43. keyBytes := a.Cipher.(*AEADCipher).KeyBytes
  44. return "AES_" + strconv.FormatInt(int64(keyBytes*8), 10) + "_GCM"
  45. case reflect.ValueOf(createChacha20Poly1305).Pointer():
  46. return "CHACHA20_POLY1305"
  47. }
  48. case *NoneCipher:
  49. return "NONE"
  50. }
  51. return ""
  52. }
  53. func createAesGcm(key []byte) cipher.AEAD {
  54. block, err := aes.NewCipher(key)
  55. common.Must(err)
  56. gcm, err := cipher.NewGCM(block)
  57. common.Must(err)
  58. return gcm
  59. }
  60. func createChacha20Poly1305(key []byte) cipher.AEAD {
  61. chacha20, err := chacha20poly1305.New(key)
  62. common.Must(err)
  63. return chacha20
  64. }
  65. func (a *Account) getCipher() (Cipher, error) {
  66. switch a.CipherType {
  67. case CipherType_AES_128_CFB:
  68. return &AesCfb{KeyBytes: 16}, nil
  69. case CipherType_AES_256_CFB:
  70. return &AesCfb{KeyBytes: 32}, nil
  71. case CipherType_CHACHA20:
  72. return &ChaCha20{IVBytes: 8}, nil
  73. case CipherType_CHACHA20_IETF:
  74. return &ChaCha20{IVBytes: 12}, nil
  75. case CipherType_AES_128_GCM:
  76. return &AEADCipher{
  77. KeyBytes: 16,
  78. IVBytes: 16,
  79. AEADAuthCreator: createAesGcm,
  80. }, nil
  81. case CipherType_AES_256_GCM:
  82. return &AEADCipher{
  83. KeyBytes: 32,
  84. IVBytes: 32,
  85. AEADAuthCreator: createAesGcm,
  86. }, nil
  87. case CipherType_CHACHA20_POLY1305:
  88. return &AEADCipher{
  89. KeyBytes: 32,
  90. IVBytes: 32,
  91. AEADAuthCreator: createChacha20Poly1305,
  92. }, nil
  93. case CipherType_NONE:
  94. return NoneCipher{}, nil
  95. default:
  96. return nil, newError("Unsupported cipher.")
  97. }
  98. }
  99. // AsAccount implements protocol.AsAccount.
  100. func (a *Account) AsAccount() (protocol.Account, error) {
  101. cipher, err := a.getCipher()
  102. if err != nil {
  103. return nil, newError("failed to get cipher").Base(err)
  104. }
  105. return &MemoryAccount{
  106. Cipher: cipher,
  107. Key: passwordToCipherKey([]byte(a.Password), cipher.KeySize()),
  108. }, nil
  109. }
  110. // Cipher is an interface for all Shadowsocks ciphers.
  111. type Cipher interface {
  112. KeySize() int32
  113. IVSize() int32
  114. NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error)
  115. NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error)
  116. IsAEAD() bool
  117. EncodePacket(key []byte, b *buf.Buffer) error
  118. DecodePacket(key []byte, b *buf.Buffer) error
  119. }
  120. // AesCfb represents all AES-CFB ciphers.
  121. type AesCfb struct {
  122. KeyBytes int32
  123. }
  124. func (*AesCfb) IsAEAD() bool {
  125. return false
  126. }
  127. func (v *AesCfb) KeySize() int32 {
  128. return v.KeyBytes
  129. }
  130. func (v *AesCfb) IVSize() int32 {
  131. return 16
  132. }
  133. func (v *AesCfb) NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error) {
  134. stream := crypto.NewAesEncryptionStream(key, iv)
  135. return &buf.SequentialWriter{Writer: crypto.NewCryptionWriter(stream, writer)}, nil
  136. }
  137. func (v *AesCfb) NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error) {
  138. stream := crypto.NewAesDecryptionStream(key, iv)
  139. return &buf.SingleReader{
  140. Reader: crypto.NewCryptionReader(stream, reader),
  141. }, nil
  142. }
  143. func (v *AesCfb) EncodePacket(key []byte, b *buf.Buffer) error {
  144. iv := b.BytesTo(v.IVSize())
  145. stream := crypto.NewAesEncryptionStream(key, iv)
  146. stream.XORKeyStream(b.BytesFrom(v.IVSize()), b.BytesFrom(v.IVSize()))
  147. return nil
  148. }
  149. func (v *AesCfb) DecodePacket(key []byte, b *buf.Buffer) error {
  150. if b.Len() <= v.IVSize() {
  151. return newError("insufficient data: ", b.Len())
  152. }
  153. iv := b.BytesTo(v.IVSize())
  154. stream := crypto.NewAesDecryptionStream(key, iv)
  155. stream.XORKeyStream(b.BytesFrom(v.IVSize()), b.BytesFrom(v.IVSize()))
  156. b.Advance(v.IVSize())
  157. return nil
  158. }
  159. type AEADCipher struct {
  160. KeyBytes int32
  161. IVBytes int32
  162. AEADAuthCreator func(key []byte) cipher.AEAD
  163. }
  164. func (*AEADCipher) IsAEAD() bool {
  165. return true
  166. }
  167. func (c *AEADCipher) KeySize() int32 {
  168. return c.KeyBytes
  169. }
  170. func (c *AEADCipher) IVSize() int32 {
  171. return c.IVBytes
  172. }
  173. func (c *AEADCipher) createAuthenticator(key []byte, iv []byte) *crypto.AEADAuthenticator {
  174. nonce := crypto.GenerateInitialAEADNonce()
  175. subkey := make([]byte, c.KeyBytes)
  176. hkdfSHA1(key, iv, subkey)
  177. return &crypto.AEADAuthenticator{
  178. AEAD: c.AEADAuthCreator(subkey),
  179. NonceGenerator: nonce,
  180. }
  181. }
  182. func (c *AEADCipher) NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error) {
  183. auth := c.createAuthenticator(key, iv)
  184. return crypto.NewAuthenticationWriter(auth, &crypto.AEADChunkSizeParser{
  185. Auth: auth,
  186. }, writer, protocol.TransferTypeStream, nil), nil
  187. }
  188. func (c *AEADCipher) NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error) {
  189. auth := c.createAuthenticator(key, iv)
  190. return crypto.NewAuthenticationReader(auth, &crypto.AEADChunkSizeParser{
  191. Auth: auth,
  192. }, reader, protocol.TransferTypeStream, nil), nil
  193. }
  194. func (c *AEADCipher) EncodePacket(key []byte, b *buf.Buffer) error {
  195. ivLen := c.IVSize()
  196. payloadLen := b.Len()
  197. auth := c.createAuthenticator(key, b.BytesTo(ivLen))
  198. b.Extend(int32(auth.Overhead()))
  199. _, err := auth.Seal(b.BytesTo(ivLen), b.BytesRange(ivLen, payloadLen))
  200. return err
  201. }
  202. func (c *AEADCipher) DecodePacket(key []byte, b *buf.Buffer) error {
  203. if b.Len() <= c.IVSize() {
  204. return newError("insufficient data: ", b.Len())
  205. }
  206. ivLen := c.IVSize()
  207. payloadLen := b.Len()
  208. auth := c.createAuthenticator(key, b.BytesTo(ivLen))
  209. bbb, err := auth.Open(b.BytesTo(ivLen), b.BytesRange(ivLen, payloadLen))
  210. if err != nil {
  211. return err
  212. }
  213. b.Resize(ivLen, int32(len(bbb)))
  214. return nil
  215. }
  216. type ChaCha20 struct {
  217. IVBytes int32
  218. }
  219. func (*ChaCha20) IsAEAD() bool {
  220. return false
  221. }
  222. func (v *ChaCha20) KeySize() int32 {
  223. return 32
  224. }
  225. func (v *ChaCha20) IVSize() int32 {
  226. return v.IVBytes
  227. }
  228. func (v *ChaCha20) NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error) {
  229. stream := crypto.NewChaCha20Stream(key, iv)
  230. return &buf.SequentialWriter{Writer: crypto.NewCryptionWriter(stream, writer)}, nil
  231. }
  232. func (v *ChaCha20) NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error) {
  233. stream := crypto.NewChaCha20Stream(key, iv)
  234. return &buf.SingleReader{Reader: crypto.NewCryptionReader(stream, reader)}, nil
  235. }
  236. func (v *ChaCha20) EncodePacket(key []byte, b *buf.Buffer) error {
  237. iv := b.BytesTo(v.IVSize())
  238. stream := crypto.NewChaCha20Stream(key, iv)
  239. stream.XORKeyStream(b.BytesFrom(v.IVSize()), b.BytesFrom(v.IVSize()))
  240. return nil
  241. }
  242. func (v *ChaCha20) DecodePacket(key []byte, b *buf.Buffer) error {
  243. if b.Len() <= v.IVSize() {
  244. return newError("insufficient data: ", b.Len())
  245. }
  246. iv := b.BytesTo(v.IVSize())
  247. stream := crypto.NewChaCha20Stream(key, iv)
  248. stream.XORKeyStream(b.BytesFrom(v.IVSize()), b.BytesFrom(v.IVSize()))
  249. b.Advance(v.IVSize())
  250. return nil
  251. }
  252. type NoneCipher struct{}
  253. func (NoneCipher) KeySize() int32 { return 0 }
  254. func (NoneCipher) IVSize() int32 { return 0 }
  255. func (NoneCipher) IsAEAD() bool {
  256. return true // to avoid OTA
  257. }
  258. func (NoneCipher) NewDecryptionReader(key []byte, iv []byte, reader io.Reader) (buf.Reader, error) {
  259. return buf.NewReader(reader), nil
  260. }
  261. func (NoneCipher) NewEncryptionWriter(key []byte, iv []byte, writer io.Writer) (buf.Writer, error) {
  262. return buf.NewWriter(writer), nil
  263. }
  264. func (NoneCipher) EncodePacket(key []byte, b *buf.Buffer) error {
  265. return nil
  266. }
  267. func (NoneCipher) DecodePacket(key []byte, b *buf.Buffer) error {
  268. return nil
  269. }
  270. func passwordToCipherKey(password []byte, keySize int32) []byte {
  271. key := make([]byte, 0, keySize)
  272. md5Sum := md5.Sum(password)
  273. key = append(key, md5Sum[:]...)
  274. for int32(len(key)) < keySize {
  275. md5Hash := md5.New()
  276. common.Must2(md5Hash.Write(md5Sum[:]))
  277. common.Must2(md5Hash.Write(password))
  278. md5Hash.Sum(md5Sum[:0])
  279. key = append(key, md5Sum[:]...)
  280. }
  281. return key
  282. }
  283. func hkdfSHA1(secret, salt, outkey []byte) {
  284. r := hkdf.New(sha1.New, secret, salt, []byte("ss-subkey"))
  285. common.Must2(io.ReadFull(r, outkey))
  286. }