protocol.go 9.9 KB

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