tun.go 91 KB

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