udp.go 15 KB

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