protocol.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. "v2ray.com/core/proxy/socks"
  13. )
  14. const (
  15. Version = 1
  16. RequestOptionOneTimeAuth bitmask.Byte = 0x01
  17. AddrTypeIPv4 = 1
  18. AddrTypeIPv6 = 4
  19. AddrTypeDomain = 3
  20. )
  21. // ReadTCPSession reads a Shadowsocks TCP session from the given reader, returns its header and remaining parts.
  22. func ReadTCPSession(user *protocol.User, reader io.Reader) (*protocol.RequestHeader, buf.Reader, error) {
  23. rawAccount, err := user.GetTypedAccount()
  24. if err != nil {
  25. return nil, nil, newError("failed to parse account").Base(err).AtError()
  26. }
  27. account := rawAccount.(*MemoryAccount)
  28. buffer := buf.NewLocal(512)
  29. defer buffer.Release()
  30. ivLen := account.Cipher.IVSize()
  31. var iv []byte
  32. if ivLen > 0 {
  33. if err := buffer.AppendSupplier(buf.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.NewBufferedReader(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. if err := buffer.Reset(buf.ReadFullFrom(br, 1)); err != nil {
  51. return nil, nil, newError("failed to read address type").Base(err)
  52. }
  53. if !account.Cipher.IsAEAD() {
  54. if (buffer.Byte(0) & 0x10) == 0x10 {
  55. request.Option.Set(RequestOptionOneTimeAuth)
  56. }
  57. if request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Disabled {
  58. return nil, nil, newError("rejecting connection with OTA enabled, while server disables OTA")
  59. }
  60. if !request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Enabled {
  61. return nil, nil, newError("rejecting connection with OTA disabled, while server enables OTA")
  62. }
  63. }
  64. addrType := (buffer.Byte(0) & 0x0F)
  65. addr, port, err := socks.ReadAddress(buffer, addrType, br)
  66. if err != nil {
  67. // Invalid address. Continue to read some bytes to confuse client.
  68. nBytes := dice.Roll(32)
  69. buffer.Clear()
  70. buffer.AppendSupplier(buf.ReadFullFrom(br, nBytes))
  71. return nil, nil, newError("failed to read address").Base(err)
  72. }
  73. request.Address = addr
  74. request.Port = port
  75. if request.Option.Has(RequestOptionOneTimeAuth) {
  76. actualAuth := make([]byte, AuthSize)
  77. authenticator.Authenticate(buffer.Bytes())(actualAuth)
  78. err := buffer.AppendSupplier(buf.ReadFullFrom(br, AuthSize))
  79. if err != nil {
  80. return nil, nil, newError("Failed to read OTA").Base(err)
  81. }
  82. if !bytes.Equal(actualAuth, buffer.BytesFrom(-AuthSize)) {
  83. return nil, nil, newError("invalid OTA")
  84. }
  85. }
  86. if request.Address == nil {
  87. return nil, nil, newError("invalid remote address.")
  88. }
  89. br.SetBuffered(false)
  90. var chunkReader buf.Reader
  91. if request.Option.Has(RequestOptionOneTimeAuth) {
  92. chunkReader = NewChunkReader(br, NewAuthenticator(ChunkKeyGenerator(iv)))
  93. } else {
  94. chunkReader = buf.NewReader(br)
  95. }
  96. return request, chunkReader, nil
  97. }
  98. // WriteTCPRequest writes Shadowsocks request into the given writer, and returns a writer for body.
  99. func WriteTCPRequest(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
  100. user := request.User
  101. rawAccount, err := user.GetTypedAccount()
  102. if err != nil {
  103. return nil, newError("failed to parse account").Base(err).AtError()
  104. }
  105. account := rawAccount.(*MemoryAccount)
  106. if account.Cipher.IsAEAD() {
  107. request.Option.Clear(RequestOptionOneTimeAuth)
  108. }
  109. var iv []byte
  110. if account.Cipher.IVSize() > 0 {
  111. iv = make([]byte, account.Cipher.IVSize())
  112. common.Must2(rand.Read(iv))
  113. _, err = writer.Write(iv)
  114. if err != nil {
  115. return nil, newError("failed to write IV")
  116. }
  117. }
  118. w, err := account.Cipher.NewEncryptionWriter(account.Key, iv, writer)
  119. if err != nil {
  120. return nil, newError("failed to create encoding stream").Base(err).AtError()
  121. }
  122. header := buf.NewLocal(512)
  123. if err := socks.AppendAddress(header, request.Address, request.Port); err != nil {
  124. return nil, newError("failed to write address").Base(err)
  125. }
  126. if request.Option.Has(RequestOptionOneTimeAuth) {
  127. header.SetByte(0, header.Byte(0)|0x10)
  128. authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
  129. common.Must(header.AppendSupplier(authenticator.Authenticate(header.Bytes())))
  130. }
  131. if err := w.WriteMultiBuffer(buf.NewMultiBufferValue(header)); err != nil {
  132. return nil, newError("failed to write header").Base(err)
  133. }
  134. var chunkWriter buf.Writer
  135. if request.Option.Has(RequestOptionOneTimeAuth) {
  136. chunkWriter = NewChunkWriter(w.(io.Writer), NewAuthenticator(ChunkKeyGenerator(iv)))
  137. } else {
  138. chunkWriter = w
  139. }
  140. return chunkWriter, nil
  141. }
  142. func ReadTCPResponse(user *protocol.User, reader io.Reader) (buf.Reader, error) {
  143. rawAccount, err := user.GetTypedAccount()
  144. if err != nil {
  145. return nil, newError("failed to parse account").Base(err).AtError()
  146. }
  147. account := rawAccount.(*MemoryAccount)
  148. var iv []byte
  149. if account.Cipher.IVSize() > 0 {
  150. iv = make([]byte, account.Cipher.IVSize())
  151. _, err = io.ReadFull(reader, iv)
  152. if err != nil {
  153. return nil, newError("failed to read IV").Base(err)
  154. }
  155. }
  156. return account.Cipher.NewDecryptionReader(account.Key, iv, reader)
  157. }
  158. func WriteTCPResponse(request *protocol.RequestHeader, writer io.Writer) (buf.Writer, error) {
  159. user := request.User
  160. rawAccount, err := user.GetTypedAccount()
  161. if err != nil {
  162. return nil, newError("failed to parse account.").Base(err).AtError()
  163. }
  164. account := rawAccount.(*MemoryAccount)
  165. var iv []byte
  166. if account.Cipher.IVSize() > 0 {
  167. iv = make([]byte, account.Cipher.IVSize())
  168. common.Must2(rand.Read(iv))
  169. _, err = writer.Write(iv)
  170. if err != nil {
  171. return nil, newError("failed to write IV.").Base(err)
  172. }
  173. }
  174. return account.Cipher.NewEncryptionWriter(account.Key, iv, writer)
  175. }
  176. func EncodeUDPPacket(request *protocol.RequestHeader, payload []byte) (*buf.Buffer, error) {
  177. user := request.User
  178. rawAccount, err := user.GetTypedAccount()
  179. if err != nil {
  180. return nil, newError("failed to parse account.").Base(err).AtError()
  181. }
  182. account := rawAccount.(*MemoryAccount)
  183. buffer := buf.New()
  184. ivLen := account.Cipher.IVSize()
  185. if ivLen > 0 {
  186. common.Must(buffer.Reset(buf.ReadFullFrom(rand.Reader, ivLen)))
  187. }
  188. iv := buffer.Bytes()
  189. if err := socks.AppendAddress(buffer, request.Address, request.Port); err != nil {
  190. return nil, newError("failed to write address").Base(err)
  191. }
  192. buffer.Append(payload)
  193. if !account.Cipher.IsAEAD() && request.Option.Has(RequestOptionOneTimeAuth) {
  194. authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
  195. buffer.SetByte(ivLen, buffer.Byte(ivLen)|0x10)
  196. common.Must(buffer.AppendSupplier(authenticator.Authenticate(buffer.BytesFrom(ivLen))))
  197. }
  198. if err := account.Cipher.EncodePacket(account.Key, buffer); err != nil {
  199. return nil, newError("failed to encrypt UDP payload").Base(err)
  200. }
  201. return buffer, nil
  202. }
  203. func DecodeUDPPacket(user *protocol.User, payload *buf.Buffer) (*protocol.RequestHeader, *buf.Buffer, error) {
  204. rawAccount, err := user.GetTypedAccount()
  205. if err != nil {
  206. return nil, nil, newError("failed to parse account").Base(err).AtError()
  207. }
  208. account := rawAccount.(*MemoryAccount)
  209. var iv []byte
  210. if !account.Cipher.IsAEAD() && account.Cipher.IVSize() > 0 {
  211. // Keep track of IV as it gets removed from payload in DecodePacket.
  212. iv = make([]byte, account.Cipher.IVSize())
  213. copy(iv, payload.BytesTo(account.Cipher.IVSize()))
  214. }
  215. if err := account.Cipher.DecodePacket(account.Key, payload); err != nil {
  216. return nil, nil, newError("failed to decrypt UDP payload").Base(err)
  217. }
  218. request := &protocol.RequestHeader{
  219. Version: Version,
  220. User: user,
  221. Command: protocol.RequestCommandUDP,
  222. }
  223. if !account.Cipher.IsAEAD() {
  224. if (payload.Byte(0) & 0x10) == 0x10 {
  225. request.Option |= RequestOptionOneTimeAuth
  226. }
  227. if request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Disabled {
  228. return nil, nil, newError("rejecting packet with OTA enabled, while server disables OTA").AtWarning()
  229. }
  230. if !request.Option.Has(RequestOptionOneTimeAuth) && account.OneTimeAuth == Account_Enabled {
  231. return nil, nil, newError("rejecting packet with OTA disabled, while server enables OTA").AtWarning()
  232. }
  233. if request.Option.Has(RequestOptionOneTimeAuth) {
  234. payloadLen := payload.Len() - AuthSize
  235. authBytes := payload.BytesFrom(payloadLen)
  236. authenticator := NewAuthenticator(HeaderKeyGenerator(account.Key, iv))
  237. actualAuth := make([]byte, AuthSize)
  238. authenticator.Authenticate(payload.BytesTo(payloadLen))(actualAuth)
  239. if !bytes.Equal(actualAuth, authBytes) {
  240. return nil, nil, newError("invalid OTA")
  241. }
  242. payload.Slice(0, payloadLen)
  243. }
  244. }
  245. addrType := (payload.Byte(0) & 0x0F)
  246. payload.SliceFrom(1)
  247. switch addrType {
  248. case AddrTypeIPv4:
  249. request.Address = net.IPAddress(payload.BytesTo(4))
  250. payload.SliceFrom(4)
  251. case AddrTypeIPv6:
  252. request.Address = net.IPAddress(payload.BytesTo(16))
  253. payload.SliceFrom(16)
  254. case AddrTypeDomain:
  255. domainLength := int(payload.Byte(0))
  256. request.Address = net.DomainAddress(string(payload.BytesRange(1, 1+domainLength)))
  257. payload.SliceFrom(1 + domainLength)
  258. default:
  259. return nil, nil, newError("unknown address type: ", addrType).AtError()
  260. }
  261. request.Port = net.PortFromBytes(payload.BytesTo(2))
  262. payload.SliceFrom(2)
  263. return request, payload, nil
  264. }
  265. type UDPReader struct {
  266. Reader io.Reader
  267. User *protocol.User
  268. }
  269. func (v *UDPReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
  270. buffer := buf.New()
  271. err := buffer.AppendSupplier(buf.ReadFrom(v.Reader))
  272. if err != nil {
  273. buffer.Release()
  274. return nil, err
  275. }
  276. _, payload, err := DecodeUDPPacket(v.User, buffer)
  277. if err != nil {
  278. buffer.Release()
  279. return nil, err
  280. }
  281. return buf.NewMultiBufferValue(payload), nil
  282. }
  283. type UDPWriter struct {
  284. Writer io.Writer
  285. Request *protocol.RequestHeader
  286. }
  287. // Write implements io.Writer.
  288. func (w *UDPWriter) Write(payload []byte) (int, error) {
  289. packet, err := EncodeUDPPacket(w.Request, payload)
  290. if err != nil {
  291. return 0, err
  292. }
  293. _, err = w.Writer.Write(packet.Bytes())
  294. packet.Release()
  295. return len(payload), err
  296. }