udp.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. "encoding/binary"
  23. "fmt"
  24. "io"
  25. "net"
  26. "runtime/debug"
  27. "sync"
  28. "sync/atomic"
  29. "github.com/Psiphon-Labs/goarista/monotime"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  33. )
  34. // handleUDPChannel implements UDP port forwarding. A single UDP
  35. // SSH channel follows the udpgw protocol, which multiplexes many
  36. // UDP port forwards.
  37. //
  38. // The udpgw protocol and original server implementation:
  39. // Copyright (c) 2009, Ambroz Bizjak <ambrop7@gmail.com>
  40. // https://github.com/ambrop72/badvpn
  41. //
  42. func (sshClient *sshClient) handleUDPChannel(newChannel ssh.NewChannel) {
  43. // Accept this channel immediately. This channel will replace any
  44. // previously existing UDP channel for this client.
  45. sshChannel, requests, err := newChannel.Accept()
  46. if err != nil {
  47. if !isExpectedTunnelIOError(err) {
  48. log.WithTraceFields(LogFields{"error": err}).Warning("accept new channel failed")
  49. }
  50. return
  51. }
  52. go ssh.DiscardRequests(requests)
  53. defer sshChannel.Close()
  54. sshClient.setUDPChannel(sshChannel)
  55. multiplexer := &udpPortForwardMultiplexer{
  56. sshClient: sshClient,
  57. sshChannel: sshChannel,
  58. portForwards: make(map[uint16]*udpPortForward),
  59. portForwardLRU: common.NewLRUConns(),
  60. relayWaitGroup: new(sync.WaitGroup),
  61. }
  62. multiplexer.run()
  63. }
  64. type udpPortForwardMultiplexer struct {
  65. sshClient *sshClient
  66. sshChannelWriteMutex sync.Mutex
  67. sshChannel ssh.Channel
  68. portForwardsMutex sync.Mutex
  69. portForwards map[uint16]*udpPortForward
  70. portForwardLRU *common.LRUConns
  71. relayWaitGroup *sync.WaitGroup
  72. }
  73. func (mux *udpPortForwardMultiplexer) run() {
  74. // In a loop, read udpgw messages from the client to this channel. Each message is
  75. // a UDP packet to send upstream either via a new port forward, or on an existing
  76. // port forward.
  77. //
  78. // A goroutine is run to read downstream packets for each UDP port forward. All read
  79. // packets are encapsulated in udpgw protocol and sent down the channel to the client.
  80. //
  81. // When the client disconnects or the server shuts down, the channel will close and
  82. // readUdpgwMessage will exit with EOF.
  83. // Recover from and log any unexpected panics caused by udpgw input handling bugs.
  84. // Note: this covers the run() goroutine only and not relayDownstream() goroutines.
  85. defer func() {
  86. if e := recover(); e != nil {
  87. err := errors.Tracef(
  88. "udpPortForwardMultiplexer panic: %s: %s", e, debug.Stack())
  89. log.WithTraceFields(LogFields{"error": err}).Warning("run failed")
  90. }
  91. }()
  92. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  93. for {
  94. // Note: message.packet points to the reusable memory in "buffer".
  95. // Each readUdpgwMessage call will overwrite the last message.packet.
  96. message, err := readUdpgwMessage(mux.sshChannel, buffer)
  97. if err != nil {
  98. if err != io.EOF {
  99. // Debug since I/O errors occur during normal operation
  100. log.WithTraceFields(LogFields{"error": err}).Debug("readUdpgwMessage failed")
  101. }
  102. break
  103. }
  104. mux.portForwardsMutex.Lock()
  105. portForward := mux.portForwards[message.connID]
  106. mux.portForwardsMutex.Unlock()
  107. if portForward != nil && message.discardExistingConn {
  108. // The port forward's goroutine will complete cleanup, including
  109. // tallying stats and calling sshClient.closedPortForward.
  110. // portForward.conn.Close() will signal this shutdown.
  111. // TODO: wait for goroutine to exit before proceeding?
  112. portForward.conn.Close()
  113. portForward = nil
  114. }
  115. if portForward != nil {
  116. // Verify that portForward remote address matches latest message
  117. if !bytes.Equal(portForward.remoteIP, message.remoteIP) ||
  118. portForward.remotePort != message.remotePort {
  119. log.WithTrace().Warning("UDP port forward remote address mismatch")
  120. continue
  121. }
  122. } else {
  123. // Create a new port forward
  124. dialIP := net.IP(message.remoteIP)
  125. dialPort := int(message.remotePort)
  126. // Validate DNS packets and check the domain blocklist both when the client
  127. // indicates DNS or when DNS is _not_ indicated and the destination port is
  128. // 53.
  129. if message.forwardDNS || message.remotePort == 53 {
  130. domain, err := common.ParseDNSQuestion(message.packet)
  131. if err != nil {
  132. log.WithTraceFields(LogFields{"error": err}).Debug("ParseDNSQuestion failed")
  133. // Drop packet
  134. continue
  135. }
  136. if domain != "" {
  137. ok, _ := mux.sshClient.isDomainPermitted(domain)
  138. if !ok {
  139. // Drop packet
  140. continue
  141. }
  142. }
  143. }
  144. if message.forwardDNS {
  145. // Transparent DNS forwarding. In this case, isPortForwardPermitted
  146. // traffic rules checks are bypassed, since DNS is essential.
  147. dialIP = mux.sshClient.sshServer.support.DNSResolver.Get()
  148. dialPort = DNS_RESOLVER_PORT
  149. } else if !mux.sshClient.isPortForwardPermitted(
  150. portForwardTypeUDP, dialIP, int(message.remotePort)) {
  151. // The udpgw protocol has no error response, so
  152. // we just discard the message and read another.
  153. continue
  154. }
  155. // Note: UDP port forward counting has no dialing phase
  156. // establishedPortForward increments the concurrent UDP port
  157. // forward counter and closes the LRU existing UDP port forward
  158. // when already at the limit.
  159. mux.sshClient.establishedPortForward(portForwardTypeUDP, mux.portForwardLRU)
  160. // Can't defer sshClient.closedPortForward() here;
  161. // relayDownstream will call sshClient.closedPortForward()
  162. log.WithTraceFields(
  163. LogFields{
  164. "remoteAddr": fmt.Sprintf("%s:%d", dialIP.String(), dialPort),
  165. "connID": message.connID}).Debug("dialing")
  166. udpConn, err := net.DialUDP(
  167. "udp", nil, &net.UDPAddr{IP: dialIP, Port: dialPort})
  168. if err != nil {
  169. mux.sshClient.closedPortForward(portForwardTypeUDP, 0, 0)
  170. // Monitor for low resource error conditions
  171. mux.sshClient.sshServer.monitorPortForwardDialError(err)
  172. // Note: Debug level, as logMessage may contain user traffic destination address information
  173. log.WithTraceFields(LogFields{"error": err}).Debug("DialUDP failed")
  174. continue
  175. }
  176. lruEntry := mux.portForwardLRU.Add(udpConn)
  177. // Can't defer lruEntry.Remove() here;
  178. // relayDownstream will call lruEntry.Remove()
  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. // Ensure nil interface if newClientSeedPortForward returns nil
  184. var updater common.ActivityUpdater
  185. seedUpdater := mux.sshClient.newClientSeedPortForward(dialIP)
  186. if seedUpdater != nil {
  187. updater = seedUpdater
  188. }
  189. conn, err := common.NewActivityMonitoredConn(
  190. udpConn,
  191. mux.sshClient.idleUDPPortForwardTimeout(),
  192. true,
  193. updater,
  194. lruEntry)
  195. if err != nil {
  196. lruEntry.Remove()
  197. mux.sshClient.closedPortForward(portForwardTypeUDP, 0, 0)
  198. log.WithTraceFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  199. continue
  200. }
  201. portForward = &udpPortForward{
  202. connID: message.connID,
  203. preambleSize: message.preambleSize,
  204. remoteIP: message.remoteIP,
  205. remotePort: message.remotePort,
  206. dialIP: dialIP,
  207. conn: conn,
  208. lruEntry: lruEntry,
  209. bytesUp: 0,
  210. bytesDown: 0,
  211. mux: mux,
  212. }
  213. if message.forwardDNS {
  214. portForward.dnsFirstWriteTime = int64(monotime.Now())
  215. }
  216. mux.portForwardsMutex.Lock()
  217. mux.portForwards[portForward.connID] = portForward
  218. mux.portForwardsMutex.Unlock()
  219. mux.relayWaitGroup.Add(1)
  220. go portForward.relayDownstream()
  221. }
  222. // Note: assumes UDP writes won't block (https://golang.org/pkg/net/#UDPConn.WriteToUDP)
  223. _, err = portForward.conn.Write(message.packet)
  224. if err != nil {
  225. // Debug since errors such as "write: operation not permitted" occur during normal operation
  226. log.WithTraceFields(LogFields{"error": err}).Debug("upstream UDP relay failed")
  227. // The port forward's goroutine will complete cleanup
  228. portForward.conn.Close()
  229. }
  230. portForward.lruEntry.Touch()
  231. atomic.AddInt64(&portForward.bytesUp, int64(len(message.packet)))
  232. }
  233. // Cleanup all UDP port forward workers when exiting
  234. mux.portForwardsMutex.Lock()
  235. for _, portForward := range mux.portForwards {
  236. // The port forward's goroutine will complete cleanup
  237. portForward.conn.Close()
  238. }
  239. mux.portForwardsMutex.Unlock()
  240. mux.relayWaitGroup.Wait()
  241. }
  242. func (mux *udpPortForwardMultiplexer) removePortForward(connID uint16) {
  243. mux.portForwardsMutex.Lock()
  244. delete(mux.portForwards, connID)
  245. mux.portForwardsMutex.Unlock()
  246. }
  247. type udpPortForward struct {
  248. // Note: 64-bit ints used with atomic operations are placed
  249. // at the start of struct to ensure 64-bit alignment.
  250. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  251. dnsFirstWriteTime int64
  252. dnsFirstReadTime int64
  253. bytesUp int64
  254. bytesDown int64
  255. connID uint16
  256. preambleSize int
  257. remoteIP []byte
  258. remotePort uint16
  259. dialIP net.IP
  260. conn net.Conn
  261. lruEntry *common.LRUConnsEntry
  262. mux *udpPortForwardMultiplexer
  263. }
  264. func (portForward *udpPortForward) relayDownstream() {
  265. defer portForward.mux.relayWaitGroup.Done()
  266. // Downstream UDP packets are read into the reusable memory
  267. // in "buffer" starting at the offset past the udpgw message
  268. // header and address, leaving enough space to write the udpgw
  269. // values into the same buffer and use for writing to the ssh
  270. // channel.
  271. //
  272. // Note: there is one downstream buffer per UDP port forward,
  273. // while for upstream there is one buffer per client.
  274. // TODO: is the buffer size larger than necessary?
  275. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  276. packetBuffer := buffer[portForward.preambleSize:udpgwProtocolMaxMessageSize]
  277. for {
  278. // TODO: if read buffer is too small, excess bytes are discarded?
  279. packetSize, err := portForward.conn.Read(packetBuffer)
  280. if packetSize > udpgwProtocolMaxPayloadSize {
  281. err = fmt.Errorf("unexpected packet size: %d", packetSize)
  282. }
  283. if err != nil {
  284. if err != io.EOF {
  285. // Debug since errors such as "use of closed network connection" occur during normal operation
  286. log.WithTraceFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  287. }
  288. break
  289. }
  290. if atomic.LoadInt64(&portForward.dnsFirstWriteTime) > 0 &&
  291. atomic.LoadInt64(&portForward.dnsFirstReadTime) == 0 { // Check if already set before invoking Now.
  292. atomic.CompareAndSwapInt64(&portForward.dnsFirstReadTime, 0, int64(monotime.Now()))
  293. }
  294. err = writeUdpgwPreamble(
  295. portForward.preambleSize,
  296. 0,
  297. portForward.connID,
  298. portForward.remoteIP,
  299. portForward.remotePort,
  300. uint16(packetSize),
  301. buffer)
  302. if err == nil {
  303. // ssh.Channel.Write cannot be called concurrently.
  304. // See: https://github.com/Psiphon-Inc/crypto/blob/82d98b4c7c05e81f92545f6fddb45d4541e6da00/ssh/channel.go#L272,
  305. // https://codereview.appspot.com/136420043/diff/80002/ssh/channel.go
  306. portForward.mux.sshChannelWriteMutex.Lock()
  307. _, err = portForward.mux.sshChannel.Write(buffer[0 : portForward.preambleSize+packetSize])
  308. portForward.mux.sshChannelWriteMutex.Unlock()
  309. }
  310. if err != nil {
  311. // Close the channel, which will interrupt the main loop.
  312. portForward.mux.sshChannel.Close()
  313. log.WithTraceFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  314. break
  315. }
  316. portForward.lruEntry.Touch()
  317. atomic.AddInt64(&portForward.bytesDown, int64(packetSize))
  318. }
  319. portForward.mux.removePortForward(portForward.connID)
  320. portForward.lruEntry.Remove()
  321. portForward.conn.Close()
  322. bytesUp := atomic.LoadInt64(&portForward.bytesUp)
  323. bytesDown := atomic.LoadInt64(&portForward.bytesDown)
  324. portForward.mux.sshClient.closedPortForward(portForwardTypeUDP, bytesUp, bytesDown)
  325. dnsStartTime := monotime.Time(atomic.LoadInt64(&portForward.dnsFirstWriteTime))
  326. if dnsStartTime > 0 {
  327. // Record DNS metrics using a heuristic: if a UDP packet was written and
  328. // then a packet was read, assume the DNS request successfully received a
  329. // valid response; failure occurs when the resolver fails to provide a
  330. // response; a "no such host" response is still a success. Limitations: we
  331. // assume a resolver will not respond when, e.g., rate limiting; we ignore
  332. // subsequent requests made via the same UDP port forward.
  333. dnsEndTime := monotime.Time(atomic.LoadInt64(&portForward.dnsFirstReadTime))
  334. dnsSuccess := true
  335. if dnsEndTime == 0 {
  336. dnsSuccess = false
  337. dnsEndTime = monotime.Now()
  338. }
  339. resolveElapsedTime := dnsEndTime.Sub(dnsStartTime)
  340. portForward.mux.sshClient.updateQualityMetricsWithDNSResult(
  341. dnsSuccess,
  342. resolveElapsedTime,
  343. net.IP(portForward.dialIP))
  344. }
  345. log.WithTraceFields(
  346. LogFields{
  347. "remoteAddr": fmt.Sprintf("%s:%d",
  348. net.IP(portForward.remoteIP).String(), portForward.remotePort),
  349. "bytesUp": bytesUp,
  350. "bytesDown": bytesDown,
  351. "connID": portForward.connID}).Debug("exiting")
  352. }
  353. // TODO: express and/or calculate udpgwProtocolMaxPayloadSize as function of MTU?
  354. const (
  355. udpgwProtocolFlagKeepalive = 1 << 0
  356. udpgwProtocolFlagRebind = 1 << 1
  357. udpgwProtocolFlagDNS = 1 << 2
  358. udpgwProtocolFlagIPv6 = 1 << 3
  359. udpgwProtocolMaxPreambleSize = 23
  360. udpgwProtocolMaxPayloadSize = 32768
  361. udpgwProtocolMaxMessageSize = udpgwProtocolMaxPreambleSize + udpgwProtocolMaxPayloadSize
  362. )
  363. type udpgwProtocolMessage struct {
  364. connID uint16
  365. preambleSize int
  366. remoteIP []byte
  367. remotePort uint16
  368. discardExistingConn bool
  369. forwardDNS bool
  370. packet []byte
  371. }
  372. func readUdpgwMessage(
  373. reader io.Reader, buffer []byte) (*udpgwProtocolMessage, error) {
  374. // udpgw message layout:
  375. //
  376. // | 2 byte size | 3 byte header | 6 or 18 byte address | variable length packet |
  377. for {
  378. // Read message
  379. _, err := io.ReadFull(reader, buffer[0:2])
  380. if err != nil {
  381. if err != io.EOF {
  382. err = errors.Trace(err)
  383. }
  384. return nil, err
  385. }
  386. size := binary.LittleEndian.Uint16(buffer[0:2])
  387. if size < 3 || int(size) > len(buffer)-2 {
  388. return nil, errors.TraceNew("invalid udpgw message size")
  389. }
  390. _, err = io.ReadFull(reader, buffer[2:2+size])
  391. if err != nil {
  392. if err != io.EOF {
  393. err = errors.Trace(err)
  394. }
  395. return nil, err
  396. }
  397. flags := buffer[2]
  398. connID := binary.LittleEndian.Uint16(buffer[3:5])
  399. // Ignore udpgw keep-alive messages -- read another message
  400. if flags&udpgwProtocolFlagKeepalive == udpgwProtocolFlagKeepalive {
  401. continue
  402. }
  403. // Read address
  404. var remoteIP []byte
  405. var remotePort uint16
  406. var packetStart, packetEnd int
  407. if flags&udpgwProtocolFlagIPv6 == udpgwProtocolFlagIPv6 {
  408. if size < 21 {
  409. return nil, errors.TraceNew("invalid udpgw message size")
  410. }
  411. remoteIP = make([]byte, 16)
  412. copy(remoteIP, buffer[5:21])
  413. remotePort = binary.BigEndian.Uint16(buffer[21:23])
  414. packetStart = 23
  415. packetEnd = 23 + int(size) - 21
  416. } else {
  417. if size < 9 {
  418. return nil, errors.TraceNew("invalid udpgw message size")
  419. }
  420. remoteIP = make([]byte, 4)
  421. copy(remoteIP, buffer[5:9])
  422. remotePort = binary.BigEndian.Uint16(buffer[9:11])
  423. packetStart = 11
  424. packetEnd = 11 + int(size) - 9
  425. }
  426. // Assemble message
  427. // Note: udpgwProtocolMessage.packet references memory in the input buffer
  428. message := &udpgwProtocolMessage{
  429. connID: connID,
  430. preambleSize: packetStart,
  431. remoteIP: remoteIP,
  432. remotePort: remotePort,
  433. discardExistingConn: flags&udpgwProtocolFlagRebind == udpgwProtocolFlagRebind,
  434. forwardDNS: flags&udpgwProtocolFlagDNS == udpgwProtocolFlagDNS,
  435. packet: buffer[packetStart:packetEnd],
  436. }
  437. return message, nil
  438. }
  439. }
  440. func writeUdpgwPreamble(
  441. preambleSize int,
  442. flags uint8,
  443. connID uint16,
  444. remoteIP []byte,
  445. remotePort uint16,
  446. packetSize uint16,
  447. buffer []byte) error {
  448. if preambleSize != 7+len(remoteIP) {
  449. return errors.TraceNew("invalid udpgw preamble size")
  450. }
  451. size := uint16(preambleSize-2) + packetSize
  452. // size
  453. binary.LittleEndian.PutUint16(buffer[0:2], size)
  454. // flags
  455. buffer[2] = flags
  456. // connID
  457. binary.LittleEndian.PutUint16(buffer[3:5], connID)
  458. // addr
  459. copy(buffer[5:5+len(remoteIP)], remoteIP)
  460. binary.BigEndian.PutUint16(buffer[5+len(remoteIP):7+len(remoteIP)], remotePort)
  461. return nil
  462. }