udp.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. "strconv"
  27. "sync"
  28. "sync/atomic"
  29. "time"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  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: psiphon.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. relayWaitGroup *sync.WaitGroup
  79. portForwardLRU *psiphon.LRUConns
  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. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  92. for {
  93. // Note: message.packet points to the reusable memory in "buffer".
  94. // Each readUdpgwMessage call will overwrite the last message.packet.
  95. message, err := readUdpgwMessage(mux.sshChannel, buffer)
  96. if err != nil {
  97. if err != io.EOF {
  98. log.WithContextFields(LogFields{"error": err}).Warning("readUpdgwMessage failed")
  99. }
  100. break
  101. }
  102. mux.portForwardsMutex.Lock()
  103. portForward := mux.portForwards[message.connID]
  104. mux.portForwardsMutex.Unlock()
  105. if portForward != nil && message.discardExistingConn {
  106. // The port forward's goroutine will complete cleanup, including
  107. // tallying stats and calling sshClient.closedPortForward.
  108. // portForward.conn.Close() will signal this shutdown.
  109. // TODO: wait for goroutine to exit before proceeding?
  110. portForward.conn.Close()
  111. portForward = nil
  112. }
  113. if portForward != nil {
  114. // Verify that portForward remote address matches latest message
  115. if 0 != bytes.Compare(portForward.remoteIP, message.remoteIP) ||
  116. portForward.remotePort != message.remotePort {
  117. log.WithContext().Warning("UDP port forward remote address mismatch")
  118. continue
  119. }
  120. } else {
  121. // Create a new port forward
  122. if !mux.sshClient.isPortForwardPermitted(
  123. int(message.remotePort),
  124. mux.sshClient.trafficRules.AllowUDPPorts,
  125. mux.sshClient.trafficRules.DenyUDPPorts) {
  126. // The udpgw protocol has no error response, so
  127. // we just discard the message and read another.
  128. continue
  129. }
  130. mux.sshClient.openedPortForward(mux.sshClient.udpTrafficState)
  131. // Note: can't defer sshClient.closedPortForward() here
  132. // TOCTOU note: important to increment the port forward count (via
  133. // openPortForward) _before_ checking isPortForwardLimitExceeded
  134. if mux.sshClient.isPortForwardLimitExceeded(
  135. mux.sshClient.tcpTrafficState,
  136. mux.sshClient.trafficRules.MaxUDPPortForwardCount) {
  137. // Close the oldest UDP port forward. CloseOldest() closes
  138. // the conn and the port forward's goroutine will complete
  139. // the cleanup asynchronously.
  140. //
  141. // See LRU comment in handleTCPChannel() for a known
  142. // limitations regarding CloseOldest().
  143. mux.portForwardLRU.CloseOldest()
  144. log.WithContextFields(
  145. LogFields{
  146. "maxCount": mux.sshClient.trafficRules.MaxUDPPortForwardCount,
  147. }).Debug("closed LRU UDP port forward")
  148. }
  149. dialIP := net.IP(message.remoteIP)
  150. dialPort := int(message.remotePort)
  151. // Transparent DNS forwarding
  152. if message.forwardDNS {
  153. dialIP, dialPort = mux.transparentDNSAddress(dialIP, dialPort)
  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) transparentDNSAddress(
  216. dialIP net.IP, dialPort int) (net.IP, int) {
  217. if mux.sshClient.sshServer.support.Config.UDPForwardDNSServerAddress != "" {
  218. // Note: UDPForwardDNSServerAddress is validated in LoadConfig
  219. host, portStr, _ := net.SplitHostPort(
  220. mux.sshClient.sshServer.support.Config.UDPForwardDNSServerAddress)
  221. dialIP = net.ParseIP(host)
  222. dialPort, _ = strconv.Atoi(portStr)
  223. }
  224. return dialIP, dialPort
  225. }
  226. func (mux *udpPortForwardMultiplexer) removePortForward(connID uint16) {
  227. mux.portForwardsMutex.Lock()
  228. delete(mux.portForwards, connID)
  229. mux.portForwardsMutex.Unlock()
  230. }
  231. type udpPortForward struct {
  232. connID uint16
  233. preambleSize int
  234. remoteIP []byte
  235. remotePort uint16
  236. conn net.Conn
  237. lruEntry *psiphon.LRUConnsEntry
  238. bytesUp int64
  239. bytesDown int64
  240. mux *udpPortForwardMultiplexer
  241. }
  242. func (portForward *udpPortForward) relayDownstream() {
  243. defer portForward.mux.relayWaitGroup.Done()
  244. // Downstream UDP packets are read into the reusable memory
  245. // in "buffer" starting at the offset past the udpgw message
  246. // header and address, leaving enough space to write the udpgw
  247. // values into the same buffer and use for writing to the ssh
  248. // channel.
  249. //
  250. // Note: there is one downstream buffer per UDP port forward,
  251. // while for upstream there is one buffer per client.
  252. // TODO: is the buffer size larger than necessary?
  253. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  254. packetBuffer := buffer[portForward.preambleSize:udpgwProtocolMaxMessageSize]
  255. for {
  256. // TODO: if read buffer is too small, excess bytes are discarded?
  257. packetSize, err := portForward.conn.Read(packetBuffer)
  258. if packetSize > udpgwProtocolMaxPayloadSize {
  259. err = fmt.Errorf("unexpected packet size: %d", packetSize)
  260. }
  261. if err != nil {
  262. if err != io.EOF {
  263. // Debug since errors such as "use of closed network connection" occur during normal operation
  264. log.WithContextFields(LogFields{"error": err}).Warning("downstream UDP relay failed")
  265. }
  266. break
  267. }
  268. err = writeUdpgwPreamble(
  269. portForward.preambleSize,
  270. portForward.connID,
  271. portForward.remoteIP,
  272. portForward.remotePort,
  273. uint16(packetSize),
  274. buffer)
  275. if err == nil {
  276. _, err = portForward.mux.sshChannel.Write(buffer[0 : portForward.preambleSize+packetSize])
  277. }
  278. if err != nil {
  279. // Close the channel, which will interrupt the main loop.
  280. portForward.mux.sshChannel.Close()
  281. log.WithContextFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  282. break
  283. }
  284. portForward.lruEntry.Touch()
  285. atomic.AddInt64(&portForward.bytesDown, int64(packetSize))
  286. }
  287. portForward.mux.removePortForward(portForward.connID)
  288. portForward.lruEntry.Remove()
  289. portForward.conn.Close()
  290. bytesUp := atomic.LoadInt64(&portForward.bytesUp)
  291. bytesDown := atomic.LoadInt64(&portForward.bytesDown)
  292. portForward.mux.sshClient.closedPortForward(
  293. portForward.mux.sshClient.udpTrafficState, bytesUp, bytesDown)
  294. log.WithContextFields(
  295. LogFields{
  296. "remoteAddr": fmt.Sprintf("%s:%d",
  297. net.IP(portForward.remoteIP).String(), portForward.remotePort),
  298. "bytesUp": bytesUp,
  299. "bytesDown": bytesDown,
  300. "connID": portForward.connID}).Debug("exiting")
  301. }
  302. // TODO: express and/or calculate udpgwProtocolMaxPayloadSize as function of MTU?
  303. const (
  304. udpgwProtocolFlagKeepalive = 1 << 0
  305. udpgwProtocolFlagRebind = 1 << 1
  306. udpgwProtocolFlagDNS = 1 << 2
  307. udpgwProtocolFlagIPv6 = 1 << 3
  308. udpgwProtocolMaxPreambleSize = 23
  309. udpgwProtocolMaxPayloadSize = 32768
  310. udpgwProtocolMaxMessageSize = udpgwProtocolMaxPreambleSize + udpgwProtocolMaxPayloadSize
  311. )
  312. type udpProtocolMessage struct {
  313. connID uint16
  314. preambleSize int
  315. remoteIP []byte
  316. remotePort uint16
  317. discardExistingConn bool
  318. forwardDNS bool
  319. packet []byte
  320. }
  321. func readUdpgwMessage(
  322. reader io.Reader, buffer []byte) (*udpProtocolMessage, error) {
  323. // udpgw message layout:
  324. //
  325. // | 2 byte size | 3 byte header | 6 or 18 byte address | variable length packet |
  326. for {
  327. // Read message
  328. _, err := io.ReadFull(reader, buffer[0:2])
  329. if err != nil {
  330. return nil, psiphon.ContextError(err)
  331. }
  332. size := uint16(buffer[0]) + uint16(buffer[1])<<8
  333. if int(size) > len(buffer)-2 {
  334. return nil, psiphon.ContextError(errors.New("invalid udpgw message size"))
  335. }
  336. _, err = io.ReadFull(reader, buffer[2:2+size])
  337. if err != nil {
  338. return nil, psiphon.ContextError(err)
  339. }
  340. flags := buffer[2]
  341. connID := uint16(buffer[3]) + uint16(buffer[4])<<8
  342. // Ignore udpgw keep-alive messages -- read another message
  343. if flags&udpgwProtocolFlagKeepalive == udpgwProtocolFlagKeepalive {
  344. continue
  345. }
  346. // Read address
  347. var remoteIP []byte
  348. var remotePort uint16
  349. var packetStart, packetEnd int
  350. if flags&udpgwProtocolFlagIPv6 == udpgwProtocolFlagIPv6 {
  351. if size < 21 {
  352. return nil, psiphon.ContextError(errors.New("invalid udpgw message size"))
  353. }
  354. remoteIP = make([]byte, 16)
  355. copy(remoteIP, buffer[5:21])
  356. remotePort = uint16(buffer[21]) + uint16(buffer[22])<<8
  357. packetStart = 23
  358. packetEnd = 23 + int(size) - 2
  359. } else {
  360. if size < 9 {
  361. return nil, psiphon.ContextError(errors.New("invalid udpgw message size"))
  362. }
  363. remoteIP = make([]byte, 4)
  364. copy(remoteIP, buffer[5:9])
  365. remotePort = uint16(buffer[9]) + uint16(buffer[10])<<8
  366. packetStart = 11
  367. packetEnd = 11 + int(size) - 2
  368. }
  369. // Assemble message
  370. // Note: udpProtocolMessage.packet references memory in the input buffer
  371. message := &udpProtocolMessage{
  372. connID: connID,
  373. preambleSize: packetStart,
  374. remoteIP: remoteIP,
  375. remotePort: remotePort,
  376. discardExistingConn: flags&udpgwProtocolFlagRebind == udpgwProtocolFlagRebind,
  377. forwardDNS: flags&udpgwProtocolFlagDNS == udpgwProtocolFlagDNS,
  378. packet: buffer[packetStart:packetEnd],
  379. }
  380. return message, nil
  381. }
  382. }
  383. func writeUdpgwPreamble(
  384. preambleSize int,
  385. connID uint16,
  386. remoteIP []byte,
  387. remotePort uint16,
  388. packetSize uint16,
  389. buffer []byte) error {
  390. if preambleSize != 7+len(remoteIP) {
  391. return errors.New("invalid udpgw preamble size")
  392. }
  393. size := uint16(preambleSize-2) + packetSize
  394. // size
  395. buffer[0] = byte(size & 0xFF)
  396. buffer[1] = byte(size >> 8)
  397. // flags
  398. buffer[2] = 0
  399. // connID
  400. buffer[3] = byte(connID & 0xFF)
  401. buffer[4] = byte(connID >> 8)
  402. // addr
  403. copy(buffer[5:5+len(remoteIP)], remoteIP)
  404. buffer[5+len(remoteIP)] = byte(remotePort & 0xFF)
  405. buffer[6+len(remoteIP)] = byte(remotePort >> 8)
  406. return nil
  407. }