protocol.go 9.0 KB

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