udp.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. "fmt"
  24. "io"
  25. "net"
  26. "runtime/debug"
  27. "sync"
  28. "sync/atomic"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  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.WithTraceFields(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 := errors.Tracef(
  87. "udpPortForwardMultiplexer panic: %s: %s", e, debug.Stack())
  88. log.WithTraceFields(LogFields{"error": err}).Warning("run failed")
  89. }
  90. }()
  91. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  92. for {
  93. // Note: message.packet points to the reusable memory in "buffer".
  94. // Each readUdpgwMessage call will overwrite the last message.packet.
  95. message, err := readUdpgwMessage(mux.sshChannel, buffer)
  96. if err != nil {
  97. if err != io.EOF {
  98. // Debug since I/O errors occur during normal operation
  99. log.WithTraceFields(LogFields{"error": err}).Debug("readUdpgwMessage failed")
  100. }
  101. break
  102. }
  103. mux.portForwardsMutex.Lock()
  104. portForward := mux.portForwards[message.connID]
  105. mux.portForwardsMutex.Unlock()
  106. if portForward != nil && message.discardExistingConn {
  107. // The port forward's goroutine will complete cleanup, including
  108. // tallying stats and calling sshClient.closedPortForward.
  109. // portForward.conn.Close() will signal this shutdown.
  110. // TODO: wait for goroutine to exit before proceeding?
  111. portForward.conn.Close()
  112. portForward = nil
  113. }
  114. if portForward != nil {
  115. // Verify that portForward remote address matches latest message
  116. if !bytes.Equal(portForward.remoteIP, message.remoteIP) ||
  117. portForward.remotePort != message.remotePort {
  118. log.WithTrace().Warning("UDP port forward remote address mismatch")
  119. continue
  120. }
  121. } else {
  122. // Create a new port forward
  123. dialIP := net.IP(message.remoteIP)
  124. dialPort := int(message.remotePort)
  125. if message.forwardDNS {
  126. // Transparent DNS forwarding. In this case, traffic rules
  127. // checks are bypassed, since DNS is essential.
  128. dialIP = mux.sshClient.sshServer.support.DNSResolver.Get()
  129. dialPort = DNS_RESOLVER_PORT
  130. } else if !mux.sshClient.isPortForwardPermitted(
  131. portForwardTypeUDP, dialIP, int(message.remotePort)) {
  132. // The udpgw protocol has no error response, so
  133. // we just discard the message and read another.
  134. continue
  135. }
  136. // Note: UDP port forward counting has no dialing phase
  137. // establishedPortForward increments the concurrent UDP port
  138. // forward counter and closes the LRU existing UDP port forward
  139. // when already at the limit.
  140. mux.sshClient.establishedPortForward(portForwardTypeUDP, mux.portForwardLRU)
  141. // Can't defer sshClient.closedPortForward() here;
  142. // relayDownstream will call sshClient.closedPortForward()
  143. log.WithTraceFields(
  144. LogFields{
  145. "remoteAddr": fmt.Sprintf("%s:%d", dialIP.String(), dialPort),
  146. "connID": message.connID}).Debug("dialing")
  147. udpConn, err := net.DialUDP(
  148. "udp", nil, &net.UDPAddr{IP: dialIP, Port: dialPort})
  149. if err != nil {
  150. mux.sshClient.closedPortForward(portForwardTypeUDP, 0, 0)
  151. // Monitor for low resource error conditions
  152. mux.sshClient.sshServer.monitorPortForwardDialError(err)
  153. // Note: Debug level, as logMessage may contain user traffic destination address information
  154. log.WithTraceFields(LogFields{"error": err}).Debug("DialUDP failed")
  155. continue
  156. }
  157. lruEntry := mux.portForwardLRU.Add(udpConn)
  158. // Can't defer lruEntry.Remove() here;
  159. // relayDownstream will call lruEntry.Remove()
  160. // ActivityMonitoredConn monitors the TCP port forward I/O and updates
  161. // its LRU status. ActivityMonitoredConn also times out I/O on the port
  162. // forward if both reads and writes have been idle for the specified
  163. // duration.
  164. // Ensure nil interface if newClientSeedPortForward returns nil
  165. var updater common.ActivityUpdater
  166. seedUpdater := mux.sshClient.newClientSeedPortForward(dialIP)
  167. if seedUpdater != nil {
  168. updater = seedUpdater
  169. }
  170. conn, err := common.NewActivityMonitoredConn(
  171. udpConn,
  172. mux.sshClient.idleUDPPortForwardTimeout(),
  173. true,
  174. updater,
  175. lruEntry)
  176. if err != nil {
  177. lruEntry.Remove()
  178. mux.sshClient.closedPortForward(portForwardTypeUDP, 0, 0)
  179. log.WithTraceFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  180. continue
  181. }
  182. portForward = &udpPortForward{
  183. connID: message.connID,
  184. preambleSize: message.preambleSize,
  185. remoteIP: message.remoteIP,
  186. remotePort: message.remotePort,
  187. conn: conn,
  188. lruEntry: lruEntry,
  189. bytesUp: 0,
  190. bytesDown: 0,
  191. mux: mux,
  192. }
  193. mux.portForwardsMutex.Lock()
  194. mux.portForwards[portForward.connID] = portForward
  195. mux.portForwardsMutex.Unlock()
  196. mux.relayWaitGroup.Add(1)
  197. go portForward.relayDownstream()
  198. }
  199. // Note: assumes UDP writes won't block (https://golang.org/pkg/net/#UDPConn.WriteToUDP)
  200. _, err = portForward.conn.Write(message.packet)
  201. if err != nil {
  202. // Debug since errors such as "write: operation not permitted" occur during normal operation
  203. log.WithTraceFields(LogFields{"error": err}).Debug("upstream UDP relay failed")
  204. // The port forward's goroutine will complete cleanup
  205. portForward.conn.Close()
  206. }
  207. portForward.lruEntry.Touch()
  208. atomic.AddInt64(&portForward.bytesUp, int64(len(message.packet)))
  209. }
  210. // Cleanup all UDP port forward workers when exiting
  211. mux.portForwardsMutex.Lock()
  212. for _, portForward := range mux.portForwards {
  213. // The port forward's goroutine will complete cleanup
  214. portForward.conn.Close()
  215. }
  216. mux.portForwardsMutex.Unlock()
  217. mux.relayWaitGroup.Wait()
  218. }
  219. func (mux *udpPortForwardMultiplexer) removePortForward(connID uint16) {
  220. mux.portForwardsMutex.Lock()
  221. delete(mux.portForwards, connID)
  222. mux.portForwardsMutex.Unlock()
  223. }
  224. type udpPortForward struct {
  225. // Note: 64-bit ints used with atomic operations are placed
  226. // at the start of struct to ensure 64-bit alignment.
  227. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  228. bytesUp int64
  229. bytesDown int64
  230. connID uint16
  231. preambleSize int
  232. remoteIP []byte
  233. remotePort uint16
  234. conn net.Conn
  235. lruEntry *common.LRUConnsEntry
  236. mux *udpPortForwardMultiplexer
  237. }
  238. func (portForward *udpPortForward) relayDownstream() {
  239. defer portForward.mux.relayWaitGroup.Done()
  240. // Downstream UDP packets are read into the reusable memory
  241. // in "buffer" starting at the offset past the udpgw message
  242. // header and address, leaving enough space to write the udpgw
  243. // values into the same buffer and use for writing to the ssh
  244. // channel.
  245. //
  246. // Note: there is one downstream buffer per UDP port forward,
  247. // while for upstream there is one buffer per client.
  248. // TODO: is the buffer size larger than necessary?
  249. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  250. packetBuffer := buffer[portForward.preambleSize:udpgwProtocolMaxMessageSize]
  251. for {
  252. // TODO: if read buffer is too small, excess bytes are discarded?
  253. packetSize, err := portForward.conn.Read(packetBuffer)
  254. if packetSize > udpgwProtocolMaxPayloadSize {
  255. err = fmt.Errorf("unexpected packet size: %d", packetSize)
  256. }
  257. if err != nil {
  258. if err != io.EOF {
  259. // Debug since errors such as "use of closed network connection" occur during normal operation
  260. log.WithTraceFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  261. }
  262. break
  263. }
  264. err = writeUdpgwPreamble(
  265. portForward.preambleSize,
  266. 0,
  267. portForward.connID,
  268. portForward.remoteIP,
  269. portForward.remotePort,
  270. uint16(packetSize),
  271. buffer)
  272. if err == nil {
  273. // ssh.Channel.Write cannot be called concurrently.
  274. // See: https://github.com/Psiphon-Inc/crypto/blob/82d98b4c7c05e81f92545f6fddb45d4541e6da00/ssh/channel.go#L272,
  275. // https://codereview.appspot.com/136420043/diff/80002/ssh/channel.go
  276. portForward.mux.sshChannelWriteMutex.Lock()
  277. _, err = portForward.mux.sshChannel.Write(buffer[0 : portForward.preambleSize+packetSize])
  278. portForward.mux.sshChannelWriteMutex.Unlock()
  279. }
  280. if err != nil {
  281. // Close the channel, which will interrupt the main loop.
  282. portForward.mux.sshChannel.Close()
  283. log.WithTraceFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  284. break
  285. }
  286. portForward.lruEntry.Touch()
  287. atomic.AddInt64(&portForward.bytesDown, int64(packetSize))
  288. }
  289. portForward.mux.removePortForward(portForward.connID)
  290. portForward.lruEntry.Remove()
  291. portForward.conn.Close()
  292. bytesUp := atomic.LoadInt64(&portForward.bytesUp)
  293. bytesDown := atomic.LoadInt64(&portForward.bytesDown)
  294. portForward.mux.sshClient.closedPortForward(portForwardTypeUDP, bytesUp, bytesDown)
  295. log.WithTraceFields(
  296. LogFields{
  297. "remoteAddr": fmt.Sprintf("%s:%d",
  298. net.IP(portForward.remoteIP).String(), portForward.remotePort),
  299. "bytesUp": bytesUp,
  300. "bytesDown": bytesDown,
  301. "connID": portForward.connID}).Debug("exiting")
  302. }
  303. // TODO: express and/or calculate udpgwProtocolMaxPayloadSize as function of MTU?
  304. const (
  305. udpgwProtocolFlagKeepalive = 1 << 0
  306. udpgwProtocolFlagRebind = 1 << 1
  307. udpgwProtocolFlagDNS = 1 << 2
  308. udpgwProtocolFlagIPv6 = 1 << 3
  309. udpgwProtocolMaxPreambleSize = 23
  310. udpgwProtocolMaxPayloadSize = 32768
  311. udpgwProtocolMaxMessageSize = udpgwProtocolMaxPreambleSize + udpgwProtocolMaxPayloadSize
  312. )
  313. type udpgwProtocolMessage struct {
  314. connID uint16
  315. preambleSize int
  316. remoteIP []byte
  317. remotePort uint16
  318. discardExistingConn bool
  319. forwardDNS bool
  320. packet []byte
  321. }
  322. func readUdpgwMessage(
  323. reader io.Reader, buffer []byte) (*udpgwProtocolMessage, error) {
  324. // udpgw message layout:
  325. //
  326. // | 2 byte size | 3 byte header | 6 or 18 byte address | variable length packet |
  327. for {
  328. // Read message
  329. _, err := io.ReadFull(reader, buffer[0:2])
  330. if err != nil {
  331. if err != io.EOF {
  332. err = errors.Trace(err)
  333. }
  334. return nil, err
  335. }
  336. size := binary.LittleEndian.Uint16(buffer[0:2])
  337. if size < 3 || int(size) > len(buffer)-2 {
  338. return nil, errors.TraceNew("invalid udpgw message size")
  339. }
  340. _, err = io.ReadFull(reader, buffer[2:2+size])
  341. if err != nil {
  342. if err != io.EOF {
  343. err = errors.Trace(err)
  344. }
  345. return nil, err
  346. }
  347. flags := buffer[2]
  348. connID := binary.LittleEndian.Uint16(buffer[3:5])
  349. // Ignore udpgw keep-alive messages -- read another message
  350. if flags&udpgwProtocolFlagKeepalive == udpgwProtocolFlagKeepalive {
  351. continue
  352. }
  353. // Read address
  354. var remoteIP []byte
  355. var remotePort uint16
  356. var packetStart, packetEnd int
  357. if flags&udpgwProtocolFlagIPv6 == udpgwProtocolFlagIPv6 {
  358. if size < 21 {
  359. return nil, errors.TraceNew("invalid udpgw message size")
  360. }
  361. remoteIP = make([]byte, 16)
  362. copy(remoteIP, buffer[5:21])
  363. remotePort = binary.BigEndian.Uint16(buffer[21:23])
  364. packetStart = 23
  365. packetEnd = 23 + int(size) - 21
  366. } else {
  367. if size < 9 {
  368. return nil, errors.TraceNew("invalid udpgw message size")
  369. }
  370. remoteIP = make([]byte, 4)
  371. copy(remoteIP, buffer[5:9])
  372. remotePort = binary.BigEndian.Uint16(buffer[9:11])
  373. packetStart = 11
  374. packetEnd = 11 + int(size) - 9
  375. }
  376. // Assemble message
  377. // Note: udpgwProtocolMessage.packet references memory in the input buffer
  378. message := &udpgwProtocolMessage{
  379. connID: connID,
  380. preambleSize: packetStart,
  381. remoteIP: remoteIP,
  382. remotePort: remotePort,
  383. discardExistingConn: flags&udpgwProtocolFlagRebind == udpgwProtocolFlagRebind,
  384. forwardDNS: flags&udpgwProtocolFlagDNS == udpgwProtocolFlagDNS,
  385. packet: buffer[packetStart:packetEnd],
  386. }
  387. return message, nil
  388. }
  389. }
  390. func writeUdpgwPreamble(
  391. preambleSize int,
  392. flags uint8,
  393. connID uint16,
  394. remoteIP []byte,
  395. remotePort uint16,
  396. packetSize uint16,
  397. buffer []byte) error {
  398. if preambleSize != 7+len(remoteIP) {
  399. return errors.TraceNew("invalid udpgw preamble size")
  400. }
  401. size := uint16(preambleSize-2) + packetSize
  402. // size
  403. binary.LittleEndian.PutUint16(buffer[0:2], size)
  404. // flags
  405. buffer[2] = flags
  406. // connID
  407. binary.LittleEndian.PutUint16(buffer[3:5], connID)
  408. // addr
  409. copy(buffer[5:5+len(remoteIP)], remoteIP)
  410. binary.BigEndian.PutUint16(buffer[5+len(remoteIP):7+len(remoteIP)], remotePort)
  411. return nil
  412. }