config.go 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190
  1. /*
  2. * Copyright (c) 2015, 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. package psiphon
  20. import (
  21. "crypto/md5"
  22. "encoding/base64"
  23. "encoding/binary"
  24. "encoding/json"
  25. "errors"
  26. "fmt"
  27. "net/http"
  28. "os"
  29. "strconv"
  30. "strings"
  31. "sync"
  32. "unicode"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  36. )
  37. const (
  38. TUNNEL_POOL_SIZE = 1
  39. )
  40. // Config is the Psiphon configuration specified by the application. This
  41. // configuration controls the behavior of the core tunnel functionality.
  42. //
  43. // To distinguish omitted timeout params from explicit 0 value timeout params,
  44. // corresponding fieldss are int pointers. nil means no value was supplied and
  45. // to use the default; a non-nil pointer to 0 means no timeout.
  46. type Config struct {
  47. // DataStoreDirectory is the directory in which to store the persistent
  48. // database, which contains information such as server entries. By
  49. // default, current working directory.
  50. //
  51. // Warning: If the datastore file, DataStoreDirectory/DATA_STORE_FILENAME,
  52. // exists but fails to open for any reason (checksum error, unexpected
  53. // file format, etc.) it will be deleted in order to pave a new datastore
  54. // and continue running.
  55. DataStoreDirectory string
  56. // PropagationChannelId is a string identifier which indicates how the
  57. // Psiphon client was distributed. This parameter is required. This value
  58. // is supplied by and depends on the Psiphon Network, and is typically
  59. // embedded in the client binary.
  60. PropagationChannelId string
  61. // SponsorId is a string identifier which indicates who is sponsoring this
  62. // Psiphon client. One purpose of this value is to determine the home
  63. // pages for display. This parameter is required. This value is supplied
  64. // by and depends on the Psiphon Network, and is typically embedded in the
  65. // client binary.
  66. SponsorId string
  67. // ClientVersion is the client version number that the client reports to
  68. // the server. The version number refers to the host client application,
  69. // not the core tunnel library. One purpose of this value is to enable
  70. // automatic updates. This value is supplied by and depends on the Psiphon
  71. // Network, and is typically embedded in the client binary.
  72. //
  73. // Note that sending a ClientPlatform string which includes "windows"
  74. // (case insensitive) and a ClientVersion of <= 44 will cause an error in
  75. // processing the response to DoConnectedRequest calls.
  76. ClientVersion string
  77. // ClientPlatform is the client platform ("Windows", "Android", etc.) that
  78. // the client reports to the server.
  79. ClientPlatform string
  80. // TunnelWholeDevice is a flag that is passed through to the handshake
  81. // request for stats purposes. Set to 1 when the host application is
  82. // tunneling the whole device, 0 otherwise.
  83. TunnelWholeDevice int
  84. // EgressRegion is a ISO 3166-1 alpha-2 country code which indicates which
  85. // country to egress from. For the default, "", the best performing server
  86. // in any country is selected.
  87. EgressRegion string
  88. // ListenInterface specifies which interface to listen on. If no
  89. // interface is provided then listen on 127.0.0.1. If 'any' is provided
  90. // then use 0.0.0.0. If there are multiple IP addresses on an interface
  91. // use the first IPv4 address.
  92. ListenInterface string
  93. // DisableLocalSocksProxy disables running the local SOCKS proxy.
  94. DisableLocalSocksProxy bool
  95. // LocalSocksProxyPort specifies a port number for the local SOCKS proxy
  96. // running at 127.0.0.1. For the default value, 0, the system selects a
  97. // free port (a notice reporting the selected port is emitted).
  98. LocalSocksProxyPort int
  99. // LocalHttpProxyPort specifies a port number for the local HTTP proxy
  100. // running at 127.0.0.1. For the default value, 0, the system selects a
  101. // free port (a notice reporting the selected port is emitted).
  102. LocalHttpProxyPort int
  103. // DisableLocalHTTPProxy disables running the local HTTP proxy.
  104. DisableLocalHTTPProxy bool
  105. // NetworkLatencyMultiplier is a multiplier that is to be applied to
  106. // default network event timeouts. Set this to tune performance for
  107. // slow networks.
  108. // When set, must be >= 1.0.
  109. NetworkLatencyMultiplier float64
  110. // TunnelProtocol indicates which protocol to use. For the default, "",
  111. // all protocols are used.
  112. //
  113. // Deprecated: Use LimitTunnelProtocols. When LimitTunnelProtocols is not
  114. // nil, this parameter is ignored.
  115. TunnelProtocol string
  116. // LimitTunnelProtocols indicates which protocols to use. Valid values
  117. // include:
  118. // "SSH", "OSSH", "UNFRONTED-MEEK-OSSH", "UNFRONTED-MEEK-HTTPS-OSSH",
  119. // "UNFRONTED-MEEK-SESSION-TICKET-OSSH", "FRONTED-MEEK-OSSH",
  120. // "FRONTED-MEEK-HTTP-OSSH", "QUIC-OSSH", "MARIONETTE-OSSH", and
  121. // "TAPDANCE-OSSH".
  122. // For the default, an empty list, all protocols are used.
  123. LimitTunnelProtocols []string
  124. // InitialLimitTunnelProtocols is an optional initial phase of limited
  125. // protocols for the first InitialLimitTunnelProtocolsCandidateCount
  126. // candidates; after these candidates, LimitTunnelProtocols applies.
  127. //
  128. // For the default, an empty list, InitialLimitTunnelProtocols is off.
  129. InitialLimitTunnelProtocols []string
  130. // InitialLimitTunnelProtocolsCandidateCount is the number of candidates
  131. // to which InitialLimitTunnelProtocols is applied instead of
  132. // LimitTunnelProtocols.
  133. //
  134. // For the default, 0, InitialLimitTunnelProtocols is off.
  135. InitialLimitTunnelProtocolsCandidateCount int
  136. // LimitTLSProfiles indicates which TLS profiles to select from. Valid
  137. // values are listed in protocols.SupportedTLSProfiles.
  138. // For the default, an empty list, all profiles are candidates for
  139. // selection.
  140. LimitTLSProfiles []string
  141. // LimitQUICVersions indicates which QUIC versions to select from. Valid
  142. // values are listed in protocols.SupportedQUICVersions.
  143. // For the default, an empty list, all versions are candidates for
  144. // selection.
  145. LimitQUICVersions []string
  146. // EstablishTunnelTimeoutSeconds specifies a time limit after which to
  147. // halt the core tunnel controller if no tunnel has been established. The
  148. // default is parameters.EstablishTunnelTimeout.
  149. EstablishTunnelTimeoutSeconds *int
  150. // EstablishTunnelPausePeriodSeconds specifies the delay between attempts
  151. // to establish tunnels. Briefly pausing allows for network conditions to
  152. // improve and for asynchronous operations such as fetch remote server
  153. // list to complete. If omitted, a default value is used. This value is
  154. // typical overridden for testing.
  155. EstablishTunnelPausePeriodSeconds *int
  156. // EstablishTunnelPausePeriodSeconds specifies the grace period, or head
  157. // start, provided to the affinity server candidate when establishing. The
  158. // affinity server is the server used for the last established tunnel.
  159. EstablishTunnelServerAffinityGracePeriodMilliseconds *int
  160. // ConnectionWorkerPoolSize specifies how many connection attempts to
  161. // attempt in parallel. If omitted of when 0, a default is used; this is
  162. // recommended.
  163. ConnectionWorkerPoolSize int
  164. // TunnelPoolSize specifies how many tunnels to run in parallel. Port
  165. // forwards are multiplexed over multiple tunnels. If omitted or when 0,
  166. // the default is TUNNEL_POOL_SIZE, which is recommended.
  167. TunnelPoolSize int
  168. // StaggerConnectionWorkersMilliseconds adds a specified delay before
  169. // making each server candidate available to connection workers. This
  170. // option is enabled when StaggerConnectionWorkersMilliseconds > 0.
  171. StaggerConnectionWorkersMilliseconds int
  172. // LimitIntensiveConnectionWorkers limits the number of concurrent
  173. // connection workers attempting connections with resource intensive
  174. // protocols. This option is enabled when LimitIntensiveConnectionWorkers
  175. // > 0.
  176. LimitIntensiveConnectionWorkers int
  177. // LimitMeekBufferSizes selects smaller buffers for meek protocols.
  178. LimitMeekBufferSizes bool
  179. // IgnoreHandshakeStatsRegexps skips compiling and using stats regexes.
  180. IgnoreHandshakeStatsRegexps bool
  181. // UpstreamProxyURL is a URL specifying an upstream proxy to use for all
  182. // outbound connections. The URL should include proxy type and
  183. // authentication information, as required. See example URLs here:
  184. // https://github.com/Psiphon-Labs/psiphon-tunnel-core/tree/master/psiphon/upstreamproxy
  185. UpstreamProxyURL string
  186. // CustomHeaders is a set of additional arbitrary HTTP headers that are
  187. // added to all plaintext HTTP requests and requests made through an HTTP
  188. // upstream proxy when specified by UpstreamProxyURL.
  189. CustomHeaders http.Header
  190. // Deprecated: Use CustomHeaders. When CustomHeaders is not nil, this
  191. // parameter is ignored.
  192. UpstreamProxyCustomHeaders http.Header
  193. // NetworkConnectivityChecker is an interface that enables tunnel-core to
  194. // call into the host application to check for network connectivity. See:
  195. // NetworkConnectivityChecker doc.
  196. //
  197. // This parameter is only applicable to library deployments.
  198. NetworkConnectivityChecker NetworkConnectivityChecker
  199. // DeviceBinder is an interface that enables tunnel-core to call into the
  200. // host application to bind sockets to specific devices. See: DeviceBinder
  201. // doc.
  202. //
  203. // This parameter is only applicable to library deployments.
  204. DeviceBinder DeviceBinder
  205. // IPv6Synthesizer is an interface that allows tunnel-core to call into
  206. // the host application to synthesize IPv6 addresses. See: IPv6Synthesizer
  207. // doc.
  208. //
  209. // This parameter is only applicable to library deployments.
  210. IPv6Synthesizer IPv6Synthesizer
  211. // DnsServerGetter is an interface that enables tunnel-core to call into
  212. // the host application to discover the native network DNS server
  213. // settings. See: DnsServerGetter doc.
  214. //
  215. // This parameter is only applicable to library deployments.
  216. DnsServerGetter DnsServerGetter
  217. // NetworkIDGetter in an interface that enables tunnel-core to call into
  218. // the host application to get an identifier for the host's current active
  219. // network. See: NetworkIDGetter doc.
  220. //
  221. // This parameter is only applicable to library deployments.
  222. NetworkIDGetter NetworkIDGetter
  223. // NetworkID, when not blank, is used as the identifier for the host's
  224. // current active network.
  225. // NetworkID is ignored when NetworkIDGetter is set.
  226. NetworkID string
  227. // DisableTactics disables tactics operations including requests, payload
  228. // handling, and application of parameters.
  229. DisableTactics bool
  230. // DisableReplay causes any persisted dial parameters to be ignored when
  231. // they would otherwise be used for replay.
  232. DisableReplay bool
  233. // TransformHostNames specifies whether to use hostname transformation
  234. // circumvention strategies. Set to "always" to always transform, "never"
  235. // to never transform, and "", the default, for the default transformation
  236. // strategy.
  237. TransformHostNames string
  238. // TargetServerEntry is an encoded server entry. When specified, this
  239. // server entry is used exclusively and all other known servers are
  240. // ignored; also, when set, ConnectionWorkerPoolSize is ignored and
  241. // the pool size is 1.
  242. TargetServerEntry string
  243. // DisableApi disables Psiphon server API calls including handshake,
  244. // connected, status, etc. This is used for special case temporary tunnels
  245. // (Windows VPN mode).
  246. DisableApi bool
  247. // TargetApiProtocol specifies whether to force use of "ssh" or "web" API
  248. // protocol. When blank, the default, the optimal API protocol is used.
  249. // Note that this capability check is not applied before the
  250. // "CandidateServers" count is emitted.
  251. //
  252. // This parameter is intended for testing and debugging only. Not all
  253. // parameters are supported in the legacy "web" API protocol, including
  254. // speed test samples.
  255. TargetApiProtocol string
  256. // RemoteServerListUrl is a URL which specifies a location to fetch out-
  257. // of-band server entries. This facility is used when a tunnel cannot be
  258. // established to known servers. This value is supplied by and depends on
  259. // the Psiphon Network, and is typically embedded in the client binary.
  260. //
  261. // Deprecated: Use RemoteServerListURLs. When RemoteServerListURLs is not
  262. // nil, this parameter is ignored.
  263. RemoteServerListUrl string
  264. // RemoteServerListURLs is list of URLs which specify locations to fetch
  265. // out-of-band server entries. This facility is used when a tunnel cannot
  266. // be established to known servers. This value is supplied by and depends
  267. // on the Psiphon Network, and is typically embedded in the client binary.
  268. // All URLs must point to the same entity with the same ETag. At least one
  269. // DownloadURL must have OnlyAfterAttempts = 0.
  270. RemoteServerListURLs parameters.DownloadURLs
  271. // RemoteServerListDownloadFilename specifies a target filename for
  272. // storing the remote server list download. Data is stored in co-located
  273. // files (RemoteServerListDownloadFilename.part*) to allow for resumable
  274. // downloading.
  275. RemoteServerListDownloadFilename string
  276. // RemoteServerListSignaturePublicKey specifies a public key that's used
  277. // to authenticate the remote server list payload. This value is supplied
  278. // by and depends on the Psiphon Network, and is typically embedded in the
  279. // client binary.
  280. RemoteServerListSignaturePublicKey string
  281. // DisableRemoteServerListFetcher disables fetching remote server lists.
  282. // This is used for special case temporary tunnels.
  283. DisableRemoteServerListFetcher bool
  284. // FetchRemoteServerListRetryPeriodMilliseconds specifies the delay before
  285. // resuming a remote server list download after a failure. If omitted, a
  286. // default value is used. This value is typical overridden for testing.
  287. FetchRemoteServerListRetryPeriodMilliseconds *int
  288. // ObfuscatedServerListRootURL is a URL which specifies the root location
  289. // from which to fetch obfuscated server list files. This value is
  290. // supplied by and depends on the Psiphon Network, and is typically
  291. // embedded in the client binary.
  292. //
  293. // Deprecated: Use ObfuscatedServerListRootURLs. When
  294. // ObfuscatedServerListRootURLs is not nil, this parameter is ignored.
  295. ObfuscatedServerListRootURL string
  296. // ObfuscatedServerListRootURLs is a list of URLs which specify root
  297. // locations from which to fetch obfuscated server list files. This value
  298. // is supplied by and depends on the Psiphon Network, and is typically
  299. // embedded in the client binary. All URLs must point to the same entity
  300. // with the same ETag. At least one DownloadURL must have
  301. // OnlyAfterAttempts = 0.
  302. ObfuscatedServerListRootURLs parameters.DownloadURLs
  303. // ObfuscatedServerListDownloadDirectory specifies a target directory for
  304. // storing the obfuscated remote server list downloads. Data is stored in
  305. // co-located files (<OSL filename>.part*) to allow for resumable
  306. // downloading.
  307. ObfuscatedServerListDownloadDirectory string
  308. // SplitTunnelRoutesURLFormat is a URL which specifies the location of a
  309. // routes file to use for split tunnel mode. The URL must include a
  310. // placeholder for the client region to be supplied. Split tunnel mode
  311. // uses the routes file to classify port forward destinations as foreign
  312. // or domestic and does not tunnel domestic destinations. Split tunnel
  313. // mode is on when all the SplitTunnel parameters are supplied. This value
  314. // is supplied by and depends on the Psiphon Network, and is typically
  315. // embedded in the client binary.
  316. SplitTunnelRoutesURLFormat string
  317. // SplitTunnelRoutesSignaturePublicKey specifies a public key that's used
  318. // to authenticate the split tunnel routes payload. This value is supplied
  319. // by and depends on the Psiphon Network, and is typically embedded in the
  320. // client binary.
  321. SplitTunnelRoutesSignaturePublicKey string
  322. // SplitTunnelDNSServer specifies a DNS server to use when resolving port
  323. // forward target domain names to IP addresses for classification. The DNS
  324. // server must support TCP requests.
  325. SplitTunnelDNSServer string
  326. // UpgradeDownloadUrl specifies a URL from which to download a host client
  327. // upgrade file, when one is available. The core tunnel controller
  328. // provides a resumable download facility which downloads this resource
  329. // and emits a notice when complete. This value is supplied by and depends
  330. // on the Psiphon Network, and is typically embedded in the client binary.
  331. //
  332. // Deprecated: Use UpgradeDownloadURLs. When UpgradeDownloadURLs is not
  333. // nil, this parameter is ignored.
  334. UpgradeDownloadUrl string
  335. // UpgradeDownloadURLs is list of URLs which specify locations from which
  336. // to download a host client upgrade file, when one is available. The core
  337. // tunnel controller provides a resumable download facility which
  338. // downloads this resource and emits a notice when complete. This value is
  339. // supplied by and depends on the Psiphon Network, and is typically
  340. // embedded in the client binary. All URLs must point to the same entity
  341. // with the same ETag. At least one DownloadURL must have
  342. // OnlyAfterAttempts = 0.
  343. UpgradeDownloadURLs parameters.DownloadURLs
  344. // UpgradeDownloadClientVersionHeader specifies the HTTP header name for
  345. // the entity at UpgradeDownloadURLs which specifies the client version
  346. // (an integer value). A HEAD request may be made to check the version
  347. // number available at UpgradeDownloadURLs.
  348. // UpgradeDownloadClientVersionHeader is required when UpgradeDownloadURLs
  349. // is specified.
  350. UpgradeDownloadClientVersionHeader string
  351. // UpgradeDownloadFilename is the local target filename for an upgrade
  352. // download. This parameter is required when UpgradeDownloadURLs (or
  353. // UpgradeDownloadUrl) is specified. Data is stored in co-located files
  354. // (UpgradeDownloadFilename.part*) to allow for resumable downloading.
  355. UpgradeDownloadFilename string
  356. // FetchUpgradeRetryPeriodMilliseconds specifies the delay before resuming
  357. // a client upgrade download after a failure. If omitted, a default value
  358. // is used. This value is typical overridden for testing.
  359. FetchUpgradeRetryPeriodMilliseconds *int
  360. // EmitBytesTransferred indicates whether to emit periodic notices showing
  361. // bytes sent and received.
  362. EmitBytesTransferred bool
  363. // TrustedCACertificatesFilename specifies a file containing trusted CA
  364. // certs. When set, this toggles use of the trusted CA certs, specified in
  365. // TrustedCACertificatesFilename, for tunneled TLS connections that expect
  366. // server certificates signed with public certificate authorities
  367. // (currently, only upgrade downloads). This option is used with stock Go
  368. // TLS in cases where Go may fail to obtain a list of root CAs from the
  369. // operating system.
  370. TrustedCACertificatesFilename string
  371. // DisablePeriodicSshKeepAlive indicates whether to send an SSH keepalive
  372. // every 1-2 minutes, when the tunnel is idle. If the SSH keepalive times
  373. // out, the tunnel is considered to have failed.
  374. DisablePeriodicSshKeepAlive bool
  375. // DeviceRegion is the optional, reported region the host device is
  376. // running in. This input value should be a ISO 3166-1 alpha-2 country
  377. // code. The device region is reported to the server in the connected
  378. // request and recorded for Psiphon stats.
  379. //
  380. // When provided, this value may be used, pre-connection, to select
  381. // performance or circumvention optimization strategies for the given
  382. // region.
  383. DeviceRegion string
  384. // EmitDiagnosticNotices indicates whether to output notices containing
  385. // detailed information about the Psiphon session. As these notices may
  386. // contain sensitive network information, they should not be insecurely
  387. // distributed or displayed to users. Default is off.
  388. EmitDiagnosticNotices bool
  389. // RateLimits specify throttling configuration for the tunnel.
  390. RateLimits common.RateLimits
  391. // EmitSLOKs indicates whether to emit notices for each seeded SLOK. As
  392. // this could reveal user browsing activity, it's intended for debugging
  393. // and testing only.
  394. EmitSLOKs bool
  395. // PacketTunnelTunDeviceFileDescriptor specifies a tun device file
  396. // descriptor to use for running a packet tunnel. When this value is > 0,
  397. // a packet tunnel is established through the server and packets are
  398. // relayed via the tun device file descriptor. The file descriptor is
  399. // duped in NewController. When PacketTunnelTunDeviceFileDescriptor is
  400. // set, TunnelPoolSize must be 1.
  401. PacketTunnelTunFileDescriptor int
  402. // SessionID specifies a client session ID to use in the Psiphon API. The
  403. // session ID should be a randomly generated value that is used only for a
  404. // single session, which is defined as the period between a user starting
  405. // a Psiphon client and stopping the client.
  406. //
  407. // A session ID must be 32 hex digits (lower case). When blank, a random
  408. // session ID is automatically generated. Supply a session ID when a
  409. // single client session will cross multiple Controller instances.
  410. SessionID string
  411. // Authorizations is a list of encoded, signed access control
  412. // authorizations that the client has obtained and will present to the
  413. // server.
  414. Authorizations []string
  415. // UseFragmentor and associated Fragmentor fields are for testing
  416. // purposes.
  417. UseFragmentor string
  418. FragmentorMinTotalBytes *int
  419. FragmentorMaxTotalBytes *int
  420. FragmentorMinWriteBytes *int
  421. FragmentorMaxWriteBytes *int
  422. FragmentorMinDelayMicroseconds *int
  423. FragmentorMaxDelayMicroseconds *int
  424. // ObfuscatedSSHAlgorithms and associated ObfuscatedSSH fields are for
  425. // testing purposes. If specified, ObfuscatedSSHAlgorithms must have 4 SSH
  426. // KEX elements in order: the kex algorithm, cipher, MAC, and server host
  427. // key algorithm.
  428. ObfuscatedSSHAlgorithms []string
  429. ObfuscatedSSHMinPadding *int
  430. ObfuscatedSSHMaxPadding *int
  431. // LivenessTestMinUpstreamBytes and other LivenessTest fields are for
  432. // testing purposes.
  433. LivenessTestMinUpstreamBytes *int
  434. LivenessTestMaxUpstreamBytes *int
  435. LivenessTestMinDownstreamBytes *int
  436. LivenessTestMaxDownstreamBytes *int
  437. // ReplayCandidateCount and other Replay fields are for
  438. // testing purposes.
  439. ReplayCandidateCount *int
  440. ReplayDialParametersTTLSeconds *int
  441. // clientParameters is the active ClientParameters with defaults, config
  442. // values, and, optionally, tactics applied.
  443. //
  444. // New tactics must be applied by calling Config.SetClientParameters;
  445. // calling clientParameters.Set directly will fail to add config values.
  446. clientParameters *parameters.ClientParameters
  447. dialParametersHash []byte
  448. dynamicConfigMutex sync.Mutex
  449. sponsorID string
  450. authorizations []string
  451. deviceBinder DeviceBinder
  452. networkIDGetter NetworkIDGetter
  453. committed bool
  454. }
  455. // LoadConfig parses a JSON format Psiphon config JSON string and returns a
  456. // Config struct populated with config values.
  457. //
  458. // The Config struct may then be programmatically populated with additional
  459. // values, including callbacks such as DeviceBinder.
  460. //
  461. // Before using the Config, Commit must be called, which will perform further
  462. // validation and initialize internal data structures.
  463. func LoadConfig(configJson []byte) (*Config, error) {
  464. var config Config
  465. err := json.Unmarshal(configJson, &config)
  466. if err != nil {
  467. return nil, common.ContextError(err)
  468. }
  469. return &config, nil
  470. }
  471. // IsCommitted checks if Commit was called.
  472. func (config *Config) IsCommitted() bool {
  473. return config.committed
  474. }
  475. // Commit validates Config fields finalizes initialization.
  476. //
  477. // Config fields should not be set after calling Config, as any changes may
  478. // not be reflected in internal data structures.
  479. func (config *Config) Commit() error {
  480. // Do SetEmitDiagnosticNotices first, to ensure config file errors are emitted.
  481. if config.EmitDiagnosticNotices {
  482. SetEmitDiagnosticNotices(true)
  483. }
  484. // Promote legacy fields.
  485. if config.CustomHeaders == nil {
  486. config.CustomHeaders = config.UpstreamProxyCustomHeaders
  487. config.UpstreamProxyCustomHeaders = nil
  488. }
  489. if config.RemoteServerListUrl != "" && config.RemoteServerListURLs == nil {
  490. config.RemoteServerListURLs = promoteLegacyDownloadURL(config.RemoteServerListUrl)
  491. }
  492. if config.ObfuscatedServerListRootURL != "" && config.ObfuscatedServerListRootURLs == nil {
  493. config.ObfuscatedServerListRootURLs = promoteLegacyDownloadURL(config.ObfuscatedServerListRootURL)
  494. }
  495. if config.UpgradeDownloadUrl != "" && config.UpgradeDownloadURLs == nil {
  496. config.UpgradeDownloadURLs = promoteLegacyDownloadURL(config.UpgradeDownloadUrl)
  497. }
  498. if config.TunnelProtocol != "" && len(config.LimitTunnelProtocols) == 0 {
  499. config.LimitTunnelProtocols = []string{config.TunnelProtocol}
  500. }
  501. // Supply default values.
  502. if config.DataStoreDirectory == "" {
  503. wd, err := os.Getwd()
  504. if err != nil {
  505. return common.ContextError(err)
  506. }
  507. config.DataStoreDirectory = wd
  508. }
  509. if config.ClientVersion == "" {
  510. config.ClientVersion = "0"
  511. }
  512. if config.TunnelPoolSize == 0 {
  513. config.TunnelPoolSize = TUNNEL_POOL_SIZE
  514. }
  515. // Validate config fields.
  516. if config.PropagationChannelId == "" {
  517. return common.ContextError(
  518. errors.New("propagation channel ID is missing from the configuration file"))
  519. }
  520. if config.SponsorId == "" {
  521. return common.ContextError(
  522. errors.New("sponsor ID is missing from the configuration file"))
  523. }
  524. _, err := strconv.Atoi(config.ClientVersion)
  525. if err != nil {
  526. return common.ContextError(
  527. fmt.Errorf("invalid client version: %s", err))
  528. }
  529. if !common.Contains(
  530. []string{"", protocol.PSIPHON_SSH_API_PROTOCOL, protocol.PSIPHON_WEB_API_PROTOCOL},
  531. config.TargetApiProtocol) {
  532. return common.ContextError(
  533. errors.New("invalid TargetApiProtocol"))
  534. }
  535. if !config.DisableRemoteServerListFetcher {
  536. if config.RemoteServerListURLs != nil {
  537. if config.RemoteServerListSignaturePublicKey == "" {
  538. return common.ContextError(errors.New("missing RemoteServerListSignaturePublicKey"))
  539. }
  540. if config.RemoteServerListDownloadFilename == "" {
  541. return common.ContextError(errors.New("missing RemoteServerListDownloadFilename"))
  542. }
  543. }
  544. if config.ObfuscatedServerListRootURLs != nil {
  545. if config.RemoteServerListSignaturePublicKey == "" {
  546. return common.ContextError(errors.New("missing RemoteServerListSignaturePublicKey"))
  547. }
  548. if config.ObfuscatedServerListDownloadDirectory == "" {
  549. return common.ContextError(errors.New("missing ObfuscatedServerListDownloadDirectory"))
  550. }
  551. }
  552. }
  553. if config.SplitTunnelRoutesURLFormat != "" {
  554. if config.SplitTunnelRoutesSignaturePublicKey == "" {
  555. return common.ContextError(errors.New("missing SplitTunnelRoutesSignaturePublicKey"))
  556. }
  557. if config.SplitTunnelDNSServer == "" {
  558. return common.ContextError(errors.New("missing SplitTunnelDNSServer"))
  559. }
  560. }
  561. if config.UpgradeDownloadURLs != nil {
  562. if config.UpgradeDownloadClientVersionHeader == "" {
  563. return common.ContextError(errors.New("missing UpgradeDownloadClientVersionHeader"))
  564. }
  565. if config.UpgradeDownloadFilename == "" {
  566. return common.ContextError(errors.New("missing UpgradeDownloadFilename"))
  567. }
  568. }
  569. // This constraint is expected by logic in Controller.runTunnels().
  570. if config.PacketTunnelTunFileDescriptor > 0 && config.TunnelPoolSize != 1 {
  571. return common.ContextError(errors.New("packet tunnel mode requires TunnelPoolSize to be 1"))
  572. }
  573. // SessionID must be PSIPHON_API_CLIENT_SESSION_ID_LENGTH lowercase hex-encoded bytes.
  574. if config.SessionID == "" {
  575. sessionID, err := MakeSessionId()
  576. if err != nil {
  577. return common.ContextError(err)
  578. }
  579. config.SessionID = sessionID
  580. }
  581. if len(config.SessionID) != 2*protocol.PSIPHON_API_CLIENT_SESSION_ID_LENGTH ||
  582. -1 != strings.IndexFunc(config.SessionID, func(c rune) bool {
  583. return !unicode.Is(unicode.ASCII_Hex_Digit, c) || unicode.IsUpper(c)
  584. }) {
  585. return common.ContextError(errors.New("invalid SessionID"))
  586. }
  587. config.clientParameters, err = parameters.NewClientParameters(
  588. func(err error) {
  589. NoticeAlert("ClientParameters getValue failed: %s", err)
  590. })
  591. if err != nil {
  592. return common.ContextError(err)
  593. }
  594. if config.ObfuscatedSSHAlgorithms != nil &&
  595. len(config.ObfuscatedSSHAlgorithms) != 4 {
  596. // TODO: validate each algorithm?
  597. return common.ContextError(errors.New("invalid ObfuscatedSSHAlgorithms"))
  598. }
  599. // clientParameters.Set will validate the config fields applied to parameters.
  600. err = config.SetClientParameters("", false, nil)
  601. if err != nil {
  602. return common.ContextError(err)
  603. }
  604. // Calculate and set the dial parameters hash. After this point, related
  605. // config fields must not change.
  606. config.setDialParametersHash()
  607. // Set defaults for dynamic config fields.
  608. config.SetDynamicConfig(config.SponsorId, config.Authorizations)
  609. // Initialize config.deviceBinder and config.config.networkIDGetter. These
  610. // wrap config.DeviceBinder and config.NetworkIDGetter/NetworkID with
  611. // loggers.
  612. //
  613. // New variables are set to avoid mutating input config fields.
  614. // Internally, code must use config.deviceBinder and
  615. // config.networkIDGetter and not the input/exported fields.
  616. if config.DeviceBinder != nil {
  617. config.deviceBinder = &loggingDeviceBinder{config.DeviceBinder}
  618. }
  619. networkIDGetter := config.NetworkIDGetter
  620. if networkIDGetter == nil {
  621. // Limitation: unlike NetworkIDGetter, which calls back to platform APIs
  622. // this method of network identification is not dynamic and will not reflect
  623. // network changes that occur while running.
  624. if config.NetworkID != "" {
  625. networkIDGetter = newStaticNetworkGetter(config.NetworkID)
  626. } else {
  627. networkIDGetter = newStaticNetworkGetter("UNKNOWN")
  628. }
  629. }
  630. config.networkIDGetter = &loggingNetworkIDGetter{networkIDGetter}
  631. config.committed = true
  632. return nil
  633. }
  634. // GetClientParameters returns a snapshot of the current client parameters.
  635. func (config *Config) GetClientParameters() *parameters.ClientParametersSnapshot {
  636. return config.clientParameters.Get()
  637. }
  638. // SetClientParameters resets Config.clientParameters to the default values,
  639. // applies any config file values, and then applies the input parameters (from
  640. // tactics, etc.)
  641. //
  642. // Set skipOnError to false when initially applying only config values, as
  643. // this will validate the values and should fail. Set skipOnError to true when
  644. // applying tactics to ignore invalid or unknown parameter values from tactics.
  645. //
  646. // In the case of applying tactics, do not call Config.clientParameters.Set
  647. // directly as this will not first apply config values.
  648. //
  649. // If there is an error, the existing Config.clientParameters are left
  650. // entirely unmodified.
  651. func (config *Config) SetClientParameters(tag string, skipOnError bool, applyParameters map[string]interface{}) error {
  652. setParameters := []map[string]interface{}{config.makeConfigParameters()}
  653. if applyParameters != nil {
  654. setParameters = append(setParameters, applyParameters)
  655. }
  656. counts, err := config.clientParameters.Set(tag, skipOnError, setParameters...)
  657. if err != nil {
  658. return common.ContextError(err)
  659. }
  660. NoticeInfo("applied %v parameters with tag '%s'", counts, tag)
  661. // Emit certain individual parameter values for quick reference in diagnostics.
  662. networkLatencyMultiplier := config.clientParameters.Get().Float(parameters.NetworkLatencyMultiplier)
  663. if networkLatencyMultiplier != 0.0 {
  664. NoticeInfo(
  665. "NetworkLatencyMultiplier: %f",
  666. config.clientParameters.Get().Float(parameters.NetworkLatencyMultiplier))
  667. }
  668. return nil
  669. }
  670. // SetDynamicConfig sets the current client sponsor ID and authorizations.
  671. // Invalid values for sponsor ID are ignored. The caller must not modify the
  672. // input authorizations slice.
  673. func (config *Config) SetDynamicConfig(sponsorID string, authorizations []string) {
  674. config.dynamicConfigMutex.Lock()
  675. defer config.dynamicConfigMutex.Unlock()
  676. if sponsorID != "" {
  677. config.sponsorID = sponsorID
  678. }
  679. config.authorizations = authorizations
  680. }
  681. // GetSponsorID returns the current client sponsor ID.
  682. func (config *Config) GetSponsorID() string {
  683. config.dynamicConfigMutex.Lock()
  684. defer config.dynamicConfigMutex.Unlock()
  685. return config.sponsorID
  686. }
  687. // GetAuthorizations returns the current client authorizations.
  688. // The caller must not modify the returned slice.
  689. func (config *Config) GetAuthorizations() []string {
  690. config.dynamicConfigMutex.Lock()
  691. defer config.dynamicConfigMutex.Unlock()
  692. return config.authorizations
  693. }
  694. // UseUpstreamProxy indicates if an upstream proxy has been
  695. // configured.
  696. func (config *Config) UseUpstreamProxy() bool {
  697. return config.UpstreamProxyURL != ""
  698. }
  699. // GetNetworkID returns the current network ID. When NetworkIDGetter
  700. // is set, this calls into the host application; otherwise, a default
  701. // value is returned.
  702. func (config *Config) GetNetworkID() string {
  703. return config.networkIDGetter.GetNetworkID()
  704. }
  705. func (config *Config) makeConfigParameters() map[string]interface{} {
  706. // Build set of config values to apply to parameters.
  707. //
  708. // Note: names of some config fields such as
  709. // StaggerConnectionWorkersMilliseconds and LimitMeekBufferSizes have
  710. // changed in the parameters. The existing config fields are retained for
  711. // backwards compatibility.
  712. applyParameters := make(map[string]interface{})
  713. if config.NetworkLatencyMultiplier > 0.0 {
  714. applyParameters[parameters.NetworkLatencyMultiplier] = config.NetworkLatencyMultiplier
  715. }
  716. if len(config.LimitTunnelProtocols) > 0 {
  717. applyParameters[parameters.LimitTunnelProtocols] = protocol.TunnelProtocols(config.LimitTunnelProtocols)
  718. }
  719. if len(config.InitialLimitTunnelProtocols) > 0 && config.InitialLimitTunnelProtocolsCandidateCount > 0 {
  720. applyParameters[parameters.InitialLimitTunnelProtocols] = protocol.TunnelProtocols(config.InitialLimitTunnelProtocols)
  721. applyParameters[parameters.InitialLimitTunnelProtocolsCandidateCount] = config.InitialLimitTunnelProtocolsCandidateCount
  722. }
  723. if len(config.LimitTLSProfiles) > 0 {
  724. applyParameters[parameters.LimitTLSProfiles] = protocol.TunnelProtocols(config.LimitTLSProfiles)
  725. }
  726. if len(config.LimitQUICVersions) > 0 {
  727. applyParameters[parameters.LimitQUICVersions] = protocol.QUICVersions(config.LimitQUICVersions)
  728. }
  729. if config.EstablishTunnelTimeoutSeconds != nil {
  730. applyParameters[parameters.EstablishTunnelTimeout] = fmt.Sprintf("%ds", *config.EstablishTunnelTimeoutSeconds)
  731. }
  732. if config.EstablishTunnelServerAffinityGracePeriodMilliseconds != nil {
  733. applyParameters[parameters.EstablishTunnelServerAffinityGracePeriod] = fmt.Sprintf("%dms", *config.EstablishTunnelServerAffinityGracePeriodMilliseconds)
  734. }
  735. if config.EstablishTunnelPausePeriodSeconds != nil {
  736. applyParameters[parameters.EstablishTunnelPausePeriod] = fmt.Sprintf("%ds", *config.EstablishTunnelPausePeriodSeconds)
  737. }
  738. if config.ConnectionWorkerPoolSize != 0 {
  739. applyParameters[parameters.ConnectionWorkerPoolSize] = config.ConnectionWorkerPoolSize
  740. }
  741. if config.StaggerConnectionWorkersMilliseconds > 0 {
  742. applyParameters[parameters.StaggerConnectionWorkersPeriod] = fmt.Sprintf("%dms", config.StaggerConnectionWorkersMilliseconds)
  743. }
  744. if config.LimitIntensiveConnectionWorkers > 0 {
  745. applyParameters[parameters.LimitIntensiveConnectionWorkers] = config.LimitIntensiveConnectionWorkers
  746. }
  747. applyParameters[parameters.MeekLimitBufferSizes] = config.LimitMeekBufferSizes
  748. applyParameters[parameters.IgnoreHandshakeStatsRegexps] = config.IgnoreHandshakeStatsRegexps
  749. if config.EstablishTunnelTimeoutSeconds != nil {
  750. applyParameters[parameters.EstablishTunnelTimeout] = fmt.Sprintf("%ds", *config.EstablishTunnelTimeoutSeconds)
  751. }
  752. if config.FetchRemoteServerListRetryPeriodMilliseconds != nil {
  753. applyParameters[parameters.FetchRemoteServerListRetryPeriod] = fmt.Sprintf("%dms", *config.FetchRemoteServerListRetryPeriodMilliseconds)
  754. }
  755. if config.FetchUpgradeRetryPeriodMilliseconds != nil {
  756. applyParameters[parameters.FetchUpgradeRetryPeriod] = fmt.Sprintf("%dms", *config.FetchUpgradeRetryPeriodMilliseconds)
  757. }
  758. switch config.TransformHostNames {
  759. case "always":
  760. applyParameters[parameters.TransformHostNameProbability] = 1.0
  761. case "never":
  762. applyParameters[parameters.TransformHostNameProbability] = 0.0
  763. }
  764. if !config.DisableRemoteServerListFetcher {
  765. if config.RemoteServerListURLs != nil {
  766. applyParameters[parameters.RemoteServerListSignaturePublicKey] = config.RemoteServerListSignaturePublicKey
  767. applyParameters[parameters.RemoteServerListURLs] = config.RemoteServerListURLs
  768. }
  769. if config.ObfuscatedServerListRootURLs != nil {
  770. applyParameters[parameters.RemoteServerListSignaturePublicKey] = config.RemoteServerListSignaturePublicKey
  771. applyParameters[parameters.ObfuscatedServerListRootURLs] = config.ObfuscatedServerListRootURLs
  772. }
  773. }
  774. applyParameters[parameters.SplitTunnelRoutesURLFormat] = config.SplitTunnelRoutesURLFormat
  775. applyParameters[parameters.SplitTunnelRoutesSignaturePublicKey] = config.SplitTunnelRoutesSignaturePublicKey
  776. applyParameters[parameters.SplitTunnelDNSServer] = config.SplitTunnelDNSServer
  777. if config.UpgradeDownloadURLs != nil {
  778. applyParameters[parameters.UpgradeDownloadClientVersionHeader] = config.UpgradeDownloadClientVersionHeader
  779. applyParameters[parameters.UpgradeDownloadURLs] = config.UpgradeDownloadURLs
  780. }
  781. applyParameters[parameters.TunnelRateLimits] = config.RateLimits
  782. switch config.UseFragmentor {
  783. case "always":
  784. applyParameters[parameters.FragmentorProbability] = 1.0
  785. case "never":
  786. applyParameters[parameters.FragmentorProbability] = 0.0
  787. }
  788. if config.FragmentorMinTotalBytes != nil {
  789. applyParameters[parameters.FragmentorMinTotalBytes] = *config.FragmentorMinTotalBytes
  790. }
  791. if config.FragmentorMaxTotalBytes != nil {
  792. applyParameters[parameters.FragmentorMaxTotalBytes] = *config.FragmentorMaxTotalBytes
  793. }
  794. if config.FragmentorMinWriteBytes != nil {
  795. applyParameters[parameters.FragmentorMinWriteBytes] = *config.FragmentorMinWriteBytes
  796. }
  797. if config.FragmentorMaxWriteBytes != nil {
  798. applyParameters[parameters.FragmentorMaxWriteBytes] = *config.FragmentorMaxWriteBytes
  799. }
  800. if config.FragmentorMinDelayMicroseconds != nil {
  801. applyParameters[parameters.FragmentorMinDelay] = fmt.Sprintf("%dus", *config.FragmentorMinDelayMicroseconds)
  802. }
  803. if config.FragmentorMaxDelayMicroseconds != nil {
  804. applyParameters[parameters.FragmentorMaxDelay] = fmt.Sprintf("%dus", *config.FragmentorMaxDelayMicroseconds)
  805. }
  806. if config.ObfuscatedSSHMinPadding != nil {
  807. applyParameters[parameters.ObfuscatedSSHMinPadding] = *config.ObfuscatedSSHMinPadding
  808. }
  809. if config.ObfuscatedSSHMaxPadding != nil {
  810. applyParameters[parameters.ObfuscatedSSHMaxPadding] = *config.ObfuscatedSSHMaxPadding
  811. }
  812. if config.LivenessTestMinUpstreamBytes != nil {
  813. applyParameters[parameters.LivenessTestMinUpstreamBytes] = *config.LivenessTestMinUpstreamBytes
  814. }
  815. if config.LivenessTestMaxUpstreamBytes != nil {
  816. applyParameters[parameters.LivenessTestMaxUpstreamBytes] = *config.LivenessTestMaxUpstreamBytes
  817. }
  818. if config.LivenessTestMinDownstreamBytes != nil {
  819. applyParameters[parameters.LivenessTestMinDownstreamBytes] = *config.LivenessTestMinDownstreamBytes
  820. }
  821. if config.LivenessTestMaxDownstreamBytes != nil {
  822. applyParameters[parameters.LivenessTestMaxDownstreamBytes] = *config.LivenessTestMaxDownstreamBytes
  823. }
  824. if config.ReplayCandidateCount != nil {
  825. applyParameters[parameters.ReplayCandidateCount] = *config.ReplayCandidateCount
  826. }
  827. if config.ReplayDialParametersTTLSeconds != nil {
  828. applyParameters[parameters.ReplayDialParametersTTL] = fmt.Sprintf("%ds", *config.ReplayDialParametersTTLSeconds)
  829. }
  830. return applyParameters
  831. }
  832. func (config *Config) setDialParametersHash() {
  833. // Calculate and store a hash of the config values that may impact
  834. // dial parameters. This hash is used as part of the dial parameters
  835. // replay mechanism to detect when persisted dial parameters must
  836. // be discarded due to conflicting config changes.
  837. //
  838. // MD5 hash is used solely as a data checksum and not for any security
  839. // purpose.
  840. hash := md5.New()
  841. if len(config.LimitTunnelProtocols) > 0 {
  842. for _, protocol := range config.LimitTunnelProtocols {
  843. hash.Write([]byte(protocol))
  844. }
  845. }
  846. if len(config.InitialLimitTunnelProtocols) > 0 && config.InitialLimitTunnelProtocolsCandidateCount > 0 {
  847. for _, protocol := range config.InitialLimitTunnelProtocols {
  848. hash.Write([]byte(protocol))
  849. }
  850. binary.Write(hash, binary.LittleEndian, config.InitialLimitTunnelProtocolsCandidateCount)
  851. }
  852. if len(config.LimitTLSProfiles) > 0 {
  853. for _, profile := range config.LimitTLSProfiles {
  854. hash.Write([]byte(profile))
  855. }
  856. }
  857. if len(config.LimitQUICVersions) > 0 {
  858. for _, version := range config.LimitQUICVersions {
  859. hash.Write([]byte(version))
  860. }
  861. }
  862. // Whether a custom User-Agent is specified is a binary flag: when not set,
  863. // the replay dial parameters value applies. When set, external
  864. // considerations apply.
  865. if _, ok := config.CustomHeaders["User-Agent"]; ok {
  866. hash.Write([]byte{1})
  867. }
  868. if config.UpstreamProxyURL != "" {
  869. hash.Write([]byte(config.UpstreamProxyURL))
  870. }
  871. if config.TransformHostNames != "" {
  872. hash.Write([]byte(config.TransformHostNames))
  873. }
  874. if config.UseFragmentor != "" {
  875. hash.Write([]byte(config.UseFragmentor))
  876. }
  877. if config.FragmentorMinTotalBytes != nil {
  878. binary.Write(hash, binary.LittleEndian, *config.FragmentorMinTotalBytes)
  879. }
  880. if config.FragmentorMaxTotalBytes != nil {
  881. binary.Write(hash, binary.LittleEndian, *config.FragmentorMaxTotalBytes)
  882. }
  883. if config.FragmentorMinWriteBytes != nil {
  884. binary.Write(hash, binary.LittleEndian, *config.FragmentorMinWriteBytes)
  885. }
  886. if config.FragmentorMaxWriteBytes != nil {
  887. binary.Write(hash, binary.LittleEndian, *config.FragmentorMaxWriteBytes)
  888. }
  889. if config.FragmentorMinDelayMicroseconds != nil {
  890. binary.Write(hash, binary.LittleEndian, *config.FragmentorMinDelayMicroseconds)
  891. }
  892. if config.FragmentorMaxDelayMicroseconds != nil {
  893. binary.Write(hash, binary.LittleEndian, *config.FragmentorMaxDelayMicroseconds)
  894. }
  895. if config.ObfuscatedSSHMinPadding != nil {
  896. binary.Write(hash, binary.LittleEndian, *config.ObfuscatedSSHMinPadding)
  897. }
  898. if config.ObfuscatedSSHMaxPadding != nil {
  899. binary.Write(hash, binary.LittleEndian, *config.ObfuscatedSSHMaxPadding)
  900. }
  901. if config.LivenessTestMinUpstreamBytes != nil {
  902. binary.Write(hash, binary.LittleEndian, *config.LivenessTestMinUpstreamBytes)
  903. }
  904. if config.LivenessTestMaxUpstreamBytes != nil {
  905. binary.Write(hash, binary.LittleEndian, *config.LivenessTestMaxUpstreamBytes)
  906. }
  907. if config.LivenessTestMinDownstreamBytes != nil {
  908. binary.Write(hash, binary.LittleEndian, *config.LivenessTestMinDownstreamBytes)
  909. }
  910. if config.LivenessTestMaxDownstreamBytes != nil {
  911. binary.Write(hash, binary.LittleEndian, *config.LivenessTestMaxDownstreamBytes)
  912. }
  913. config.dialParametersHash = hash.Sum(nil)
  914. }
  915. func promoteLegacyDownloadURL(URL string) parameters.DownloadURLs {
  916. downloadURLs := make(parameters.DownloadURLs, 1)
  917. downloadURLs[0] = &parameters.DownloadURL{
  918. URL: base64.StdEncoding.EncodeToString([]byte(URL)),
  919. SkipVerify: false,
  920. OnlyAfterAttempts: 0,
  921. }
  922. return downloadURLs
  923. }
  924. type loggingDeviceBinder struct {
  925. d DeviceBinder
  926. }
  927. func newLoggingDeviceBinder(d DeviceBinder) *loggingDeviceBinder {
  928. return &loggingDeviceBinder{d: d}
  929. }
  930. func (d *loggingDeviceBinder) BindToDevice(fileDescriptor int) (string, error) {
  931. deviceInfo, err := d.d.BindToDevice(fileDescriptor)
  932. if err == nil && deviceInfo != "" {
  933. NoticeBindToDevice(deviceInfo)
  934. }
  935. return deviceInfo, err
  936. }
  937. type staticNetworkGetter struct {
  938. networkID string
  939. }
  940. func newStaticNetworkGetter(networkID string) *staticNetworkGetter {
  941. return &staticNetworkGetter{networkID: networkID}
  942. }
  943. func (n *staticNetworkGetter) GetNetworkID() string {
  944. return n.networkID
  945. }
  946. type loggingNetworkIDGetter struct {
  947. n NetworkIDGetter
  948. }
  949. func newLoggingNetworkIDGetter(n NetworkIDGetter) *loggingNetworkIDGetter {
  950. return &loggingNetworkIDGetter{n: n}
  951. }
  952. func (n *loggingNetworkIDGetter) GetNetworkID() string {
  953. networkID := n.n.GetNetworkID()
  954. // All PII must appear after the initial "-"
  955. // See: https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter
  956. logNetworkID := networkID
  957. index := strings.Index(logNetworkID, "-")
  958. if index != -1 {
  959. logNetworkID = logNetworkID[:index]
  960. }
  961. if len(logNetworkID)+1 < len(networkID) {
  962. // Indicate when additional network info was present after the first "-".
  963. logNetworkID += "+<network info>"
  964. }
  965. NoticeNetworkID(logNetworkID)
  966. return networkID
  967. }