udp.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. "time"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  31. "golang.org/x/crypto/ssh"
  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: NewLRUConns(),
  69. relayWaitGroup: new(sync.WaitGroup),
  70. }
  71. multiplexer.run()
  72. }
  73. type udpPortForwardMultiplexer struct {
  74. sshClient *sshClient
  75. sshChannel ssh.Channel
  76. portForwardsMutex sync.Mutex
  77. portForwards map[uint16]*udpPortForward
  78. portForwardLRU *LRUConns
  79. relayWaitGroup *sync.WaitGroup
  80. }
  81. func (mux *udpPortForwardMultiplexer) run() {
  82. // In a loop, read udpgw messages from the client to this channel. Each message is
  83. // a UDP packet to send upstream either via a new port forward, or on an existing
  84. // port forward.
  85. //
  86. // A goroutine is run to read downstream packets for each UDP port forward. All read
  87. // packets are encapsulated in udpgw protocol and sent down the channel to the client.
  88. //
  89. // When the client disconnects or the server shuts down, the channel will close and
  90. // readUdpgwMessage will exit with EOF.
  91. // Recover from and log any unexpected panics caused by udpgw input handling bugs.
  92. // Note: this covers the run() goroutine only and not relayDownstream() goroutines.
  93. defer func() {
  94. if e := recover(); e != nil {
  95. err := common.ContextError(
  96. fmt.Errorf(
  97. "udpPortForwardMultiplexer panic: %s: %s", e, debug.Stack()))
  98. log.WithContextFields(LogFields{"error": err}).Warning("run failed")
  99. }
  100. }()
  101. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  102. for {
  103. // Note: message.packet points to the reusable memory in "buffer".
  104. // Each readUdpgwMessage call will overwrite the last message.packet.
  105. message, err := readUdpgwMessage(mux.sshChannel, buffer)
  106. if err != nil {
  107. if err != io.EOF {
  108. log.WithContextFields(LogFields{"error": err}).Warning("readUpdgwMessage failed")
  109. }
  110. break
  111. }
  112. mux.portForwardsMutex.Lock()
  113. portForward := mux.portForwards[message.connID]
  114. mux.portForwardsMutex.Unlock()
  115. if portForward != nil && message.discardExistingConn {
  116. // The port forward's goroutine will complete cleanup, including
  117. // tallying stats and calling sshClient.closedPortForward.
  118. // portForward.conn.Close() will signal this shutdown.
  119. // TODO: wait for goroutine to exit before proceeding?
  120. portForward.conn.Close()
  121. portForward = nil
  122. }
  123. if portForward != nil {
  124. // Verify that portForward remote address matches latest message
  125. if 0 != bytes.Compare(portForward.remoteIP, message.remoteIP) ||
  126. portForward.remotePort != message.remotePort {
  127. log.WithContext().Warning("UDP port forward remote address mismatch")
  128. continue
  129. }
  130. } else {
  131. // Create a new port forward
  132. dialIP := net.IP(message.remoteIP)
  133. dialPort := int(message.remotePort)
  134. // Transparent DNS forwarding
  135. if message.forwardDNS {
  136. dialIP = mux.sshClient.sshServer.support.DNSResolver.Get()
  137. dialPort = DNS_RESOLVER_PORT
  138. }
  139. if !mux.sshClient.isPortForwardPermitted(
  140. dialIP.String(),
  141. int(message.remotePort),
  142. mux.sshClient.trafficRules.AllowUDPPorts,
  143. mux.sshClient.trafficRules.DenyUDPPorts) {
  144. // The udpgw protocol has no error response, so
  145. // we just discard the message and read another.
  146. continue
  147. }
  148. mux.sshClient.openedPortForward(mux.sshClient.udpTrafficState)
  149. // Note: can't defer sshClient.closedPortForward() here
  150. // TOCTOU note: important to increment the port forward count (via
  151. // openPortForward) _before_ checking isPortForwardLimitExceeded
  152. if mux.sshClient.isPortForwardLimitExceeded(
  153. mux.sshClient.tcpTrafficState,
  154. mux.sshClient.trafficRules.MaxUDPPortForwardCount) {
  155. // Close the oldest UDP port forward. CloseOldest() closes
  156. // the conn and the port forward's goroutine will complete
  157. // the cleanup asynchronously.
  158. //
  159. // See LRU comment in handleTCPChannel() for a known
  160. // limitations regarding CloseOldest().
  161. mux.portForwardLRU.CloseOldest()
  162. log.WithContextFields(
  163. LogFields{
  164. "maxCount": mux.sshClient.trafficRules.MaxUDPPortForwardCount,
  165. }).Debug("closed LRU UDP port forward")
  166. }
  167. log.WithContextFields(
  168. LogFields{
  169. "remoteAddr": fmt.Sprintf("%s:%d", dialIP.String(), dialPort),
  170. "connID": message.connID}).Debug("dialing")
  171. // TODO: on EADDRNOTAVAIL, temporarily suspend new clients
  172. udpConn, err := net.DialUDP(
  173. "udp", nil, &net.UDPAddr{IP: dialIP, Port: dialPort})
  174. if err != nil {
  175. mux.sshClient.closedPortForward(mux.sshClient.udpTrafficState, 0, 0)
  176. log.WithContextFields(LogFields{"error": err}).Warning("DialUDP failed")
  177. continue
  178. }
  179. // ActivityMonitoredConn monitors the TCP port forward I/O and updates
  180. // its LRU status. ActivityMonitoredConn also times out I/O on the port
  181. // forward if both reads and writes have been idle for the specified
  182. // duration.
  183. lruEntry := mux.portForwardLRU.Add(udpConn)
  184. conn, err := NewActivityMonitoredConn(
  185. udpConn,
  186. time.Duration(mux.sshClient.trafficRules.IdleUDPPortForwardTimeoutMilliseconds)*time.Millisecond,
  187. true,
  188. lruEntry)
  189. if err != nil {
  190. lruEntry.Remove()
  191. mux.sshClient.closedPortForward(mux.sshClient.udpTrafficState, 0, 0)
  192. log.WithContextFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  193. continue
  194. }
  195. portForward = &udpPortForward{
  196. connID: message.connID,
  197. preambleSize: message.preambleSize,
  198. remoteIP: message.remoteIP,
  199. remotePort: message.remotePort,
  200. conn: conn,
  201. lruEntry: lruEntry,
  202. bytesUp: 0,
  203. bytesDown: 0,
  204. mux: mux,
  205. }
  206. mux.portForwardsMutex.Lock()
  207. mux.portForwards[portForward.connID] = portForward
  208. mux.portForwardsMutex.Unlock()
  209. // relayDownstream will call sshClient.closedPortForward()
  210. mux.relayWaitGroup.Add(1)
  211. go portForward.relayDownstream()
  212. }
  213. // Note: assumes UDP writes won't block (https://golang.org/pkg/net/#UDPConn.WriteToUDP)
  214. _, err = portForward.conn.Write(message.packet)
  215. if err != nil {
  216. // Debug since errors such as "write: operation not permitted" occur during normal operation
  217. log.WithContextFields(LogFields{"error": err}).Debug("upstream UDP relay failed")
  218. // The port forward's goroutine will complete cleanup
  219. portForward.conn.Close()
  220. }
  221. portForward.lruEntry.Touch()
  222. atomic.AddInt64(&portForward.bytesUp, int64(len(message.packet)))
  223. }
  224. // Cleanup all UDP port forward workers when exiting
  225. mux.portForwardsMutex.Lock()
  226. for _, portForward := range mux.portForwards {
  227. // The port forward's goroutine will complete cleanup
  228. portForward.conn.Close()
  229. }
  230. mux.portForwardsMutex.Unlock()
  231. mux.relayWaitGroup.Wait()
  232. }
  233. func (mux *udpPortForwardMultiplexer) removePortForward(connID uint16) {
  234. mux.portForwardsMutex.Lock()
  235. delete(mux.portForwards, connID)
  236. mux.portForwardsMutex.Unlock()
  237. }
  238. type udpPortForward struct {
  239. // Note: 64-bit ints used with atomic operations are at placed
  240. // at the start of struct to ensure 64-bit alignment.
  241. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  242. bytesUp int64
  243. bytesDown int64
  244. connID uint16
  245. preambleSize int
  246. remoteIP []byte
  247. remotePort uint16
  248. conn net.Conn
  249. lruEntry *LRUConnsEntry
  250. mux *udpPortForwardMultiplexer
  251. }
  252. func (portForward *udpPortForward) relayDownstream() {
  253. defer portForward.mux.relayWaitGroup.Done()
  254. // Downstream UDP packets are read into the reusable memory
  255. // in "buffer" starting at the offset past the udpgw message
  256. // header and address, leaving enough space to write the udpgw
  257. // values into the same buffer and use for writing to the ssh
  258. // channel.
  259. //
  260. // Note: there is one downstream buffer per UDP port forward,
  261. // while for upstream there is one buffer per client.
  262. // TODO: is the buffer size larger than necessary?
  263. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  264. packetBuffer := buffer[portForward.preambleSize:udpgwProtocolMaxMessageSize]
  265. for {
  266. // TODO: if read buffer is too small, excess bytes are discarded?
  267. packetSize, err := portForward.conn.Read(packetBuffer)
  268. if packetSize > udpgwProtocolMaxPayloadSize {
  269. err = fmt.Errorf("unexpected packet size: %d", packetSize)
  270. }
  271. if err != nil {
  272. if err != io.EOF {
  273. // Debug since errors such as "use of closed network connection" occur during normal operation
  274. log.WithContextFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  275. }
  276. break
  277. }
  278. err = writeUdpgwPreamble(
  279. portForward.preambleSize,
  280. 0,
  281. portForward.connID,
  282. portForward.remoteIP,
  283. portForward.remotePort,
  284. uint16(packetSize),
  285. buffer)
  286. if err == nil {
  287. _, err = portForward.mux.sshChannel.Write(buffer[0 : portForward.preambleSize+packetSize])
  288. }
  289. if err != nil {
  290. // Close the channel, which will interrupt the main loop.
  291. portForward.mux.sshChannel.Close()
  292. log.WithContextFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  293. break
  294. }
  295. portForward.lruEntry.Touch()
  296. atomic.AddInt64(&portForward.bytesDown, int64(packetSize))
  297. }
  298. portForward.mux.removePortForward(portForward.connID)
  299. portForward.lruEntry.Remove()
  300. portForward.conn.Close()
  301. bytesUp := atomic.LoadInt64(&portForward.bytesUp)
  302. bytesDown := atomic.LoadInt64(&portForward.bytesDown)
  303. portForward.mux.sshClient.closedPortForward(
  304. portForward.mux.sshClient.udpTrafficState, 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 := uint16(buffer[0]) + uint16(buffer[1])<<8
  344. if 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 := uint16(buffer[3]) + uint16(buffer[4])<<8
  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 = uint16(buffer[21]) + uint16(buffer[22])<<8
  368. packetStart = 23
  369. packetEnd = 23 + int(size) - 2
  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 = uint16(buffer[9]) + uint16(buffer[10])<<8
  377. packetStart = 11
  378. packetEnd = 11 + int(size) - 2
  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. buffer[0] = byte(size & 0xFF)
  408. buffer[1] = byte(size >> 8)
  409. // flags
  410. buffer[2] = flags
  411. // connID
  412. buffer[3] = byte(connID & 0xFF)
  413. buffer[4] = byte(connID >> 8)
  414. // addr
  415. copy(buffer[5:5+len(remoteIP)], remoteIP)
  416. buffer[5+len(remoteIP)] = byte(remotePort & 0xFF)
  417. buffer[6+len(remoteIP)] = byte(remotePort >> 8)
  418. return nil
  419. }