protocol.go 9.0 KB

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