protocol.go 9.9 KB

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