tun.go 101 KB

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