config.go 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336
  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 information, they should not be insecurely distributed
  382. // or displayed to users. Default is off.
  383. EmitDiagnosticNotices bool
  384. // EmitDiagnosticNetworkParameters indicates whether to include network
  385. // parameters in diagnostic notices. As these parameters are sensitive
  386. // circumvention network information, they should not be insecurely
  387. // distributed or displayed to users. Default is off.
  388. EmitDiagnosticNetworkParameters 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. // ServerEntrySignaturePublicKey is a base64-encoded, ed25519 public
  416. // key value used to verify individual server entry signatures. This value
  417. // is supplied by and depends on the Psiphon Network, and is typically
  418. // embedded in the client binary.
  419. ServerEntrySignaturePublicKey string
  420. // ExchangeObfuscationKey is a base64-encoded, NaCl secretbox key used to
  421. // obfuscate server info exchanges between clients.
  422. // Required for the exchange functionality.
  423. ExchangeObfuscationKey string
  424. // EmitTapdanceLogs indicates whether to emit gotapdance log messages
  425. // to stdout. Note that gotapdance log messages do not conform to the
  426. // Notice format standard. Default is off.
  427. EmitTapdanceLogs bool
  428. // TransformHostNameProbability is for testing purposes.
  429. TransformHostNameProbability *float64
  430. // FragmentorProbability and associated Fragmentor fields are for testing
  431. // purposes.
  432. FragmentorProbability *float64
  433. FragmentorLimitProtocols []string
  434. FragmentorMinTotalBytes *int
  435. FragmentorMaxTotalBytes *int
  436. FragmentorMinWriteBytes *int
  437. FragmentorMaxWriteBytes *int
  438. FragmentorMinDelayMicroseconds *int
  439. FragmentorMaxDelayMicroseconds *int
  440. // MeekTrafficShapingProbability and associated fields are for testing
  441. // purposes.
  442. MeekTrafficShapingProbability *float64
  443. MeekTrafficShapingLimitProtocols []string
  444. MeekMinLimitRequestPayloadLength *int
  445. MeekMaxLimitRequestPayloadLength *int
  446. MeekRedialTLSProbability *float64
  447. // ObfuscatedSSHAlgorithms and associated ObfuscatedSSH fields are for
  448. // testing purposes. If specified, ObfuscatedSSHAlgorithms must have 4 SSH
  449. // KEX elements in order: the kex algorithm, cipher, MAC, and server host
  450. // key algorithm.
  451. ObfuscatedSSHAlgorithms []string
  452. ObfuscatedSSHMinPadding *int
  453. ObfuscatedSSHMaxPadding *int
  454. // LivenessTestMinUpstreamBytes and other LivenessTest fields are for
  455. // testing purposes.
  456. LivenessTestMinUpstreamBytes *int
  457. LivenessTestMaxUpstreamBytes *int
  458. LivenessTestMinDownstreamBytes *int
  459. LivenessTestMaxDownstreamBytes *int
  460. // ReplayCandidateCount and other Replay fields are for testing purposes.
  461. ReplayCandidateCount *int
  462. ReplayDialParametersTTLSeconds *int
  463. ReplayTargetUpstreamBytes *int
  464. ReplayTargetDownstreamBytes *int
  465. ReplayTargetTunnelDurationSeconds *int
  466. ReplayLaterRoundMoveToFrontProbability *float64
  467. ReplayRetainFailedProbability *float64
  468. // NetworkLatencyMultiplierMin and NetworkLatencyMultiplierMax are for
  469. // testing purposes.
  470. NetworkLatencyMultiplierMin float64
  471. NetworkLatencyMultiplierMax float64
  472. // UseOnlyCustomTLSProfiles and other TLS configuration fields are for
  473. // testing purposes.
  474. UseOnlyCustomTLSProfiles *bool
  475. CustomTLSProfiles protocol.CustomTLSProfiles
  476. SelectRandomizedTLSProfileProbability *float64
  477. NoDefaultTLSSessionIDProbability *float64
  478. // clientParameters is the active ClientParameters with defaults, config
  479. // values, and, optionally, tactics applied.
  480. //
  481. // New tactics must be applied by calling Config.SetClientParameters;
  482. // calling clientParameters.Set directly will fail to add config values.
  483. clientParameters *parameters.ClientParameters
  484. dialParametersHash []byte
  485. dynamicConfigMutex sync.Mutex
  486. sponsorID string
  487. authorizations []string
  488. deviceBinder DeviceBinder
  489. networkIDGetter NetworkIDGetter
  490. committed bool
  491. loadTimestamp string
  492. }
  493. // LoadConfig parses a JSON format Psiphon config JSON string and returns a
  494. // Config struct populated with config values.
  495. //
  496. // The Config struct may then be programmatically populated with additional
  497. // values, including callbacks such as DeviceBinder.
  498. //
  499. // Before using the Config, Commit must be called, which will perform further
  500. // validation and initialize internal data structures.
  501. func LoadConfig(configJson []byte) (*Config, error) {
  502. var config Config
  503. err := json.Unmarshal(configJson, &config)
  504. if err != nil {
  505. return nil, common.ContextError(err)
  506. }
  507. config.loadTimestamp = common.TruncateTimestampToHour(
  508. common.GetCurrentTimestamp())
  509. return &config, nil
  510. }
  511. // IsCommitted checks if Commit was called.
  512. func (config *Config) IsCommitted() bool {
  513. return config.committed
  514. }
  515. // Commit validates Config fields finalizes initialization.
  516. //
  517. // Config fields should not be set after calling Config, as any changes may
  518. // not be reflected in internal data structures.
  519. func (config *Config) Commit() error {
  520. // Do SetEmitDiagnosticNotices first, to ensure config file errors are
  521. // emitted.
  522. if config.EmitDiagnosticNotices {
  523. SetEmitDiagnosticNotices(
  524. true, config.EmitDiagnosticNetworkParameters)
  525. }
  526. // Promote legacy fields.
  527. if config.CustomHeaders == nil {
  528. config.CustomHeaders = config.UpstreamProxyCustomHeaders
  529. config.UpstreamProxyCustomHeaders = nil
  530. }
  531. if config.RemoteServerListUrl != "" && config.RemoteServerListURLs == nil {
  532. config.RemoteServerListURLs = promoteLegacyDownloadURL(config.RemoteServerListUrl)
  533. }
  534. if config.ObfuscatedServerListRootURL != "" && config.ObfuscatedServerListRootURLs == nil {
  535. config.ObfuscatedServerListRootURLs = promoteLegacyDownloadURL(config.ObfuscatedServerListRootURL)
  536. }
  537. if config.UpgradeDownloadUrl != "" && config.UpgradeDownloadURLs == nil {
  538. config.UpgradeDownloadURLs = promoteLegacyDownloadURL(config.UpgradeDownloadUrl)
  539. }
  540. if config.TunnelProtocol != "" && len(config.LimitTunnelProtocols) == 0 {
  541. config.LimitTunnelProtocols = []string{config.TunnelProtocol}
  542. }
  543. // Supply default values.
  544. if config.DataStoreDirectory == "" {
  545. wd, err := os.Getwd()
  546. if err != nil {
  547. return common.ContextError(err)
  548. }
  549. config.DataStoreDirectory = wd
  550. }
  551. if config.ClientVersion == "" {
  552. config.ClientVersion = "0"
  553. }
  554. if config.TunnelPoolSize == 0 {
  555. config.TunnelPoolSize = TUNNEL_POOL_SIZE
  556. }
  557. // Validate config fields.
  558. if config.PropagationChannelId == "" {
  559. return common.ContextError(
  560. errors.New("propagation channel ID is missing from the configuration file"))
  561. }
  562. if config.SponsorId == "" {
  563. return common.ContextError(
  564. errors.New("sponsor ID is missing from the configuration file"))
  565. }
  566. _, err := strconv.Atoi(config.ClientVersion)
  567. if err != nil {
  568. return common.ContextError(
  569. fmt.Errorf("invalid client version: %s", err))
  570. }
  571. if !common.Contains(
  572. []string{"", protocol.PSIPHON_SSH_API_PROTOCOL, protocol.PSIPHON_WEB_API_PROTOCOL},
  573. config.TargetApiProtocol) {
  574. return common.ContextError(
  575. errors.New("invalid TargetApiProtocol"))
  576. }
  577. if !config.DisableRemoteServerListFetcher {
  578. if config.RemoteServerListURLs != nil {
  579. if config.RemoteServerListSignaturePublicKey == "" {
  580. return common.ContextError(errors.New("missing RemoteServerListSignaturePublicKey"))
  581. }
  582. if config.RemoteServerListDownloadFilename == "" {
  583. return common.ContextError(errors.New("missing RemoteServerListDownloadFilename"))
  584. }
  585. }
  586. if config.ObfuscatedServerListRootURLs != nil {
  587. if config.RemoteServerListSignaturePublicKey == "" {
  588. return common.ContextError(errors.New("missing RemoteServerListSignaturePublicKey"))
  589. }
  590. if config.ObfuscatedServerListDownloadDirectory == "" {
  591. return common.ContextError(errors.New("missing ObfuscatedServerListDownloadDirectory"))
  592. }
  593. }
  594. }
  595. if config.SplitTunnelRoutesURLFormat != "" {
  596. if config.SplitTunnelRoutesSignaturePublicKey == "" {
  597. return common.ContextError(errors.New("missing SplitTunnelRoutesSignaturePublicKey"))
  598. }
  599. if config.SplitTunnelDNSServer == "" {
  600. return common.ContextError(errors.New("missing SplitTunnelDNSServer"))
  601. }
  602. }
  603. if config.UpgradeDownloadURLs != nil {
  604. if config.UpgradeDownloadClientVersionHeader == "" {
  605. return common.ContextError(errors.New("missing UpgradeDownloadClientVersionHeader"))
  606. }
  607. if config.UpgradeDownloadFilename == "" {
  608. return common.ContextError(errors.New("missing UpgradeDownloadFilename"))
  609. }
  610. }
  611. // This constraint is expected by logic in Controller.runTunnels().
  612. if config.PacketTunnelTunFileDescriptor > 0 && config.TunnelPoolSize != 1 {
  613. return common.ContextError(errors.New("packet tunnel mode requires TunnelPoolSize to be 1"))
  614. }
  615. // SessionID must be PSIPHON_API_CLIENT_SESSION_ID_LENGTH lowercase hex-encoded bytes.
  616. if config.SessionID == "" {
  617. sessionID, err := MakeSessionId()
  618. if err != nil {
  619. return common.ContextError(err)
  620. }
  621. config.SessionID = sessionID
  622. }
  623. if len(config.SessionID) != 2*protocol.PSIPHON_API_CLIENT_SESSION_ID_LENGTH ||
  624. -1 != strings.IndexFunc(config.SessionID, func(c rune) bool {
  625. return !unicode.Is(unicode.ASCII_Hex_Digit, c) || unicode.IsUpper(c)
  626. }) {
  627. return common.ContextError(errors.New("invalid SessionID"))
  628. }
  629. config.clientParameters, err = parameters.NewClientParameters(
  630. func(err error) {
  631. NoticeAlert("ClientParameters getValue failed: %s", err)
  632. })
  633. if err != nil {
  634. return common.ContextError(err)
  635. }
  636. if config.ObfuscatedSSHAlgorithms != nil &&
  637. len(config.ObfuscatedSSHAlgorithms) != 4 {
  638. // TODO: validate each algorithm?
  639. return common.ContextError(errors.New("invalid ObfuscatedSSHAlgorithms"))
  640. }
  641. // clientParameters.Set will validate the config fields applied to parameters.
  642. err = config.SetClientParameters("", false, nil)
  643. if err != nil {
  644. return common.ContextError(err)
  645. }
  646. // Calculate and set the dial parameters hash. After this point, related
  647. // config fields must not change.
  648. config.setDialParametersHash()
  649. // Set defaults for dynamic config fields.
  650. config.SetDynamicConfig(config.SponsorId, config.Authorizations)
  651. // Initialize config.deviceBinder and config.config.networkIDGetter. These
  652. // wrap config.DeviceBinder and config.NetworkIDGetter/NetworkID with
  653. // loggers.
  654. //
  655. // New variables are set to avoid mutating input config fields.
  656. // Internally, code must use config.deviceBinder and
  657. // config.networkIDGetter and not the input/exported fields.
  658. if config.DeviceBinder != nil {
  659. config.deviceBinder = &loggingDeviceBinder{config.DeviceBinder}
  660. }
  661. networkIDGetter := config.NetworkIDGetter
  662. if networkIDGetter == nil {
  663. // Limitation: unlike NetworkIDGetter, which calls back to platform APIs
  664. // this method of network identification is not dynamic and will not reflect
  665. // network changes that occur while running.
  666. if config.NetworkID != "" {
  667. networkIDGetter = newStaticNetworkGetter(config.NetworkID)
  668. } else {
  669. networkIDGetter = newStaticNetworkGetter("UNKNOWN")
  670. }
  671. }
  672. config.networkIDGetter = &loggingNetworkIDGetter{networkIDGetter}
  673. config.committed = true
  674. return nil
  675. }
  676. // GetClientParameters returns a the current client parameters.
  677. func (config *Config) GetClientParameters() *parameters.ClientParameters {
  678. return config.clientParameters
  679. }
  680. // SetClientParameters resets Config.clientParameters to the default values,
  681. // applies any config file values, and then applies the input parameters (from
  682. // tactics, etc.)
  683. //
  684. // Set skipOnError to false when initially applying only config values, as
  685. // this will validate the values and should fail. Set skipOnError to true when
  686. // applying tactics to ignore invalid or unknown parameter values from tactics.
  687. //
  688. // In the case of applying tactics, do not call Config.clientParameters.Set
  689. // directly as this will not first apply config values.
  690. //
  691. // If there is an error, the existing Config.clientParameters are left
  692. // entirely unmodified.
  693. func (config *Config) SetClientParameters(tag string, skipOnError bool, applyParameters map[string]interface{}) error {
  694. setParameters := []map[string]interface{}{config.makeConfigParameters()}
  695. if applyParameters != nil {
  696. setParameters = append(setParameters, applyParameters)
  697. }
  698. counts, err := config.clientParameters.Set(tag, skipOnError, setParameters...)
  699. if err != nil {
  700. return common.ContextError(err)
  701. }
  702. NoticeInfo("applied %v parameters with tag '%s'", counts, tag)
  703. // Emit certain individual parameter values for quick reference in diagnostics.
  704. p := config.clientParameters.Get()
  705. NoticeInfo(
  706. "NetworkLatencyMultiplier Min/Max: %f/%f",
  707. p.Float(parameters.NetworkLatencyMultiplierMin),
  708. p.Float(parameters.NetworkLatencyMultiplierMax))
  709. return nil
  710. }
  711. // SetDynamicConfig sets the current client sponsor ID and authorizations.
  712. // Invalid values for sponsor ID are ignored. The caller must not modify the
  713. // input authorizations slice.
  714. func (config *Config) SetDynamicConfig(sponsorID string, authorizations []string) {
  715. config.dynamicConfigMutex.Lock()
  716. defer config.dynamicConfigMutex.Unlock()
  717. if sponsorID != "" {
  718. config.sponsorID = sponsorID
  719. }
  720. config.authorizations = authorizations
  721. }
  722. // GetSponsorID returns the current client sponsor ID.
  723. func (config *Config) GetSponsorID() string {
  724. config.dynamicConfigMutex.Lock()
  725. defer config.dynamicConfigMutex.Unlock()
  726. return config.sponsorID
  727. }
  728. // GetAuthorizations returns the current client authorizations.
  729. // The caller must not modify the returned slice.
  730. func (config *Config) GetAuthorizations() []string {
  731. config.dynamicConfigMutex.Lock()
  732. defer config.dynamicConfigMutex.Unlock()
  733. return config.authorizations
  734. }
  735. // UseUpstreamProxy indicates if an upstream proxy has been
  736. // configured.
  737. func (config *Config) UseUpstreamProxy() bool {
  738. return config.UpstreamProxyURL != ""
  739. }
  740. // GetNetworkID returns the current network ID. When NetworkIDGetter
  741. // is set, this calls into the host application; otherwise, a default
  742. // value is returned.
  743. func (config *Config) GetNetworkID() string {
  744. return config.networkIDGetter.GetNetworkID()
  745. }
  746. func (config *Config) makeConfigParameters() map[string]interface{} {
  747. // Build set of config values to apply to parameters.
  748. //
  749. // Note: names of some config fields such as
  750. // StaggerConnectionWorkersMilliseconds and LimitMeekBufferSizes have
  751. // changed in the parameters. The existing config fields are retained for
  752. // backwards compatibility.
  753. applyParameters := make(map[string]interface{})
  754. // To support platform clients that configure NetworkLatencyMultiplier, set
  755. // the NetworkLatencyMultiplierMin/NetworkLatencyMultiplierMax range to the
  756. // specified value. Also set the older NetworkLatencyMultiplier tactic, since
  757. // that will be used in the case of replaying with dial parameters persisted
  758. // by an older client version.
  759. if config.NetworkLatencyMultiplier > 0.0 {
  760. applyParameters[parameters.NetworkLatencyMultiplier] = config.NetworkLatencyMultiplier
  761. applyParameters[parameters.NetworkLatencyMultiplierMin] = config.NetworkLatencyMultiplier
  762. applyParameters[parameters.NetworkLatencyMultiplierMax] = config.NetworkLatencyMultiplier
  763. }
  764. if config.NetworkLatencyMultiplierMin > 0.0 {
  765. applyParameters[parameters.NetworkLatencyMultiplierMin] = config.NetworkLatencyMultiplierMin
  766. }
  767. if config.NetworkLatencyMultiplierMax > 0.0 {
  768. applyParameters[parameters.NetworkLatencyMultiplierMax] = config.NetworkLatencyMultiplierMax
  769. }
  770. if len(config.LimitTunnelProtocols) > 0 {
  771. applyParameters[parameters.LimitTunnelProtocols] = protocol.TunnelProtocols(config.LimitTunnelProtocols)
  772. }
  773. if len(config.InitialLimitTunnelProtocols) > 0 && config.InitialLimitTunnelProtocolsCandidateCount > 0 {
  774. applyParameters[parameters.InitialLimitTunnelProtocols] = protocol.TunnelProtocols(config.InitialLimitTunnelProtocols)
  775. applyParameters[parameters.InitialLimitTunnelProtocolsCandidateCount] = config.InitialLimitTunnelProtocolsCandidateCount
  776. }
  777. if len(config.LimitTLSProfiles) > 0 {
  778. applyParameters[parameters.LimitTLSProfiles] = protocol.TunnelProtocols(config.LimitTLSProfiles)
  779. }
  780. if len(config.LimitQUICVersions) > 0 {
  781. applyParameters[parameters.LimitQUICVersions] = protocol.QUICVersions(config.LimitQUICVersions)
  782. }
  783. if config.EstablishTunnelTimeoutSeconds != nil {
  784. applyParameters[parameters.EstablishTunnelTimeout] = fmt.Sprintf("%ds", *config.EstablishTunnelTimeoutSeconds)
  785. }
  786. if config.EstablishTunnelServerAffinityGracePeriodMilliseconds != nil {
  787. applyParameters[parameters.EstablishTunnelServerAffinityGracePeriod] = fmt.Sprintf("%dms", *config.EstablishTunnelServerAffinityGracePeriodMilliseconds)
  788. }
  789. if config.EstablishTunnelPausePeriodSeconds != nil {
  790. applyParameters[parameters.EstablishTunnelPausePeriod] = fmt.Sprintf("%ds", *config.EstablishTunnelPausePeriodSeconds)
  791. }
  792. if config.ConnectionWorkerPoolSize != 0 {
  793. applyParameters[parameters.ConnectionWorkerPoolSize] = config.ConnectionWorkerPoolSize
  794. }
  795. if config.StaggerConnectionWorkersMilliseconds > 0 {
  796. applyParameters[parameters.StaggerConnectionWorkersPeriod] = fmt.Sprintf("%dms", config.StaggerConnectionWorkersMilliseconds)
  797. }
  798. if config.LimitIntensiveConnectionWorkers > 0 {
  799. applyParameters[parameters.LimitIntensiveConnectionWorkers] = config.LimitIntensiveConnectionWorkers
  800. }
  801. applyParameters[parameters.MeekLimitBufferSizes] = config.LimitMeekBufferSizes
  802. applyParameters[parameters.IgnoreHandshakeStatsRegexps] = config.IgnoreHandshakeStatsRegexps
  803. if config.EstablishTunnelTimeoutSeconds != nil {
  804. applyParameters[parameters.EstablishTunnelTimeout] = fmt.Sprintf("%ds", *config.EstablishTunnelTimeoutSeconds)
  805. }
  806. if config.FetchRemoteServerListRetryPeriodMilliseconds != nil {
  807. applyParameters[parameters.FetchRemoteServerListRetryPeriod] = fmt.Sprintf("%dms", *config.FetchRemoteServerListRetryPeriodMilliseconds)
  808. }
  809. if config.FetchUpgradeRetryPeriodMilliseconds != nil {
  810. applyParameters[parameters.FetchUpgradeRetryPeriod] = fmt.Sprintf("%dms", *config.FetchUpgradeRetryPeriodMilliseconds)
  811. }
  812. if !config.DisableRemoteServerListFetcher {
  813. if config.RemoteServerListURLs != nil {
  814. applyParameters[parameters.RemoteServerListSignaturePublicKey] = config.RemoteServerListSignaturePublicKey
  815. applyParameters[parameters.RemoteServerListURLs] = config.RemoteServerListURLs
  816. }
  817. if config.ObfuscatedServerListRootURLs != nil {
  818. applyParameters[parameters.RemoteServerListSignaturePublicKey] = config.RemoteServerListSignaturePublicKey
  819. applyParameters[parameters.ObfuscatedServerListRootURLs] = config.ObfuscatedServerListRootURLs
  820. }
  821. }
  822. applyParameters[parameters.SplitTunnelRoutesURLFormat] = config.SplitTunnelRoutesURLFormat
  823. applyParameters[parameters.SplitTunnelRoutesSignaturePublicKey] = config.SplitTunnelRoutesSignaturePublicKey
  824. applyParameters[parameters.SplitTunnelDNSServer] = config.SplitTunnelDNSServer
  825. if config.UpgradeDownloadURLs != nil {
  826. applyParameters[parameters.UpgradeDownloadClientVersionHeader] = config.UpgradeDownloadClientVersionHeader
  827. applyParameters[parameters.UpgradeDownloadURLs] = config.UpgradeDownloadURLs
  828. }
  829. applyParameters[parameters.TunnelRateLimits] = config.RateLimits
  830. if config.TransformHostNameProbability != nil {
  831. applyParameters[parameters.TransformHostNameProbability] = *config.TransformHostNameProbability
  832. }
  833. if config.FragmentorProbability != nil {
  834. applyParameters[parameters.FragmentorProbability] = *config.FragmentorProbability
  835. }
  836. if len(config.FragmentorLimitProtocols) > 0 {
  837. applyParameters[parameters.FragmentorLimitProtocols] = protocol.TunnelProtocols(config.FragmentorLimitProtocols)
  838. }
  839. if config.FragmentorMinTotalBytes != nil {
  840. applyParameters[parameters.FragmentorMinTotalBytes] = *config.FragmentorMinTotalBytes
  841. }
  842. if config.FragmentorMaxTotalBytes != nil {
  843. applyParameters[parameters.FragmentorMaxTotalBytes] = *config.FragmentorMaxTotalBytes
  844. }
  845. if config.FragmentorMinWriteBytes != nil {
  846. applyParameters[parameters.FragmentorMinWriteBytes] = *config.FragmentorMinWriteBytes
  847. }
  848. if config.FragmentorMaxWriteBytes != nil {
  849. applyParameters[parameters.FragmentorMaxWriteBytes] = *config.FragmentorMaxWriteBytes
  850. }
  851. if config.FragmentorMinDelayMicroseconds != nil {
  852. applyParameters[parameters.FragmentorMinDelay] = fmt.Sprintf("%dus", *config.FragmentorMinDelayMicroseconds)
  853. }
  854. if config.FragmentorMaxDelayMicroseconds != nil {
  855. applyParameters[parameters.FragmentorMaxDelay] = fmt.Sprintf("%dus", *config.FragmentorMaxDelayMicroseconds)
  856. }
  857. if config.MeekTrafficShapingProbability != nil {
  858. applyParameters[parameters.MeekTrafficShapingProbability] = *config.MeekTrafficShapingProbability
  859. }
  860. if len(config.MeekTrafficShapingLimitProtocols) > 0 {
  861. applyParameters[parameters.MeekTrafficShapingLimitProtocols] = protocol.TunnelProtocols(config.MeekTrafficShapingLimitProtocols)
  862. }
  863. if config.MeekMinLimitRequestPayloadLength != nil {
  864. applyParameters[parameters.MeekMinLimitRequestPayloadLength] = *config.MeekMinLimitRequestPayloadLength
  865. }
  866. if config.MeekMaxLimitRequestPayloadLength != nil {
  867. applyParameters[parameters.MeekMaxLimitRequestPayloadLength] = *config.MeekMaxLimitRequestPayloadLength
  868. }
  869. if config.MeekRedialTLSProbability != nil {
  870. applyParameters[parameters.MeekRedialTLSProbability] = *config.MeekRedialTLSProbability
  871. }
  872. if config.ObfuscatedSSHMinPadding != nil {
  873. applyParameters[parameters.ObfuscatedSSHMinPadding] = *config.ObfuscatedSSHMinPadding
  874. }
  875. if config.ObfuscatedSSHMaxPadding != nil {
  876. applyParameters[parameters.ObfuscatedSSHMaxPadding] = *config.ObfuscatedSSHMaxPadding
  877. }
  878. if config.LivenessTestMinUpstreamBytes != nil {
  879. applyParameters[parameters.LivenessTestMinUpstreamBytes] = *config.LivenessTestMinUpstreamBytes
  880. }
  881. if config.LivenessTestMaxUpstreamBytes != nil {
  882. applyParameters[parameters.LivenessTestMaxUpstreamBytes] = *config.LivenessTestMaxUpstreamBytes
  883. }
  884. if config.LivenessTestMinDownstreamBytes != nil {
  885. applyParameters[parameters.LivenessTestMinDownstreamBytes] = *config.LivenessTestMinDownstreamBytes
  886. }
  887. if config.LivenessTestMaxDownstreamBytes != nil {
  888. applyParameters[parameters.LivenessTestMaxDownstreamBytes] = *config.LivenessTestMaxDownstreamBytes
  889. }
  890. if config.ReplayCandidateCount != nil {
  891. applyParameters[parameters.ReplayCandidateCount] = *config.ReplayCandidateCount
  892. }
  893. if config.ReplayDialParametersTTLSeconds != nil {
  894. applyParameters[parameters.ReplayDialParametersTTL] = fmt.Sprintf("%ds", *config.ReplayDialParametersTTLSeconds)
  895. }
  896. if config.ReplayTargetUpstreamBytes != nil {
  897. applyParameters[parameters.ReplayTargetUpstreamBytes] = *config.ReplayTargetUpstreamBytes
  898. }
  899. if config.ReplayTargetDownstreamBytes != nil {
  900. applyParameters[parameters.ReplayTargetDownstreamBytes] = *config.ReplayTargetDownstreamBytes
  901. }
  902. if config.ReplayTargetTunnelDurationSeconds != nil {
  903. applyParameters[parameters.ReplayTargetTunnelDuration] = fmt.Sprintf("%ds", *config.ReplayTargetTunnelDurationSeconds)
  904. }
  905. if config.ReplayLaterRoundMoveToFrontProbability != nil {
  906. applyParameters[parameters.ReplayLaterRoundMoveToFrontProbability] = *config.ReplayLaterRoundMoveToFrontProbability
  907. }
  908. if config.ReplayRetainFailedProbability != nil {
  909. applyParameters[parameters.ReplayRetainFailedProbability] = *config.ReplayRetainFailedProbability
  910. }
  911. if config.UseOnlyCustomTLSProfiles != nil {
  912. applyParameters[parameters.UseOnlyCustomTLSProfiles] = *config.UseOnlyCustomTLSProfiles
  913. }
  914. if config.CustomTLSProfiles != nil {
  915. applyParameters[parameters.CustomTLSProfiles] = config.CustomTLSProfiles
  916. }
  917. if config.SelectRandomizedTLSProfileProbability != nil {
  918. applyParameters[parameters.SelectRandomizedTLSProfileProbability] = *config.SelectRandomizedTLSProfileProbability
  919. }
  920. if config.NoDefaultTLSSessionIDProbability != nil {
  921. applyParameters[parameters.NoDefaultTLSSessionIDProbability] = *config.NoDefaultTLSSessionIDProbability
  922. }
  923. return applyParameters
  924. }
  925. func (config *Config) setDialParametersHash() {
  926. // Calculate and store a hash of the config values that may impact
  927. // dial parameters. This hash is used as part of the dial parameters
  928. // replay mechanism to detect when persisted dial parameters must
  929. // be discarded due to conflicting config changes.
  930. //
  931. // MD5 hash is used solely as a data checksum and not for any security
  932. // purpose.
  933. hash := md5.New()
  934. if len(config.LimitTunnelProtocols) > 0 {
  935. for _, protocol := range config.LimitTunnelProtocols {
  936. hash.Write([]byte(protocol))
  937. }
  938. }
  939. if len(config.InitialLimitTunnelProtocols) > 0 && config.InitialLimitTunnelProtocolsCandidateCount > 0 {
  940. for _, protocol := range config.InitialLimitTunnelProtocols {
  941. hash.Write([]byte(protocol))
  942. }
  943. binary.Write(hash, binary.LittleEndian, config.InitialLimitTunnelProtocolsCandidateCount)
  944. }
  945. if len(config.LimitTLSProfiles) > 0 {
  946. for _, profile := range config.LimitTLSProfiles {
  947. hash.Write([]byte(profile))
  948. }
  949. }
  950. if len(config.LimitQUICVersions) > 0 {
  951. for _, version := range config.LimitQUICVersions {
  952. hash.Write([]byte(version))
  953. }
  954. }
  955. // Whether a custom User-Agent is specified is a binary flag: when not set,
  956. // the replay dial parameters value applies. When set, external
  957. // considerations apply.
  958. if _, ok := config.CustomHeaders["User-Agent"]; ok {
  959. hash.Write([]byte{1})
  960. }
  961. if config.UpstreamProxyURL != "" {
  962. hash.Write([]byte(config.UpstreamProxyURL))
  963. }
  964. if config.TransformHostNameProbability != nil {
  965. binary.Write(hash, binary.LittleEndian, *config.TransformHostNameProbability)
  966. }
  967. if config.FragmentorProbability != nil {
  968. binary.Write(hash, binary.LittleEndian, *config.FragmentorProbability)
  969. }
  970. if len(config.FragmentorLimitProtocols) > 0 {
  971. for _, protocol := range config.FragmentorLimitProtocols {
  972. hash.Write([]byte(protocol))
  973. }
  974. }
  975. if config.FragmentorMinTotalBytes != nil {
  976. binary.Write(hash, binary.LittleEndian, *config.FragmentorMinTotalBytes)
  977. }
  978. if config.FragmentorMaxTotalBytes != nil {
  979. binary.Write(hash, binary.LittleEndian, *config.FragmentorMaxTotalBytes)
  980. }
  981. if config.FragmentorMinWriteBytes != nil {
  982. binary.Write(hash, binary.LittleEndian, *config.FragmentorMinWriteBytes)
  983. }
  984. if config.FragmentorMaxWriteBytes != nil {
  985. binary.Write(hash, binary.LittleEndian, *config.FragmentorMaxWriteBytes)
  986. }
  987. if config.FragmentorMinDelayMicroseconds != nil {
  988. binary.Write(hash, binary.LittleEndian, *config.FragmentorMinDelayMicroseconds)
  989. }
  990. if config.FragmentorMaxDelayMicroseconds != nil {
  991. binary.Write(hash, binary.LittleEndian, *config.FragmentorMaxDelayMicroseconds)
  992. }
  993. if config.MeekTrafficShapingProbability != nil {
  994. binary.Write(hash, binary.LittleEndian, *config.MeekTrafficShapingProbability)
  995. }
  996. if len(config.MeekTrafficShapingLimitProtocols) > 0 {
  997. for _, protocol := range config.MeekTrafficShapingLimitProtocols {
  998. hash.Write([]byte(protocol))
  999. }
  1000. }
  1001. if config.MeekMinLimitRequestPayloadLength != nil {
  1002. binary.Write(hash, binary.LittleEndian, *config.MeekMinLimitRequestPayloadLength)
  1003. }
  1004. if config.MeekMaxLimitRequestPayloadLength != nil {
  1005. binary.Write(hash, binary.LittleEndian, *config.MeekMaxLimitRequestPayloadLength)
  1006. }
  1007. if config.MeekRedialTLSProbability != nil {
  1008. binary.Write(hash, binary.LittleEndian, *config.MeekRedialTLSProbability)
  1009. }
  1010. if config.ObfuscatedSSHMinPadding != nil {
  1011. binary.Write(hash, binary.LittleEndian, *config.ObfuscatedSSHMinPadding)
  1012. }
  1013. if config.ObfuscatedSSHMaxPadding != nil {
  1014. binary.Write(hash, binary.LittleEndian, *config.ObfuscatedSSHMaxPadding)
  1015. }
  1016. if config.LivenessTestMinUpstreamBytes != nil {
  1017. binary.Write(hash, binary.LittleEndian, *config.LivenessTestMinUpstreamBytes)
  1018. }
  1019. if config.LivenessTestMaxUpstreamBytes != nil {
  1020. binary.Write(hash, binary.LittleEndian, *config.LivenessTestMaxUpstreamBytes)
  1021. }
  1022. if config.LivenessTestMinDownstreamBytes != nil {
  1023. binary.Write(hash, binary.LittleEndian, *config.LivenessTestMinDownstreamBytes)
  1024. }
  1025. if config.LivenessTestMaxDownstreamBytes != nil {
  1026. binary.Write(hash, binary.LittleEndian, *config.LivenessTestMaxDownstreamBytes)
  1027. }
  1028. config.dialParametersHash = hash.Sum(nil)
  1029. }
  1030. func promoteLegacyDownloadURL(URL string) parameters.DownloadURLs {
  1031. downloadURLs := make(parameters.DownloadURLs, 1)
  1032. downloadURLs[0] = &parameters.DownloadURL{
  1033. URL: base64.StdEncoding.EncodeToString([]byte(URL)),
  1034. SkipVerify: false,
  1035. OnlyAfterAttempts: 0,
  1036. }
  1037. return downloadURLs
  1038. }
  1039. type loggingDeviceBinder struct {
  1040. d DeviceBinder
  1041. }
  1042. func newLoggingDeviceBinder(d DeviceBinder) *loggingDeviceBinder {
  1043. return &loggingDeviceBinder{d: d}
  1044. }
  1045. func (d *loggingDeviceBinder) BindToDevice(fileDescriptor int) (string, error) {
  1046. deviceInfo, err := d.d.BindToDevice(fileDescriptor)
  1047. if err == nil && deviceInfo != "" {
  1048. NoticeBindToDevice(deviceInfo)
  1049. }
  1050. return deviceInfo, err
  1051. }
  1052. type staticNetworkGetter struct {
  1053. networkID string
  1054. }
  1055. func newStaticNetworkGetter(networkID string) *staticNetworkGetter {
  1056. return &staticNetworkGetter{networkID: networkID}
  1057. }
  1058. func (n *staticNetworkGetter) GetNetworkID() string {
  1059. return n.networkID
  1060. }
  1061. type loggingNetworkIDGetter struct {
  1062. n NetworkIDGetter
  1063. }
  1064. func newLoggingNetworkIDGetter(n NetworkIDGetter) *loggingNetworkIDGetter {
  1065. return &loggingNetworkIDGetter{n: n}
  1066. }
  1067. func (n *loggingNetworkIDGetter) GetNetworkID() string {
  1068. networkID := n.n.GetNetworkID()
  1069. // All PII must appear after the initial "-"
  1070. // See: https://godoc.org/github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon#NetworkIDGetter
  1071. logNetworkID := networkID
  1072. index := strings.Index(logNetworkID, "-")
  1073. if index != -1 {
  1074. logNetworkID = logNetworkID[:index]
  1075. }
  1076. if len(logNetworkID)+1 < len(networkID) {
  1077. // Indicate when additional network info was present after the first "-".
  1078. logNetworkID += "+[redacted]"
  1079. }
  1080. NoticeNetworkID(logNetworkID)
  1081. return networkID
  1082. }