protocol.go 9.8 KB

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