udp.go 14 KB

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