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