protocol.go 9.0 KB

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