udp.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package server
  20. import (
  21. "bytes"
  22. "encoding/binary"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "net"
  27. "runtime/debug"
  28. "sync"
  29. "sync/atomic"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh"
  32. )
  33. // handleUDPChannel implements UDP port forwarding. A single UDP
  34. // SSH channel follows the udpgw protocol, which multiplexes many
  35. // UDP port forwards.
  36. //
  37. // The udpgw protocol and original server implementation:
  38. // Copyright (c) 2009, Ambroz Bizjak <ambrop7@gmail.com>
  39. // https://github.com/ambrop72/badvpn
  40. //
  41. func (sshClient *sshClient) handleUDPChannel(newChannel ssh.NewChannel) {
  42. // Accept this channel immediately. This channel will replace any
  43. // previously existing UDP channel for this client.
  44. sshChannel, requests, err := newChannel.Accept()
  45. if err != nil {
  46. if !isExpectedTunnelIOError(err) {
  47. log.WithContextFields(LogFields{"error": err}).Warning("accept new channel failed")
  48. }
  49. return
  50. }
  51. go ssh.DiscardRequests(requests)
  52. defer sshChannel.Close()
  53. sshClient.setUDPChannel(sshChannel)
  54. multiplexer := &udpPortForwardMultiplexer{
  55. sshClient: sshClient,
  56. sshChannel: sshChannel,
  57. portForwards: make(map[uint16]*udpPortForward),
  58. portForwardLRU: common.NewLRUConns(),
  59. relayWaitGroup: new(sync.WaitGroup),
  60. }
  61. multiplexer.run()
  62. }
  63. type udpPortForwardMultiplexer struct {
  64. sshClient *sshClient
  65. sshChannelWriteMutex sync.Mutex
  66. sshChannel ssh.Channel
  67. portForwardsMutex sync.Mutex
  68. portForwards map[uint16]*udpPortForward
  69. portForwardLRU *common.LRUConns
  70. relayWaitGroup *sync.WaitGroup
  71. }
  72. func (mux *udpPortForwardMultiplexer) run() {
  73. // In a loop, read udpgw messages from the client to this channel. Each message is
  74. // a UDP packet to send upstream either via a new port forward, or on an existing
  75. // port forward.
  76. //
  77. // A goroutine is run to read downstream packets for each UDP port forward. All read
  78. // packets are encapsulated in udpgw protocol and sent down the channel to the client.
  79. //
  80. // When the client disconnects or the server shuts down, the channel will close and
  81. // readUdpgwMessage will exit with EOF.
  82. // Recover from and log any unexpected panics caused by udpgw input handling bugs.
  83. // Note: this covers the run() goroutine only and not relayDownstream() goroutines.
  84. defer func() {
  85. if e := recover(); e != nil {
  86. err := common.ContextError(
  87. fmt.Errorf(
  88. "udpPortForwardMultiplexer panic: %s: %s", e, debug.Stack()))
  89. log.WithContextFields(LogFields{"error": err}).Warning("run failed")
  90. }
  91. }()
  92. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  93. for {
  94. // Note: message.packet points to the reusable memory in "buffer".
  95. // Each readUdpgwMessage call will overwrite the last message.packet.
  96. message, err := readUdpgwMessage(mux.sshChannel, buffer)
  97. if err != nil {
  98. if err != io.EOF {
  99. // Debug since I/O errors occur during normal operation
  100. log.WithContextFields(LogFields{"error": err}).Debug("readUdpgwMessage failed")
  101. }
  102. break
  103. }
  104. mux.portForwardsMutex.Lock()
  105. portForward := mux.portForwards[message.connID]
  106. mux.portForwardsMutex.Unlock()
  107. if portForward != nil && message.discardExistingConn {
  108. // The port forward's goroutine will complete cleanup, including
  109. // tallying stats and calling sshClient.closedPortForward.
  110. // portForward.conn.Close() will signal this shutdown.
  111. // TODO: wait for goroutine to exit before proceeding?
  112. portForward.conn.Close()
  113. portForward = nil
  114. }
  115. if portForward != nil {
  116. // Verify that portForward remote address matches latest message
  117. if 0 != bytes.Compare(portForward.remoteIP, message.remoteIP) ||
  118. portForward.remotePort != message.remotePort {
  119. log.WithContext().Warning("UDP port forward remote address mismatch")
  120. continue
  121. }
  122. } else {
  123. // Create a new port forward
  124. dialIP := net.IP(message.remoteIP)
  125. dialPort := int(message.remotePort)
  126. // Transparent DNS forwarding
  127. if message.forwardDNS {
  128. dialIP = mux.sshClient.sshServer.support.DNSResolver.Get()
  129. dialPort = DNS_RESOLVER_PORT
  130. }
  131. if !mux.sshClient.isPortForwardPermitted(
  132. portForwardTypeUDP, message.forwardDNS, dialIP, int(message.remotePort)) {
  133. // The udpgw protocol has no error response, so
  134. // we just discard the message and read another.
  135. continue
  136. }
  137. // Note: UDP port forward counting has no dialing phase
  138. // establishedPortForward increments the concurrent UDP port
  139. // forward counter and closes the LRU existing UDP port forward
  140. // when already at the limit.
  141. mux.sshClient.establishedPortForward(portForwardTypeUDP, mux.portForwardLRU)
  142. // Can't defer sshClient.closedPortForward() here;
  143. // relayDownstream will call sshClient.closedPortForward()
  144. log.WithContextFields(
  145. LogFields{
  146. "remoteAddr": fmt.Sprintf("%s:%d", dialIP.String(), dialPort),
  147. "connID": message.connID}).Debug("dialing")
  148. udpConn, err := net.DialUDP(
  149. "udp", nil, &net.UDPAddr{IP: dialIP, Port: dialPort})
  150. if err != nil {
  151. mux.sshClient.closedPortForward(portForwardTypeUDP, 0, 0)
  152. // Monitor for low resource error conditions
  153. mux.sshClient.sshServer.monitorPortForwardDialError(err)
  154. // Note: Debug level, as logMessage may contain user traffic destination address information
  155. log.WithContextFields(LogFields{"error": err}).Debug("DialUDP failed")
  156. continue
  157. }
  158. lruEntry := mux.portForwardLRU.Add(udpConn)
  159. // Can't defer lruEntry.Remove() here;
  160. // relayDownstream will call lruEntry.Remove()
  161. // ActivityMonitoredConn monitors the TCP port forward I/O and updates
  162. // its LRU status. ActivityMonitoredConn also times out I/O on the port
  163. // forward if both reads and writes have been idle for the specified
  164. // duration.
  165. // Ensure nil interface if newClientSeedPortForward returns nil
  166. var updater common.ActivityUpdater
  167. seedUpdater := mux.sshClient.newClientSeedPortForward(dialIP)
  168. if seedUpdater != nil {
  169. updater = seedUpdater
  170. }
  171. conn, err := common.NewActivityMonitoredConn(
  172. udpConn,
  173. mux.sshClient.idleUDPPortForwardTimeout(),
  174. true,
  175. updater,
  176. lruEntry)
  177. if err != nil {
  178. lruEntry.Remove()
  179. mux.sshClient.closedPortForward(portForwardTypeUDP, 0, 0)
  180. log.WithContextFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  181. continue
  182. }
  183. portForward = &udpPortForward{
  184. connID: message.connID,
  185. preambleSize: message.preambleSize,
  186. remoteIP: message.remoteIP,
  187. remotePort: message.remotePort,
  188. conn: conn,
  189. lruEntry: lruEntry,
  190. bytesUp: 0,
  191. bytesDown: 0,
  192. mux: mux,
  193. }
  194. mux.portForwardsMutex.Lock()
  195. mux.portForwards[portForward.connID] = portForward
  196. mux.portForwardsMutex.Unlock()
  197. mux.relayWaitGroup.Add(1)
  198. go portForward.relayDownstream()
  199. }
  200. // Note: assumes UDP writes won't block (https://golang.org/pkg/net/#UDPConn.WriteToUDP)
  201. _, err = portForward.conn.Write(message.packet)
  202. if err != nil {
  203. // Debug since errors such as "write: operation not permitted" occur during normal operation
  204. log.WithContextFields(LogFields{"error": err}).Debug("upstream UDP relay failed")
  205. // The port forward's goroutine will complete cleanup
  206. portForward.conn.Close()
  207. }
  208. portForward.lruEntry.Touch()
  209. atomic.AddInt64(&portForward.bytesUp, int64(len(message.packet)))
  210. }
  211. // Cleanup all UDP port forward workers when exiting
  212. mux.portForwardsMutex.Lock()
  213. for _, portForward := range mux.portForwards {
  214. // The port forward's goroutine will complete cleanup
  215. portForward.conn.Close()
  216. }
  217. mux.portForwardsMutex.Unlock()
  218. mux.relayWaitGroup.Wait()
  219. }
  220. func (mux *udpPortForwardMultiplexer) removePortForward(connID uint16) {
  221. mux.portForwardsMutex.Lock()
  222. delete(mux.portForwards, connID)
  223. mux.portForwardsMutex.Unlock()
  224. }
  225. type udpPortForward struct {
  226. // Note: 64-bit ints used with atomic operations are placed
  227. // at the start of struct to ensure 64-bit alignment.
  228. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  229. bytesUp int64
  230. bytesDown int64
  231. connID uint16
  232. preambleSize int
  233. remoteIP []byte
  234. remotePort uint16
  235. conn net.Conn
  236. lruEntry *common.LRUConnsEntry
  237. mux *udpPortForwardMultiplexer
  238. }
  239. func (portForward *udpPortForward) relayDownstream() {
  240. defer portForward.mux.relayWaitGroup.Done()
  241. // Downstream UDP packets are read into the reusable memory
  242. // in "buffer" starting at the offset past the udpgw message
  243. // header and address, leaving enough space to write the udpgw
  244. // values into the same buffer and use for writing to the ssh
  245. // channel.
  246. //
  247. // Note: there is one downstream buffer per UDP port forward,
  248. // while for upstream there is one buffer per client.
  249. // TODO: is the buffer size larger than necessary?
  250. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  251. packetBuffer := buffer[portForward.preambleSize:udpgwProtocolMaxMessageSize]
  252. for {
  253. // TODO: if read buffer is too small, excess bytes are discarded?
  254. packetSize, err := portForward.conn.Read(packetBuffer)
  255. if packetSize > udpgwProtocolMaxPayloadSize {
  256. err = fmt.Errorf("unexpected packet size: %d", packetSize)
  257. }
  258. if err != nil {
  259. if err != io.EOF {
  260. // Debug since errors such as "use of closed network connection" occur during normal operation
  261. log.WithContextFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  262. }
  263. break
  264. }
  265. err = writeUdpgwPreamble(
  266. portForward.preambleSize,
  267. 0,
  268. portForward.connID,
  269. portForward.remoteIP,
  270. portForward.remotePort,
  271. uint16(packetSize),
  272. buffer)
  273. if err == nil {
  274. // ssh.Channel.Write cannot be called concurrently.
  275. // See: https://github.com/Psiphon-Inc/crypto/blob/82d98b4c7c05e81f92545f6fddb45d4541e6da00/ssh/channel.go#L272,
  276. // https://codereview.appspot.com/136420043/diff/80002/ssh/channel.go
  277. portForward.mux.sshChannelWriteMutex.Lock()
  278. _, err = portForward.mux.sshChannel.Write(buffer[0 : portForward.preambleSize+packetSize])
  279. portForward.mux.sshChannelWriteMutex.Unlock()
  280. }
  281. if err != nil {
  282. // Close the channel, which will interrupt the main loop.
  283. portForward.mux.sshChannel.Close()
  284. log.WithContextFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  285. break
  286. }
  287. portForward.lruEntry.Touch()
  288. atomic.AddInt64(&portForward.bytesDown, int64(packetSize))
  289. }
  290. portForward.mux.removePortForward(portForward.connID)
  291. portForward.lruEntry.Remove()
  292. portForward.conn.Close()
  293. bytesUp := atomic.LoadInt64(&portForward.bytesUp)
  294. bytesDown := atomic.LoadInt64(&portForward.bytesDown)
  295. portForward.mux.sshClient.closedPortForward(portForwardTypeUDP, bytesUp, bytesDown)
  296. log.WithContextFields(
  297. LogFields{
  298. "remoteAddr": fmt.Sprintf("%s:%d",
  299. net.IP(portForward.remoteIP).String(), portForward.remotePort),
  300. "bytesUp": bytesUp,
  301. "bytesDown": bytesDown,
  302. "connID": portForward.connID}).Debug("exiting")
  303. }
  304. // TODO: express and/or calculate udpgwProtocolMaxPayloadSize as function of MTU?
  305. const (
  306. udpgwProtocolFlagKeepalive = 1 << 0
  307. udpgwProtocolFlagRebind = 1 << 1
  308. udpgwProtocolFlagDNS = 1 << 2
  309. udpgwProtocolFlagIPv6 = 1 << 3
  310. udpgwProtocolMaxPreambleSize = 23
  311. udpgwProtocolMaxPayloadSize = 32768
  312. udpgwProtocolMaxMessageSize = udpgwProtocolMaxPreambleSize + udpgwProtocolMaxPayloadSize
  313. )
  314. type udpgwProtocolMessage struct {
  315. connID uint16
  316. preambleSize int
  317. remoteIP []byte
  318. remotePort uint16
  319. discardExistingConn bool
  320. forwardDNS bool
  321. packet []byte
  322. }
  323. func readUdpgwMessage(
  324. reader io.Reader, buffer []byte) (*udpgwProtocolMessage, error) {
  325. // udpgw message layout:
  326. //
  327. // | 2 byte size | 3 byte header | 6 or 18 byte address | variable length packet |
  328. for {
  329. // Read message
  330. _, err := io.ReadFull(reader, buffer[0:2])
  331. if err != nil {
  332. if err != io.EOF {
  333. err = common.ContextError(err)
  334. }
  335. return nil, err
  336. }
  337. size := binary.LittleEndian.Uint16(buffer[0:2])
  338. if size < 3 || int(size) > len(buffer)-2 {
  339. return nil, common.ContextError(errors.New("invalid udpgw message size"))
  340. }
  341. _, err = io.ReadFull(reader, buffer[2:2+size])
  342. if err != nil {
  343. if err != io.EOF {
  344. err = common.ContextError(err)
  345. }
  346. return nil, err
  347. }
  348. flags := buffer[2]
  349. connID := binary.LittleEndian.Uint16(buffer[3:5])
  350. // Ignore udpgw keep-alive messages -- read another message
  351. if flags&udpgwProtocolFlagKeepalive == udpgwProtocolFlagKeepalive {
  352. continue
  353. }
  354. // Read address
  355. var remoteIP []byte
  356. var remotePort uint16
  357. var packetStart, packetEnd int
  358. if flags&udpgwProtocolFlagIPv6 == udpgwProtocolFlagIPv6 {
  359. if size < 21 {
  360. return nil, common.ContextError(errors.New("invalid udpgw message size"))
  361. }
  362. remoteIP = make([]byte, 16)
  363. copy(remoteIP, buffer[5:21])
  364. remotePort = binary.BigEndian.Uint16(buffer[21:23])
  365. packetStart = 23
  366. packetEnd = 23 + int(size) - 21
  367. } else {
  368. if size < 9 {
  369. return nil, common.ContextError(errors.New("invalid udpgw message size"))
  370. }
  371. remoteIP = make([]byte, 4)
  372. copy(remoteIP, buffer[5:9])
  373. remotePort = binary.BigEndian.Uint16(buffer[9:11])
  374. packetStart = 11
  375. packetEnd = 11 + int(size) - 9
  376. }
  377. // Assemble message
  378. // Note: udpgwProtocolMessage.packet references memory in the input buffer
  379. message := &udpgwProtocolMessage{
  380. connID: connID,
  381. preambleSize: packetStart,
  382. remoteIP: remoteIP,
  383. remotePort: remotePort,
  384. discardExistingConn: flags&udpgwProtocolFlagRebind == udpgwProtocolFlagRebind,
  385. forwardDNS: flags&udpgwProtocolFlagDNS == udpgwProtocolFlagDNS,
  386. packet: buffer[packetStart:packetEnd],
  387. }
  388. return message, nil
  389. }
  390. }
  391. func writeUdpgwPreamble(
  392. preambleSize int,
  393. flags uint8,
  394. connID uint16,
  395. remoteIP []byte,
  396. remotePort uint16,
  397. packetSize uint16,
  398. buffer []byte) error {
  399. if preambleSize != 7+len(remoteIP) {
  400. return common.ContextError(errors.New("invalid udpgw preamble size"))
  401. }
  402. size := uint16(preambleSize-2) + packetSize
  403. // size
  404. binary.LittleEndian.PutUint16(buffer[0:2], size)
  405. // flags
  406. buffer[2] = flags
  407. // connID
  408. binary.LittleEndian.PutUint16(buffer[3:5], connID)
  409. // addr
  410. copy(buffer[5:5+len(remoteIP)], remoteIP)
  411. binary.BigEndian.PutUint16(buffer[5+len(remoteIP):7+len(remoteIP)], remotePort)
  412. return nil
  413. }