protocol.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. // +build !confonly
  2. package shadowsocks
  3. import (
  4. "bytes"
  5. "crypto/hmac"
  6. "crypto/rand"
  7. "crypto/sha256"
  8. "hash"
  9. "hash/crc32"
  10. "io"
  11. "io/ioutil"
  12. "v2ray.com/core/common/dice"
  13. "v2ray.com/core/common"
  14. "v2ray.com/core/common/bitmask"
  15. "v2ray.com/core/common/buf"
  16. "v2ray.com/core/common/net"
  17. "v2ray.com/core/common/protocol"
  18. )
  19. const (
  20. Version = 1
  21. RequestOptionOneTimeAuth bitmask.Byte = 0x01
  22. )
  23. var addrParser = protocol.NewAddressParser(
  24. protocol.AddressFamilyByte(0x01, net.AddressFamilyIPv4),
  25. protocol.AddressFamilyByte(0x04, net.AddressFamilyIPv6),
  26. protocol.AddressFamilyByte(0x03, net.AddressFamilyDomain),
  27. protocol.WithAddressTypeParser(func(b byte) byte {
  28. return b & 0x0F
  29. }),
  30. )
  31. // ReadTCPSession reads a Shadowsocks TCP session from the given reader, returns its header and remaining parts.
  32. func ReadTCPSession(user *protocol.MemoryUser, reader io.Reader) (*protocol.RequestHeader, buf.Reader, error) {
  33. account := user.Account.(*MemoryAccount)
  34. hashkdf := hmac.New(func()hash.Hash{return sha256.New()}, []byte("SSBSKDF"))
  35. hashkdf.Write(account.Key)
  36. behaviorSeed := crc32.ChecksumIEEE(hashkdf.Sum(nil))
  37. behaviorRand := dice.NewDeterministicDice(int64(behaviorSeed))
  38. BaseDrainSize := behaviorRand.Roll(3266)
  39. RandDrainMax := behaviorRand.Roll(64) + 1
  40. RandDrainRolled := dice.Roll(RandDrainMax)
  41. DrainSize := BaseDrainSize + 16 + 38 + RandDrainRolled
  42. readSizeRemain := DrainSize
  43. buffer := buf.New()
  44. defer buffer.Release()
  45. ivLen := account.Cipher.IVSize()
  46. var iv []byte
  47. if ivLen > 0 {
  48. if _, err := buffer.ReadFullFrom(reader, ivLen); err != nil {
  49. readSizeRemain -= int(buffer.Len())
  50. DrainConnN(reader,readSizeRemain)
  51. return nil, nil, newError("failed to read IV").Base(err)
  52. }
  53. iv = append([]byte(nil), buffer.BytesTo(ivLen)...)
  54. }
  55. r, err := account.Cipher.NewDecryptionReader(account.Key, iv, reader)
  56. if err != nil {
  57. readSizeRemain -= int(buffer.Len())
  58. DrainConnN(reader,readSizeRemain)
  59. return nil, nil, newError("failed to initialize decoding stream").Base(err).AtError()
  60. }
  61. br := &buf.BufferedReader{Reader: r}
  62. authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
  63. request := &protocol.RequestHeader{
  64. Version: Version,
  65. User: user,
  66. Command: protocol.RequestCommandTCP,
  67. }
  68. readSizeRemain -= int(buffer.Len())
  69. buffer.Clear()
  70. addr, port, err := addrParser.ReadAddressPort(buffer, br)
  71. if err != nil {
  72. readSizeRemain -= int(buffer.Len())
  73. DrainConnN(reader,readSizeRemain)
  74. return nil, nil, newError("failed to read address").Base(err)
  75. }
  76. request.Address = addr
  77. request.Port = port
  78. if !account.Cipher.IsAEAD() {
  79. if (buffer.Byte(0) & 0x10) == 0x10 {
  80. request.Option.Set(RequestOptionOneTimeAuth)
  81. }
  82. if request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Disabled {
  83. readSizeRemain -= int(buffer.Len())
  84. DrainConnN(reader,readSizeRemain)
  85. return nil, nil, newError("rejecting connection with OTA enabled, while server disables OTA")
  86. }
  87. if !request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Enabled {
  88. readSizeRemain -= int(buffer.Len())
  89. DrainConnN(reader,readSizeRemain)
  90. return nil, nil, newError("rejecting connection with OTA disabled, while server enables OTA")
  91. }
  92. }
  93. if request.Option.Has(RequestOptionOneTimeAuth) {
  94. actualAuth := make([]byte, AuthSize)
  95. authenticator.Authenticate(buffer.Bytes(), actualAuth)
  96. _, err := buffer.ReadFullFrom(br, AuthSize)
  97. if err != nil {
  98. readSizeRemain -= int(buffer.Len())
  99. DrainConnN(reader,readSizeRemain)
  100. return nil, nil, newError("Failed to read OTA").Base(err)
  101. }
  102. if !bytes.Equal(actualAuth, buffer.BytesFrom(-AuthSize)) {
  103. readSizeRemain -= int(buffer.Len())
  104. DrainConnN(reader,readSizeRemain)
  105. return nil, nil, newError("invalid OTA")
  106. }
  107. }
  108. if request.Address == nil {
  109. readSizeRemain -= int(buffer.Len())
  110. DrainConnN(reader,readSizeRemain)
  111. return nil, nil, newError("invalid remote address.")
  112. }
  113. var chunkReader buf.Reader
  114. if request.Option.Has(RequestOptionOneTimeAuth) {
  115. chunkReader = NewChunkReader(br, NewAuthenticator(ChunkKeyGenerator(iv)))
  116. } else {
  117. chunkReader = buf.NewReader(br)
  118. }
  119. return request, chunkReader, nil
  120. }
  121. func DrainConnN(reader io.Reader, n int) error {
  122. _, err := io.CopyN(ioutil.Discard, reader, int64(n))
  123. return err
  124. }
  125. // WriteTCPRequest writes Shadowsocks request into the given writer, and returns a writer for body.
  126. func WriteTCPRequest(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
  127. user := request.User
  128. account := user.Account.(*MemoryAccount)
  129. if account.Cipher.IsAEAD() {
  130. request.Option.Clear(RequestOptionOneTimeAuth)
  131. }
  132. var iv []byte
  133. if account.Cipher.IVSize() > 0 {
  134. iv = make([]byte, account.Cipher.IVSize())
  135. common.Must2(rand.Read(iv))
  136. if err := buf.WriteAllBytes(writer, iv); err != nil {
  137. return nil, newError("failed to write IV")
  138. }
  139. }
  140. w, err := account.Cipher.NewEncryptionWriter(account.Key, iv, writer)
  141. if err != nil {
  142. return nil, newError("failed to create encoding stream").Base(err).AtError()
  143. }
  144. header := buf.New()
  145. if err := addrParser.WriteAddressPort(header, request.Address, request.Port); err != nil {
  146. return nil, newError("failed to write address").Base(err)
  147. }
  148. if request.Option.Has(RequestOptionOneTimeAuth) {
  149. header.SetByte(0, header.Byte(0)|0x10)
  150. authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
  151. authPayload := header.Bytes()
  152. authBuffer := header.Extend(AuthSize)
  153. authenticator.Authenticate(authPayload, authBuffer)
  154. }
  155. if err := w.WriteMultiBuffer(buf.MultiBuffer{header}); err != nil {
  156. return nil, newError("failed to write header").Base(err)
  157. }
  158. var chunkWriter buf.Writer
  159. if request.Option.Has(RequestOptionOneTimeAuth) {
  160. chunkWriter = NewChunkWriter(w.(io.Writer), NewAuthenticator(ChunkKeyGenerator(iv)))
  161. } else {
  162. chunkWriter = w
  163. }
  164. return chunkWriter, nil
  165. }
  166. func ReadTCPResponse(user *protocol.MemoryUser, reader io.Reader) (buf.Reader, error) {
  167. account := user.Account.(*MemoryAccount)
  168. var iv []byte
  169. if account.Cipher.IVSize() > 0 {
  170. iv = make([]byte, account.Cipher.IVSize())
  171. if _, err := io.ReadFull(reader, iv); err != nil {
  172. return nil, newError("failed to read IV").Base(err)
  173. }
  174. }
  175. return account.Cipher.NewDecryptionReader(account.Key, iv, reader)
  176. }
  177. func WriteTCPResponse(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
  178. user := request.User
  179. account := user.Account.(*MemoryAccount)
  180. var iv []byte
  181. if account.Cipher.IVSize() > 0 {
  182. iv = make([]byte, account.Cipher.IVSize())
  183. common.Must2(rand.Read(iv))
  184. if err := buf.WriteAllBytes(writer, iv); err != nil {
  185. return nil, newError("failed to write IV.").Base(err)
  186. }
  187. }
  188. return account.Cipher.NewEncryptionWriter(account.Key, iv, writer)
  189. }
  190. func EncodeUDPPacket(request *protocol.RequestHeader, payload []byte) (*buf.Buffer, error) {
  191. user := request.User
  192. account := user.Account.(*MemoryAccount)
  193. buffer := buf.New()
  194. ivLen := account.Cipher.IVSize()
  195. if ivLen > 0 {
  196. common.Must2(buffer.ReadFullFrom(rand.Reader, ivLen))
  197. }
  198. iv := buffer.Bytes()
  199. if err := addrParser.WriteAddressPort(buffer, request.Address, request.Port); err != nil {
  200. return nil, newError("failed to write address").Base(err)
  201. }
  202. buffer.Write(payload)
  203. if !account.Cipher.IsAEAD() && request.Option.Has(RequestOptionOneTimeAuth) {
  204. authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
  205. buffer.SetByte(ivLen, buffer.Byte(ivLen)|0x10)
  206. authPayload := buffer.BytesFrom(ivLen)
  207. authBuffer := buffer.Extend(AuthSize)
  208. authenticator.Authenticate(authPayload, authBuffer)
  209. }
  210. if err := account.Cipher.EncodePacket(account.Key, buffer); err != nil {
  211. return nil, newError("failed to encrypt UDP payload").Base(err)
  212. }
  213. return buffer, nil
  214. }
  215. func DecodeUDPPacket(user *protocol.MemoryUser, payload *buf.Buffer) (*protocol.RequestHeader, *buf.Buffer, error) {
  216. account := user.Account.(*MemoryAccount)
  217. var iv []byte
  218. if !account.Cipher.IsAEAD() && account.Cipher.IVSize() > 0 {
  219. // Keep track of IV as it gets removed from payload in DecodePacket.
  220. iv = make([]byte, account.Cipher.IVSize())
  221. copy(iv, payload.BytesTo(account.Cipher.IVSize()))
  222. }
  223. if err := account.Cipher.DecodePacket(account.Key, payload); err != nil {
  224. return nil, nil, newError("failed to decrypt UDP payload").Base(err)
  225. }
  226. request := &protocol.RequestHeader{
  227. Version: Version,
  228. User: user,
  229. Command: protocol.RequestCommandUDP,
  230. }
  231. if !account.Cipher.IsAEAD() {
  232. if (payload.Byte(0) & 0x10) == 0x10 {
  233. request.Option |= RequestOptionOneTimeAuth
  234. }
  235. if request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Disabled {
  236. return nil, nil, newError("rejecting packet with OTA enabled, while server disables OTA").AtWarning()
  237. }
  238. if !request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Enabled {
  239. return nil, nil, newError("rejecting packet with OTA disabled, while server enables OTA").AtWarning()
  240. }
  241. if request.Option.Has(RequestOptionOneTimeAuth) {
  242. payloadLen := payload.Len() - AuthSize
  243. authBytes := payload.BytesFrom(payloadLen)
  244. authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
  245. actualAuth := make([]byte, AuthSize)
  246. authenticator.Authenticate(payload.BytesTo(payloadLen), actualAuth)
  247. if !bytes.Equal(actualAuth, authBytes) {
  248. return nil, nil, newError("invalid OTA")
  249. }
  250. payload.Resize(0, payloadLen)
  251. }
  252. }
  253. payload.SetByte(0, payload.Byte(0)&0x0F)
  254. addr, port, err := addrParser.ReadAddressPort(nil, payload)
  255. if err != nil {
  256. return nil, nil, newError("failed to parse address").Base(err)
  257. }
  258. request.Address = addr
  259. request.Port = port
  260. return request, payload, nil
  261. }
  262. type UDPReader struct {
  263. Reader io.Reader
  264. User *protocol.MemoryUser
  265. }
  266. func (v *UDPReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  267. buffer := buf.New()
  268. _, err := buffer.ReadFrom(v.Reader)
  269. if err != nil {
  270. buffer.Release()
  271. return nil, err
  272. }
  273. _, payload, err := DecodeUDPPacket(v.User, buffer)
  274. if err != nil {
  275. buffer.Release()
  276. return nil, err
  277. }
  278. return buf.MultiBuffer{payload}, nil
  279. }
  280. type UDPWriter struct {
  281. Writer io.Writer
  282. Request *protocol.RequestHeader
  283. }
  284. // Write implements io.Writer.
  285. func (w *UDPWriter) Write(payload []byte) (int, error) {
  286. packet, err := EncodeUDPPacket(w.Request, payload)
  287. if err != nil {
  288. return 0, err
  289. }
  290. _, err = w.Writer.Write(packet.Bytes())
  291. packet.Release()
  292. return len(payload), err
  293. }