protocol.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. var chunkReader buf.Reader
  86. if request.Option.Has(RequestOptionOneTimeAuth) {
  87. chunkReader = NewChunkReader(br, NewAuthenticator(ChunkKeyGenerator(iv)))
  88. } else {
  89. chunkReader = buf.NewReader(br)
  90. }
  91. return request, chunkReader, nil
  92. }
  93. // WriteTCPRequest writes Shadowsocks request into the given writer, and returns a writer for body.
  94. func WriteTCPRequest(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
  95. user := request.User
  96. rawAccount, err := user.GetTypedAccount()
  97. if err != nil {
  98. return nil, newError("failed to parse account").Base(err).AtError()
  99. }
  100. account := rawAccount.(*MemoryAccount)
  101. if account.Cipher.IsAEAD() {
  102. request.Option.Clear(RequestOptionOneTimeAuth)
  103. }
  104. var iv []byte
  105. if account.Cipher.IVSize() > 0 {
  106. iv = make([]byte, account.Cipher.IVSize())
  107. common.Must2(rand.Read(iv))
  108. if err := buf.WriteAllBytes(writer, iv); err != nil {
  109. return nil, newError("failed to write IV")
  110. }
  111. }
  112. w, err := account.Cipher.NewEncryptionWriter(account.Key, iv, writer)
  113. if err != nil {
  114. return nil, newError("failed to create encoding stream").Base(err).AtError()
  115. }
  116. header := buf.New()
  117. if err := addrParser.WriteAddressPort(header, request.Address, request.Port); err != nil {
  118. return nil, newError("failed to write address").Base(err)
  119. }
  120. if request.Option.Has(RequestOptionOneTimeAuth) {
  121. header.SetByte(0, header.Byte(0)|0x10)
  122. authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
  123. common.Must(header.AppendSupplier(authenticator.Authenticate(header.Bytes())))
  124. }
  125. if err := w.WriteMultiBuffer(buf.NewMultiBufferValue(header)); err != nil {
  126. return nil, newError("failed to write header").Base(err)
  127. }
  128. var chunkWriter buf.Writer
  129. if request.Option.Has(RequestOptionOneTimeAuth) {
  130. chunkWriter = NewChunkWriter(w.(io.Writer), NewAuthenticator(ChunkKeyGenerator(iv)))
  131. } else {
  132. chunkWriter = w
  133. }
  134. return chunkWriter, nil
  135. }
  136. func ReadTCPResponse(user *protocol.User, reader io.Reader) (buf.Reader, error) {
  137. rawAccount, err := user.GetTypedAccount()
  138. if err != nil {
  139. return nil, newError("failed to parse account").Base(err).AtError()
  140. }
  141. account := rawAccount.(*MemoryAccount)
  142. var iv []byte
  143. if account.Cipher.IVSize() > 0 {
  144. iv = make([]byte, account.Cipher.IVSize())
  145. if _, err = io.ReadFull(reader, iv); err != nil {
  146. return nil, newError("failed to read IV").Base(err)
  147. }
  148. }
  149. return account.Cipher.NewDecryptionReader(account.Key, iv, reader)
  150. }
  151. func WriteTCPResponse(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
  152. user := request.User
  153. rawAccount, err := user.GetTypedAccount()
  154. if err != nil {
  155. return nil, newError("failed to parse account.").Base(err).AtError()
  156. }
  157. account := rawAccount.(*MemoryAccount)
  158. var iv []byte
  159. if account.Cipher.IVSize() > 0 {
  160. iv = make([]byte, account.Cipher.IVSize())
  161. common.Must2(rand.Read(iv))
  162. if err := buf.WriteAllBytes(writer, iv); err != nil {
  163. return nil, newError("failed to write IV.").Base(err)
  164. }
  165. }
  166. return account.Cipher.NewEncryptionWriter(account.Key, iv, writer)
  167. }
  168. func EncodeUDPPacket(request *protocol.RequestHeader, payload []byte) (*buf.Buffer, error) {
  169. user := request.User
  170. rawAccount, err := user.GetTypedAccount()
  171. if err != nil {
  172. return nil, newError("failed to parse account.").Base(err).AtError()
  173. }
  174. account := rawAccount.(*MemoryAccount)
  175. buffer := buf.New()
  176. ivLen := account.Cipher.IVSize()
  177. if ivLen > 0 {
  178. common.Must(buffer.Reset(buf.ReadFullFrom(rand.Reader, ivLen)))
  179. }
  180. iv := buffer.Bytes()
  181. if err := addrParser.WriteAddressPort(buffer, request.Address, request.Port); err != nil {
  182. return nil, newError("failed to write address").Base(err)
  183. }
  184. buffer.Write(payload)
  185. if !account.Cipher.IsAEAD() && request.Option.Has(RequestOptionOneTimeAuth) {
  186. authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
  187. buffer.SetByte(ivLen, buffer.Byte(ivLen)|0x10)
  188. common.Must(buffer.AppendSupplier(authenticator.Authenticate(buffer.BytesFrom(ivLen))))
  189. }
  190. if err := account.Cipher.EncodePacket(account.Key, buffer); err != nil {
  191. return nil, newError("failed to encrypt UDP payload").Base(err)
  192. }
  193. return buffer, nil
  194. }
  195. func DecodeUDPPacket(user *protocol.User, payload *buf.Buffer) (*protocol.RequestHeader, *buf.Buffer, error) {
  196. rawAccount, err := user.GetTypedAccount()
  197. if err != nil {
  198. return nil, nil, newError("failed to parse account").Base(err).AtError()
  199. }
  200. account := rawAccount.(*MemoryAccount)
  201. var iv []byte
  202. if !account.Cipher.IsAEAD() && account.Cipher.IVSize() > 0 {
  203. // Keep track of IV as it gets removed from payload in DecodePacket.
  204. iv = make([]byte, account.Cipher.IVSize())
  205. copy(iv, payload.BytesTo(account.Cipher.IVSize()))
  206. }
  207. if err := account.Cipher.DecodePacket(account.Key, payload); err != nil {
  208. return nil, nil, newError("failed to decrypt UDP payload").Base(err)
  209. }
  210. request := &protocol.RequestHeader{
  211. Version: Version,
  212. User: user,
  213. Command: protocol.RequestCommandUDP,
  214. }
  215. if !account.Cipher.IsAEAD() {
  216. if (payload.Byte(0) & 0x10) == 0x10 {
  217. request.Option |= RequestOptionOneTimeAuth
  218. }
  219. if request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Disabled {
  220. return nil, nil, newError("rejecting packet with OTA enabled, while server disables OTA").AtWarning()
  221. }
  222. if !request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Enabled {
  223. return nil, nil, newError("rejecting packet with OTA disabled, while server enables OTA").AtWarning()
  224. }
  225. if request.Option.Has(RequestOptionOneTimeAuth) {
  226. payloadLen := payload.Len() - AuthSize
  227. authBytes := payload.BytesFrom(payloadLen)
  228. authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
  229. actualAuth := make([]byte, AuthSize)
  230. common.Must2(authenticator.Authenticate(payload.BytesTo(payloadLen))(actualAuth))
  231. if !bytes.Equal(actualAuth, authBytes) {
  232. return nil, nil, newError("invalid OTA")
  233. }
  234. payload.Resize(0, payloadLen)
  235. }
  236. }
  237. payload.SetByte(0, payload.Byte(0)&0x0F)
  238. addr, port, err := addrParser.ReadAddressPort(nil, payload)
  239. if err != nil {
  240. return nil, nil, newError("failed to parse address").Base(err)
  241. }
  242. request.Address = addr
  243. request.Port = port
  244. return request, payload, nil
  245. }
  246. type UDPReader struct {
  247. Reader io.Reader
  248. User *protocol.User
  249. }
  250. func (v *UDPReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  251. buffer := buf.New()
  252. err := buffer.AppendSupplier(buf.ReadFrom(v.Reader))
  253. if err != nil {
  254. buffer.Release()
  255. return nil, err
  256. }
  257. _, payload, err := DecodeUDPPacket(v.User, buffer)
  258. if err != nil {
  259. buffer.Release()
  260. return nil, err
  261. }
  262. return buf.NewMultiBufferValue(payload), nil
  263. }
  264. type UDPWriter struct {
  265. Writer io.Writer
  266. Request *protocol.RequestHeader
  267. }
  268. // Write implements io.Writer.
  269. func (w *UDPWriter) Write(payload []byte) (int, error) {
  270. packet, err := EncodeUDPPacket(w.Request, payload)
  271. if err != nil {
  272. return 0, err
  273. }
  274. _, err = w.Writer.Write(packet.Bytes())
  275. packet.Release()
  276. return len(payload), err
  277. }