tun.go 89 KB

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