tun.go 97 KB

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