| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751 |
- /*
- * Copyright (c) 2018, Psiphon Inc.
- * All rights reserved.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
- */
- package psiphon
- import (
- "bytes"
- "crypto/md5"
- "encoding/binary"
- "errors"
- "fmt"
- "net"
- "net/http"
- "net/url"
- "sync/atomic"
- "time"
- "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
- "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
- "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
- "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
- "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
- utls "github.com/refraction-networking/utls"
- regen "github.com/zach-klippenstein/goregen"
- )
- // DialParameters represents a selected protocol and all the related selected
- // protocol attributes, many chosen at random, for a tunnel dial attempt.
- //
- // DialParameters is used:
- // - to configure dialers
- // - as a persistent record to store successful dial parameters for replay
- // - to report dial stats in notices and Psiphon API calls.
- //
- // MeekResolvedIPAddress is set asynchronously, as it is not known until the
- // dial process has begun. The atomic.Value will contain a string, initialized
- // to "", and set to the resolved IP address once that part of the dial
- // process has completed.
- //
- // DialParameters is not safe for concurrent use.
- type DialParameters struct {
- ServerEntry *protocol.ServerEntry `json:"-"`
- NetworkID string `json:"-"`
- IsReplay bool `json:"-"`
- CandidateNumber int `json:"-"`
- LastUsedTimestamp time.Time
- LastUsedConfigStateHash []byte
- TunnelProtocol string
- DirectDialAddress string
- DialPortNumber string
- UpstreamProxyType string `json:"-"`
- UpstreamProxyCustomHeaderNames []string `json:"-"`
- SelectedSSHClientVersion bool
- SSHClientVersion string
- SSHKEXSeed *prng.Seed
- ObfuscatorPaddingSeed *prng.Seed
- FragmentorSeed *prng.Seed
- MeekFrontingDialAddress string
- MeekFrontingHost string
- MeekDialAddress string
- MeekTransformedHostName bool
- MeekSNIServerName string
- MeekHostHeader string
- MeekObfuscatorPaddingSeed *prng.Seed
- MeekResolvedIPAddress atomic.Value `json:"-"`
- SelectedUserAgent bool
- UserAgent string
- SelectedTLSProfile bool
- TLSProfile string
- TLSVersion string
- RandomizedTLSProfileSeed *prng.Seed
- QUICVersion string
- QUICDialSNIAddress string
- ObfuscatedQUICPaddingSeed *prng.Seed
- LivenessTestSeed *prng.Seed
- APIRequestPaddingSeed *prng.Seed
- DialConnMetrics common.MetricsSource `json:"-"`
- ObfuscatedSSHConnMetrics common.MetricsSource `json:"-"`
- DialDuration time.Duration `json:"-"`
- dialConfig *DialConfig `json:"-"`
- meekConfig *MeekConfig `json:"-"`
- }
- // MakeDialParameters creates a new DialParameters for the candidate server
- // entry, including selecting a protocol and all the various protocol
- // attributes. The input selectProtocol is used to comply with any active
- // protocol selection constraints.
- //
- // When stored dial parameters are available and may be used,
- // MakeDialParameters may replay previous dial parameters in an effort to
- // leverage "known working" values instead of always chosing at random from a
- // large space.
- //
- // MakeDialParameters will return nil/nil in cases where the candidate server
- // entry should be skipped.
- //
- // To support replay, the caller must call DialParameters.Succeeded when a
- // successful tunnel is established with the returned DialParameters; and must
- // call DialParameters.Failed when a tunnel dial or activation fails, except
- // when establishment is cancelled.
- func MakeDialParameters(
- config *Config,
- canReplay func(serverEntry *protocol.ServerEntry, replayProtocol string) bool,
- selectProtocol func(serverEntry *protocol.ServerEntry) (string, bool),
- serverEntry *protocol.ServerEntry,
- isTactics bool,
- candidateNumber int) (*DialParameters, error) {
- networkID := config.GetNetworkID()
- p := config.clientParameters.Get()
- ttl := p.Duration(parameters.ReplayDialParametersTTL)
- replaySSH := p.Bool(parameters.ReplaySSH)
- replayObfuscatorPadding := p.Bool(parameters.ReplayObfuscatorPadding)
- replayFragmentor := p.Bool(parameters.ReplayFragmentor)
- replayTLSProfile := p.Bool(parameters.ReplayTLSProfile)
- replayRandomizedTLSProfile := p.Bool(parameters.ReplayRandomizedTLSProfile)
- replayFronting := p.Bool(parameters.ReplayFronting)
- replayHostname := p.Bool(parameters.ReplayHostname)
- replayQUICVersion := p.Bool(parameters.ReplayQUICVersion)
- replayObfuscatedQUIC := p.Bool(parameters.ReplayObfuscatedQUIC)
- replayLivenessTest := p.Bool(parameters.ReplayLivenessTest)
- replayUserAgent := p.Bool(parameters.ReplayUserAgent)
- replayAPIRequestPadding := p.Bool(parameters.ReplayAPIRequestPadding)
- // Check for existing dial parameters for this server/network ID.
- dialParams, err := GetDialParameters(serverEntry.IpAddress, networkID)
- if err != nil {
- NoticeAlert("GetDialParameters failed: %s", err)
- dialParams = nil
- // Proceed, without existing dial parameters.
- }
- // Check if replay is permitted:
- // - TTL must be > 0 and existing dial parameters must not have expired
- // as indicated by LastUsedTimestamp + TTL.
- // - Config/tactics/server entry values must be unchanged from when
- // previous dial parameters were established.
- // - The protocol selection constraints must permit replay, as indicated
- // by canReplay.
- // - Must not be using an obsolete TLS profile that is no longer supported.
- //
- // When existing dial parameters don't meet these conditions, dialParams
- // is reset to nil and new dial parameters will be generated.
- var currentTimestamp time.Time
- var configStateHash []byte
- // When TTL is 0, replay is disabled; the timestamp remains 0 and the
- // output DialParameters will not be stored by Success.
- if ttl > 0 {
- currentTimestamp = time.Now()
- configStateHash = getConfigStateHash(config, p, serverEntry)
- }
- if dialParams != nil &&
- (ttl <= 0 ||
- dialParams.LastUsedTimestamp.Before(currentTimestamp.Add(-ttl)) ||
- bytes.Compare(dialParams.LastUsedConfigStateHash, configStateHash) != 0 ||
- (dialParams.TLSProfile != "" &&
- !common.Contains(protocol.SupportedTLSProfiles, dialParams.TLSProfile))) {
- // In these cases, existing dial parameters are expired or no longer
- // match the config state and so are cleared to avoid rechecking them.
- err = DeleteDialParameters(serverEntry.IpAddress, networkID)
- if err != nil {
- NoticeAlert("DeleteDialParameters failed: %s", err)
- }
- dialParams = nil
- }
- if dialParams != nil {
- if config.DisableReplay ||
- !canReplay(serverEntry, dialParams.TunnelProtocol) {
- // In these ephemeral cases, existing dial parameters may still be valid
- // and used in future establishment phases, and so are retained.
- dialParams = nil
- }
- }
- isReplay := (dialParams != nil)
- if !isReplay {
- dialParams = &DialParameters{}
- }
- dialParams.ServerEntry = serverEntry
- dialParams.NetworkID = networkID
- dialParams.IsReplay = isReplay
- dialParams.CandidateNumber = candidateNumber
- // Even when replaying, LastUsedTimestamp is updated to extend the TTL of
- // replayed dial parameters which will be updated in the datastore upon
- // success.
- dialParams.LastUsedTimestamp = currentTimestamp
- dialParams.LastUsedConfigStateHash = configStateHash
- // Initialize dial parameters.
- //
- // When not replaying, all required parameters are initialized. When
- // replaying, existing parameters are retaing, subject to the replay-X
- // tactics flags.
- if !isReplay {
- // TODO: should there be a pre-check of selectProtocol before incurring
- // overhead of unmarshaling dial parameters? In may be that a server entry
- // is fully incapable of satisfying the current protocol selection
- // constraints.
- selectedProtocol, ok := selectProtocol(serverEntry)
- if !ok {
- return nil, nil
- }
- dialParams.TunnelProtocol = selectedProtocol
- }
- if !isReplay || !replaySSH {
- dialParams.SelectedSSHClientVersion = true
- dialParams.SSHClientVersion = pickSSHClientVersion()
- dialParams.SSHKEXSeed, err = prng.NewSeed()
- if err != nil {
- return nil, common.ContextError(err)
- }
- }
- if !isReplay || !replayObfuscatorPadding {
- dialParams.ObfuscatorPaddingSeed, err = prng.NewSeed()
- if err != nil {
- return nil, common.ContextError(err)
- }
- if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
- dialParams.MeekObfuscatorPaddingSeed, err = prng.NewSeed()
- if err != nil {
- return nil, common.ContextError(err)
- }
- }
- }
- if !isReplay || !replayFragmentor {
- dialParams.FragmentorSeed, err = prng.NewSeed()
- if err != nil {
- return nil, common.ContextError(err)
- }
- }
- if (!isReplay || !replayTLSProfile) &&
- protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) {
- dialParams.SelectedTLSProfile = true
- dialParams.TLSProfile = SelectTLSProfile(p)
- }
- if (!isReplay || !replayRandomizedTLSProfile) &&
- protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) &&
- protocol.TLSProfileIsRandomized(dialParams.TLSProfile) {
- dialParams.RandomizedTLSProfileSeed, err = prng.NewSeed()
- if err != nil {
- return nil, common.ContextError(err)
- }
- }
- if (!isReplay || !replayTLSProfile) &&
- protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) {
- // Since "Randomized-v2" may be TLS 1.2 or TLS 1.3, construct the
- // ClientHello to determine if it's TLS 1.3. This test also covers
- // non-randomized TLS 1.3 profiles. This check must come after
- // dialParams.TLSProfile and dialParams.RandomizedTLSProfileSeed are set.
- // No actual dial is made here.
- utlsClientHelloID := getUTLSClientHelloID(dialParams.TLSProfile)
- if protocol.TLSProfileIsRandomized(dialParams.TLSProfile) {
- utlsClientHelloID.Seed = new(utls.PRNGSeed)
- *utlsClientHelloID.Seed = [32]byte(*dialParams.RandomizedTLSProfileSeed)
- }
- dialParams.TLSVersion, err = getClientHelloVersion(utlsClientHelloID)
- if err != nil {
- return nil, common.ContextError(err)
- }
- }
- if (!isReplay || !replayFronting) &&
- protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) {
- dialParams.MeekFrontingDialAddress, dialParams.MeekFrontingHost, err =
- selectFrontingParameters(serverEntry)
- if err != nil {
- return nil, common.ContextError(err)
- }
- }
- if !isReplay || !replayHostname {
- if protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol) ||
- protocol.TunnelProtocolUsesFrontedQUIC(dialParams.TunnelProtocol) {
- dialParams.MeekSNIServerName = ""
- if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
- dialParams.MeekSNIServerName = common.GenerateHostName()
- dialParams.MeekTransformedHostName = true
- }
- } else if protocol.TunnelProtocolUsesMeekHTTP(dialParams.TunnelProtocol) {
- dialParams.MeekHostHeader = ""
- hostname := serverEntry.IpAddress
- if p.WeightedCoinFlip(parameters.TransformHostNameProbability) {
- hostname = common.GenerateHostName()
- dialParams.MeekTransformedHostName = true
- }
- if serverEntry.MeekServerPort == 80 {
- dialParams.MeekHostHeader = hostname
- } else {
- dialParams.MeekHostHeader = fmt.Sprintf("%s:%d", hostname, serverEntry.MeekServerPort)
- }
- } else if protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
- dialParams.QUICDialSNIAddress = fmt.Sprintf(
- "%s:%d", common.GenerateHostName(), serverEntry.SshObfuscatedQUICPort)
- }
- }
- if (!isReplay || !replayQUICVersion) &&
- protocol.TunnelProtocolUsesQUIC(dialParams.TunnelProtocol) {
- allowObfuscatedQUIC := !protocol.TunnelProtocolUsesFrontedQUIC(dialParams.TunnelProtocol)
- dialParams.QUICVersion = selectQUICVersion(allowObfuscatedQUIC, p)
- }
- if (!isReplay || !replayObfuscatedQUIC) &&
- protocol.QUICVersionIsObfuscated(dialParams.QUICVersion) {
- dialParams.ObfuscatedQUICPaddingSeed, err = prng.NewSeed()
- if err != nil {
- return nil, common.ContextError(err)
- }
- }
- if !isReplay || !replayLivenessTest {
- // TODO: initialize only when LivenessTestMaxUp/DownstreamBytes > 0?
- dialParams.LivenessTestSeed, err = prng.NewSeed()
- if err != nil {
- return nil, common.ContextError(err)
- }
- }
- if !isReplay || !replayAPIRequestPadding {
- dialParams.APIRequestPaddingSeed, err = prng.NewSeed()
- if err != nil {
- return nil, common.ContextError(err)
- }
- }
- // Set dial address fields. This portion of configuration is
- // deterministic, given the parameters established or replayed so far.
- switch dialParams.TunnelProtocol {
- case protocol.TUNNEL_PROTOCOL_SSH:
- dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshPort)
- case protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH:
- dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedPort)
- case protocol.TUNNEL_PROTOCOL_TAPDANCE_OBFUSCATED_SSH:
- dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedTapdancePort)
- case protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
- dialParams.DirectDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.SshObfuscatedQUICPort)
- case protocol.TUNNEL_PROTOCOL_FRONTED_QUIC_OBFUSCATED_SSH:
- dialParams.MeekDialAddress = fmt.Sprintf("%s:443", dialParams.MeekFrontingDialAddress)
- dialParams.MeekHostHeader = dialParams.MeekFrontingHost
- if !dialParams.MeekTransformedHostName {
- dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
- }
- case protocol.TUNNEL_PROTOCOL_MARIONETTE_OBFUSCATED_SSH:
- // Note: port comes from marionnete "format"
- dialParams.DirectDialAddress = serverEntry.IpAddress
- case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK:
- dialParams.MeekDialAddress = fmt.Sprintf("%s:443", dialParams.MeekFrontingDialAddress)
- dialParams.MeekHostHeader = dialParams.MeekFrontingHost
- if serverEntry.MeekFrontingDisableSNI {
- dialParams.MeekSNIServerName = ""
- } else if !dialParams.MeekTransformedHostName {
- dialParams.MeekSNIServerName = dialParams.MeekFrontingDialAddress
- }
- case protocol.TUNNEL_PROTOCOL_FRONTED_MEEK_HTTP:
- dialParams.MeekDialAddress = fmt.Sprintf("%s:80", dialParams.MeekFrontingDialAddress)
- dialParams.MeekHostHeader = dialParams.MeekFrontingHost
- case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK:
- dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
- if !dialParams.MeekTransformedHostName {
- if serverEntry.MeekServerPort == 80 {
- dialParams.MeekHostHeader = serverEntry.IpAddress
- } else {
- dialParams.MeekHostHeader = dialParams.MeekDialAddress
- }
- }
- case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
- protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET:
- dialParams.MeekDialAddress = fmt.Sprintf("%s:%d", serverEntry.IpAddress, serverEntry.MeekServerPort)
- if !dialParams.MeekTransformedHostName {
- // Note: IP address in SNI field will be omitted.
- dialParams.MeekSNIServerName = serverEntry.IpAddress
- }
- if serverEntry.MeekServerPort == 443 {
- dialParams.MeekHostHeader = serverEntry.IpAddress
- } else {
- dialParams.MeekHostHeader = dialParams.MeekDialAddress
- }
- default:
- return nil, common.ContextError(
- fmt.Errorf("unknown tunnel protocol: %s", dialParams.TunnelProtocol))
- }
- if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
- host, port, _ := net.SplitHostPort(dialParams.MeekDialAddress)
- if p.Bool(parameters.MeekDialDomainsOnly) {
- if net.ParseIP(host) != nil {
- // No error, as this is a "not supported" case.
- return nil, nil
- }
- }
- dialParams.DialPortNumber = port
- // The underlying TLS will automatically disable SNI for IP address server name
- // values; we have this explicit check here so we record the correct value for stats.
- if net.ParseIP(dialParams.MeekSNIServerName) != nil {
- dialParams.MeekSNIServerName = ""
- }
- } else {
- _, dialParams.DialPortNumber, _ = net.SplitHostPort(dialParams.DirectDialAddress)
- }
- // Initialize/replay User-Agent header for HTTP upstream proxy and meek protocols.
- if config.UseUpstreamProxy() {
- // Note: UpstreamProxyURL will be validated in the dial
- proxyURL, err := url.Parse(config.UpstreamProxyURL)
- if err == nil {
- dialParams.UpstreamProxyType = proxyURL.Scheme
- }
- }
- dialCustomHeaders := makeDialCustomHeaders(config, p)
- if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) || dialParams.UpstreamProxyType == "http" {
- if !isReplay || !replayUserAgent {
- dialParams.SelectedUserAgent, dialParams.UserAgent = PickUserAgentIfUnset(p, dialCustomHeaders)
- }
- if dialParams.SelectedUserAgent {
- dialCustomHeaders.Set("User-Agent", dialParams.UserAgent)
- }
- }
- // UpstreamProxyCustomHeaderNames is a reported metric. Just the names and
- // not the values are reported, in case the values are identifying.
- if len(config.CustomHeaders) > 0 {
- dialParams.UpstreamProxyCustomHeaderNames = make([]string, 0)
- for name := range dialCustomHeaders {
- if name == "User-Agent" && dialParams.SelectedUserAgent {
- continue
- }
- dialParams.UpstreamProxyCustomHeaderNames = append(dialParams.UpstreamProxyCustomHeaderNames, name)
- }
- }
- // Initialize Dial/MeekConfigs to be passed to the corresponding dialers.
- dialParams.dialConfig = &DialConfig{
- UpstreamProxyURL: config.UpstreamProxyURL,
- CustomHeaders: dialCustomHeaders,
- DeviceBinder: config.deviceBinder,
- DnsServerGetter: config.DnsServerGetter,
- IPv6Synthesizer: config.IPv6Synthesizer,
- TrustedCACertificatesFilename: config.TrustedCACertificatesFilename,
- FragmentorConfig: fragmentor.NewUpstreamConfig(p, dialParams.TunnelProtocol, dialParams.FragmentorSeed),
- }
- // Unconditionally initialize MeekResolvedIPAddress, so a valid string can
- // always be read.
- dialParams.MeekResolvedIPAddress.Store("")
- if protocol.TunnelProtocolUsesMeek(dialParams.TunnelProtocol) {
- dialParams.meekConfig = &MeekConfig{
- ClientParameters: config.clientParameters,
- DialAddress: dialParams.MeekDialAddress,
- UseQUIC: protocol.TunnelProtocolUsesFrontedQUIC(dialParams.TunnelProtocol),
- QUICVersion: dialParams.QUICVersion,
- UseHTTPS: protocol.TunnelProtocolUsesMeekHTTPS(dialParams.TunnelProtocol),
- TLSProfile: dialParams.TLSProfile,
- RandomizedTLSProfileSeed: dialParams.RandomizedTLSProfileSeed,
- UseObfuscatedSessionTickets: dialParams.TunnelProtocol == protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
- SNIServerName: dialParams.MeekSNIServerName,
- HostHeader: dialParams.MeekHostHeader,
- TransformedHostName: dialParams.MeekTransformedHostName,
- ClientTunnelProtocol: dialParams.TunnelProtocol,
- MeekCookieEncryptionPublicKey: serverEntry.MeekCookieEncryptionPublicKey,
- MeekObfuscatedKey: serverEntry.MeekObfuscatedKey,
- MeekObfuscatorPaddingSeed: dialParams.MeekObfuscatorPaddingSeed,
- }
- // Use an asynchronous callback to record the resolved IP address when
- // dialing a domain name. Note that DialMeek doesn't immediately
- // establish any HTTP connections, so the resolved IP address won't be
- // reported in all cases until after SSH traffic is relayed or a
- // endpoint request is made over the meek connection.
- dialParams.dialConfig.ResolvedIPCallback = func(IPAddress string) {
- dialParams.MeekResolvedIPAddress.Store(IPAddress)
- }
- if isTactics {
- dialParams.meekConfig.RoundTripperOnly = true
- }
- }
- return dialParams, nil
- }
- func (dialParams *DialParameters) GetDialConfig() *DialConfig {
- return dialParams.dialConfig
- }
- func (dialParams *DialParameters) GetMeekConfig() *MeekConfig {
- return dialParams.meekConfig
- }
- func (dialParams *DialParameters) Succeeded() {
- // When TTL is 0, don't store dial parameters.
- if dialParams.LastUsedTimestamp.IsZero() {
- return
- }
- NoticeInfo("Set dial parameters for %s", dialParams.ServerEntry.IpAddress)
- err := SetDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID, dialParams)
- if err != nil {
- NoticeAlert("SetDialParameters failed: %s", err)
- }
- }
- func (dialParams *DialParameters) Failed() {
- // When a tunnel fails, and the dial is a replay, clear the stored dial
- // parameters which are now presumed to be blocked, impaired or otherwise
- // no longer effective.
- //
- // It may be the case that a dial is not using stored dial parameters, and
- // in this case we retain those dial parameters since they were not
- // exercised and may still be efective.
- if dialParams.IsReplay {
- NoticeInfo("Delete dial parameters for %s", dialParams.ServerEntry.IpAddress)
- err := DeleteDialParameters(dialParams.ServerEntry.IpAddress, dialParams.NetworkID)
- if err != nil {
- NoticeAlert("DeleteDialParameters failed: %s", err)
- }
- }
- }
- func getConfigStateHash(
- config *Config,
- p *parameters.ClientParametersSnapshot,
- serverEntry *protocol.ServerEntry) []byte {
- // The config state hash should reflect config, tactics, and server entry
- // settings that impact the dial parameters. The hash should change if any
- // of these input values change in a way that invalidates any stored dial
- // parameters.
- // MD5 hash is used solely as a data checksum and not for any security
- // purpose.
- hash := md5.New()
- // Add a hash of relevant config fields.
- // Limitation: the config hash may change even when tactics will override the
- // changed config field.
- hash.Write(config.dialParametersHash)
- // Add the active tactics tag.
- hash.Write([]byte(p.Tag()))
- // Add the server entry version and local timestamp, both of which should
- // change when the server entry contents change and/or a new local copy is
- // imported.
- // TODO: marshal entire server entry?
- var serverEntryConfigurationVersion [8]byte
- binary.BigEndian.PutUint64(
- serverEntryConfigurationVersion[:],
- uint64(serverEntry.ConfigurationVersion))
- hash.Write(serverEntryConfigurationVersion[:])
- hash.Write([]byte(serverEntry.LocalTimestamp))
- return hash.Sum(nil)
- }
- func selectFrontingParameters(serverEntry *protocol.ServerEntry) (string, string, error) {
- frontingDialHost := ""
- frontingHost := ""
- if len(serverEntry.MeekFrontingAddressesRegex) > 0 {
- // Generate a front address based on the regex.
- var err error
- frontingDialHost, err = regen.Generate(serverEntry.MeekFrontingAddressesRegex)
- if err != nil {
- return "", "", common.ContextError(err)
- }
- } else {
- // Randomly select, for this connection attempt, one front address for
- // fronting-capable servers.
- if len(serverEntry.MeekFrontingAddresses) == 0 {
- return "", "", common.ContextError(errors.New("MeekFrontingAddresses is empty"))
- }
- index := prng.Intn(len(serverEntry.MeekFrontingAddresses))
- frontingDialHost = serverEntry.MeekFrontingAddresses[index]
- }
- if len(serverEntry.MeekFrontingHosts) > 0 {
- index := prng.Intn(len(serverEntry.MeekFrontingHosts))
- frontingHost = serverEntry.MeekFrontingHosts[index]
- } else {
- // Backwards compatibility case
- frontingHost = serverEntry.MeekFrontingHost
- }
- return frontingDialHost, frontingHost, nil
- }
- func selectQUICVersion(allowObfuscatedQUIC bool, p *parameters.ClientParametersSnapshot) string {
- limitQUICVersions := p.QUICVersions(parameters.LimitQUICVersions)
- quicVersions := make([]string, 0)
- for _, quicVersion := range protocol.SupportedQUICVersions {
- if len(limitQUICVersions) > 0 &&
- !common.Contains(limitQUICVersions, quicVersion) {
- continue
- }
- if !allowObfuscatedQUIC &&
- protocol.QUICVersionIsObfuscated(quicVersion) {
- continue
- }
- quicVersions = append(quicVersions, quicVersion)
- }
- if len(quicVersions) == 0 {
- return ""
- }
- choice := prng.Intn(len(quicVersions))
- return quicVersions[choice]
- }
- func makeDialCustomHeaders(
- config *Config,
- p *parameters.ClientParametersSnapshot) http.Header {
- dialCustomHeaders := make(http.Header)
- if config.CustomHeaders != nil {
- for k, v := range config.CustomHeaders {
- dialCustomHeaders[k] = make([]string, len(v))
- copy(dialCustomHeaders[k], v)
- }
- }
- additionalCustomHeaders := p.HTTPHeaders(parameters.AdditionalCustomHeaders)
- if additionalCustomHeaders != nil {
- for k, v := range additionalCustomHeaders {
- dialCustomHeaders[k] = make([]string, len(v))
- copy(dialCustomHeaders[k], v)
- }
- }
- return dialCustomHeaders
- }
|