udpChannel.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. "math"
  26. "net"
  27. "strconv"
  28. "sync"
  29. "sync/atomic"
  30. "time"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  32. "golang.org/x/crypto/ssh"
  33. )
  34. // setUDPChannel sets the single UDP channel for this sshClient.
  35. // Each sshClient may have only one concurrent UDP channel. Each
  36. // UDP channel multiplexes many UDP port forwards via the udpgw
  37. // protocol. Any existing UDP channel is closed.
  38. func (sshClient *sshClient) setUDPChannel(channel ssh.Channel) {
  39. sshClient.Lock()
  40. if sshClient.udpChannel != nil {
  41. sshClient.udpChannel.Close()
  42. }
  43. sshClient.udpChannel = channel
  44. sshClient.Unlock()
  45. }
  46. // handleUDPChannel implements UDP port forwarding. A single UDP
  47. // SSH channel follows the udpgw protocol, which multiplexes many
  48. // UDP port forwards.
  49. //
  50. // The udpgw protocol and original server implementation:
  51. // Copyright (c) 2009, Ambroz Bizjak <ambrop7@gmail.com>
  52. // https://github.com/ambrop72/badvpn
  53. //
  54. func (sshClient *sshClient) handleUDPChannel(newChannel ssh.NewChannel) {
  55. // Accept this channel immediately. This channel will replace any
  56. // previously existing UDP channel for this client.
  57. sshChannel, requests, err := newChannel.Accept()
  58. if err != nil {
  59. log.WithContextFields(LogFields{"error": err}).Warning("accept new channel failed")
  60. return
  61. }
  62. go ssh.DiscardRequests(requests)
  63. defer sshChannel.Close()
  64. sshClient.setUDPChannel(sshChannel)
  65. multiplexer := &udpPortForwardMultiplexer{
  66. sshClient: sshClient,
  67. sshChannel: sshChannel,
  68. portForwards: make(map[uint16]*udpPortForward),
  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. 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. // When the UDP port forward limit is exceeded, we
  137. // select the least recently used (read from or written
  138. // to) port forward and discard it.
  139. mux.closeLeastRecentlyUsedPortForward()
  140. }
  141. dialIP := net.IP(message.remoteIP)
  142. dialPort := int(message.remotePort)
  143. // Transparent DNS forwarding
  144. if message.forwardDNS {
  145. dialIP, dialPort = mux.transparentDNSAddress(dialIP, dialPort)
  146. }
  147. log.WithContextFields(
  148. LogFields{
  149. "remoteAddr": fmt.Sprintf("%s:%d", dialIP.String(), dialPort),
  150. "connID": message.connID}).Debug("dialing")
  151. // TODO: on EADDRNOTAVAIL, temporarily suspend new clients
  152. updConn, err := net.DialUDP(
  153. "udp", nil, &net.UDPAddr{IP: dialIP, Port: dialPort})
  154. if err != nil {
  155. mux.sshClient.closedPortForward(mux.sshClient.udpTrafficState, 0, 0)
  156. log.WithContextFields(LogFields{"error": err}).Warning("DialUDP failed")
  157. continue
  158. }
  159. portForward = &udpPortForward{
  160. connID: message.connID,
  161. preambleSize: message.preambleSize,
  162. remoteIP: message.remoteIP,
  163. remotePort: message.remotePort,
  164. conn: updConn,
  165. lastActivity: time.Now().UnixNano(),
  166. bytesUp: 0,
  167. bytesDown: 0,
  168. mux: mux,
  169. }
  170. mux.portForwardsMutex.Lock()
  171. mux.portForwards[portForward.connID] = portForward
  172. mux.portForwardsMutex.Unlock()
  173. // TODO: timeout inactive UDP port forwards
  174. // relayDownstream will call sshClient.closedPortForward()
  175. mux.relayWaitGroup.Add(1)
  176. go portForward.relayDownstream()
  177. }
  178. // Note: assumes UDP writes won't block (https://golang.org/pkg/net/#UDPConn.WriteToUDP)
  179. _, err = portForward.conn.Write(message.packet)
  180. if err != nil {
  181. // Debug since errors such as "write: operation not permitted" occur during normal operation
  182. log.WithContextFields(LogFields{"error": err}).Debug("upstream UDP relay failed")
  183. // The port forward's goroutine will complete cleanup
  184. portForward.conn.Close()
  185. }
  186. atomic.StoreInt64(&portForward.lastActivity, time.Now().UnixNano())
  187. atomic.AddInt64(&portForward.bytesUp, int64(len(message.packet)))
  188. }
  189. // Cleanup all UDP port forward workers when exiting
  190. mux.portForwardsMutex.Lock()
  191. for _, portForward := range mux.portForwards {
  192. // The port forward's goroutine will complete cleanup
  193. portForward.conn.Close()
  194. }
  195. mux.portForwardsMutex.Unlock()
  196. mux.relayWaitGroup.Wait()
  197. }
  198. func (mux *udpPortForwardMultiplexer) closeLeastRecentlyUsedPortForward() {
  199. // TODO: use "container/list" and avoid a linear scan?
  200. mux.portForwardsMutex.Lock()
  201. oldestActivity := int64(math.MaxInt64)
  202. var oldestPortForward *udpPortForward
  203. for _, nextPortForward := range mux.portForwards {
  204. if nextPortForward.lastActivity < oldestActivity {
  205. oldestPortForward = nextPortForward
  206. }
  207. }
  208. if oldestPortForward != nil {
  209. // The port forward's goroutine will complete cleanup
  210. oldestPortForward.conn.Close()
  211. }
  212. mux.portForwardsMutex.Unlock()
  213. }
  214. func (mux *udpPortForwardMultiplexer) transparentDNSAddress(
  215. dialIP net.IP, dialPort int) (net.IP, int) {
  216. if mux.sshClient.sshServer.config.DNSServerAddress != "" {
  217. // Note: DNSServerAddress is validated in LoadConfig
  218. host, portStr, _ := net.SplitHostPort(
  219. mux.sshClient.sshServer.config.DNSServerAddress)
  220. dialIP = net.ParseIP(host)
  221. dialPort, _ = strconv.Atoi(portStr)
  222. }
  223. return dialIP, dialPort
  224. }
  225. func (mux *udpPortForwardMultiplexer) removePortForward(connID uint16) {
  226. mux.portForwardsMutex.Lock()
  227. delete(mux.portForwards, connID)
  228. mux.portForwardsMutex.Unlock()
  229. }
  230. type udpPortForward struct {
  231. connID uint16
  232. preambleSize int
  233. remoteIP []byte
  234. remotePort uint16
  235. conn *net.UDPConn
  236. lastActivity int64
  237. bytesUp int64
  238. bytesDown int64
  239. mux *udpPortForwardMultiplexer
  240. }
  241. func (portForward *udpPortForward) relayDownstream() {
  242. defer portForward.mux.relayWaitGroup.Done()
  243. // Downstream UDP packets are read into the reusable memory
  244. // in "buffer" starting at the offset past the udpgw message
  245. // header and address, leaving enough space to write the udpgw
  246. // values into the same buffer and use for writing to the ssh
  247. // channel.
  248. //
  249. // Note: there is one downstream buffer per UDP port forward,
  250. // while for upstream there is one buffer per client.
  251. // TODO: is the buffer size larger than necessary?
  252. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  253. packetBuffer := buffer[portForward.preambleSize:udpgwProtocolMaxMessageSize]
  254. for {
  255. // TODO: if read buffer is too small, excess bytes are discarded?
  256. packetSize, err := portForward.conn.Read(packetBuffer)
  257. if packetSize > udpgwProtocolMaxPayloadSize {
  258. err = fmt.Errorf("unexpected packet size: %d", packetSize)
  259. }
  260. if err != nil {
  261. if err != io.EOF {
  262. // Debug since errors such as "use of closed network connection" occur during normal operation
  263. log.WithContextFields(LogFields{"error": err}).Warning("downstream UDP relay failed")
  264. }
  265. break
  266. }
  267. err = writeUdpgwPreamble(
  268. portForward.preambleSize,
  269. portForward.connID,
  270. portForward.remoteIP,
  271. portForward.remotePort,
  272. uint16(packetSize),
  273. buffer)
  274. if err == nil {
  275. _, err = portForward.mux.sshChannel.Write(buffer[0 : portForward.preambleSize+packetSize])
  276. }
  277. if err != nil {
  278. // Close the channel, which will interrupt the main loop.
  279. portForward.mux.sshChannel.Close()
  280. log.WithContextFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  281. break
  282. }
  283. atomic.StoreInt64(&portForward.lastActivity, time.Now().UnixNano())
  284. atomic.AddInt64(&portForward.bytesDown, int64(packetSize))
  285. }
  286. portForward.mux.removePortForward(portForward.connID)
  287. portForward.conn.Close()
  288. bytesUp := atomic.LoadInt64(&portForward.bytesUp)
  289. bytesDown := atomic.LoadInt64(&portForward.bytesDown)
  290. portForward.mux.sshClient.closedPortForward(
  291. portForward.mux.sshClient.udpTrafficState, bytesUp, bytesDown)
  292. log.WithContextFields(
  293. LogFields{
  294. "remoteAddr": fmt.Sprintf("%s:%d",
  295. net.IP(portForward.remoteIP).String(), portForward.remotePort),
  296. "bytesUp": bytesUp,
  297. "bytesDown": bytesDown,
  298. "connID": portForward.connID}).Debug("exiting")
  299. }
  300. // TODO: express and/or calculate udpgwProtocolMaxPayloadSize as function of MTU?
  301. const (
  302. udpgwProtocolFlagKeepalive = 1 << 0
  303. udpgwProtocolFlagRebind = 1 << 1
  304. udpgwProtocolFlagDNS = 1 << 2
  305. udpgwProtocolFlagIPv6 = 1 << 3
  306. udpgwProtocolMaxPreambleSize = 23
  307. udpgwProtocolMaxPayloadSize = 32768
  308. udpgwProtocolMaxMessageSize = udpgwProtocolMaxPreambleSize + udpgwProtocolMaxPayloadSize
  309. )
  310. type udpProtocolMessage struct {
  311. connID uint16
  312. preambleSize int
  313. remoteIP []byte
  314. remotePort uint16
  315. discardExistingConn bool
  316. forwardDNS bool
  317. packet []byte
  318. }
  319. func readUdpgwMessage(
  320. reader io.Reader, buffer []byte) (*udpProtocolMessage, error) {
  321. // udpgw message layout:
  322. //
  323. // | 2 byte size | 3 byte header | 6 or 18 byte address | variable length packet |
  324. for {
  325. // Read message
  326. _, err := io.ReadFull(reader, buffer[0:2])
  327. if err != nil {
  328. return nil, psiphon.ContextError(err)
  329. }
  330. size := uint16(buffer[0]) + uint16(buffer[1])<<8
  331. if int(size) > len(buffer)-2 {
  332. return nil, psiphon.ContextError(errors.New("invalid udpgw message size"))
  333. }
  334. _, err = io.ReadFull(reader, buffer[2:2+size])
  335. if err != nil {
  336. return nil, psiphon.ContextError(err)
  337. }
  338. flags := buffer[2]
  339. connID := uint16(buffer[3]) + uint16(buffer[4])<<8
  340. // Ignore udpgw keep-alive messages -- read another message
  341. if flags&udpgwProtocolFlagKeepalive == udpgwProtocolFlagKeepalive {
  342. continue
  343. }
  344. // Read address
  345. var remoteIP []byte
  346. var remotePort uint16
  347. var packetStart, packetEnd int
  348. if flags&udpgwProtocolFlagIPv6 == udpgwProtocolFlagIPv6 {
  349. if size < 21 {
  350. return nil, psiphon.ContextError(errors.New("invalid udpgw message size"))
  351. }
  352. remoteIP = make([]byte, 16)
  353. copy(remoteIP, buffer[5:21])
  354. remotePort = uint16(buffer[21]) + uint16(buffer[22])<<8
  355. packetStart = 23
  356. packetEnd = 23 + int(size) - 2
  357. } else {
  358. if size < 9 {
  359. return nil, psiphon.ContextError(errors.New("invalid udpgw message size"))
  360. }
  361. remoteIP = make([]byte, 4)
  362. copy(remoteIP, buffer[5:9])
  363. remotePort = uint16(buffer[9]) + uint16(buffer[10])<<8
  364. packetStart = 11
  365. packetEnd = 11 + int(size) - 2
  366. }
  367. // Assemble message
  368. // Note: udpProtocolMessage.packet references memory in the input buffer
  369. message := &udpProtocolMessage{
  370. connID: connID,
  371. preambleSize: packetStart,
  372. remoteIP: remoteIP,
  373. remotePort: remotePort,
  374. discardExistingConn: flags&udpgwProtocolFlagRebind == udpgwProtocolFlagRebind,
  375. forwardDNS: flags&udpgwProtocolFlagDNS == udpgwProtocolFlagDNS,
  376. packet: buffer[packetStart:packetEnd],
  377. }
  378. return message, nil
  379. }
  380. }
  381. func writeUdpgwPreamble(
  382. preambleSize int,
  383. connID uint16,
  384. remoteIP []byte,
  385. remotePort uint16,
  386. packetSize uint16,
  387. buffer []byte) error {
  388. if preambleSize != 7+len(remoteIP) {
  389. return errors.New("invalid udpgw preamble size")
  390. }
  391. size := uint16(preambleSize-2) + packetSize
  392. // size
  393. buffer[0] = byte(size & 0xFF)
  394. buffer[1] = byte(size >> 8)
  395. // flags
  396. buffer[2] = 0
  397. // connID
  398. buffer[3] = byte(connID & 0xFF)
  399. buffer[4] = byte(connID >> 8)
  400. // addr
  401. copy(buffer[5:5+len(remoteIP)], remoteIP)
  402. buffer[5+len(remoteIP)] = byte(remotePort & 0xFF)
  403. buffer[6+len(remoteIP)] = byte(remotePort >> 8)
  404. return nil
  405. }