protocol.go 9.0 KB

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