udp.go 14 KB

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