udp.go 15 KB

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