tun.go 97 KB

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