config.go 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  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. // TargetServerEntry is an encoded server entry. When specified, this
  234. // server entry is used exclusively and all other known servers are
  235. // ignored; also, when set, ConnectionWorkerPoolSize is ignored and
  236. // the pool size is 1.
  237. TargetServerEntry string
  238. // DisableApi disables Psiphon server API calls including handshake,
  239. // connected, status, etc. This is used for special case temporary tunnels
  240. // (Windows VPN mode).
  241. DisableApi bool
  242. // TargetApiProtocol specifies whether to force use of "ssh" or "web" API
  243. // protocol. When blank, the default, the optimal API protocol is used.
  244. // Note that this capability check is not applied before the
  245. // "CandidateServers" count is emitted.
  246. //
  247. // This parameter is intended for testing and debugging only. Not all
  248. // parameters are supported in the legacy "web" API protocol, including
  249. // speed test samples.
  250. TargetApiProtocol string
  251. // RemoteServerListUrl is a URL which specifies a location to fetch out-
  252. // of-band server entries. This facility is used when a tunnel cannot be
  253. // established to known servers. This value is supplied by and depends on
  254. // the Psiphon Network, and is typically embedded in the client binary.
  255. //
  256. // Deprecated: Use RemoteServerListURLs. When RemoteServerListURLs is not
  257. // nil, this parameter is ignored.
  258. RemoteServerListUrl string
  259. // RemoteServerListURLs is list of URLs which specify locations to fetch
  260. // out-of-band server entries. This facility is used when a tunnel cannot
  261. // be established to known servers. This value is supplied by and depends
  262. // on the Psiphon Network, and is typically embedded in the client binary.
  263. // All URLs must point to the same entity with the same ETag. At least one
  264. // DownloadURL must have OnlyAfterAttempts = 0.
  265. RemoteServerListURLs parameters.DownloadURLs
  266. // RemoteServerListDownloadFilename specifies a target filename for
  267. // storing the remote server list download. Data is stored in co-located
  268. // files (RemoteServerListDownloadFilename.part*) to allow for resumable
  269. // downloading.
  270. RemoteServerListDownloadFilename string
  271. // RemoteServerListSignaturePublicKey specifies a public key that's used
  272. // to authenticate the remote server list payload. This value is supplied
  273. // by and depends on the Psiphon Network, and is typically embedded in the
  274. // client binary.
  275. RemoteServerListSignaturePublicKey string
  276. // DisableRemoteServerListFetcher disables fetching remote server lists.
  277. // This is used for special case temporary tunnels.
  278. DisableRemoteServerListFetcher bool
  279. // FetchRemoteServerListRetryPeriodMilliseconds specifies the delay before
  280. // resuming a remote server list download after a failure. If omitted, a
  281. // default value is used. This value is typical overridden for testing.
  282. FetchRemoteServerListRetryPeriodMilliseconds *int
  283. // ObfuscatedServerListRootURL is a URL which specifies the root location
  284. // from which to fetch obfuscated server list files. This value is
  285. // supplied by and depends on the Psiphon Network, and is typically
  286. // embedded in the client binary.
  287. //
  288. // Deprecated: Use ObfuscatedServerListRootURLs. When
  289. // ObfuscatedServerListRootURLs is not nil, this parameter is ignored.
  290. ObfuscatedServerListRootURL string
  291. // ObfuscatedServerListRootURLs is a list of URLs which specify root
  292. // locations from which to fetch obfuscated server list files. This value
  293. // is supplied by and depends on the Psiphon Network, and is typically
  294. // embedded in the client binary. All URLs must point to the same entity
  295. // with the same ETag. At least one DownloadURL must have
  296. // OnlyAfterAttempts = 0.
  297. ObfuscatedServerListRootURLs parameters.DownloadURLs
  298. // ObfuscatedServerListDownloadDirectory specifies a target directory for
  299. // storing the obfuscated remote server list downloads. Data is stored in
  300. // co-located files (<OSL filename>.part*) to allow for resumable
  301. // downloading.
  302. ObfuscatedServerListDownloadDirectory string
  303. // SplitTunnelRoutesURLFormat is a URL which specifies the location of a
  304. // routes file to use for split tunnel mode. The URL must include a
  305. // placeholder for the client region to be supplied. Split tunnel mode
  306. // uses the routes file to classify port forward destinations as foreign
  307. // or domestic and does not tunnel domestic destinations. Split tunnel
  308. // mode is on when all the SplitTunnel parameters are supplied. This value
  309. // is supplied by and depends on the Psiphon Network, and is typically
  310. // embedded in the client binary.
  311. SplitTunnelRoutesURLFormat string
  312. // SplitTunnelRoutesSignaturePublicKey specifies a public key that's used
  313. // to authenticate the split tunnel routes payload. This value is supplied
  314. // by and depends on the Psiphon Network, and is typically embedded in the
  315. // client binary.
  316. SplitTunnelRoutesSignaturePublicKey string
  317. // SplitTunnelDNSServer specifies a DNS server to use when resolving port
  318. // forward target domain names to IP addresses for classification. The DNS
  319. // server must support TCP requests.
  320. SplitTunnelDNSServer string
  321. // UpgradeDownloadUrl specifies a URL from which to download a host client
  322. // upgrade file, when one is available. The core tunnel controller
  323. // provides a resumable download facility which downloads this resource
  324. // and emits a notice when complete. This value is supplied by and depends
  325. // on the Psiphon Network, and is typically embedded in the client binary.
  326. //
  327. // Deprecated: Use UpgradeDownloadURLs. When UpgradeDownloadURLs is not
  328. // nil, this parameter is ignored.
  329. UpgradeDownloadUrl string
  330. // UpgradeDownloadURLs is list of URLs which specify locations from which
  331. // to download a host client upgrade file, when one is available. The core
  332. // tunnel controller provides a resumable download facility which
  333. // downloads this resource and emits a notice when complete. This value is
  334. // supplied by and depends on the Psiphon Network, and is typically
  335. // embedded in the client binary. All URLs must point to the same entity
  336. // with the same ETag. At least one DownloadURL must have
  337. // OnlyAfterAttempts = 0.
  338. UpgradeDownloadURLs parameters.DownloadURLs
  339. // UpgradeDownloadClientVersionHeader specifies the HTTP header name for
  340. // the entity at UpgradeDownloadURLs which specifies the client version
  341. // (an integer value). A HEAD request may be made to check the version
  342. // number available at UpgradeDownloadURLs.
  343. // UpgradeDownloadClientVersionHeader is required when UpgradeDownloadURLs
  344. // is specified.
  345. UpgradeDownloadClientVersionHeader string
  346. // UpgradeDownloadFilename is the local target filename for an upgrade
  347. // download. This parameter is required when UpgradeDownloadURLs (or
  348. // UpgradeDownloadUrl) is specified. Data is stored in co-located files
  349. // (UpgradeDownloadFilename.part*) to allow for resumable downloading.
  350. UpgradeDownloadFilename string
  351. // FetchUpgradeRetryPeriodMilliseconds specifies the delay before resuming
  352. // a client upgrade download after a failure. If omitted, a default value
  353. // is used. This value is typical overridden for testing.
  354. FetchUpgradeRetryPeriodMilliseconds *int
  355. // EmitBytesTransferred indicates whether to emit periodic notices showing
  356. // bytes sent and received.
  357. EmitBytesTransferred bool
  358. // TrustedCACertificatesFilename specifies a file containing trusted CA
  359. // certs. When set, this toggles use of the trusted CA certs, specified in
  360. // TrustedCACertificatesFilename, for tunneled TLS connections that expect
  361. // server certificates signed with public certificate authorities
  362. // (currently, only upgrade downloads). This option is used with stock Go
  363. // TLS in cases where Go may fail to obtain a list of root CAs from the
  364. // operating system.
  365. TrustedCACertificatesFilename string
  366. // DisablePeriodicSshKeepAlive indicates whether to send an SSH keepalive
  367. // every 1-2 minutes, when the tunnel is idle. If the SSH keepalive times
  368. // out, the tunnel is considered to have failed.
  369. DisablePeriodicSshKeepAlive bool
  370. // DeviceRegion is the optional, reported region the host device is
  371. // running in. This input value should be a ISO 3166-1 alpha-2 country
  372. // code. The device region is reported to the server in the connected
  373. // request and recorded for Psiphon stats.
  374. //
  375. // When provided, this value may be used, pre-connection, to select
  376. // performance or circumvention optimization strategies for the given
  377. // region.
  378. DeviceRegion string
  379. // EmitDiagnosticNotices indicates whether to output notices containing
  380. // detailed information about the Psiphon session. As these notices may
  381. // contain sensitive network information, they should not be insecurely
  382. // distributed or displayed to users. Default is off.
  383. EmitDiagnosticNotices bool
  384. // RateLimits specify throttling configuration for the tunnel.
  385. RateLimits common.RateLimits
  386. // EmitSLOKs indicates whether to emit notices for each seeded SLOK. As
  387. // this could reveal user browsing activity, it's intended for debugging
  388. // and testing only.
  389. EmitSLOKs bool
  390. // PacketTunnelTunDeviceFileDescriptor specifies a tun device file
  391. // descriptor to use for running a packet tunnel. When this value is > 0,
  392. // a packet tunnel is established through the server and packets are
  393. // relayed via the tun device file descriptor. The file descriptor is
  394. // duped in NewController. When PacketTunnelTunDeviceFileDescriptor is
  395. // set, TunnelPoolSize must be 1.
  396. PacketTunnelTunFileDescriptor int
  397. // SessionID specifies a client session ID to use in the Psiphon API. The
  398. // session ID should be a randomly generated value that is used only for a
  399. // single session, which is defined as the period between a user starting
  400. // a Psiphon client and stopping the client.
  401. //
  402. // A session ID must be 32 hex digits (lower case). When blank, a random
  403. // session ID is automatically generated. Supply a session ID when a
  404. // single client session will cross multiple Controller instances.
  405. SessionID string
  406. // Authorizations is a list of encoded, signed access control
  407. // authorizations that the client has obtained and will present to the
  408. // server.
  409. Authorizations []string
  410. // TransformHostNameProbability is for testing purposes.
  411. TransformHostNameProbability *float64
  412. // FragmentorProbability and associated Fragmentor fields are for testing
  413. // purposes.
  414. FragmentorProbability *float64
  415. FragmentorLimitProtocols []string
  416. FragmentorMinTotalBytes *int
  417. FragmentorMaxTotalBytes *int
  418. FragmentorMinWriteBytes *int
  419. FragmentorMaxWriteBytes *int
  420. FragmentorMinDelayMicroseconds *int
  421. FragmentorMaxDelayMicroseconds *int
  422. // MeekTrafficShapingProbability and associated fields are for testing
  423. // purposes.
  424. MeekTrafficShapingProbability *float64
  425. MeekTrafficShapingLimitProtocols []string
  426. MeekMinLimitRequestPayloadLength *int
  427. MeekMaxLimitRequestPayloadLength *int
  428. MeekRedialTLSProbability *float64
  429. // ObfuscatedSSHAlgorithms and associated ObfuscatedSSH fields are for
  430. // testing purposes. If specified, ObfuscatedSSHAlgorithms must have 4 SSH
  431. // KEX elements in order: the kex algorithm, cipher, MAC, and server host
  432. // key algorithm.
  433. ObfuscatedSSHAlgorithms []string
  434. ObfuscatedSSHMinPadding *int
  435. ObfuscatedSSHMaxPadding *int
  436. // LivenessTestMinUpstreamBytes and other LivenessTest fields are for
  437. // testing purposes.
  438. LivenessTestMinUpstreamBytes *int
  439. LivenessTestMaxUpstreamBytes *int
  440. LivenessTestMinDownstreamBytes *int
  441. LivenessTestMaxDownstreamBytes *int
  442. // ReplayCandidateCount and other Replay fields are for
  443. // testing purposes.
  444. ReplayCandidateCount *int
  445. ReplayDialParametersTTLSeconds *int
  446. // clientParameters is the active ClientParameters with defaults, config
  447. // values, and, optionally, tactics applied.
  448. //
  449. // New tactics must be applied by calling Config.SetClientParameters;
  450. // calling clientParameters.Set directly will fail to add config values.
  451. clientParameters *parameters.ClientParameters
  452. dialParametersHash []byte
  453. dynamicConfigMutex sync.Mutex
  454. sponsorID string
  455. authorizations []string
  456. deviceBinder DeviceBinder
  457. networkIDGetter NetworkIDGetter
  458. committed bool
  459. }
  460. // LoadConfig parses a JSON format Psiphon config JSON string and returns a
  461. // Config struct populated with config values.
  462. //
  463. // The Config struct may then be programmatically populated with additional
  464. // values, including callbacks such as DeviceBinder.
  465. //
  466. // Before using the Config, Commit must be called, which will perform further
  467. // validation and initialize internal data structures.
  468. func LoadConfig(configJson []byte) (*Config, error) {
  469. var config Config
  470. err := json.Unmarshal(configJson, &config)
  471. if err != nil {
  472. return nil, common.ContextError(err)
  473. }
  474. return &config, nil
  475. }
  476. // IsCommitted checks if Commit was called.
  477. func (config *Config) IsCommitted() bool {
  478. return config.committed
  479. }
  480. // Commit validates Config fields finalizes initialization.
  481. //
  482. // Config fields should not be set after calling Config, as any changes may
  483. // not be reflected in internal data structures.
  484. func (config *Config) Commit() error {
  485. // Do SetEmitDiagnosticNotices first, to ensure config file errors are emitted.
  486. if config.EmitDiagnosticNotices {
  487. SetEmitDiagnosticNotices(true)
  488. }
  489. // Promote legacy fields.
  490. if config.CustomHeaders == nil {
  491. config.CustomHeaders = config.UpstreamProxyCustomHeaders
  492. config.UpstreamProxyCustomHeaders = nil
  493. }
  494. if config.RemoteServerListUrl != "" && config.RemoteServerListURLs == nil {
  495. config.RemoteServerListURLs = promoteLegacyDownloadURL(config.RemoteServerListUrl)
  496. }
  497. if config.ObfuscatedServerListRootURL != "" && config.ObfuscatedServerListRootURLs == nil {
  498. config.ObfuscatedServerListRootURLs = promoteLegacyDownloadURL(config.ObfuscatedServerListRootURL)
  499. }
  500. if config.UpgradeDownloadUrl != "" && config.UpgradeDownloadURLs == nil {
  501. config.UpgradeDownloadURLs = promoteLegacyDownloadURL(config.UpgradeDownloadUrl)
  502. }
  503. if config.TunnelProtocol != "" && len(config.LimitTunnelProtocols) == 0 {
  504. config.LimitTunnelProtocols = []string{config.TunnelProtocol}
  505. }
  506. // Supply default values.
  507. if config.DataStoreDirectory == "" {
  508. wd, err := os.Getwd()
  509. if err != nil {
  510. return common.ContextError(err)
  511. }
  512. config.DataStoreDirectory = wd
  513. }
  514. if config.ClientVersion == "" {
  515. config.ClientVersion = "0"
  516. }
  517. if config.TunnelPoolSize == 0 {
  518. config.TunnelPoolSize = TUNNEL_POOL_SIZE
  519. }
  520. // Validate config fields.
  521. if config.PropagationChannelId == "" {
  522. return common.ContextError(
  523. errors.New("propagation channel ID is missing from the configuration file"))
  524. }
  525. if config.SponsorId == "" {
  526. return common.ContextError(
  527. errors.New("sponsor ID is missing from the configuration file"))
  528. }
  529. _, err := strconv.Atoi(config.ClientVersion)
  530. if err != nil {
  531. return common.ContextError(
  532. fmt.Errorf("invalid client version: %s", err))
  533. }
  534. if !common.Contains(
  535. []string{"", protocol.PSIPHON_SSH_API_PROTOCOL, protocol.PSIPHON_WEB_API_PROTOCOL},
  536. config.TargetApiProtocol) {
  537. return common.ContextError(
  538. errors.New("invalid TargetApiProtocol"))
  539. }
  540. if !config.DisableRemoteServerListFetcher {
  541. if config.RemoteServerListURLs != nil {
  542. if config.RemoteServerListSignaturePublicKey == "" {
  543. return common.ContextError(errors.New("missing RemoteServerListSignaturePublicKey"))
  544. }
  545. if config.RemoteServerListDownloadFilename == "" {
  546. return common.ContextError(errors.New("missing RemoteServerListDownloadFilename"))
  547. }
  548. }
  549. if config.ObfuscatedServerListRootURLs != nil {
  550. if config.RemoteServerListSignaturePublicKey == "" {
  551. return common.ContextError(errors.New("missing RemoteServerListSignaturePublicKey"))
  552. }
  553. if config.ObfuscatedServerListDownloadDirectory == "" {
  554. return common.ContextError(errors.New("missing ObfuscatedServerListDownloadDirectory"))
  555. }
  556. }
  557. }
  558. if config.SplitTunnelRoutesURLFormat != "" {
  559. if config.SplitTunnelRoutesSignaturePublicKey == "" {
  560. return common.ContextError(errors.New("missing SplitTunnelRoutesSignaturePublicKey"))
  561. }
  562. if config.SplitTunnelDNSServer == "" {
  563. return common.ContextError(errors.New("missing SplitTunnelDNSServer"))
  564. }
  565. }
  566. if config.UpgradeDownloadURLs != nil {
  567. if config.UpgradeDownloadClientVersionHeader == "" {
  568. return common.ContextError(errors.New("missing UpgradeDownloadClientVersionHeader"))
  569. }
  570. if config.UpgradeDownloadFilename == "" {
  571. return common.ContextError(errors.New("missing UpgradeDownloadFilename"))
  572. }
  573. }
  574. // This constraint is expected by logic in Controller.runTunnels().
  575. if config.PacketTunnelTunFileDescriptor > 0 && config.TunnelPoolSize != 1 {
  576. return common.ContextError(errors.New("packet tunnel mode requires TunnelPoolSize to be 1"))
  577. }
  578. // SessionID must be PSIPHON_API_CLIENT_SESSION_ID_LENGTH lowercase hex-encoded bytes.
  579. if config.SessionID == "" {
  580. sessionID, err := MakeSessionId()
  581. if err != nil {
  582. return common.ContextError(err)
  583. }
  584. config.SessionID = sessionID
  585. }
  586. if len(config.SessionID) != 2*protocol.PSIPHON_API_CLIENT_SESSION_ID_LENGTH ||
  587. -1 != strings.IndexFunc(config.SessionID, func(c rune) bool {
  588. return !unicode.Is(unicode.ASCII_Hex_Digit, c) || unicode.IsUpper(c)
  589. }) {
  590. return common.ContextError(errors.New("invalid SessionID"))
  591. }
  592. config.clientParameters, err = parameters.NewClientParameters(
  593. func(err error) {
  594. NoticeAlert("ClientParameters getValue failed: %s", err)
  595. })
  596. if err != nil {
  597. return common.ContextError(err)
  598. }
  599. if config.ObfuscatedSSHAlgorithms != nil &&
  600. len(config.ObfuscatedSSHAlgorithms) != 4 {
  601. // TODO: validate each algorithm?
  602. return common.ContextError(errors.New("invalid ObfuscatedSSHAlgorithms"))
  603. }
  604. // clientParameters.Set will validate the config fields applied to parameters.
  605. err = config.SetClientParameters("", false, nil)
  606. if err != nil {
  607. return common.ContextError(err)
  608. }
  609. // Calculate and set the dial parameters hash. After this point, related
  610. // config fields must not change.
  611. config.setDialParametersHash()
  612. // Set defaults for dynamic config fields.
  613. config.SetDynamicConfig(config.SponsorId, config.Authorizations)
  614. // Initialize config.deviceBinder and config.config.networkIDGetter. These
  615. // wrap config.DeviceBinder and config.NetworkIDGetter/NetworkID with
  616. // loggers.
  617. //
  618. // New variables are set to avoid mutating input config fields.
  619. // Internally, code must use config.deviceBinder and
  620. // config.networkIDGetter and not the input/exported fields.
  621. if config.DeviceBinder != nil {
  622. config.deviceBinder = &loggingDeviceBinder{config.DeviceBinder}
  623. }
  624. networkIDGetter := config.NetworkIDGetter
  625. if networkIDGetter == nil {
  626. // Limitation: unlike NetworkIDGetter, which calls back to platform APIs
  627. // this method of network identification is not dynamic and will not reflect
  628. // network changes that occur while running.
  629. if config.NetworkID != "" {
  630. networkIDGetter = newStaticNetworkGetter(config.NetworkID)
  631. } else {
  632. networkIDGetter = newStaticNetworkGetter("UNKNOWN")
  633. }
  634. }
  635. config.networkIDGetter = &loggingNetworkIDGetter{networkIDGetter}
  636. config.committed = true
  637. return nil
  638. }
  639. // GetClientParameters returns a snapshot of the current client parameters.
  640. func (config *Config) GetClientParameters() *parameters.ClientParametersSnapshot {
  641. return config.clientParameters.Get()
  642. }
  643. // SetClientParameters resets Config.clientParameters to the default values,
  644. // applies any config file values, and then applies the input parameters (from
  645. // tactics, etc.)
  646. //
  647. // Set skipOnError to false when initially applying only config values, as
  648. // this will validate the values and should fail. Set skipOnError to true when
  649. // applying tactics to ignore invalid or unknown parameter values from tactics.
  650. //
  651. // In the case of applying tactics, do not call Config.clientParameters.Set
  652. // directly as this will not first apply config values.
  653. //
  654. // If there is an error, the existing Config.clientParameters are left
  655. // entirely unmodified.
  656. func (config *Config) SetClientParameters(tag string, skipOnError bool, applyParameters map[string]interface{}) error {
  657. setParameters := []map[string]interface{}{config.makeConfigParameters()}
  658. if applyParameters != nil {
  659. setParameters = append(setParameters, applyParameters)
  660. }
  661. counts, err := config.clientParameters.Set(tag, skipOnError, setParameters...)
  662. if err != nil {
  663. return common.ContextError(err)
  664. }
  665. NoticeInfo("applied %v parameters with tag '%s'", counts, tag)
  666. // Emit certain individual parameter values for quick reference in diagnostics.
  667. networkLatencyMultiplier := config.clientParameters.Get().Float(parameters.NetworkLatencyMultiplier)
  668. if networkLatencyMultiplier != 0.0 {
  669. NoticeInfo(
  670. "NetworkLatencyMultiplier: %f",
  671. config.clientParameters.Get().Float(parameters.NetworkLatencyMultiplier))
  672. }
  673. return nil
  674. }
  675. // SetDynamicConfig sets the current client sponsor ID and authorizations.
  676. // Invalid values for sponsor ID are ignored. The caller must not modify the
  677. // input authorizations slice.
  678. func (config *Config) SetDynamicConfig(sponsorID string, authorizations []string) {
  679. config.dynamicConfigMutex.Lock()
  680. defer config.dynamicConfigMutex.Unlock()
  681. if sponsorID != "" {
  682. config.sponsorID = sponsorID
  683. }
  684. config.authorizations = authorizations
  685. }
  686. // GetSponsorID returns the current client sponsor ID.
  687. func (config *Config) GetSponsorID() string {
  688. config.dynamicConfigMutex.Lock()
  689. defer config.dynamicConfigMutex.Unlock()
  690. return config.sponsorID
  691. }
  692. // GetAuthorizations returns the current client authorizations.
  693. // The caller must not modify the returned slice.
  694. func (config *Config) GetAuthorizations() []string {
  695. config.dynamicConfigMutex.Lock()
  696. defer config.dynamicConfigMutex.Unlock()
  697. return config.authorizations
  698. }
  699. // UseUpstreamProxy indicates if an upstream proxy has been
  700. // configured.
  701. func (config *Config) UseUpstreamProxy() bool {
  702. return config.UpstreamProxyURL != ""
  703. }
  704. // GetNetworkID returns the current network ID. When NetworkIDGetter
  705. // is set, this calls into the host application; otherwise, a default
  706. // value is returned.
  707. func (config *Config) GetNetworkID() string {
  708. return config.networkIDGetter.GetNetworkID()
  709. }
  710. func (config *Config) makeConfigParameters() map[string]interface{} {
  711. // Build set of config values to apply to parameters.
  712. //
  713. // Note: names of some config fields such as
  714. // StaggerConnectionWorkersMilliseconds and LimitMeekBufferSizes have
  715. // changed in the parameters. The existing config fields are retained for
  716. // backwards compatibility.
  717. applyParameters := make(map[string]interface{})
  718. if config.NetworkLatencyMultiplier > 0.0 {
  719. applyParameters[parameters.NetworkLatencyMultiplier] = config.NetworkLatencyMultiplier
  720. }
  721. if len(config.LimitTunnelProtocols) > 0 {
  722. applyParameters[parameters.LimitTunnelProtocols] = protocol.TunnelProtocols(config.LimitTunnelProtocols)
  723. }
  724. if len(config.InitialLimitTunnelProtocols) > 0 && config.InitialLimitTunnelProtocolsCandidateCount > 0 {
  725. applyParameters[parameters.InitialLimitTunnelProtocols] = protocol.TunnelProtocols(config.InitialLimitTunnelProtocols)
  726. applyParameters[parameters.InitialLimitTunnelProtocolsCandidateCount] = config.InitialLimitTunnelProtocolsCandidateCount
  727. }
  728. if len(config.LimitTLSProfiles) > 0 {
  729. applyParameters[parameters.LimitTLSProfiles] = protocol.TunnelProtocols(config.LimitTLSProfiles)
  730. }
  731. if len(config.LimitQUICVersions) > 0 {
  732. applyParameters[parameters.LimitQUICVersions] = protocol.QUICVersions(config.LimitQUICVersions)
  733. }
  734. if config.EstablishTunnelTimeoutSeconds != nil {
  735. applyParameters[parameters.EstablishTunnelTimeout] = fmt.Sprintf("%ds", *config.EstablishTunnelTimeoutSeconds)
  736. }
  737. if config.EstablishTunnelServerAffinityGracePeriodMilliseconds != nil {
  738. applyParameters[parameters.EstablishTunnelServerAffinityGracePeriod] = fmt.Sprintf("%dms", *config.EstablishTunnelServerAffinityGracePeriodMilliseconds)
  739. }
  740. if config.EstablishTunnelPausePeriodSeconds != nil {
  741. applyParameters[parameters.EstablishTunnelPausePeriod] = fmt.Sprintf("%ds", *config.EstablishTunnelPausePeriodSeconds)
  742. }
  743. if config.ConnectionWorkerPoolSize != 0 {
  744. applyParameters[parameters.ConnectionWorkerPoolSize] = config.ConnectionWorkerPoolSize
  745. }
  746. if config.StaggerConnectionWorkersMilliseconds > 0 {
  747. applyParameters[parameters.StaggerConnectionWorkersPeriod] = fmt.Sprintf("%dms", config.StaggerConnectionWorkersMilliseconds)
  748. }
  749. if config.LimitIntensiveConnectionWorkers > 0 {
  750. applyParameters[parameters.LimitIntensiveConnectionWorkers] = config.LimitIntensiveConnectionWorkers
  751. }
  752. applyParameters[parameters.MeekLimitBufferSizes] = config.LimitMeekBufferSizes
  753. applyParameters[parameters.IgnoreHandshakeStatsRegexps] = config.IgnoreHandshakeStatsRegexps
  754. if config.EstablishTunnelTimeoutSeconds != nil {
  755. applyParameters[parameters.EstablishTunnelTimeout] = fmt.Sprintf("%ds", *config.EstablishTunnelTimeoutSeconds)
  756. }
  757. if config.FetchRemoteServerListRetryPeriodMilliseconds != nil {
  758. applyParameters[parameters.FetchRemoteServerListRetryPeriod] = fmt.Sprintf("%dms", *config.FetchRemoteServerListRetryPeriodMilliseconds)
  759. }
  760. if config.FetchUpgradeRetryPeriodMilliseconds != nil {
  761. applyParameters[parameters.FetchUpgradeRetryPeriod] = fmt.Sprintf("%dms", *config.FetchUpgradeRetryPeriodMilliseconds)
  762. }
  763. if !config.DisableRemoteServerListFetcher {
  764. if config.RemoteServerListURLs != nil {
  765. applyParameters[parameters.RemoteServerListSignaturePublicKey] = config.RemoteServerListSignaturePublicKey
  766. applyParameters[parameters.RemoteServerListURLs] = config.RemoteServerListURLs
  767. }
  768. if config.ObfuscatedServerListRootURLs != nil {
  769. applyParameters[parameters.RemoteServerListSignaturePublicKey] = config.RemoteServerListSignaturePublicKey
  770. applyParameters[parameters.ObfuscatedServerListRootURLs] = config.ObfuscatedServerListRootURLs
  771. }
  772. }
  773. applyParameters[parameters.SplitTunnelRoutesURLFormat] = config.SplitTunnelRoutesURLFormat
  774. applyParameters[parameters.SplitTunnelRoutesSignaturePublicKey] = config.SplitTunnelRoutesSignaturePublicKey
  775. applyParameters[parameters.SplitTunnelDNSServer] = config.SplitTunnelDNSServer
  776. if config.UpgradeDownloadURLs != nil {
  777. applyParameters[parameters.UpgradeDownloadClientVersionHeader] = config.UpgradeDownloadClientVersionHeader
  778. applyParameters[parameters.UpgradeDownloadURLs] = config.UpgradeDownloadURLs
  779. }
  780. applyParameters[parameters.TunnelRateLimits] = config.RateLimits
  781. if config.TransformHostNameProbability != nil {
  782. applyParameters[parameters.TransformHostNameProbability] = *config.TransformHostNameProbability
  783. }
  784. if config.FragmentorProbability != nil {
  785. applyParameters[parameters.FragmentorProbability] = *config.FragmentorProbability
  786. }
  787. if len(config.FragmentorLimitProtocols) > 0 {
  788. applyParameters[parameters.FragmentorLimitProtocols] = protocol.TunnelProtocols(config.FragmentorLimitProtocols)
  789. }
  790. if config.FragmentorMinTotalBytes != nil {
  791. applyParameters[parameters.FragmentorMinTotalBytes] = *config.FragmentorMinTotalBytes
  792. }
  793. if config.FragmentorMaxTotalBytes != nil {
  794. applyParameters[parameters.FragmentorMaxTotalBytes] = *config.FragmentorMaxTotalBytes
  795. }
  796. if config.FragmentorMinWriteBytes != nil {
  797. applyParameters[parameters.FragmentorMinWriteBytes] = *config.FragmentorMinWriteBytes
  798. }
  799. if config.FragmentorMaxWriteBytes != nil {
  800. applyParameters[parameters.FragmentorMaxWriteBytes] = *config.FragmentorMaxWriteBytes
  801. }
  802. if config.FragmentorMinDelayMicroseconds != nil {
  803. applyParameters[parameters.FragmentorMinDelay] = fmt.Sprintf("%dus", *config.FragmentorMinDelayMicroseconds)
  804. }
  805. if config.FragmentorMaxDelayMicroseconds != nil {
  806. applyParameters[parameters.FragmentorMaxDelay] = fmt.Sprintf("%dus", *config.FragmentorMaxDelayMicroseconds)
  807. }
  808. if config.MeekTrafficShapingProbability != nil {
  809. applyParameters[parameters.MeekTrafficShapingProbability] = *config.MeekTrafficShapingProbability
  810. }
  811. if len(config.MeekTrafficShapingLimitProtocols) > 0 {
  812. applyParameters[parameters.MeekTrafficShapingLimitProtocols] = protocol.TunnelProtocols(config.MeekTrafficShapingLimitProtocols)
  813. }
  814. if config.MeekMinLimitRequestPayloadLength != nil {
  815. applyParameters[parameters.MeekMinLimitRequestPayloadLength] = *config.MeekMinLimitRequestPayloadLength
  816. }
  817. if config.MeekMaxLimitRequestPayloadLength != nil {
  818. applyParameters[parameters.MeekMaxLimitRequestPayloadLength] = *config.MeekMaxLimitRequestPayloadLength
  819. }
  820. if config.MeekRedialTLSProbability != nil {
  821. applyParameters[parameters.MeekRedialTLSProbability] = *config.MeekRedialTLSProbability
  822. }
  823. if config.ObfuscatedSSHMinPadding != nil {
  824. applyParameters[parameters.ObfuscatedSSHMinPadding] = *config.ObfuscatedSSHMinPadding
  825. }
  826. if config.ObfuscatedSSHMaxPadding != nil {
  827. applyParameters[parameters.ObfuscatedSSHMaxPadding] = *config.ObfuscatedSSHMaxPadding
  828. }
  829. if config.LivenessTestMinUpstreamBytes != nil {
  830. applyParameters[parameters.LivenessTestMinUpstreamBytes] = *config.LivenessTestMinUpstreamBytes
  831. }
  832. if config.LivenessTestMaxUpstreamBytes != nil {
  833. applyParameters[parameters.LivenessTestMaxUpstreamBytes] = *config.LivenessTestMaxUpstreamBytes
  834. }
  835. if config.LivenessTestMinDownstreamBytes != nil {
  836. applyParameters[parameters.LivenessTestMinDownstreamBytes] = *config.LivenessTestMinDownstreamBytes
  837. }
  838. if config.LivenessTestMaxDownstreamBytes != nil {
  839. applyParameters[parameters.LivenessTestMaxDownstreamBytes] = *config.LivenessTestMaxDownstreamBytes
  840. }
  841. if config.ReplayCandidateCount != nil {
  842. applyParameters[parameters.ReplayCandidateCount] = *config.ReplayCandidateCount
  843. }
  844. if config.ReplayDialParametersTTLSeconds != nil {
  845. applyParameters[parameters.ReplayDialParametersTTL] = fmt.Sprintf("%ds", *config.ReplayDialParametersTTLSeconds)
  846. }
  847. return applyParameters
  848. }
  849. func (config *Config) setDialParametersHash() {
  850. // Calculate and store a hash of the config values that may impact
  851. // dial parameters. This hash is used as part of the dial parameters
  852. // replay mechanism to detect when persisted dial parameters must
  853. // be discarded due to conflicting config changes.
  854. //
  855. // MD5 hash is used solely as a data checksum and not for any security
  856. // purpose.
  857. hash := md5.New()
  858. if len(config.LimitTunnelProtocols) > 0 {
  859. for _, protocol := range config.LimitTunnelProtocols {
  860. hash.Write([]byte(protocol))
  861. }
  862. }
  863. if len(config.InitialLimitTunnelProtocols) > 0 && config.InitialLimitTunnelProtocolsCandidateCount > 0 {
  864. for _, protocol := range config.InitialLimitTunnelProtocols {
  865. hash.Write([]byte(protocol))
  866. }
  867. binary.Write(hash, binary.LittleEndian, config.InitialLimitTunnelProtocolsCandidateCount)
  868. }
  869. if len(config.LimitTLSProfiles) > 0 {
  870. for _, profile := range config.LimitTLSProfiles {
  871. hash.Write([]byte(profile))
  872. }
  873. }
  874. if len(config.LimitQUICVersions) > 0 {
  875. for _, version := range config.LimitQUICVersions {
  876. hash.Write([]byte(version))
  877. }
  878. }
  879. // Whether a custom User-Agent is specified is a binary flag: when not set,
  880. // the replay dial parameters value applies. When set, external
  881. // considerations apply.
  882. if _, ok := config.CustomHeaders["User-Agent"]; ok {
  883. hash.Write([]byte{1})
  884. }
  885. if config.UpstreamProxyURL != "" {
  886. hash.Write([]byte(config.UpstreamProxyURL))
  887. }
  888. if config.TransformHostNameProbability != nil {
  889. binary.Write(hash, binary.LittleEndian, *config.TransformHostNameProbability)
  890. }
  891. if config.FragmentorProbability != nil {
  892. binary.Write(hash, binary.LittleEndian, *config.FragmentorProbability)
  893. }
  894. if len(config.FragmentorLimitProtocols) > 0 {
  895. for _, protocol := range config.FragmentorLimitProtocols {
  896. hash.Write([]byte(protocol))
  897. }
  898. }
  899. if config.FragmentorMinTotalBytes != nil {
  900. binary.Write(hash, binary.LittleEndian, *config.FragmentorMinTotalBytes)
  901. }
  902. if config.FragmentorMaxTotalBytes != nil {
  903. binary.Write(hash, binary.LittleEndian, *config.FragmentorMaxTotalBytes)
  904. }
  905. if config.FragmentorMinWriteBytes != nil {
  906. binary.Write(hash, binary.LittleEndian, *config.FragmentorMinWriteBytes)
  907. }
  908. if config.FragmentorMaxWriteBytes != nil {
  909. binary.Write(hash, binary.LittleEndian, *config.FragmentorMaxWriteBytes)
  910. }
  911. if config.FragmentorMinDelayMicroseconds != nil {
  912. binary.Write(hash, binary.LittleEndian, *config.FragmentorMinDelayMicroseconds)
  913. }
  914. if config.FragmentorMaxDelayMicroseconds != nil {
  915. binary.Write(hash, binary.LittleEndian, *config.FragmentorMaxDelayMicroseconds)
  916. }
  917. if config.MeekTrafficShapingProbability != nil {
  918. binary.Write(hash, binary.LittleEndian, *config.MeekTrafficShapingProbability)
  919. }
  920. if len(config.MeekTrafficShapingLimitProtocols) > 0 {
  921. for _, protocol := range config.MeekTrafficShapingLimitProtocols {
  922. hash.Write([]byte(protocol))
  923. }
  924. }
  925. if config.MeekMinLimitRequestPayloadLength != nil {
  926. binary.Write(hash, binary.LittleEndian, *config.MeekMinLimitRequestPayloadLength)
  927. }
  928. if config.MeekMaxLimitRequestPayloadLength != nil {
  929. binary.Write(hash, binary.LittleEndian, *config.MeekMaxLimitRequestPayloadLength)
  930. }
  931. if config.MeekRedialTLSProbability != nil {
  932. binary.Write(hash, binary.LittleEndian, *config.MeekRedialTLSProbability)
  933. }
  934. if config.ObfuscatedSSHMinPadding != nil {
  935. binary.Write(hash, binary.LittleEndian, *config.ObfuscatedSSHMinPadding)
  936. }
  937. if config.ObfuscatedSSHMaxPadding != nil {
  938. binary.Write(hash, binary.LittleEndian, *config.ObfuscatedSSHMaxPadding)
  939. }
  940. if config.LivenessTestMinUpstreamBytes != nil {
  941. binary.Write(hash, binary.LittleEndian, *config.LivenessTestMinUpstreamBytes)
  942. }
  943. if config.LivenessTestMaxUpstreamBytes != nil {
  944. binary.Write(hash, binary.LittleEndian, *config.LivenessTestMaxUpstreamBytes)
  945. }
  946. if config.LivenessTestMinDownstreamBytes != nil {
  947. binary.Write(hash, binary.LittleEndian, *config.LivenessTestMinDownstreamBytes)
  948. }
  949. if config.LivenessTestMaxDownstreamBytes != nil {
  950. binary.Write(hash, binary.LittleEndian, *config.LivenessTestMaxDownstreamBytes)
  951. }
  952. config.dialParametersHash = hash.Sum(nil)
  953. }
  954. func promoteLegacyDownloadURL(URL string) parameters.DownloadURLs {
  955. downloadURLs := make(parameters.DownloadURLs, 1)
  956. downloadURLs[0] = &parameters.DownloadURL{
  957. URL: base64.StdEncoding.EncodeToString([]byte(URL)),
  958. SkipVerify: false,
  959. OnlyAfterAttempts: 0,
  960. }
  961. return downloadURLs
  962. }
  963. type loggingDeviceBinder struct {
  964. d DeviceBinder
  965. }
  966. func newLoggingDeviceBinder(d DeviceBinder) *loggingDeviceBinder {
  967. return &loggingDeviceBinder{d: d}
  968. }
  969. func (d *loggingDeviceBinder) BindToDevice(fileDescriptor int) (string, error) {
  970. deviceInfo, err := d.d.BindToDevice(fileDescriptor)
  971. if err == nil && deviceInfo != "" {
  972. NoticeBindToDevice(deviceInfo)
  973. }
  974. return deviceInfo, err
  975. }
  976. type staticNetworkGetter struct {
  977. networkID string
  978. }
  979. func newStaticNetworkGetter(networkID string) *staticNetworkGetter {
  980. return &staticNetworkGetter{networkID: networkID}
  981. }
  982. func (n *staticNetworkGetter) GetNetworkID() string {
  983. return n.networkID
  984. }
  985. type loggingNetworkIDGetter struct {
  986. n NetworkIDGetter
  987. }
  988. func newLoggingNetworkIDGetter(n NetworkIDGetter) *loggingNetworkIDGetter {
  989. return &loggingNetworkIDGetter{n: n}
  990. }
  991. func (n *loggingNetworkIDGetter) GetNetworkID() string {
  992. networkID := n.n.GetNetworkID()
  993. // All PII must appear after the initial "-"
  994. // See: https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter
  995. logNetworkID := networkID
  996. index := strings.Index(logNetworkID, "-")
  997. if index != -1 {
  998. logNetworkID = logNetworkID[:index]
  999. }
  1000. if len(logNetworkID)+1 < len(networkID) {
  1001. // Indicate when additional network info was present after the first "-".
  1002. logNetworkID += "+<network info>"
  1003. }
  1004. NoticeNetworkID(logNetworkID)
  1005. return networkID
  1006. }