tun.go 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645
  1. /*
  2. * Copyright (c) 2017, 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. // Copyright 2009 The Go Authors. All rights reserved.
  20. // Use of this source code is governed by a BSD-style
  21. // license that can be found in the LICENSE file.
  22. /*
  23. Package tun is an IP packet tunnel server and client. It supports tunneling
  24. both IPv4 and IPv6.
  25. ......................................................... .-,( ),-.
  26. . [server] .-----. . .-( )-.
  27. . | NIC |<---->( Internet )
  28. . ....................................... '-----' . '-( ).-'
  29. . . [packet tunnel daemon] . ^ . '-.( ).-'
  30. . . . | .
  31. . . ........................... . | .
  32. . . . [session] . . NAT .
  33. . . . . . | .
  34. . . . . . v .
  35. . . . . . .---. .
  36. . . . . . | t | .
  37. . . . . . | u | .
  38. . . . .---. . .---. . | n | .
  39. . . . | q | . | d | . | | .
  40. . . . | u | . | e | . | d | .
  41. . . . .------| e |<-----| m |<---------| e | .
  42. . . . | | u | . | u | . | v | .
  43. . . . | | e | . | x | . | i | .
  44. . . . rewrite '---' . '---' . | c | .
  45. . . . | . . | e | .
  46. . . . v . . '---' .
  47. . . . .---------. . . ^ .
  48. . . . | channel |--rewrite--------------------' .
  49. . . . '---------' . . .
  50. . . ...........^............... . .
  51. . .............|......................... .
  52. ...............|.........................................
  53. |
  54. | (typically via Internet)
  55. |
  56. ...............|.................
  57. . [client] | .
  58. . | .
  59. . .............|............... .
  60. . . v . .
  61. . . .---------. . .
  62. . . | channel | . .
  63. . . '---------' . .
  64. . . ^ . .
  65. . .............|............... .
  66. . v .
  67. . .------------. .
  68. . | tun device | .
  69. . '------------' .
  70. .................................
  71. The client relays IP packets between a local tun device and a channel, which
  72. is a transport to the server. In Psiphon, the channel will be an SSH channel
  73. within an SSH connection to a Psiphon server.
  74. The server relays packets between each client and its own tun device. The
  75. server tun device is NATed to the Internet via an external network interface.
  76. In this way, client traffic is tunneled and will egress from the server host.
  77. Similar to a typical VPN, IP addresses are assigned to each client. Unlike
  78. a typical VPN, the assignment is not transmitted to the client. Instead, the
  79. server transparently rewrites the source addresses of client packets to
  80. the assigned IP address. The server also rewrites the destination address of
  81. certain DNS packets. The purpose of this is to allow clients to reconnect
  82. to different servers without having to tear down or change their local
  83. network configuration. Clients may configure their local tun device with an
  84. arbitrary IP address and a static DNS resolver address.
  85. The server uses the 24-bit 10.0.0.0/8 IPv4 private address space to maximize
  86. the number of addresses available, due to Psiphon client churn and minimum
  87. address lease time constraints. For IPv6, a 24-bit unique local space is used.
  88. When a client is allocated addresses, a unique, unused 24-bit "index" is
  89. reserved/leased. This index maps to and from IPv4 and IPv6 private addresses.
  90. The server multiplexes all client packets into a single tun device. When a
  91. packet is read, the destination address is used to map the packet back to the
  92. correct index, which maps back to the client.
  93. The server maintains client "sessions". A session maintains client IP
  94. address state and effectively holds the lease on assigned addresses. If a
  95. client is disconnected and quickly reconnects, it will resume its previous
  96. session, retaining its IP address and network connection states. Idle
  97. sessions with no client connection will eventually expire.
  98. Packet count and bytes transferred metrics are logged for each client session.
  99. The server integrates with and enforces Psiphon traffic rules and logging
  100. facilities. The server parses and validates packets. Client-to-client packets
  101. are not permitted. Only global unicast packets are permitted. Only TCP and UDP
  102. packets are permitted. The client also filters out, before sending, packets
  103. that the server won't route.
  104. Certain aspects of packet tunneling are outside the scope of this package;
  105. e.g, the Psiphon client and server are responsible for establishing an SSH
  106. channel and negotiating the correct MTU and DNS settings. The Psiphon
  107. server will call Server.ClientConnected when a client connects and establishes
  108. a packet tunnel channel; and Server.ClientDisconnected when the client closes
  109. the channel and/or disconnects.
  110. */
  111. package tun
  112. import (
  113. "context"
  114. "encoding/binary"
  115. "errors"
  116. "fmt"
  117. "io"
  118. "math/rand"
  119. "net"
  120. "sync"
  121. "sync/atomic"
  122. "time"
  123. "github.com/Psiphon-Inc/goarista/monotime"
  124. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  125. )
  126. const (
  127. DEFAULT_MTU = 1500
  128. DEFAULT_DOWNSTREAM_PACKET_QUEUE_SIZE = 32768 * 16
  129. DEFAULT_UPSTREAM_PACKET_QUEUE_SIZE = 32768
  130. DEFAULT_IDLE_SESSION_EXPIRY_SECONDS = 300
  131. ORPHAN_METRICS_CHECKPOINTER_PERIOD = 30 * time.Minute
  132. FLOW_IDLE_EXPIRY = 60 * time.Second
  133. )
  134. // ServerConfig specifies the configuration of a packet tunnel server.
  135. type ServerConfig struct {
  136. // Logger is used for logging events and metrics.
  137. Logger common.Logger
  138. // SudoNetworkConfigCommands specifies whether to use "sudo"
  139. // when executing network configuration commands. This is required
  140. // when the packet tunnel server is not run as root and when
  141. // process capabilities are not available (only Linux kernel 4.3+
  142. // has the required capabilities support). The host sudoers file
  143. // must be configured to allow the tunnel server process user to
  144. // execute the commands invoked in configureServerInterface; see
  145. // the implementation for the appropriate platform.
  146. SudoNetworkConfigCommands bool
  147. // AllowNoIPv6NetworkConfiguration indicates that failures while
  148. // configuring tun interfaces and routing for IPv6 are to be
  149. // logged as warnings only. This option is intended to support
  150. // test cases on hosts without IPv6 and is not for production use;
  151. // the packet tunnel server will still accept IPv6 packets and
  152. // replay them to the tun device.
  153. // AllowNoIPv6NetworkConfiguration may not be supported on all
  154. // platforms.
  155. AllowNoIPv6NetworkConfiguration bool
  156. // EgressInterface is the interface to which client traffic is
  157. // masqueraded/NATed. For example, "eth0". If blank, a platform-
  158. // appropriate default is used.
  159. EgressInterface string
  160. // GetDNSResolverIPv4Addresses is a function which returns the
  161. // DNS resolvers to use as transparent DNS rewrite targets for
  162. // IPv4 DNS traffic.
  163. //
  164. // GetDNSResolverIPv4Addresses is invoked for each new client
  165. // session and the list of resolvers is stored with the session.
  166. // This is a compromise between checking current resolvers for
  167. // each packet (too expensive) and simply passing in a static
  168. // list (won't pick up resolver changes). As implemented, only
  169. // new client sessions will pick up resolver changes.
  170. //
  171. // Transparent DNS rewriting occurs when the client uses the
  172. // specific, target transparent DNS addresses specified by
  173. // GetTransparentDNSResolverIPv4/6Address.
  174. //
  175. // For outbound DNS packets with a target resolver IP address,
  176. // a random resolver is selected and used for the rewrite.
  177. // For inbound packets, _any_ resolver in the list is rewritten
  178. // back to the target resolver IP address. As a side-effect,
  179. // responses to client DNS packets originally destined for a
  180. // resolver in GetDNSResolverIPv4Addresses will be lost.
  181. GetDNSResolverIPv4Addresses func() []net.IP
  182. // GetDNSResolverIPv6Addresses is a function which returns the
  183. // DNS resolvers to use as transparent DNS rewrite targets for
  184. // IPv6 DNS traffic. It functions like GetDNSResolverIPv4Addresses.
  185. GetDNSResolverIPv6Addresses func() []net.IP
  186. // DownstreamPacketQueueSize specifies the size of the downstream
  187. // packet queue. The packet tunnel server multiplexes all client
  188. // packets through a single tun device, so when a packet is read,
  189. // it must be queued or dropped if it cannot be immediately routed
  190. // to the appropriate client. Note that the TCP and SSH windows
  191. // for the underlying channel transport will impact transfer rate
  192. // and queuing.
  193. // When DownstreamPacketQueueSize is 0, a default value tuned for
  194. // Psiphon is used.
  195. DownstreamPacketQueueSize int
  196. // MTU specifies the maximum transmission unit for the packet
  197. // tunnel. Clients must be configured with the same MTU. The
  198. // server's tun device will be set to this MTU value and is
  199. // assumed not to change for the duration of the server.
  200. // When MTU is 0, a default value is used.
  201. MTU int
  202. // SessionIdleExpirySeconds specifies how long to retain client
  203. // sessions which have no client attached. Sessions are retained
  204. // across client connections so reconnecting clients can resume
  205. // a previous session. Resuming avoids leasing new IP addresses
  206. // for reconnection, and also retains NAT state for active
  207. // tunneled connections.
  208. //
  209. // SessionIdleExpirySeconds is also, effectively, the lease
  210. // time for assigned IP addresses.
  211. SessionIdleExpirySeconds int
  212. }
  213. // Server is a packet tunnel server. A packet tunnel server
  214. // maintains client sessions, relays packets through client
  215. // channels, and multiplexes packets through a single tun
  216. // device. The server assigns IP addresses to clients, performs
  217. // IP address and transparent DNS rewriting, and enforces
  218. // traffic rules.
  219. type Server struct {
  220. config *ServerConfig
  221. device *Device
  222. indexToSession sync.Map
  223. sessionIDToIndex sync.Map
  224. connectedInProgress *sync.WaitGroup
  225. workers *sync.WaitGroup
  226. runContext context.Context
  227. stopRunning context.CancelFunc
  228. orphanMetrics *packetMetrics
  229. }
  230. // NewServer initializes a server.
  231. func NewServer(config *ServerConfig) (*Server, error) {
  232. device, err := NewServerDevice(config)
  233. if err != nil {
  234. return nil, common.ContextError(err)
  235. }
  236. runContext, stopRunning := context.WithCancel(context.Background())
  237. return &Server{
  238. config: config,
  239. device: device,
  240. connectedInProgress: new(sync.WaitGroup),
  241. workers: new(sync.WaitGroup),
  242. runContext: runContext,
  243. stopRunning: stopRunning,
  244. orphanMetrics: new(packetMetrics),
  245. }, nil
  246. }
  247. // Start starts a server and returns with it running.
  248. func (server *Server) Start() {
  249. server.config.Logger.WithContext().Info("starting")
  250. server.workers.Add(1)
  251. go server.runSessionReaper()
  252. server.workers.Add(1)
  253. go server.runOrphanMetricsCheckpointer()
  254. server.workers.Add(1)
  255. go server.runDeviceDownstream()
  256. }
  257. // Stop halts a running server.
  258. func (server *Server) Stop() {
  259. server.config.Logger.WithContext().Info("stopping")
  260. server.stopRunning()
  261. // Interrupt blocked device read/writes.
  262. server.device.Close()
  263. // Wait for any in-progress ClientConnected calls to complete.
  264. server.connectedInProgress.Wait()
  265. // After this point, no further clients will be added: all
  266. // in-progress ClientConnected calls have finished; and any
  267. // later ClientConnected calls won't get past their
  268. // server.runContext.Done() checks.
  269. // Close all clients. Client workers will be joined
  270. // by the following server.workers.Wait().
  271. server.indexToSession.Range(func(_, value interface{}) bool {
  272. session := value.(*session)
  273. server.interruptSession(session)
  274. return true
  275. })
  276. server.workers.Wait()
  277. server.config.Logger.WithContext().Info("stopped")
  278. }
  279. // AllowedPortChecker is a function which returns true when it is
  280. // permitted to relay packets to the specified upstream IP address
  281. // and/or port.
  282. type AllowedPortChecker func(upstreamIPAddress net.IP, port int) bool
  283. // FlowActivityUpdater defines an interface for receiving updates for
  284. // flow activity. Values passed to UpdateProgress are bytes transferred
  285. // and flow duration since the previous UpdateProgress.
  286. type FlowActivityUpdater interface {
  287. UpdateProgress(upstreamBytes, downstreamBytes int64, durationNanoseconds int64)
  288. }
  289. // FlowActivityUpdaterMaker is a function which returns a list of
  290. // appropriate updaters for a new flow to the specified upstream
  291. // hostname (if known -- may be ""), and IP address.
  292. type FlowActivityUpdaterMaker func(
  293. upstreamHostname string, upstreamIPAddress net.IP) []FlowActivityUpdater
  294. // ClientConnected handles new client connections, creating or resuming
  295. // a session and returns with client packet handlers running.
  296. //
  297. // sessionID is used to identify sessions for resumption.
  298. //
  299. // transport provides the channel for relaying packets to and from
  300. // the client.
  301. //
  302. // checkAllowedTCPPortFunc/checkAllowedUDPPortFunc are callbacks used
  303. // to enforce traffic rules. For each TCP/UDP packet, the corresponding
  304. // function is called to check if traffic to the packet's port is
  305. // permitted. These callbacks must be efficient and safe for concurrent
  306. // calls.
  307. //
  308. // It is safe to make concurrent calls to ClientConnected for distinct
  309. // session IDs. The caller is responsible for serializing calls with the
  310. // same session ID. Further, the caller must ensure, in the case of a client
  311. // transport reconnect when an existing transport has not yet disconnected,
  312. // that ClientDisconnected is called first -- so it doesn't undo the new
  313. // ClientConnected. (psiphond meets these constraints by closing any
  314. // existing SSH client with duplicate session ID early in the lifecycle of
  315. // a new SSH client connection.)
  316. func (server *Server) ClientConnected(
  317. sessionID string,
  318. transport io.ReadWriteCloser,
  319. checkAllowedTCPPortFunc, checkAllowedUDPPortFunc AllowedPortChecker,
  320. flowActivityUpdaterMaker FlowActivityUpdaterMaker) error {
  321. // It's unusual to call both sync.WaitGroup.Add() _and_ Done() in the same
  322. // goroutine. There's no other place to call Add() since ClientConnected is
  323. // an API entrypoint. And Done() works because the invariant enforced by
  324. // connectedInProgress.Wait() is not that no ClientConnected calls are in
  325. // progress, but that no such calls are in progress past the
  326. // server.runContext.Done() check.
  327. // TODO: will this violate https://golang.org/pkg/sync/#WaitGroup.Add:
  328. // "calls with a positive delta that occur when the counter is zero must happen before a Wait"?
  329. server.connectedInProgress.Add(1)
  330. defer server.connectedInProgress.Done()
  331. select {
  332. case <-server.runContext.Done():
  333. return common.ContextError(errors.New("server stopping"))
  334. default:
  335. }
  336. server.config.Logger.WithContextFields(
  337. common.LogFields{"sessionID": sessionID}).Info("client connected")
  338. MTU := getMTU(server.config.MTU)
  339. clientSession := server.getSession(sessionID)
  340. if clientSession != nil {
  341. // Call interruptSession to ensure session is in the
  342. // expected idle state.
  343. server.interruptSession(clientSession)
  344. // Note: we don't check the session expiry; whether it has
  345. // already expired and not yet been reaped; or is about
  346. // to expire very shortly. It could happen that the reaper
  347. // will kill this session between now and when the expiry
  348. // is reset in the following resumeSession call. In this
  349. // unlikely case, the packet tunnel client should reconnect.
  350. } else {
  351. downstreamPacketQueueSize := DEFAULT_DOWNSTREAM_PACKET_QUEUE_SIZE
  352. if server.config.DownstreamPacketQueueSize > 0 {
  353. downstreamPacketQueueSize = server.config.DownstreamPacketQueueSize
  354. }
  355. // Store IPv4 resolver addresses in 4-byte representation
  356. // for use in rewritting.
  357. resolvers := server.config.GetDNSResolverIPv4Addresses()
  358. DNSResolverIPv4Addresses := make([]net.IP, len(resolvers))
  359. for i, resolver := range resolvers {
  360. // Assumes To4 is non-nil
  361. DNSResolverIPv4Addresses[i] = resolver.To4()
  362. }
  363. clientSession = &session{
  364. lastActivity: int64(monotime.Now()),
  365. sessionID: sessionID,
  366. metrics: new(packetMetrics),
  367. DNSResolverIPv4Addresses: append([]net.IP(nil), DNSResolverIPv4Addresses...),
  368. DNSResolverIPv6Addresses: append([]net.IP(nil), server.config.GetDNSResolverIPv6Addresses()...),
  369. checkAllowedTCPPortFunc: checkAllowedTCPPortFunc,
  370. checkAllowedUDPPortFunc: checkAllowedUDPPortFunc,
  371. flowActivityUpdaterMaker: flowActivityUpdaterMaker,
  372. downstreamPackets: NewPacketQueue(downstreamPacketQueueSize),
  373. workers: new(sync.WaitGroup),
  374. }
  375. // allocateIndex initializes session.index, session.assignedIPv4Address,
  376. // and session.assignedIPv6Address; and updates server.indexToSession and
  377. // server.sessionIDToIndex.
  378. err := server.allocateIndex(clientSession)
  379. if err != nil {
  380. return common.ContextError(err)
  381. }
  382. }
  383. // Note: it's possible that a client disconnects (or reconnects before a
  384. // disconnect is detected) and interruptSession is called between
  385. // allocateIndex and resumeSession calls here, so interruptSession and
  386. // related code must not assume resumeSession has been called.
  387. server.resumeSession(clientSession, NewChannel(transport, MTU))
  388. return nil
  389. }
  390. // ClientDisconnected handles clients disconnecting. Packet handlers
  391. // are halted, but the client session is left intact to reserve the
  392. // assigned IP addresses and retain network state in case the client
  393. // soon reconnects.
  394. func (server *Server) ClientDisconnected(sessionID string) {
  395. session := server.getSession(sessionID)
  396. if session != nil {
  397. server.config.Logger.WithContextFields(
  398. common.LogFields{"sessionID": sessionID}).Info("client disconnected")
  399. server.interruptSession(session)
  400. }
  401. }
  402. func (server *Server) getSession(sessionID string) *session {
  403. if index, ok := server.sessionIDToIndex.Load(sessionID); ok {
  404. s, ok := server.indexToSession.Load(index.(int32))
  405. if ok {
  406. return s.(*session)
  407. }
  408. server.config.Logger.WithContext().Warning("unexpected missing session")
  409. }
  410. return nil
  411. }
  412. func (server *Server) resumeSession(session *session, channel *Channel) {
  413. session.mutex.Lock()
  414. defer session.mutex.Unlock()
  415. session.channel = channel
  416. // Parent context is not server.runContext so that session workers
  417. // need only check session.stopRunning to act on shutdown events.
  418. session.runContext, session.stopRunning = context.WithCancel(context.Background())
  419. // When a session is interrupted, all goroutines in session.workers
  420. // are joined. When the server is stopped, all goroutines in
  421. // server.workers are joined. So, in both cases we synchronously
  422. // stop all workers associated with this session.
  423. session.workers.Add(1)
  424. go server.runClientUpstream(session)
  425. session.workers.Add(1)
  426. go server.runClientDownstream(session)
  427. session.touch()
  428. }
  429. func (server *Server) interruptSession(session *session) {
  430. session.mutex.Lock()
  431. defer session.mutex.Unlock()
  432. wasRunning := (session.channel != nil)
  433. if session.stopRunning != nil {
  434. session.stopRunning()
  435. }
  436. if session.channel != nil {
  437. // Interrupt blocked channel read/writes.
  438. session.channel.Close()
  439. }
  440. session.workers.Wait()
  441. if session.channel != nil {
  442. // Don't hold a reference to channel, allowing both it and
  443. // its conn to be garbage collected.
  444. // Setting channel to nil must happen after workers.Wait()
  445. // to ensure no goroutine remains which may access
  446. // session.channel.
  447. session.channel = nil
  448. }
  449. // interruptSession may be called for idle sessions, to ensure
  450. // the session is in an expected state: in ClientConnected,
  451. // and in server.Stop(); don't log in those cases.
  452. if wasRunning {
  453. session.metrics.checkpoint(
  454. server.config.Logger, "packet_metrics", packetMetricsAll)
  455. }
  456. }
  457. func (server *Server) runSessionReaper() {
  458. defer server.workers.Done()
  459. // Periodically iterate over all sessions and discard expired
  460. // sessions. This action, removing the index from server.indexToSession,
  461. // releases the IP addresses assigned to the session.
  462. // TODO: As-is, this will discard sessions for live SSH tunnels,
  463. // as long as the SSH channel for such a session has been idle for
  464. // a sufficient period. Should the session be retained as long as
  465. // the SSH tunnel is alive (e.g., expose and call session.touch()
  466. // on keepalive events)? Or is it better to free up resources held
  467. // by idle sessions?
  468. idleExpiry := server.sessionIdleExpiry()
  469. ticker := time.NewTicker(idleExpiry / 2)
  470. defer ticker.Stop()
  471. for {
  472. select {
  473. case <-ticker.C:
  474. server.indexToSession.Range(func(_, value interface{}) bool {
  475. session := value.(*session)
  476. if session.expired(idleExpiry) {
  477. server.removeSession(session)
  478. }
  479. return true
  480. })
  481. case <-server.runContext.Done():
  482. return
  483. }
  484. }
  485. }
  486. func (server *Server) sessionIdleExpiry() time.Duration {
  487. sessionIdleExpirySeconds := DEFAULT_IDLE_SESSION_EXPIRY_SECONDS
  488. if server.config.SessionIdleExpirySeconds > 2 {
  489. sessionIdleExpirySeconds = server.config.SessionIdleExpirySeconds
  490. }
  491. return time.Duration(sessionIdleExpirySeconds) * time.Second
  492. }
  493. func (server *Server) removeSession(session *session) {
  494. server.sessionIDToIndex.Delete(session.sessionID)
  495. server.indexToSession.Delete(session.index)
  496. server.interruptSession(session)
  497. }
  498. func (server *Server) runOrphanMetricsCheckpointer() {
  499. defer server.workers.Done()
  500. // Periodically log orphan packet metrics. Orphan metrics
  501. // are not associated with any session. This includes
  502. // packets that are rejected before they can be associated
  503. // with a session.
  504. ticker := time.NewTicker(ORPHAN_METRICS_CHECKPOINTER_PERIOD)
  505. defer ticker.Stop()
  506. for {
  507. done := false
  508. select {
  509. case <-ticker.C:
  510. case <-server.runContext.Done():
  511. done = true
  512. }
  513. // TODO: skip log if all zeros?
  514. server.orphanMetrics.checkpoint(
  515. server.config.Logger, "orphan_packet_metrics", packetMetricsRejected)
  516. if done {
  517. return
  518. }
  519. }
  520. }
  521. func (server *Server) runDeviceDownstream() {
  522. defer server.workers.Done()
  523. // Read incoming packets from the tun device, parse and validate the
  524. // packets, map them to a session/client, perform rewriting, and relay
  525. // the packets to the client.
  526. for {
  527. readPacket, err := server.device.ReadPacket()
  528. select {
  529. case <-server.runContext.Done():
  530. // No error is logged as shutdown may have interrupted read.
  531. return
  532. default:
  533. }
  534. if err != nil {
  535. server.config.Logger.WithContextFields(
  536. common.LogFields{"error": err}).Warning("read device packet failed")
  537. // May be temporary error condition, keep reading.
  538. continue
  539. }
  540. // destinationIPAddress determines which client receives this packet.
  541. // At this point, only enough of the packet is inspected to determine
  542. // this routing info; further validation happens in subsequent
  543. // processPacket in runClientDownstream.
  544. // Note that masquerading/NAT stands between the Internet and the tun
  545. // device, so arbitrary packets cannot be sent through to this point.
  546. // TODO: getPacketDestinationIPAddress and processPacket perform redundant
  547. // packet parsing; refactor to avoid extra work?
  548. destinationIPAddress, ok := getPacketDestinationIPAddress(
  549. server.orphanMetrics, packetDirectionServerDownstream, readPacket)
  550. if !ok {
  551. // Packet is dropped. Reason will be counted in orphan metrics.
  552. continue
  553. }
  554. // Map destination IP address to client session.
  555. index := server.convertIPAddressToIndex(destinationIPAddress)
  556. s, ok := server.indexToSession.Load(index)
  557. if !ok {
  558. server.orphanMetrics.rejectedPacket(
  559. packetDirectionServerDownstream, packetRejectNoSession)
  560. continue
  561. }
  562. session := s.(*session)
  563. // Simply enqueue the packet for client handling, and move on to
  564. // read the next packet. The packet tunnel server multiplexes all
  565. // client packets through a single tun device, so we must not block
  566. // on client channel I/O here.
  567. //
  568. // When the queue is full, the packet is dropped. This is standard
  569. // behavior for routers, VPN servers, etc.
  570. //
  571. // We allow packets to enqueue in an idle session in case a client
  572. // is in the process of reconnecting.
  573. //
  574. // TODO: processPacket is performed here, instead of runClientDownstream,
  575. // since packets are packed contiguously into the packet queue and if
  576. // the packet it to be omitted, that should be done before enqueuing.
  577. // The potential downside is that all packet processing is done in this
  578. // single thread of execution, blocking the next packet for the next
  579. // client. Try handing off the packet to another worker which will
  580. // call processPacket and Enqueue?
  581. // In downstream mode, processPacket rewrites the destination address
  582. // to the original client source IP address, and also rewrites DNS
  583. // packets. As documented in runClientUpstream, the original address
  584. // should already be populated via an upstream packet; if not, the
  585. // packet will be rejected.
  586. if !processPacket(
  587. session.metrics,
  588. session,
  589. packetDirectionServerDownstream,
  590. readPacket) {
  591. // Packet is rejected and dropped. Reason will be counted in metrics.
  592. continue
  593. }
  594. session.downstreamPackets.Enqueue(readPacket)
  595. }
  596. }
  597. func (server *Server) runClientUpstream(session *session) {
  598. defer session.workers.Done()
  599. // Read incoming packets from the client channel, validate the packets,
  600. // perform rewriting, and send them through to the tun device.
  601. for {
  602. readPacket, err := session.channel.ReadPacket()
  603. select {
  604. case <-session.runContext.Done():
  605. // No error is logged as shutdown may have interrupted read.
  606. return
  607. default:
  608. }
  609. if err != nil {
  610. // Debug since channel I/O errors occur during normal operation.
  611. server.config.Logger.WithContextFields(
  612. common.LogFields{"error": err}).Debug("read channel packet failed")
  613. // Tear down the session. Must be invoked asynchronously.
  614. go server.interruptSession(session)
  615. return
  616. }
  617. session.touch()
  618. // processPacket transparently rewrites the source address to the
  619. // session's assigned address and rewrites the destination of any
  620. // DNS packets destined to the target DNS resolver.
  621. //
  622. // The first time the source address is rewritten, the original
  623. // value is recorded so inbound packets can have the reverse
  624. // rewrite applied. This assumes that the client will send a
  625. // packet before receiving any packet, which is the case since
  626. // only clients can initiate TCP or UDP connections or flows.
  627. if !processPacket(
  628. session.metrics,
  629. session,
  630. packetDirectionServerUpstream,
  631. readPacket) {
  632. // Packet is rejected and dropped. Reason will be counted in metrics.
  633. continue
  634. }
  635. err = server.device.WritePacket(readPacket)
  636. if err != nil {
  637. server.config.Logger.WithContextFields(
  638. common.LogFields{"error": err}).Warning("write device packet failed")
  639. // May be temporary error condition, keep working. The packet is
  640. // most likely dropped.
  641. continue
  642. }
  643. }
  644. }
  645. func (server *Server) runClientDownstream(session *session) {
  646. defer session.workers.Done()
  647. // Dequeue, process, and relay packets to be sent to the client channel.
  648. for {
  649. packetBuffer, ok := session.downstreamPackets.DequeueFramedPackets(session.runContext)
  650. if !ok {
  651. // Dequeue aborted due to session.runContext.Done()
  652. return
  653. }
  654. err := session.channel.WriteFramedPackets(packetBuffer)
  655. if err != nil {
  656. // Debug since channel I/O errors occur during normal operation.
  657. server.config.Logger.WithContextFields(
  658. common.LogFields{"error": err}).Debug("write channel packets failed")
  659. session.downstreamPackets.Replace(packetBuffer)
  660. // Tear down the session. Must be invoked asynchronously.
  661. go server.interruptSession(session)
  662. return
  663. }
  664. session.touch()
  665. session.downstreamPackets.Replace(packetBuffer)
  666. }
  667. }
  668. var (
  669. serverIPv4AddressCIDR = "10.0.0.1/8"
  670. transparentDNSResolverIPv4Address = net.ParseIP("10.0.0.2").To4() // 4-byte for rewriting
  671. _, privateSubnetIPv4, _ = net.ParseCIDR("10.0.0.0/8")
  672. assignedIPv4AddressTemplate = "10.%02d.%02d.%02d"
  673. serverIPv6AddressCIDR = "fd19:ca83:e6d5:1c44:0000:0000:0000:0001/64"
  674. transparentDNSResolverIPv6Address = net.ParseIP("fd19:ca83:e6d5:1c44:0000:0000:0000:0002")
  675. _, privateSubnetIPv6, _ = net.ParseCIDR("fd19:ca83:e6d5:1c44::/64")
  676. assignedIPv6AddressTemplate = "fd19:ca83:e6d5:1c44:8c57:4434:ee%02x:%02x%02x"
  677. )
  678. func (server *Server) allocateIndex(newSession *session) error {
  679. // Find and assign an available index in the 24-bit index space.
  680. // The index directly maps to and so determines the assigned
  681. // IPv4 and IPv6 addresses.
  682. // Search is a random index selection followed by a linear probe.
  683. // TODO: is this the most effective (fast on average, simple) algorithm?
  684. max := 0x00FFFFFF
  685. randomInt, err := common.MakeSecureRandomInt(max + 1)
  686. if err != nil {
  687. return common.ContextError(err)
  688. }
  689. index := int32(randomInt)
  690. index &= int32(max)
  691. idleExpiry := server.sessionIdleExpiry()
  692. for tries := 0; tries < 100000; index++ {
  693. tries++
  694. // The index/address space isn't exactly 24-bits:
  695. // - 0 and 0x00FFFFFF are reserved since they map to
  696. // the network identifier (10.0.0.0) and broadcast
  697. // address (10.255.255.255) respectively
  698. // - 1 is reserved as the server tun device address,
  699. // (10.0.0.1, and IPv6 equivalent)
  700. // - 2 is reserver as the transparent DNS target
  701. // address (10.0.0.2, and IPv6 equivalent)
  702. if index <= 2 {
  703. continue
  704. }
  705. if index == 0x00FFFFFF {
  706. index = 0
  707. continue
  708. }
  709. if s, ok := server.indexToSession.LoadOrStore(index, newSession); ok {
  710. // Index is already in use or acquired concurrently.
  711. // If the existing session is expired, reap it and try again
  712. // to acquire it.
  713. existingSession := s.(*session)
  714. if existingSession.expired(idleExpiry) {
  715. server.removeSession(existingSession)
  716. // Try to acquire this index again. We can't fall through and
  717. // use this index as removeSession has cleared indexToSession.
  718. index--
  719. }
  720. continue
  721. }
  722. // Note: the To4() for assignedIPv4Address is essential since
  723. // that address value is assumed to be 4 bytes when rewriting.
  724. newSession.index = index
  725. newSession.assignedIPv4Address = server.convertIndexToIPv4Address(index).To4()
  726. newSession.assignedIPv6Address = server.convertIndexToIPv6Address(index)
  727. server.sessionIDToIndex.Store(newSession.sessionID, index)
  728. server.resetRouting(newSession.assignedIPv4Address, newSession.assignedIPv6Address)
  729. return nil
  730. }
  731. return common.ContextError(errors.New("unallocated index not found"))
  732. }
  733. func (server *Server) resetRouting(IPv4Address, IPv6Address net.IP) {
  734. // Attempt to clear the NAT table of any existing connection
  735. // states. This will prevent the (already unlikely) delivery
  736. // of packets to the wrong client when an assigned IP address is
  737. // recycled. Silently has no effect on some platforms, see
  738. // resetNATTables implementations.
  739. err := resetNATTables(server.config, IPv4Address)
  740. if err != nil {
  741. server.config.Logger.WithContextFields(
  742. common.LogFields{"error": err}).Warning("reset IPv4 routing failed")
  743. }
  744. err = resetNATTables(server.config, IPv6Address)
  745. if err != nil {
  746. server.config.Logger.WithContextFields(
  747. common.LogFields{"error": err}).Warning("reset IPv6 routing failed")
  748. }
  749. }
  750. func (server *Server) convertIPAddressToIndex(IP net.IP) int32 {
  751. // Assumes IP is at least 3 bytes.
  752. size := len(IP)
  753. return int32(IP[size-3])<<16 | int32(IP[size-2])<<8 | int32(IP[size-1])
  754. }
  755. func (server *Server) convertIndexToIPv4Address(index int32) net.IP {
  756. return net.ParseIP(
  757. fmt.Sprintf(
  758. assignedIPv4AddressTemplate,
  759. (index>>16)&0xFF,
  760. (index>>8)&0xFF,
  761. index&0xFF))
  762. }
  763. func (server *Server) convertIndexToIPv6Address(index int32) net.IP {
  764. return net.ParseIP(
  765. fmt.Sprintf(
  766. assignedIPv6AddressTemplate,
  767. (index>>16)&0xFF,
  768. (index>>8)&0xFF,
  769. index&0xFF))
  770. }
  771. // GetTransparentDNSResolverIPv4Address returns the static IPv4 address
  772. // to use as a DNS resolver when transparent DNS rewriting is desired.
  773. func GetTransparentDNSResolverIPv4Address() net.IP {
  774. return transparentDNSResolverIPv4Address
  775. }
  776. // GetTransparentDNSResolverIPv6Address returns the static IPv6 address
  777. // to use as a DNS resolver when transparent DNS rewriting is desired.
  778. func GetTransparentDNSResolverIPv6Address() net.IP {
  779. return transparentDNSResolverIPv6Address
  780. }
  781. type session struct {
  782. // Note: 64-bit ints used with atomic operations are placed
  783. // at the start of struct to ensure 64-bit alignment.
  784. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  785. lastActivity int64
  786. lastFlowReapIndex int64
  787. metrics *packetMetrics
  788. sessionID string
  789. index int32
  790. DNSResolverIPv4Addresses []net.IP
  791. assignedIPv4Address net.IP
  792. setOriginalIPv4Address int32
  793. originalIPv4Address net.IP
  794. DNSResolverIPv6Addresses []net.IP
  795. assignedIPv6Address net.IP
  796. setOriginalIPv6Address int32
  797. originalIPv6Address net.IP
  798. checkAllowedTCPPortFunc AllowedPortChecker
  799. checkAllowedUDPPortFunc AllowedPortChecker
  800. flowActivityUpdaterMaker FlowActivityUpdaterMaker
  801. downstreamPackets *PacketQueue
  802. flows sync.Map
  803. workers *sync.WaitGroup
  804. mutex sync.Mutex
  805. channel *Channel
  806. runContext context.Context
  807. stopRunning context.CancelFunc
  808. }
  809. // flowID identifies an IP traffic flow using the conventional
  810. // network 5-tuple. flowIDs track bidirectional flows.
  811. type flowID struct {
  812. downstreamIPAddress [net.IPv6len]byte
  813. downstreamPort uint16
  814. upstreamIPAddress [net.IPv6len]byte
  815. upstreamPort uint16
  816. protocol internetProtocol
  817. }
  818. // From: https://github.com/golang/go/blob/b88efc7e7ac15f9e0b5d8d9c82f870294f6a3839/src/net/ip.go#L55
  819. var v4InV6Prefix = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}
  820. func (f *flowID) set(
  821. downstreamIPAddress net.IP,
  822. downstreamPort uint16,
  823. upstreamIPAddress net.IP,
  824. upstreamPort uint16,
  825. protocol internetProtocol) {
  826. if len(downstreamIPAddress) == net.IPv4len {
  827. copy(f.downstreamIPAddress[:], v4InV6Prefix)
  828. copy(f.downstreamIPAddress[len(v4InV6Prefix):], downstreamIPAddress)
  829. } else { // net.IPv6len
  830. copy(f.downstreamIPAddress[:], downstreamIPAddress)
  831. }
  832. f.downstreamPort = downstreamPort
  833. if len(upstreamIPAddress) == net.IPv4len {
  834. copy(f.upstreamIPAddress[:], v4InV6Prefix)
  835. copy(f.upstreamIPAddress[len(v4InV6Prefix):], upstreamIPAddress)
  836. } else { // net.IPv6len
  837. copy(f.upstreamIPAddress[:], upstreamIPAddress)
  838. }
  839. f.upstreamPort = upstreamPort
  840. f.protocol = protocol
  841. }
  842. type flowState struct {
  843. // Note: 64-bit ints used with atomic operations are placed
  844. // at the start of struct to ensure 64-bit alignment.
  845. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  846. lastUpstreamPacketTime int64
  847. lastDownstreamPacketTime int64
  848. activityUpdaters []FlowActivityUpdater
  849. }
  850. func (flowState *flowState) expired(idleExpiry time.Duration) bool {
  851. now := monotime.Now()
  852. return (now.Sub(monotime.Time(atomic.LoadInt64(&flowState.lastUpstreamPacketTime))) > idleExpiry) ||
  853. (now.Sub(monotime.Time(atomic.LoadInt64(&flowState.lastDownstreamPacketTime))) > idleExpiry)
  854. }
  855. func (session *session) touch() {
  856. atomic.StoreInt64(&session.lastActivity, int64(monotime.Now()))
  857. }
  858. func (session *session) expired(idleExpiry time.Duration) bool {
  859. lastActivity := monotime.Time(atomic.LoadInt64(&session.lastActivity))
  860. return monotime.Since(lastActivity) > idleExpiry
  861. }
  862. func (session *session) setOriginalIPv4AddressIfNotSet(IPAddress net.IP) {
  863. if !atomic.CompareAndSwapInt32(&session.setOriginalIPv4Address, 0, 1) {
  864. return
  865. }
  866. // Make a copy of IPAddress; don't reference a slice of a reusable
  867. // packet buffer, which will be overwritten.
  868. session.originalIPv4Address = net.IP(append([]byte(nil), []byte(IPAddress)...))
  869. }
  870. func (session *session) getOriginalIPv4Address() net.IP {
  871. if atomic.LoadInt32(&session.setOriginalIPv4Address) == 0 {
  872. return nil
  873. }
  874. return session.originalIPv4Address
  875. }
  876. func (session *session) setOriginalIPv6AddressIfNotSet(IPAddress net.IP) {
  877. if !atomic.CompareAndSwapInt32(&session.setOriginalIPv6Address, 0, 1) {
  878. return
  879. }
  880. // Make a copy of IPAddress.
  881. session.originalIPv6Address = net.IP(append([]byte(nil), []byte(IPAddress)...))
  882. }
  883. func (session *session) getOriginalIPv6Address() net.IP {
  884. if atomic.LoadInt32(&session.setOriginalIPv6Address) == 0 {
  885. return nil
  886. }
  887. return session.originalIPv6Address
  888. }
  889. // isTrackingFlow checks if a flow is being tracked.
  890. func (session *session) isTrackingFlow(ID flowID) bool {
  891. f, ok := session.flows.Load(ID)
  892. if !ok {
  893. return false
  894. }
  895. flowState := f.(*flowState)
  896. // Check if flow is expired but not yet reaped.
  897. if flowState.expired(FLOW_IDLE_EXPIRY) {
  898. session.flows.Delete(ID)
  899. return false
  900. }
  901. return true
  902. }
  903. // startTrackingFlow starts flow tracking for the flow identified
  904. // by ID.
  905. //
  906. // Flow tracking is used to implement:
  907. // - one-time permissions checks for a flow
  908. // - OSLs
  909. // - domain bytes transferred [TODO]
  910. //
  911. // The applicationData from the first packet in the flow is
  912. // inspected to determine any associated hostname, using HTTP or
  913. // TLS payload. The session's FlowActivityUpdaterMaker is invoked
  914. // to determine a list of updaters to track flow activity.
  915. //
  916. // Updaters receive reports with the number of application data
  917. // bytes in each flow packet. This number, totalled for all packets
  918. // in a flow, may exceed the total bytes transferred at the
  919. // application level due to TCP retransmission. Currently, the flow
  920. // tracking logic doesn't exclude retransmitted packets from update
  921. // reporting.
  922. //
  923. // Flows are untracked after an idle expiry period. Transport
  924. // protocol indicators of end of flow, such as FIN or RST for TCP,
  925. // which may or may not appear in a flow, are not currently used.
  926. //
  927. // startTrackingFlow may be called from concurrent goroutines; if
  928. // the flow is already tracked, it is simply updated.
  929. func (session *session) startTrackingFlow(
  930. ID flowID, direction packetDirection, applicationData []byte) {
  931. now := int64(monotime.Now())
  932. // Once every period, iterate over flows and reap expired entries.
  933. reapIndex := now / int64(monotime.Time(FLOW_IDLE_EXPIRY/2))
  934. previousReapIndex := atomic.LoadInt64(&session.lastFlowReapIndex)
  935. if reapIndex != previousReapIndex &&
  936. atomic.CompareAndSwapInt64(&session.lastFlowReapIndex, previousReapIndex, reapIndex) {
  937. session.reapFlows()
  938. }
  939. var hostname string
  940. if ID.protocol == internetProtocolTCP {
  941. // TODO: implement
  942. // hostname = common.ExtractHostnameFromTCPFlow(applicationData)
  943. }
  944. flowState := &flowState{
  945. activityUpdaters: session.flowActivityUpdaterMaker(
  946. hostname,
  947. net.IP(ID.upstreamIPAddress[:])),
  948. }
  949. if direction == packetDirectionServerUpstream {
  950. flowState.lastUpstreamPacketTime = now
  951. } else {
  952. flowState.lastDownstreamPacketTime = now
  953. }
  954. // LoadOrStore will retain any existing entry
  955. session.flows.LoadOrStore(ID, flowState)
  956. session.updateFlow(ID, direction, applicationData)
  957. }
  958. func (session *session) updateFlow(
  959. ID flowID, direction packetDirection, applicationData []byte) {
  960. f, ok := session.flows.Load(ID)
  961. if !ok {
  962. return
  963. }
  964. flowState := f.(*flowState)
  965. // Note: no expired check here, since caller is assumed to
  966. // have just called isTrackingFlow.
  967. now := int64(monotime.Now())
  968. var upstreamBytes, downstreamBytes, durationNanoseconds int64
  969. if direction == packetDirectionServerUpstream {
  970. upstreamBytes = int64(len(applicationData))
  971. atomic.StoreInt64(&flowState.lastUpstreamPacketTime, now)
  972. } else {
  973. downstreamBytes = int64(len(applicationData))
  974. // Follows common.ActivityMonitoredConn semantics, where
  975. // duration is updated only for downstream activity. This
  976. // is intened to produce equivalent behaviour for port
  977. // forward clients (tracked with ActivityUpdaters) and
  978. // packet tunnel clients (tracked with FlowActivityUpdaters).
  979. durationNanoseconds = now - atomic.SwapInt64(&flowState.lastDownstreamPacketTime, now)
  980. }
  981. for _, updater := range flowState.activityUpdaters {
  982. updater.UpdateProgress(upstreamBytes, downstreamBytes, durationNanoseconds)
  983. }
  984. }
  985. // reapFlows removes expired idle flows.
  986. func (session *session) reapFlows() {
  987. session.flows.Range(func(key, value interface{}) bool {
  988. flowState := value.(*flowState)
  989. if flowState.expired(FLOW_IDLE_EXPIRY) {
  990. session.flows.Delete(key)
  991. }
  992. return true
  993. })
  994. }
  995. type packetMetrics struct {
  996. upstreamRejectReasons [packetRejectReasonCount]int64
  997. downstreamRejectReasons [packetRejectReasonCount]int64
  998. TCPIPv4 relayedPacketMetrics
  999. TCPIPv6 relayedPacketMetrics
  1000. UDPIPv4 relayedPacketMetrics
  1001. UDPIPv6 relayedPacketMetrics
  1002. }
  1003. type relayedPacketMetrics struct {
  1004. packetsUp int64
  1005. packetsDown int64
  1006. bytesUp int64
  1007. bytesDown int64
  1008. }
  1009. func (metrics *packetMetrics) rejectedPacket(
  1010. direction packetDirection,
  1011. reason packetRejectReason) {
  1012. if direction == packetDirectionServerUpstream ||
  1013. direction == packetDirectionClientUpstream {
  1014. atomic.AddInt64(&metrics.upstreamRejectReasons[reason], 1)
  1015. } else { // packetDirectionDownstream
  1016. atomic.AddInt64(&metrics.downstreamRejectReasons[reason], 1)
  1017. }
  1018. }
  1019. func (metrics *packetMetrics) relayedPacket(
  1020. direction packetDirection,
  1021. version int,
  1022. protocol internetProtocol,
  1023. packetLength int) {
  1024. var packetsMetric, bytesMetric *int64
  1025. if direction == packetDirectionServerUpstream ||
  1026. direction == packetDirectionClientUpstream {
  1027. if version == 4 {
  1028. if protocol == internetProtocolTCP {
  1029. packetsMetric = &metrics.TCPIPv4.packetsUp
  1030. bytesMetric = &metrics.TCPIPv4.bytesUp
  1031. } else { // UDP
  1032. packetsMetric = &metrics.UDPIPv4.packetsUp
  1033. bytesMetric = &metrics.UDPIPv4.bytesUp
  1034. }
  1035. } else { // IPv6
  1036. if protocol == internetProtocolTCP {
  1037. packetsMetric = &metrics.TCPIPv6.packetsUp
  1038. bytesMetric = &metrics.TCPIPv6.bytesUp
  1039. } else { // UDP
  1040. packetsMetric = &metrics.UDPIPv6.packetsUp
  1041. bytesMetric = &metrics.UDPIPv6.bytesUp
  1042. }
  1043. }
  1044. } else { // packetDirectionDownstream
  1045. if version == 4 {
  1046. if protocol == internetProtocolTCP {
  1047. packetsMetric = &metrics.TCPIPv4.packetsDown
  1048. bytesMetric = &metrics.TCPIPv4.bytesDown
  1049. } else { // UDP
  1050. packetsMetric = &metrics.UDPIPv4.packetsDown
  1051. bytesMetric = &metrics.UDPIPv4.bytesDown
  1052. }
  1053. } else { // IPv6
  1054. if protocol == internetProtocolTCP {
  1055. packetsMetric = &metrics.TCPIPv6.packetsDown
  1056. bytesMetric = &metrics.TCPIPv6.bytesDown
  1057. } else { // UDP
  1058. packetsMetric = &metrics.UDPIPv6.packetsDown
  1059. bytesMetric = &metrics.UDPIPv6.bytesDown
  1060. }
  1061. }
  1062. }
  1063. // Note: packet length, and so bytes transferred, includes IP and TCP/UDP
  1064. // headers, not just payload data, as is counted in port forwarding. It
  1065. // makes sense to include this packet overhead, since we have to tunnel it.
  1066. atomic.AddInt64(packetsMetric, 1)
  1067. atomic.AddInt64(bytesMetric, int64(packetLength))
  1068. }
  1069. const (
  1070. packetMetricsRejected = 1
  1071. packetMetricsRelayed = 2
  1072. packetMetricsAll = packetMetricsRejected | packetMetricsRelayed
  1073. )
  1074. func (metrics *packetMetrics) checkpoint(
  1075. logger common.Logger, logName string, whichMetrics int) {
  1076. // Report all metric counters in a single log message. Each
  1077. // counter is reset to 0 when added to the log.
  1078. logFields := make(common.LogFields)
  1079. if whichMetrics&packetMetricsRejected != 0 {
  1080. for i := 0; i < packetRejectReasonCount; i++ {
  1081. logFields["upstream_packet_rejected_"+packetRejectReasonDescription(packetRejectReason(i))] =
  1082. atomic.SwapInt64(&metrics.upstreamRejectReasons[i], 0)
  1083. logFields["downstream_packet_rejected_"+packetRejectReasonDescription(packetRejectReason(i))] =
  1084. atomic.SwapInt64(&metrics.downstreamRejectReasons[i], 0)
  1085. }
  1086. }
  1087. if whichMetrics&packetMetricsRelayed != 0 {
  1088. relayedMetrics := []struct {
  1089. prefix string
  1090. metrics *relayedPacketMetrics
  1091. }{
  1092. {"tcp_ipv4_", &metrics.TCPIPv4},
  1093. {"tcp_ipv6_", &metrics.TCPIPv6},
  1094. {"udp_ipv4_", &metrics.UDPIPv4},
  1095. {"udp_ipv6_", &metrics.UDPIPv6},
  1096. }
  1097. for _, r := range relayedMetrics {
  1098. logFields[r.prefix+"packets_up"] = atomic.SwapInt64(&r.metrics.packetsUp, 0)
  1099. logFields[r.prefix+"packets_down"] = atomic.SwapInt64(&r.metrics.packetsDown, 0)
  1100. logFields[r.prefix+"bytes_up"] = atomic.SwapInt64(&r.metrics.bytesUp, 0)
  1101. logFields[r.prefix+"bytes_down"] = atomic.SwapInt64(&r.metrics.bytesDown, 0)
  1102. }
  1103. }
  1104. logger.LogMetric(logName, logFields)
  1105. }
  1106. // PacketQueue is a fixed-size, preallocated queue of packets.
  1107. // Enqueued packets are packed into a contiguous buffer with channel
  1108. // framing, allowing the entire queue to be written to a channel
  1109. // in a single call.
  1110. // Reuse of the queue buffers avoids GC churn. To avoid memory use
  1111. // spikes when many clients connect and may disconnect before relaying
  1112. // packets, the packet queue buffers start small and grow when required,
  1113. // up to the maximum size, and then remain static.
  1114. type PacketQueue struct {
  1115. maxSize int
  1116. emptyBuffers chan []byte
  1117. activeBuffer chan []byte
  1118. }
  1119. // NewPacketQueue creates a new PacketQueue.
  1120. // The caller must ensure that maxSize exceeds the
  1121. // packet MTU, or packets will will never enqueue.
  1122. func NewPacketQueue(maxSize int) *PacketQueue {
  1123. // Two buffers of size up to maxSize are allocated, to
  1124. // allow packets to continue to enqueue while one buffer
  1125. // is borrowed by the DequeueFramedPackets caller.
  1126. //
  1127. // TODO: is there a way to implement this without
  1128. // allocating up to 2x maxSize bytes? A circular queue
  1129. // won't work because we want DequeueFramedPackets
  1130. // to return a contiguous buffer. Perhaps a Bip
  1131. // Buffer would work here:
  1132. // https://www.codeproject.com/Articles/3479/The-Bip-Buffer-The-Circular-Buffer-with-a-Twist
  1133. queue := &PacketQueue{
  1134. maxSize: maxSize,
  1135. emptyBuffers: make(chan []byte, 2),
  1136. activeBuffer: make(chan []byte, 1),
  1137. }
  1138. queue.emptyBuffers <- make([]byte, 0)
  1139. queue.emptyBuffers <- make([]byte, 0)
  1140. return queue
  1141. }
  1142. // Enqueue adds a packet to the queue.
  1143. // If the queue is full, the packet is dropped.
  1144. // Enqueue is _not_ safe for concurrent calls.
  1145. func (queue *PacketQueue) Enqueue(packet []byte) {
  1146. var buffer []byte
  1147. select {
  1148. case buffer = <-queue.activeBuffer:
  1149. default:
  1150. buffer = <-queue.emptyBuffers
  1151. }
  1152. packetSize := len(packet)
  1153. if queue.maxSize-len(buffer) >= channelHeaderSize+packetSize {
  1154. // Assumes len(packet)/MTU <= 64K
  1155. var channelHeader [channelHeaderSize]byte
  1156. binary.BigEndian.PutUint16(channelHeader[:], uint16(packetSize))
  1157. // Once the buffer has reached maxSize capacity
  1158. // and been replaced (buffer = buffer[0:0]), these
  1159. // appends should no longer allocate new memory and
  1160. // should just copy to preallocated memory.
  1161. buffer = append(buffer, channelHeader[:]...)
  1162. buffer = append(buffer, packet...)
  1163. }
  1164. // Else, queue is full, so drop packet.
  1165. queue.activeBuffer <- buffer
  1166. }
  1167. // DequeueFramedPackets waits until at least one packet is
  1168. // enqueued, and then returns a packet buffer containing one
  1169. // or more framed packets. The returned buffer remains part
  1170. // of the PacketQueue structure and the caller _must_ replace
  1171. // the buffer by calling Replace.
  1172. // DequeueFramedPackets unblocks and returns false if it receives
  1173. // runContext.Done().
  1174. // DequeueFramedPackets is _not_ safe for concurrent calls.
  1175. func (queue *PacketQueue) DequeueFramedPackets(
  1176. runContext context.Context) ([]byte, bool) {
  1177. var buffer []byte
  1178. select {
  1179. case buffer = <-queue.activeBuffer:
  1180. case <-runContext.Done():
  1181. return nil, false
  1182. }
  1183. return buffer, true
  1184. }
  1185. // Replace returns the buffer to the PacketQueue to be
  1186. // reused.
  1187. // The input must be a return value from DequeueFramedPackets.
  1188. func (queue *PacketQueue) Replace(buffer []byte) {
  1189. buffer = buffer[0:0]
  1190. // This won't block (as long as it is a DequeueFramedPackets return value).
  1191. queue.emptyBuffers <- buffer
  1192. }
  1193. // ClientConfig specifies the configuration of a packet tunnel client.
  1194. type ClientConfig struct {
  1195. // Logger is used for logging events and metrics.
  1196. Logger common.Logger
  1197. // SudoNetworkConfigCommands specifies whether to use "sudo"
  1198. // when executing network configuration commands. See description
  1199. // for ServerConfig.SudoNetworkConfigCommands.
  1200. SudoNetworkConfigCommands bool
  1201. // AllowNoIPv6NetworkConfiguration indicates that failures while
  1202. // configuring tun interfaces and routing for IPv6 are to be
  1203. // logged as warnings only. See description for
  1204. // ServerConfig.AllowNoIPv6NetworkConfiguration.
  1205. AllowNoIPv6NetworkConfiguration bool
  1206. // MTU is the packet MTU value to use; this value
  1207. // should be obtained from the packet tunnel server.
  1208. // When MTU is 0, a default value is used.
  1209. MTU int
  1210. // UpstreamPacketQueueSize specifies the size of the upstream
  1211. // packet queue.
  1212. // When UpstreamPacketQueueSize is 0, a default value tuned for
  1213. // Psiphon is used.
  1214. UpstreamPacketQueueSize int
  1215. // Transport is an established transport channel that
  1216. // will be used to relay packets to and from a packet
  1217. // tunnel server.
  1218. Transport io.ReadWriteCloser
  1219. // TunFileDescriptor specifies a file descriptor to use to
  1220. // read and write packets to be relayed to the client. When
  1221. // TunFileDescriptor is specified, the Client will use this
  1222. // existing tun device and not create its own; in this case,
  1223. // network address and routing configuration is not performed
  1224. // by the Client. As the packet tunnel server performs
  1225. // transparent source IP address and DNS rewriting, the tun
  1226. // device may have any assigned IP address, but should be
  1227. // configured with the given MTU; and DNS should be configured
  1228. // to use the transparent DNS target resolver addresses.
  1229. // Set TunFileDescriptor to <= 0 to ignore this parameter
  1230. // and create and configure a tun device.
  1231. TunFileDescriptor int
  1232. // IPv4AddressCIDR is the IPv4 address and netmask to
  1233. // assign to a newly created tun device.
  1234. IPv4AddressCIDR string
  1235. // IPv6AddressCIDR is the IPv6 address and prefix to
  1236. // assign to a newly created tun device.
  1237. IPv6AddressCIDR string
  1238. // RouteDestinations are hosts (IPs) or networks (CIDRs)
  1239. // to be configured to be routed through a newly
  1240. // created tun device.
  1241. RouteDestinations []string
  1242. }
  1243. // Client is a packet tunnel client. A packet tunnel client
  1244. // relays packets between a local tun device and a packet
  1245. // tunnel server via a transport channel.
  1246. type Client struct {
  1247. config *ClientConfig
  1248. device *Device
  1249. channel *Channel
  1250. upstreamPackets *PacketQueue
  1251. metrics *packetMetrics
  1252. runContext context.Context
  1253. stopRunning context.CancelFunc
  1254. workers *sync.WaitGroup
  1255. }
  1256. // NewClient initializes a new Client. Unless using the
  1257. // TunFileDescriptor configuration parameter, a new tun
  1258. // device is created for the client.
  1259. func NewClient(config *ClientConfig) (*Client, error) {
  1260. var device *Device
  1261. var err error
  1262. if config.TunFileDescriptor > 0 {
  1263. device, err = NewClientDeviceFromFD(config)
  1264. } else {
  1265. device, err = NewClientDevice(config)
  1266. }
  1267. if err != nil {
  1268. return nil, common.ContextError(err)
  1269. }
  1270. upstreamPacketQueueSize := DEFAULT_UPSTREAM_PACKET_QUEUE_SIZE
  1271. if config.UpstreamPacketQueueSize > 0 {
  1272. upstreamPacketQueueSize = config.UpstreamPacketQueueSize
  1273. }
  1274. runContext, stopRunning := context.WithCancel(context.Background())
  1275. return &Client{
  1276. config: config,
  1277. device: device,
  1278. channel: NewChannel(config.Transport, getMTU(config.MTU)),
  1279. upstreamPackets: NewPacketQueue(upstreamPacketQueueSize),
  1280. metrics: new(packetMetrics),
  1281. runContext: runContext,
  1282. stopRunning: stopRunning,
  1283. workers: new(sync.WaitGroup),
  1284. }, nil
  1285. }
  1286. // Start starts a client and returns with it running.
  1287. func (client *Client) Start() {
  1288. client.config.Logger.WithContext().Info("starting")
  1289. client.workers.Add(1)
  1290. go func() {
  1291. defer client.workers.Done()
  1292. for {
  1293. readPacket, err := client.device.ReadPacket()
  1294. select {
  1295. case <-client.runContext.Done():
  1296. // No error is logged as shutdown may have interrupted read.
  1297. return
  1298. default:
  1299. }
  1300. if err != nil {
  1301. client.config.Logger.WithContextFields(
  1302. common.LogFields{"error": err}).Info("read device packet failed")
  1303. // May be temporary error condition, keep working.
  1304. continue
  1305. }
  1306. // processPacket will check for packets the server will reject
  1307. // and drop those without sending.
  1308. // Limitation: packet metrics, including successful relay count,
  1309. // are incremented _before_ the packet is written to the channel.
  1310. if !processPacket(
  1311. client.metrics,
  1312. nil,
  1313. packetDirectionClientUpstream,
  1314. readPacket) {
  1315. continue
  1316. }
  1317. // Instead of immediately writing to the channel, the
  1318. // packet is enqueued, which has the effect of batching
  1319. // up IP packets into a single channel packet (for Psiphon,
  1320. // and SSH packet) to minimize overhead and, as benchmarked,
  1321. // improve throughput.
  1322. // Packet will be dropped if queue is full.
  1323. client.upstreamPackets.Enqueue(readPacket)
  1324. }
  1325. }()
  1326. client.workers.Add(1)
  1327. go func() {
  1328. defer client.workers.Done()
  1329. for {
  1330. packetBuffer, ok := client.upstreamPackets.DequeueFramedPackets(client.runContext)
  1331. if !ok {
  1332. // Dequeue aborted due to session.runContext.Done()
  1333. return
  1334. }
  1335. err := client.channel.WriteFramedPackets(packetBuffer)
  1336. client.upstreamPackets.Replace(packetBuffer)
  1337. if err != nil {
  1338. client.config.Logger.WithContextFields(
  1339. common.LogFields{"error": err}).Info("write channel packets failed")
  1340. // May be temporary error condition, such as reconnecting the tunnel;
  1341. // keep working. The packets are most likely dropped.
  1342. continue
  1343. }
  1344. }
  1345. }()
  1346. client.workers.Add(1)
  1347. go func() {
  1348. defer client.workers.Done()
  1349. for {
  1350. readPacket, err := client.channel.ReadPacket()
  1351. select {
  1352. case <-client.runContext.Done():
  1353. // No error is logged as shutdown may have interrupted read.
  1354. return
  1355. default:
  1356. }
  1357. if err != nil {
  1358. client.config.Logger.WithContextFields(
  1359. common.LogFields{"error": err}).Info("read channel packet failed")
  1360. // May be temporary error condition, such as reconnecting the tunnel;
  1361. // keep working.
  1362. continue
  1363. }
  1364. if !processPacket(
  1365. client.metrics,
  1366. nil,
  1367. packetDirectionClientDownstream,
  1368. readPacket) {
  1369. continue
  1370. }
  1371. err = client.device.WritePacket(readPacket)
  1372. if err != nil {
  1373. client.config.Logger.WithContextFields(
  1374. common.LogFields{"error": err}).Info("write device packet failed")
  1375. // May be temporary error condition, keep working. The packet is
  1376. // most likely dropped.
  1377. continue
  1378. }
  1379. }
  1380. }()
  1381. }
  1382. // Stop halts a running client.
  1383. func (client *Client) Stop() {
  1384. client.config.Logger.WithContext().Info("stopping")
  1385. client.stopRunning()
  1386. client.device.Close()
  1387. client.channel.Close()
  1388. client.workers.Wait()
  1389. client.metrics.checkpoint(
  1390. client.config.Logger, "packet_metrics", packetMetricsAll)
  1391. client.config.Logger.WithContext().Info("stopped")
  1392. }
  1393. /*
  1394. Packet offset constants in getPacketDestinationIPAddress and
  1395. processPacket are from the following RFC definitions.
  1396. IPv4 header: https://tools.ietf.org/html/rfc791
  1397. 0 1 2 3
  1398. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  1399. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1400. |Version| IHL |Type of Service| Total Length |
  1401. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1402. | Identification |Flags| Fragment Offset |
  1403. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1404. | Time to Live | Protocol | Header Checksum |
  1405. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1406. | Source Address |
  1407. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1408. | Destination Address |
  1409. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1410. | Options | Padding |
  1411. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1412. IPv6 header: https://tools.ietf.org/html/rfc2460
  1413. 0 1 2 3
  1414. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  1415. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1416. |Version| Traffic Class | Flow Label |
  1417. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1418. | Payload Length | Next Header | Hop Limit |
  1419. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1420. | |
  1421. + +
  1422. | |
  1423. + Source Address +
  1424. | |
  1425. + +
  1426. | |
  1427. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1428. | |
  1429. + +
  1430. | |
  1431. + Destination Address +
  1432. | |
  1433. + +
  1434. | |
  1435. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1436. TCP header: https://tools.ietf.org/html/rfc793
  1437. 0 1 2 3
  1438. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  1439. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1440. | Source Port | Destination Port |
  1441. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1442. | Sequence Number |
  1443. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1444. | Acknowledgment Number |
  1445. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1446. | Data | |U|A|P|R|S|F| |
  1447. | Offset| Reserved |R|C|S|S|Y|I| Window |
  1448. | | |G|K|H|T|N|N| |
  1449. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1450. | Checksum | Urgent Pointer |
  1451. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1452. | Options | Padding |
  1453. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1454. | data |
  1455. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1456. UDP header: https://tools.ietf.org/html/rfc768
  1457. 0 7 8 15 16 23 24 31
  1458. +--------+--------+--------+--------+
  1459. | Source | Destination |
  1460. | Port | Port |
  1461. +--------+--------+--------+--------+
  1462. | | |
  1463. | Length | Checksum |
  1464. +--------+--------+--------+--------+
  1465. |
  1466. | data octets ...
  1467. +---------------- ...
  1468. */
  1469. const (
  1470. packetDirectionServerUpstream = 0
  1471. packetDirectionServerDownstream = 1
  1472. packetDirectionClientUpstream = 2
  1473. packetDirectionClientDownstream = 3
  1474. internetProtocolTCP = 6
  1475. internetProtocolUDP = 17
  1476. portNumberDNS = 53
  1477. packetRejectNoSession = 0
  1478. packetRejectDestinationAddress = 1
  1479. packetRejectLength = 2
  1480. packetRejectVersion = 3
  1481. packetRejectOptions = 4
  1482. packetRejectProtocol = 5
  1483. packetRejectTCPProtocolLength = 6
  1484. packetRejectUDPProtocolLength = 7
  1485. packetRejectTCPPort = 8
  1486. packetRejectUDPPort = 9
  1487. packetRejectNoOriginalAddress = 10
  1488. packetRejectNoDNSResolvers = 11
  1489. packetRejectReasonCount = 12
  1490. packetOk = 12
  1491. )
  1492. type packetDirection int
  1493. type internetProtocol int
  1494. type packetRejectReason int
  1495. func packetRejectReasonDescription(reason packetRejectReason) string {
  1496. // Description strings follow the metrics naming
  1497. // convention: all lowercase; underscore seperators.
  1498. switch reason {
  1499. case packetRejectNoSession:
  1500. return "no_session"
  1501. case packetRejectDestinationAddress:
  1502. return "invalid_destination_address"
  1503. case packetRejectLength:
  1504. return "invalid_ip_packet_length"
  1505. case packetRejectVersion:
  1506. return "invalid_ip_header_version"
  1507. case packetRejectOptions:
  1508. return "invalid_ip_header_options"
  1509. case packetRejectProtocol:
  1510. return "invalid_ip_header_protocol"
  1511. case packetRejectTCPProtocolLength:
  1512. return "invalid_tcp_packet_length"
  1513. case packetRejectUDPProtocolLength:
  1514. return "invalid_tcp_packet_length"
  1515. case packetRejectTCPPort:
  1516. return "disallowed_tcp_destination_port"
  1517. case packetRejectUDPPort:
  1518. return "disallowed_udp_destination_port"
  1519. case packetRejectNoOriginalAddress:
  1520. return "no_original_address"
  1521. case packetRejectNoDNSResolvers:
  1522. return "no_dns_resolvers"
  1523. }
  1524. return "unknown_reason"
  1525. }
  1526. // Caller: the destination IP address return value is
  1527. // a slice of the packet input value and only valid while
  1528. // the packet buffer remains valid.
  1529. func getPacketDestinationIPAddress(
  1530. metrics *packetMetrics,
  1531. direction packetDirection,
  1532. packet []byte) (net.IP, bool) {
  1533. // TODO: this function duplicates a subset of the packet
  1534. // parsing code in processPacket. Refactor to reuse code;
  1535. // also, both getPacketDestinationIPAddress and processPacket
  1536. // are called for some packets; refactor to only parse once.
  1537. if len(packet) < 1 {
  1538. metrics.rejectedPacket(direction, packetRejectLength)
  1539. return nil, false
  1540. }
  1541. version := packet[0] >> 4
  1542. if version != 4 && version != 6 {
  1543. metrics.rejectedPacket(direction, packetRejectVersion)
  1544. return nil, false
  1545. }
  1546. if version == 4 {
  1547. if len(packet) < 20 {
  1548. metrics.rejectedPacket(direction, packetRejectLength)
  1549. return nil, false
  1550. }
  1551. return packet[16:20], true
  1552. } else { // IPv6
  1553. if len(packet) < 40 {
  1554. metrics.rejectedPacket(direction, packetRejectLength)
  1555. return nil, false
  1556. }
  1557. return packet[24:40], true
  1558. }
  1559. }
  1560. // processPacket parses IP packets, applies relaying rules,
  1561. // and rewrites packet elements as required. processPacket
  1562. // returns true if a packet parses correctly, is accepted
  1563. // by the relay rules, and is successfully rewritten.
  1564. //
  1565. // When a packet is rejected, processPacket returns false
  1566. // and updates a reason in the supplied metrics.
  1567. //
  1568. // Rejection may result in partially rewritten packets.
  1569. func processPacket(
  1570. metrics *packetMetrics,
  1571. session *session,
  1572. direction packetDirection,
  1573. packet []byte) bool {
  1574. // Parse and validate IP packet structure
  1575. // Must have an IP version field.
  1576. if len(packet) < 1 {
  1577. metrics.rejectedPacket(direction, packetRejectLength)
  1578. return false
  1579. }
  1580. version := packet[0] >> 4
  1581. // Must be IPv4 or IPv6.
  1582. if version != 4 && version != 6 {
  1583. metrics.rejectedPacket(direction, packetRejectVersion)
  1584. return false
  1585. }
  1586. var protocol internetProtocol
  1587. var sourceIPAddress, destinationIPAddress net.IP
  1588. var sourcePort, destinationPort uint16
  1589. var IPChecksum, TCPChecksum, UDPChecksum []byte
  1590. var applicationData []byte
  1591. if version == 4 {
  1592. // IHL must be 5: options are not supported; a fixed
  1593. // 20 byte header is expected.
  1594. headerLength := packet[0] & 0x0F
  1595. if headerLength != 5 {
  1596. metrics.rejectedPacket(direction, packetRejectOptions)
  1597. return false
  1598. }
  1599. if len(packet) < 20 {
  1600. metrics.rejectedPacket(direction, packetRejectLength)
  1601. return false
  1602. }
  1603. // Protocol must be TCP or UDP.
  1604. protocol = internetProtocol(packet[9])
  1605. dataOffset := 0
  1606. if protocol == internetProtocolTCP {
  1607. if len(packet) < 32 {
  1608. metrics.rejectedPacket(direction, packetRejectTCPProtocolLength)
  1609. return false
  1610. }
  1611. dataOffset = 20 + 4*int(packet[32]>>4)
  1612. if len(packet) < dataOffset {
  1613. metrics.rejectedPacket(direction, packetRejectTCPProtocolLength)
  1614. return false
  1615. }
  1616. } else if protocol == internetProtocolUDP {
  1617. dataOffset := 28
  1618. if len(packet) < dataOffset {
  1619. metrics.rejectedPacket(direction, packetRejectUDPProtocolLength)
  1620. return false
  1621. }
  1622. } else {
  1623. metrics.rejectedPacket(direction, packetRejectProtocol)
  1624. return false
  1625. }
  1626. applicationData = packet[dataOffset:]
  1627. // Slices reference packet bytes to be rewritten.
  1628. sourceIPAddress = packet[12:16]
  1629. destinationIPAddress = packet[16:20]
  1630. IPChecksum = packet[10:12]
  1631. // Port numbers have the same offset in TCP and UDP.
  1632. sourcePort = binary.BigEndian.Uint16(packet[20:22])
  1633. destinationPort = binary.BigEndian.Uint16(packet[22:24])
  1634. if protocol == internetProtocolTCP {
  1635. TCPChecksum = packet[36:38]
  1636. } else { // UDP
  1637. UDPChecksum = packet[26:28]
  1638. }
  1639. } else { // IPv6
  1640. if len(packet) < 40 {
  1641. metrics.rejectedPacket(direction, packetRejectLength)
  1642. return false
  1643. }
  1644. // Next Header must be TCP or UDP.
  1645. nextHeader := packet[6]
  1646. protocol = internetProtocol(nextHeader)
  1647. dataOffset := 0
  1648. if protocol == internetProtocolTCP {
  1649. if len(packet) < 52 {
  1650. metrics.rejectedPacket(direction, packetRejectTCPProtocolLength)
  1651. return false
  1652. }
  1653. dataOffset = 40 + 4*int(packet[52]>>4)
  1654. if len(packet) < dataOffset {
  1655. metrics.rejectedPacket(direction, packetRejectTCPProtocolLength)
  1656. return false
  1657. }
  1658. } else if protocol == internetProtocolUDP {
  1659. dataOffset := 48
  1660. if len(packet) < dataOffset {
  1661. metrics.rejectedPacket(direction, packetRejectUDPProtocolLength)
  1662. return false
  1663. }
  1664. } else {
  1665. metrics.rejectedPacket(direction, packetRejectProtocol)
  1666. return false
  1667. }
  1668. applicationData = packet[dataOffset:]
  1669. // Slices reference packet bytes to be rewritten.
  1670. sourceIPAddress = packet[8:24]
  1671. destinationIPAddress = packet[24:40]
  1672. // Port numbers have the same offset in TCP and UDP.
  1673. sourcePort = binary.BigEndian.Uint16(packet[40:42])
  1674. destinationPort = binary.BigEndian.Uint16(packet[42:44])
  1675. if protocol == internetProtocolTCP {
  1676. TCPChecksum = packet[56:58]
  1677. } else { // UDP
  1678. UDPChecksum = packet[46:48]
  1679. }
  1680. }
  1681. // Apply rules
  1682. //
  1683. // Most of this logic is only applied on the server, as only
  1684. // the server knows the traffic rules configuration, and is
  1685. // tracking flows.
  1686. isServer := (direction == packetDirectionServerUpstream ||
  1687. direction == packetDirectionServerDownstream)
  1688. // Check if the packet qualifies for transparent DNS rewriting
  1689. //
  1690. // - Both TCP and UDP DNS packets may qualify
  1691. // - Transparent DNS flows are not tracked, as most DNS
  1692. // resolutions are very-short lived exchanges
  1693. // - The traffic rules checks are bypassed, since transparent
  1694. // DNS is essential
  1695. doTransparentDNS := false
  1696. if isServer {
  1697. if direction == packetDirectionServerUpstream {
  1698. // DNS packets destinated for the transparent DNS target addresses
  1699. // will be rewritten to go to one of the server's resolvers.
  1700. if destinationPort == portNumberDNS {
  1701. if version == 4 && destinationIPAddress.Equal(transparentDNSResolverIPv4Address) {
  1702. numResolvers := len(session.DNSResolverIPv4Addresses)
  1703. if numResolvers > 0 {
  1704. doTransparentDNS = true
  1705. } else {
  1706. metrics.rejectedPacket(direction, packetRejectNoDNSResolvers)
  1707. return false
  1708. }
  1709. } else if version == 6 && destinationIPAddress.Equal(transparentDNSResolverIPv6Address) {
  1710. numResolvers := len(session.DNSResolverIPv6Addresses)
  1711. if numResolvers > 0 {
  1712. doTransparentDNS = true
  1713. } else {
  1714. metrics.rejectedPacket(direction, packetRejectNoDNSResolvers)
  1715. return false
  1716. }
  1717. }
  1718. }
  1719. } else { // packetDirectionServerDownstream
  1720. // DNS packets with a source address of any of the server's
  1721. // resolvers will be rewritten back to the transparent DNS target
  1722. // address.
  1723. // Limitation: responses to client DNS packets _originally
  1724. // destined_ for a resolver in GetDNSResolverIPv4Addresses will
  1725. // be lost. This would happen if some process on the client
  1726. // ignores the system set DNS values; and forces use of the same
  1727. // resolvers as the server.
  1728. if sourcePort == portNumberDNS {
  1729. if version == 4 {
  1730. for _, IPAddress := range session.DNSResolverIPv4Addresses {
  1731. if sourceIPAddress.Equal(IPAddress) {
  1732. doTransparentDNS = true
  1733. break
  1734. }
  1735. }
  1736. } else if version == 6 {
  1737. for _, IPAddress := range session.DNSResolverIPv6Addresses {
  1738. if sourceIPAddress.Equal(IPAddress) {
  1739. doTransparentDNS = true
  1740. break
  1741. }
  1742. }
  1743. }
  1744. }
  1745. }
  1746. }
  1747. // Check if flow is tracked before checking traffic permission
  1748. doFlowTracking := !doTransparentDNS && isServer
  1749. // TODO: verify this struct is stack allocated
  1750. var ID flowID
  1751. isTrackingFlow := false
  1752. if doFlowTracking {
  1753. if direction == packetDirectionServerUpstream {
  1754. ID.set(
  1755. destinationIPAddress, destinationPort, sourceIPAddress, sourcePort, protocol)
  1756. } else if direction == packetDirectionServerDownstream {
  1757. ID.set(
  1758. sourceIPAddress, sourcePort, destinationIPAddress, destinationPort, protocol)
  1759. }
  1760. isTrackingFlow = session.isTrackingFlow(ID)
  1761. }
  1762. // Check packet source/destination is permitted; except for:
  1763. // - existing flows, which have already been checked
  1764. // - transparent DNS, which is always allowed
  1765. if !doTransparentDNS && !isTrackingFlow {
  1766. // Enforce traffic rules (allowed TCP/UDP ports).
  1767. checkPort := 0
  1768. if direction == packetDirectionServerUpstream ||
  1769. direction == packetDirectionClientUpstream {
  1770. checkPort = int(destinationPort)
  1771. } else if direction == packetDirectionServerDownstream ||
  1772. direction == packetDirectionClientDownstream {
  1773. checkPort = int(sourcePort)
  1774. }
  1775. if protocol == internetProtocolTCP {
  1776. if checkPort == 0 ||
  1777. (isServer &&
  1778. !session.checkAllowedTCPPortFunc(net.IP(ID.upstreamIPAddress[:]), checkPort)) {
  1779. metrics.rejectedPacket(direction, packetRejectTCPPort)
  1780. return false
  1781. }
  1782. } else if protocol == internetProtocolUDP {
  1783. if checkPort == 0 ||
  1784. (isServer &&
  1785. !session.checkAllowedUDPPortFunc(net.IP(ID.upstreamIPAddress[:]), checkPort)) {
  1786. metrics.rejectedPacket(direction, packetRejectUDPPort)
  1787. return false
  1788. }
  1789. }
  1790. // Enforce no localhost, multicast or broadcast packets; and
  1791. // no client-to-client packets.
  1792. if !destinationIPAddress.IsGlobalUnicast() ||
  1793. (direction == packetDirectionServerUpstream &&
  1794. ((version == 4 &&
  1795. !destinationIPAddress.Equal(transparentDNSResolverIPv4Address) &&
  1796. privateSubnetIPv4.Contains(destinationIPAddress)) ||
  1797. (version == 6 &&
  1798. !destinationIPAddress.Equal(transparentDNSResolverIPv6Address) &&
  1799. privateSubnetIPv6.Contains(destinationIPAddress)))) {
  1800. metrics.rejectedPacket(direction, packetRejectDestinationAddress)
  1801. return false
  1802. }
  1803. }
  1804. // Configure rewriting.
  1805. var checksumAccumulator int32
  1806. var rewriteSourceIPAddress, rewriteDestinationIPAddress net.IP
  1807. if direction == packetDirectionServerUpstream {
  1808. // Store original source IP address to be replaced in
  1809. // downstream rewriting.
  1810. if version == 4 {
  1811. session.setOriginalIPv4AddressIfNotSet(sourceIPAddress)
  1812. rewriteSourceIPAddress = session.assignedIPv4Address
  1813. } else { // version == 6
  1814. session.setOriginalIPv6AddressIfNotSet(sourceIPAddress)
  1815. rewriteSourceIPAddress = session.assignedIPv6Address
  1816. }
  1817. // Rewrite DNS packets destinated for the transparent DNS target
  1818. // addresses to go to one of the server's resolvers.
  1819. if doTransparentDNS {
  1820. if version == 4 {
  1821. rewriteDestinationIPAddress = session.DNSResolverIPv4Addresses[rand.Intn(
  1822. len(session.DNSResolverIPv4Addresses))]
  1823. } else { // version == 6
  1824. rewriteDestinationIPAddress = session.DNSResolverIPv6Addresses[rand.Intn(
  1825. len(session.DNSResolverIPv6Addresses))]
  1826. }
  1827. }
  1828. } else if direction == packetDirectionServerDownstream {
  1829. // Destination address will be original source address.
  1830. if version == 4 {
  1831. rewriteDestinationIPAddress = session.getOriginalIPv4Address()
  1832. } else { // version == 6
  1833. rewriteDestinationIPAddress = session.getOriginalIPv6Address()
  1834. }
  1835. if rewriteDestinationIPAddress == nil {
  1836. metrics.rejectedPacket(direction, packetRejectNoOriginalAddress)
  1837. return false
  1838. }
  1839. // Rewrite source address of packets from servers' resolvers
  1840. // to transparent DNS target address.
  1841. if doTransparentDNS {
  1842. if version == 4 {
  1843. rewriteSourceIPAddress = transparentDNSResolverIPv4Address
  1844. } else { // version == 6
  1845. rewriteSourceIPAddress = transparentDNSResolverIPv6Address
  1846. }
  1847. }
  1848. }
  1849. // Apply rewrites. IP (v4 only) and TCP/UDP all have packet
  1850. // checksums which are updated to relect the rewritten headers.
  1851. if rewriteSourceIPAddress != nil {
  1852. checksumAccumulate(sourceIPAddress, false, &checksumAccumulator)
  1853. copy(sourceIPAddress, rewriteSourceIPAddress)
  1854. checksumAccumulate(sourceIPAddress, true, &checksumAccumulator)
  1855. }
  1856. if rewriteDestinationIPAddress != nil {
  1857. checksumAccumulate(destinationIPAddress, false, &checksumAccumulator)
  1858. copy(destinationIPAddress, rewriteDestinationIPAddress)
  1859. checksumAccumulate(destinationIPAddress, true, &checksumAccumulator)
  1860. }
  1861. if rewriteSourceIPAddress != nil || rewriteDestinationIPAddress != nil {
  1862. // IPv6 doesn't have an IP header checksum.
  1863. if version == 4 {
  1864. checksumAdjust(IPChecksum, checksumAccumulator)
  1865. }
  1866. if protocol == internetProtocolTCP {
  1867. checksumAdjust(TCPChecksum, checksumAccumulator)
  1868. } else { // UDP
  1869. checksumAdjust(UDPChecksum, checksumAccumulator)
  1870. }
  1871. }
  1872. // Start/update flow tracking, only once past all possible packet rejects
  1873. if doFlowTracking {
  1874. if !isTrackingFlow {
  1875. session.startTrackingFlow(ID, direction, applicationData)
  1876. } else {
  1877. session.updateFlow(ID, direction, applicationData)
  1878. }
  1879. }
  1880. metrics.relayedPacket(direction, int(version), protocol, len(packet))
  1881. return true
  1882. }
  1883. // Checksum code based on https://github.com/OpenVPN/openvpn:
  1884. /*
  1885. OpenVPN (TM) -- An Open Source VPN daemon
  1886. Copyright (C) 2002-2017 OpenVPN Technologies, Inc. <sales@openvpn.net>
  1887. OpenVPN license:
  1888. ----------------
  1889. OpenVPN is distributed under the GPL license version 2 (see COPYRIGHT.GPL).
  1890. */
  1891. func checksumAccumulate(data []byte, newData bool, accumulator *int32) {
  1892. // Based on ADD_CHECKSUM_32 and SUB_CHECKSUM_32 macros from OpenVPN:
  1893. // https://github.com/OpenVPN/openvpn/blob/58716979640b5d8850b39820f91da616964398cc/src/openvpn/proto.h#L177
  1894. // Assumes length of data is factor of 4.
  1895. for i := 0; i < len(data); i += 4 {
  1896. var word uint32
  1897. word = uint32(data[i+0])<<24 | uint32(data[i+1])<<16 | uint32(data[i+2])<<8 | uint32(data[i+3])
  1898. if newData {
  1899. *accumulator -= int32(word & 0xFFFF)
  1900. *accumulator -= int32(word >> 16)
  1901. } else {
  1902. *accumulator += int32(word & 0xFFFF)
  1903. *accumulator += int32(word >> 16)
  1904. }
  1905. }
  1906. }
  1907. func checksumAdjust(checksumData []byte, accumulator int32) {
  1908. // Based on ADJUST_CHECKSUM macro from OpenVPN:
  1909. // https://github.com/OpenVPN/openvpn/blob/58716979640b5d8850b39820f91da616964398cc/src/openvpn/proto.h#L177
  1910. // Assumes checksumData is 2 byte slice.
  1911. checksum := uint16(checksumData[0])<<8 | uint16(checksumData[1])
  1912. accumulator += int32(checksum)
  1913. if accumulator < 0 {
  1914. accumulator = -accumulator
  1915. accumulator = (accumulator >> 16) + (accumulator & 0xFFFF)
  1916. accumulator += accumulator >> 16
  1917. checksum = uint16(^accumulator)
  1918. } else {
  1919. accumulator = (accumulator >> 16) + (accumulator & 0xFFFF)
  1920. accumulator += accumulator >> 16
  1921. checksum = uint16(accumulator)
  1922. }
  1923. checksumData[0] = byte(checksum >> 8)
  1924. checksumData[1] = byte(checksum & 0xFF)
  1925. }
  1926. /*
  1927. packet debugging snippet:
  1928. import (
  1929. "github.com/google/gopacket"
  1930. "github.com/google/gopacket/layers"
  1931. )
  1932. func tracePacket(where string, packet []byte) {
  1933. var p gopacket.Packet
  1934. if len(packet) > 0 && packet[0]>>4 == 4 {
  1935. p = gopacket.NewPacket(packet, layers.LayerTypeIPv4, gopacket.Default)
  1936. } else {
  1937. p = gopacket.NewPacket(packet, layers.LayerTypeIPv6, gopacket.Default)
  1938. }
  1939. fmt.Printf("[%s packet]:\n%s\n\n", where, p)
  1940. }
  1941. */
  1942. // Device manages a tun device. It handles packet I/O using static,
  1943. // preallocated buffers to avoid GC churn.
  1944. type Device struct {
  1945. name string
  1946. writeMutex sync.Mutex
  1947. deviceIO io.ReadWriteCloser
  1948. inboundBuffer []byte
  1949. outboundBuffer []byte
  1950. }
  1951. // NewServerDevice creates and configures a new server tun device.
  1952. // Since the server uses fixed address spaces, only one server
  1953. // device may exist per host.
  1954. func NewServerDevice(config *ServerConfig) (*Device, error) {
  1955. file, deviceName, err := OpenTunDevice("")
  1956. if err != nil {
  1957. return nil, common.ContextError(err)
  1958. }
  1959. defer file.Close()
  1960. err = configureServerInterface(config, deviceName)
  1961. if err != nil {
  1962. return nil, common.ContextError(err)
  1963. }
  1964. nio, err := NewNonblockingIO(int(file.Fd()))
  1965. if err != nil {
  1966. return nil, common.ContextError(err)
  1967. }
  1968. return newDevice(
  1969. deviceName,
  1970. nio,
  1971. getMTU(config.MTU)), nil
  1972. }
  1973. // NewClientDevice creates and configures a new client tun device.
  1974. // Multiple client tun devices may exist per host.
  1975. func NewClientDevice(config *ClientConfig) (*Device, error) {
  1976. file, deviceName, err := OpenTunDevice("")
  1977. if err != nil {
  1978. return nil, common.ContextError(err)
  1979. }
  1980. defer file.Close()
  1981. err = configureClientInterface(
  1982. config, deviceName)
  1983. if err != nil {
  1984. return nil, common.ContextError(err)
  1985. }
  1986. nio, err := NewNonblockingIO(int(file.Fd()))
  1987. if err != nil {
  1988. return nil, common.ContextError(err)
  1989. }
  1990. return newDevice(
  1991. deviceName,
  1992. nio,
  1993. getMTU(config.MTU)), nil
  1994. }
  1995. func newDevice(
  1996. name string,
  1997. deviceIO io.ReadWriteCloser,
  1998. MTU int) *Device {
  1999. return &Device{
  2000. name: name,
  2001. deviceIO: deviceIO,
  2002. inboundBuffer: makeDeviceInboundBuffer(MTU),
  2003. outboundBuffer: makeDeviceOutboundBuffer(MTU),
  2004. }
  2005. }
  2006. // NewClientDeviceFromFD wraps an existing tun device.
  2007. func NewClientDeviceFromFD(config *ClientConfig) (*Device, error) {
  2008. nio, err := NewNonblockingIO(config.TunFileDescriptor)
  2009. if err != nil {
  2010. return nil, common.ContextError(err)
  2011. }
  2012. MTU := getMTU(config.MTU)
  2013. return &Device{
  2014. name: "",
  2015. deviceIO: nio,
  2016. inboundBuffer: makeDeviceInboundBuffer(MTU),
  2017. outboundBuffer: makeDeviceOutboundBuffer(MTU),
  2018. }, nil
  2019. }
  2020. // Name returns the interface name for a created tun device,
  2021. // or returns "" for a device created by NewClientDeviceFromFD.
  2022. // The interface name may be used for additional network and
  2023. // routing configuration.
  2024. func (device *Device) Name() string {
  2025. return device.name
  2026. }
  2027. // ReadPacket reads one full packet from the tun device. The
  2028. // return value is a slice of a static, reused buffer, so the
  2029. // value is only valid until the next ReadPacket call.
  2030. // Concurrent calls to ReadPacket are _not_ supported.
  2031. func (device *Device) ReadPacket() ([]byte, error) {
  2032. // readTunPacket performs the platform dependent
  2033. // packet read operation.
  2034. offset, size, err := device.readTunPacket()
  2035. if err != nil {
  2036. return nil, common.ContextError(err)
  2037. }
  2038. return device.inboundBuffer[offset : offset+size], nil
  2039. }
  2040. // WritePacket writes one full packet to the tun device.
  2041. // Concurrent calls to WritePacket are supported.
  2042. func (device *Device) WritePacket(packet []byte) error {
  2043. // This mutex ensures that only one concurrent goroutine
  2044. // can use outboundBuffer when writing.
  2045. device.writeMutex.Lock()
  2046. defer device.writeMutex.Unlock()
  2047. // writeTunPacket performs the platform dependent
  2048. // packet write operation.
  2049. err := device.writeTunPacket(packet)
  2050. if err != nil {
  2051. return common.ContextError(err)
  2052. }
  2053. return nil
  2054. }
  2055. // Close interrupts any blocking Read/Write calls and
  2056. // tears down the tun device.
  2057. func (device *Device) Close() error {
  2058. return device.deviceIO.Close()
  2059. }
  2060. // Channel manages packet transport over a communications channel.
  2061. // Any io.ReadWriteCloser can provide transport. In psiphond, the
  2062. // io.ReadWriteCloser will be an SSH channel. Channel I/O frames
  2063. // packets with a length header and uses static, preallocated
  2064. // buffers to avoid GC churn.
  2065. type Channel struct {
  2066. transport io.ReadWriteCloser
  2067. inboundBuffer []byte
  2068. outboundBuffer []byte
  2069. }
  2070. // IP packets cannot be larger that 64K, so a 16-bit length
  2071. // header is sufficient.
  2072. const (
  2073. channelHeaderSize = 2
  2074. )
  2075. // NewChannel initializes a new Channel.
  2076. func NewChannel(transport io.ReadWriteCloser, MTU int) *Channel {
  2077. return &Channel{
  2078. transport: transport,
  2079. inboundBuffer: make([]byte, channelHeaderSize+MTU),
  2080. outboundBuffer: make([]byte, channelHeaderSize+MTU),
  2081. }
  2082. }
  2083. // ReadPacket reads one full packet from the channel. The
  2084. // return value is a slice of a static, reused buffer, so the
  2085. // value is only valid until the next ReadPacket call.
  2086. // Concurrent calls to ReadPacket are not supported.
  2087. func (channel *Channel) ReadPacket() ([]byte, error) {
  2088. header := channel.inboundBuffer[0:channelHeaderSize]
  2089. _, err := io.ReadFull(channel.transport, header)
  2090. if err != nil {
  2091. return nil, common.ContextError(err)
  2092. }
  2093. size := int(binary.BigEndian.Uint16(header))
  2094. if size > len(channel.inboundBuffer[channelHeaderSize:]) {
  2095. return nil, common.ContextError(fmt.Errorf("packet size exceeds MTU: %d", size))
  2096. }
  2097. packet := channel.inboundBuffer[channelHeaderSize : channelHeaderSize+size]
  2098. _, err = io.ReadFull(channel.transport, packet)
  2099. if err != nil {
  2100. return nil, common.ContextError(err)
  2101. }
  2102. return packet, nil
  2103. }
  2104. // WritePacket writes one full packet to the channel.
  2105. // Concurrent calls to WritePacket are not supported.
  2106. func (channel *Channel) WritePacket(packet []byte) error {
  2107. // Flow control assumed to be provided by the transport. In the case
  2108. // of SSH, the channel window size will determine whether the packet
  2109. // data is transmitted immediately or whether the transport.Write will
  2110. // block. When the channel window is full and transport.Write blocks,
  2111. // the sender's tun device will not be read (client case) or the send
  2112. // queue will fill (server case) and packets will be dropped. In this
  2113. // way, the channel window size will influence the TCP window size for
  2114. // tunneled traffic.
  2115. // When the transport is an SSH channel, the overhead per packet message
  2116. // includes:
  2117. //
  2118. // - SSH_MSG_CHANNEL_DATA: 5 bytes (https://tools.ietf.org/html/rfc4254#section-5.2)
  2119. // - SSH packet: ~28 bytes (https://tools.ietf.org/html/rfc4253#section-5.3), with MAC
  2120. // - TCP/IP transport for SSH: 40 bytes for IPv4
  2121. // Assumes MTU <= 64K and len(packet) <= MTU
  2122. size := len(packet)
  2123. binary.BigEndian.PutUint16(channel.outboundBuffer, uint16(size))
  2124. copy(channel.outboundBuffer[channelHeaderSize:], packet)
  2125. _, err := channel.transport.Write(channel.outboundBuffer[0 : channelHeaderSize+size])
  2126. if err != nil {
  2127. return common.ContextError(err)
  2128. }
  2129. return nil
  2130. }
  2131. // WriteFramedPackets writes a buffer of pre-framed packets to
  2132. // the channel.
  2133. // Concurrent calls to WriteFramedPackets are not supported.
  2134. func (channel *Channel) WriteFramedPackets(packetBuffer []byte) error {
  2135. _, err := channel.transport.Write(packetBuffer)
  2136. if err != nil {
  2137. return common.ContextError(err)
  2138. }
  2139. return nil
  2140. }
  2141. // Close interrupts any blocking Read/Write calls and
  2142. // closes the channel transport.
  2143. func (channel *Channel) Close() error {
  2144. return channel.transport.Close()
  2145. }