udp.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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("readUpdgwMessage 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, dialIP.String(), 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. mux.sshClient.openedPortForward(portForwardTypeUDP)
  147. // Note: can't defer sshClient.closedPortForward() here
  148. // TOCTOU note: important to increment the port forward count (via
  149. // openPortForward) _before_ checking isPortForwardLimitExceeded
  150. if maxCount, exceeded := mux.sshClient.isPortForwardLimitExceeded(portForwardTypeUDP); exceeded {
  151. // Close the oldest UDP port forward. CloseOldest() closes
  152. // the conn and the port forward's goroutine will complete
  153. // the cleanup asynchronously.
  154. //
  155. // See LRU comment in handleTCPChannel() for a known
  156. // limitations regarding CloseOldest().
  157. mux.portForwardLRU.CloseOldest()
  158. log.WithContextFields(
  159. LogFields{
  160. "maxCount": maxCount,
  161. }).Debug("closed LRU UDP port forward")
  162. }
  163. log.WithContextFields(
  164. LogFields{
  165. "remoteAddr": fmt.Sprintf("%s:%d", dialIP.String(), dialPort),
  166. "connID": message.connID}).Debug("dialing")
  167. // TODO: on EADDRNOTAVAIL, temporarily suspend new clients
  168. udpConn, err := net.DialUDP(
  169. "udp", nil, &net.UDPAddr{IP: dialIP, Port: dialPort})
  170. if err != nil {
  171. mux.sshClient.closedPortForward(portForwardTypeUDP, 0, 0)
  172. log.WithContextFields(LogFields{"error": err}).Warning("DialUDP failed")
  173. continue
  174. }
  175. // ActivityMonitoredConn monitors the TCP port forward I/O and updates
  176. // its LRU status. ActivityMonitoredConn also times out I/O on the port
  177. // forward if both reads and writes have been idle for the specified
  178. // duration.
  179. lruEntry := mux.portForwardLRU.Add(udpConn)
  180. conn, err := common.NewActivityMonitoredConn(
  181. udpConn,
  182. mux.sshClient.idleUDPPortForwardTimeout(),
  183. true,
  184. lruEntry)
  185. if err != nil {
  186. lruEntry.Remove()
  187. mux.sshClient.closedPortForward(portForwardTypeUDP, 0, 0)
  188. log.WithContextFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  189. continue
  190. }
  191. portForward = &udpPortForward{
  192. connID: message.connID,
  193. preambleSize: message.preambleSize,
  194. remoteIP: message.remoteIP,
  195. remotePort: message.remotePort,
  196. conn: conn,
  197. lruEntry: lruEntry,
  198. bytesUp: 0,
  199. bytesDown: 0,
  200. mux: mux,
  201. }
  202. mux.portForwardsMutex.Lock()
  203. mux.portForwards[portForward.connID] = portForward
  204. mux.portForwardsMutex.Unlock()
  205. // relayDownstream will call sshClient.closedPortForward()
  206. mux.relayWaitGroup.Add(1)
  207. go portForward.relayDownstream()
  208. }
  209. // Note: assumes UDP writes won't block (https://golang.org/pkg/net/#UDPConn.WriteToUDP)
  210. _, err = portForward.conn.Write(message.packet)
  211. if err != nil {
  212. // Debug since errors such as "write: operation not permitted" occur during normal operation
  213. log.WithContextFields(LogFields{"error": err}).Debug("upstream UDP relay failed")
  214. // The port forward's goroutine will complete cleanup
  215. portForward.conn.Close()
  216. }
  217. portForward.lruEntry.Touch()
  218. atomic.AddInt64(&portForward.bytesUp, int64(len(message.packet)))
  219. }
  220. // Cleanup all UDP port forward workers when exiting
  221. mux.portForwardsMutex.Lock()
  222. for _, portForward := range mux.portForwards {
  223. // The port forward's goroutine will complete cleanup
  224. portForward.conn.Close()
  225. }
  226. mux.portForwardsMutex.Unlock()
  227. mux.relayWaitGroup.Wait()
  228. }
  229. func (mux *udpPortForwardMultiplexer) removePortForward(connID uint16) {
  230. mux.portForwardsMutex.Lock()
  231. delete(mux.portForwards, connID)
  232. mux.portForwardsMutex.Unlock()
  233. }
  234. type udpPortForward struct {
  235. // Note: 64-bit ints used with atomic operations are at placed
  236. // at the start of struct to ensure 64-bit alignment.
  237. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  238. bytesUp int64
  239. bytesDown int64
  240. connID uint16
  241. preambleSize int
  242. remoteIP []byte
  243. remotePort uint16
  244. conn net.Conn
  245. lruEntry *common.LRUConnsEntry
  246. mux *udpPortForwardMultiplexer
  247. }
  248. func (portForward *udpPortForward) relayDownstream() {
  249. defer portForward.mux.relayWaitGroup.Done()
  250. // Downstream UDP packets are read into the reusable memory
  251. // in "buffer" starting at the offset past the udpgw message
  252. // header and address, leaving enough space to write the udpgw
  253. // values into the same buffer and use for writing to the ssh
  254. // channel.
  255. //
  256. // Note: there is one downstream buffer per UDP port forward,
  257. // while for upstream there is one buffer per client.
  258. // TODO: is the buffer size larger than necessary?
  259. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  260. packetBuffer := buffer[portForward.preambleSize:udpgwProtocolMaxMessageSize]
  261. for {
  262. // TODO: if read buffer is too small, excess bytes are discarded?
  263. packetSize, err := portForward.conn.Read(packetBuffer)
  264. if packetSize > udpgwProtocolMaxPayloadSize {
  265. err = fmt.Errorf("unexpected packet size: %d", packetSize)
  266. }
  267. if err != nil {
  268. if err != io.EOF {
  269. // Debug since errors such as "use of closed network connection" occur during normal operation
  270. log.WithContextFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  271. }
  272. break
  273. }
  274. err = writeUdpgwPreamble(
  275. portForward.preambleSize,
  276. 0,
  277. portForward.connID,
  278. portForward.remoteIP,
  279. portForward.remotePort,
  280. uint16(packetSize),
  281. buffer)
  282. if err == nil {
  283. // ssh.Channel.Write cannot be called concurrently.
  284. // See: https://github.com/Psiphon-Inc/crypto/blob/82d98b4c7c05e81f92545f6fddb45d4541e6da00/ssh/channel.go#L272,
  285. // https://codereview.appspot.com/136420043/diff/80002/ssh/channel.go
  286. portForward.mux.sshChannelWriteMutex.Lock()
  287. _, err = portForward.mux.sshChannel.Write(buffer[0 : portForward.preambleSize+packetSize])
  288. portForward.mux.sshChannelWriteMutex.Unlock()
  289. }
  290. if err != nil {
  291. // Close the channel, which will interrupt the main loop.
  292. portForward.mux.sshChannel.Close()
  293. log.WithContextFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  294. break
  295. }
  296. portForward.lruEntry.Touch()
  297. atomic.AddInt64(&portForward.bytesDown, int64(packetSize))
  298. }
  299. portForward.mux.removePortForward(portForward.connID)
  300. portForward.lruEntry.Remove()
  301. portForward.conn.Close()
  302. bytesUp := atomic.LoadInt64(&portForward.bytesUp)
  303. bytesDown := atomic.LoadInt64(&portForward.bytesDown)
  304. portForward.mux.sshClient.closedPortForward(portForwardTypeUDP, bytesUp, bytesDown)
  305. log.WithContextFields(
  306. LogFields{
  307. "remoteAddr": fmt.Sprintf("%s:%d",
  308. net.IP(portForward.remoteIP).String(), portForward.remotePort),
  309. "bytesUp": bytesUp,
  310. "bytesDown": bytesDown,
  311. "connID": portForward.connID}).Debug("exiting")
  312. }
  313. // TODO: express and/or calculate udpgwProtocolMaxPayloadSize as function of MTU?
  314. const (
  315. udpgwProtocolFlagKeepalive = 1 << 0
  316. udpgwProtocolFlagRebind = 1 << 1
  317. udpgwProtocolFlagDNS = 1 << 2
  318. udpgwProtocolFlagIPv6 = 1 << 3
  319. udpgwProtocolMaxPreambleSize = 23
  320. udpgwProtocolMaxPayloadSize = 32768
  321. udpgwProtocolMaxMessageSize = udpgwProtocolMaxPreambleSize + udpgwProtocolMaxPayloadSize
  322. )
  323. type udpgwProtocolMessage struct {
  324. connID uint16
  325. preambleSize int
  326. remoteIP []byte
  327. remotePort uint16
  328. discardExistingConn bool
  329. forwardDNS bool
  330. packet []byte
  331. }
  332. func readUdpgwMessage(
  333. reader io.Reader, buffer []byte) (*udpgwProtocolMessage, error) {
  334. // udpgw message layout:
  335. //
  336. // | 2 byte size | 3 byte header | 6 or 18 byte address | variable length packet |
  337. for {
  338. // Read message
  339. _, err := io.ReadFull(reader, buffer[0:2])
  340. if err != nil {
  341. return nil, common.ContextError(err)
  342. }
  343. size := binary.LittleEndian.Uint16(buffer[0:2])
  344. if size < 3 || int(size) > len(buffer)-2 {
  345. return nil, common.ContextError(errors.New("invalid udpgw message size"))
  346. }
  347. _, err = io.ReadFull(reader, buffer[2:2+size])
  348. if err != nil {
  349. return nil, common.ContextError(err)
  350. }
  351. flags := buffer[2]
  352. connID := binary.LittleEndian.Uint16(buffer[3:5])
  353. // Ignore udpgw keep-alive messages -- read another message
  354. if flags&udpgwProtocolFlagKeepalive == udpgwProtocolFlagKeepalive {
  355. continue
  356. }
  357. // Read address
  358. var remoteIP []byte
  359. var remotePort uint16
  360. var packetStart, packetEnd int
  361. if flags&udpgwProtocolFlagIPv6 == udpgwProtocolFlagIPv6 {
  362. if size < 21 {
  363. return nil, common.ContextError(errors.New("invalid udpgw message size"))
  364. }
  365. remoteIP = make([]byte, 16)
  366. copy(remoteIP, buffer[5:21])
  367. remotePort = binary.BigEndian.Uint16(buffer[21:23])
  368. packetStart = 23
  369. packetEnd = 23 + int(size) - 21
  370. } else {
  371. if size < 9 {
  372. return nil, common.ContextError(errors.New("invalid udpgw message size"))
  373. }
  374. remoteIP = make([]byte, 4)
  375. copy(remoteIP, buffer[5:9])
  376. remotePort = binary.BigEndian.Uint16(buffer[9:11])
  377. packetStart = 11
  378. packetEnd = 11 + int(size) - 9
  379. }
  380. // Assemble message
  381. // Note: udpgwProtocolMessage.packet references memory in the input buffer
  382. message := &udpgwProtocolMessage{
  383. connID: connID,
  384. preambleSize: packetStart,
  385. remoteIP: remoteIP,
  386. remotePort: remotePort,
  387. discardExistingConn: flags&udpgwProtocolFlagRebind == udpgwProtocolFlagRebind,
  388. forwardDNS: flags&udpgwProtocolFlagDNS == udpgwProtocolFlagDNS,
  389. packet: buffer[packetStart:packetEnd],
  390. }
  391. return message, nil
  392. }
  393. }
  394. func writeUdpgwPreamble(
  395. preambleSize int,
  396. flags uint8,
  397. connID uint16,
  398. remoteIP []byte,
  399. remotePort uint16,
  400. packetSize uint16,
  401. buffer []byte) error {
  402. if preambleSize != 7+len(remoteIP) {
  403. return common.ContextError(errors.New("invalid udpgw preamble size"))
  404. }
  405. size := uint16(preambleSize-2) + packetSize
  406. // size
  407. binary.LittleEndian.PutUint16(buffer[0:2], size)
  408. // flags
  409. buffer[2] = flags
  410. // connID
  411. binary.LittleEndian.PutUint16(buffer[3:5], connID)
  412. // addr
  413. copy(buffer[5:5+len(remoteIP)], remoteIP)
  414. binary.BigEndian.PutUint16(buffer[5+len(remoteIP):7+len(remoteIP)], remotePort)
  415. return nil
  416. }