udp.go 15 KB

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