udp.go 15 KB

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