psiphon

package
v0.0.5-alpha Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 15, 2014 License: GPL-3.0 Imports: 38 Imported by: 0

Documentation

Overview

Package psiphon implements the core tunnel functionality of a Psiphon client. The main function is RunForever, which runs a Controller that obtains lists of servers, establishes tunnel connections, and runs local proxies through which tunneled traffic may be sent.

Package stats counts and keeps track of session stats. These are per-domain bytes transferred and total bytes transferred.

Index

Constants

View Source
const (
	VERSION                                  = "0.0.5"
	DATA_STORE_FILENAME                      = "psiphon.db"
	CONNECTION_WORKER_POOL_SIZE              = 10
	TUNNEL_POOL_SIZE                         = 1
	TUNNEL_CONNECT_TIMEOUT                   = 15 * time.Second
	TUNNEL_READ_TIMEOUT                      = 0 * time.Second
	TUNNEL_WRITE_TIMEOUT                     = 5 * time.Second
	TUNNEL_SSH_KEEP_ALIVE_PERIOD             = 60 * time.Second
	ESTABLISH_TUNNEL_TIMEOUT                 = 60 * time.Second
	ESTABLISH_TUNNEL_PAUSE_PERIOD            = 10 * time.Second
	PORT_FORWARD_FAILURE_THRESHOLD           = 10
	HTTP_PROXY_ORIGIN_SERVER_TIMEOUT         = 15 * time.Second
	HTTP_PROXY_MAX_IDLE_CONNECTIONS_PER_HOST = 50
	FETCH_REMOTE_SERVER_LIST_TIMEOUT         = 10 * time.Second
	FETCH_REMOTE_SERVER_LIST_RETRY_TIMEOUT   = 5 * time.Second
	FETCH_REMOTE_SERVER_LIST_STALE_TIMEOUT   = 6 * time.Hour
	PSIPHON_API_CLIENT_SESSION_ID_LENGTH     = 16
	PSIPHON_API_SERVER_TIMEOUT               = 20 * time.Second
)
View Source
const (
	MEEK_PROTOCOL_VERSION      = 2
	MEEK_COOKIE_MAX_PADDING    = 32
	MAX_SEND_PAYLOAD_LENGTH    = 65536
	FULL_RECEIVE_BUFFER_LENGTH = 4194304
	READ_PAYLOAD_CHUNK_LENGTH  = 65536
	MIN_POLL_INTERVAL          = 100 * time.Millisecond
	MAX_POLL_INTERVAL          = 5 * time.Second
	POLL_INTERNAL_MULTIPLIER   = 1.5
)
View Source
const (
	NOTICE_INFO            = "INFO"
	NOTICE_ALERT           = "ALERT"
	NOTICE_VERSION         = "VERSION"
	NOTICE_TUNNELS         = "TUNNELS"
	NOTICE_SOCKS_PROXY     = "SOCKS-PROXY"
	NOTICE_HTTP_PROXY      = "HTTP-PROXY"
	NOTICE_UPGRADE         = "UPGRADE"
	NOTICE_HOMEPAGE        = "HOMEPAGE"
	NOTICE_PAGE_VIEW_REGEX = "PAGE-VIEW-REGEX"
	NOTICE_HTTPS_REGEX     = "HTTPS-REGEX"
)
View Source
const (
	OBFUSCATION_READ_STATE_SERVER_IDENTIFICATION_LINE = iota
	OBFUSCATION_READ_STATE_SERVER_KEX_PACKETS
	OBFUSCATION_READ_STATE_FLUSH
	OBFUSCATION_READ_STATE_FINISHED
)
View Source
const (
	OBFUSCATION_WRITE_STATE_SEND_CLIENT_SEED_MESSAGE = iota
	OBFUSCATION_WRITE_STATE_CLIENT_IDENTIFICATION_LINE
	OBFUSCATION_WRITE_STATE_CLIENT_KEX_PACKETS
	OBFUSCATION_WRITE_STATE_FINISHED
)
View Source
const (
	SSH_MAX_SERVER_LINE_LENGTH = 1024
	SSH_PACKET_PREFIX_LENGTH   = 5          // uint32 + byte
	SSH_MAX_PACKET_LENGTH      = 256 * 1024 // OpenSSH max packet length
	SSH_MSG_NEWKEYS            = 21
	SSH_MAX_PADDING_LENGTH     = 255 // RFC 4253 sec. 6
	SSH_PADDING_MULTIPLE       = 16  // Default cipher block size
)
View Source
const (
	OBFUSCATE_SEED_LENGTH         = 16
	OBFUSCATE_KEY_LENGTH          = 16
	OBFUSCATE_HASH_ITERATIONS     = 6000
	OBFUSCATE_MAX_PADDING         = 8192
	OBFUSCATE_MAGIC_VALUE         = 0x0BF5CA7E
	OBFUSCATE_CLIENT_TO_SERVER_IV = "client_to_server"
	OBFUSCATE_SERVER_TO_CLIENT_IV = "server_to_client"
)
View Source
const (
	TUNNEL_PROTOCOL_SSH            = "SSH"
	TUNNEL_PROTOCOL_OBFUSCATED_SSH = "OSSH"
	TUNNEL_PROTOCOL_UNFRONTED_MEEK = "UNFRONTED-MEEK-OSSH"
	TUNNEL_PROTOCOL_FRONTED_MEEK   = "FRONTED-MEEK-OSSH"
)
View Source
const DNS_PORT = 53

Variables

This is a list of supported tunnel protocols, in default preference order

Functions

func Contains

func Contains(list []string, target string) bool

Contains is a helper function that returns true if the target string is in the list.

func ContextError

func ContextError(err error) error

ContextError prefixes an error message with the current function name

func CustomTLSDial

func CustomTLSDial(network, addr string, config *CustomTLSConfig) (*tls.Conn, error)

CustomTLSDialWithDialer is a customized replacement for tls.Dial. Based on tlsdialer.DialWithDialer which is based on crypto/tls.DialWithDialer.

tlsdialer comment:

Note - if sendServerName is false, the VerifiedChains field on the
connection's ConnectionState will never get populated.

func DecodeCertificate

func DecodeCertificate(encodedCertificate string) (certificate *x509.Certificate, err error)

func FetchRemoteServerList

func FetchRemoteServerList(config *Config, pendingConns *Conns) (err error)

FetchRemoteServerList downloads a remote server list JSON record from config.RemoteServerListUrl; validates its digital signature using the public key config.RemoteServerListSignaturePublicKey; and parses the data field into ServerEntry records.

func GetForServer

func GetForServer(serverID string) (payload *serverStats)

GetForServer returns the json-able stats package for the given server. If there are no stats, nil will be returned.

func GetKeyValue

func GetKeyValue(key string) (value string, err error)

GetKeyValue retrieves the value for a given key. If not found, it returns an empty string value.

func GetServerEntryIpAddresses

func GetServerEntryIpAddresses() (ipAddresses []string, err error)

GetServerEntryIpAddresses returns an array containing all stored server IP addresses.

func HasServerEntries

func HasServerEntries(region, protocol string) bool

HasServerEntries returns true if the data store contains at least one server entry (for the specified region and/or protocol, when not blank).

func HttpProxyConnect

func HttpProxyConnect(rawConn net.Conn, addr string) (err error)

HttpProxyConnect establishes a HTTP CONNECT tunnel to addr through an established network connection to an HTTP proxy. It is assumed that no payload bytes have been sent through the connection to the proxy.

func InitDataStore

func InitDataStore(config *Config) (err error)

InitDataStore initializes the singleton instance of dataStore. This function uses a sync.Once and is safe for use by concurrent goroutines. The underlying sql.DB connection pool is also safe.

Note: the sync.Once was more useful when initDataStore was private and called on-demand by the public functions below. Now we require an explicit InitDataStore() call with the filename passed in. The on-demand calls have been replaced by checkInitDataStore() to assert that Init was called.

func LookupIP

func LookupIP(host string, config *DialConfig) (addrs []net.IP, err error)

LookupIP resolves a hostname. When BindToDevice is not required, it simply uses net.LookuIP. When BindToDevice is required, LookupIP explicitly creates a UDP socket, binds it to the device, and makes an explicit DNS request to the specified DNS resolver.

func MakeSecureRandomBytes

func MakeSecureRandomBytes(length int) ([]byte, error)

MakeSecureRandomBytes is a helper function that wraps crypto/rand.Read.

func MakeSecureRandomInt

func MakeSecureRandomInt(max int) (int, error)

MakeSecureRandomInt is a helper function that wraps crypto/rand.Int, which returns a uniform random value in [0, max).

func MakeSessionId

func MakeSessionId() (id string, err error)

func NextSendPeriod

func NextSendPeriod() (duration time.Duration)

NextSendPeriod returns the amount of time that should be waited before the next time stats are sent.

func Notice

func Notice(prefix, format string, args ...interface{})

func PromoteServerEntry

func PromoteServerEntry(ipAddress string) error

PromoteServerEntry assigns the top rank (one more than current max rank) to the specified server entry. Server candidates are iterated in decending rank order, so this server entry will be the first candidate in a subsequent tunnel establishment.

func PutBack

func PutBack(serverID string, ss *serverStats)

PutBack re-adds a set of server stats to the collection.

func Relay

func Relay(localConn, remoteConn net.Conn)

Relay sends to remoteConn bytes received from localConn, and sends to localConn bytes received from remoteConn.

func SetKeyValue

func SetKeyValue(key, value string) error

SetKeyValue stores a key/value pair.

func Stats_Start

func Stats_Start()

Start initializes and begins stats collection. Must be called once, when the application starts.

func Stats_Stop

func Stats_Stop()

Stop ends stats collection. Must be called once, before the application terminates.

func StoreServerEntry

func StoreServerEntry(serverEntry *ServerEntry, replaceIfExists bool) error

StoreServerEntry adds the server entry to the data store. A newly stored (or re-stored) server entry is assigned the next-to-top rank for iteration order (the previous top ranked entry is promoted). The purpose of inserting at next-to-top is to keep the last selected server as the top ranked server. Note, server candidates are iterated in decending rank order, so the largest rank is top rank. When replaceIfExists is true, an existing server entry record is overwritten; otherwise, the existing record is unchanged.

func TrimError

func TrimError(err error) error

TrimError removes the middle of over-long error message strings

Types

type Config

type Config struct {
	LogFilename                        string
	DataStoreDirectory                 string
	DataStoreTempDirectory             string
	PropagationChannelId               string
	SponsorId                          string
	RemoteServerListUrl                string
	RemoteServerListSignaturePublicKey string
	ClientVersion                      int
	ClientPlatform                     string
	TunnelWholeDevice                  int
	EgressRegion                       string
	TunnelProtocol                     string
	LocalSocksProxyPort                int
	LocalHttpProxyPort                 int
	ConnectionWorkerPoolSize           int
	TunnelPoolSize                     int
	PortForwardFailureThreshold        int
	UpstreamHttpProxyAddress           string
	BindToDeviceProvider               DeviceBinder
	BindToDeviceDnsServer              string
}

func LoadConfig

func LoadConfig(configJson []byte) (*Config, error)

LoadConfig parses and validates a JSON format Psiphon config JSON string and returns a Config struct populated with config values.

type Conn

type Conn interface {
	net.Conn

	// SetClosedSignal sets the channel which will be signaled
	// when the connection is closed. This function returns an error
	// if the connection is already closed (and would never send
	// the signal). SetClosedSignal and Close may be called by
	// concurrent goroutines.
	SetClosedSignal(closedSignal chan struct{}) (err error)
}

Conn is a net.Conn which supports sending a signal to a channel when it is closed. In Psiphon, this interface is implemented by tunnel connection types (DirectConn and MeekConn) and the close signal is used as one trigger for tearing down the tunnel.

type Conns

type Conns struct {
	// contains filtered or unexported fields
}

Conns is a synchronized list of Conns that is used to coordinate interrupting a set of goroutines establishing connections, or close a set of open connections, etc.

func (*Conns) Add

func (conns *Conns) Add(conn net.Conn)

func (*Conns) CloseAll

func (conns *Conns) CloseAll()

func (*Conns) Remove

func (conns *Conns) Remove(conn net.Conn)

type Controller

type Controller struct {
	// contains filtered or unexported fields
}

Controller is a tunnel lifecycle coordinator. It manages lists of servers to connect to; establishes and monitors tunnels; and runs local proxies which route traffic through the tunnels.

func NewController

func NewController(config *Config) (controller *Controller)

NewController initializes a new controller.

func (*Controller) Dial

func (controller *Controller) Dial(remoteAddr string) (conn net.Conn, err error)

Dial selects an active tunnel and establishes a port forward connection through the selected tunnel. Failure to connect is considered a port foward failure, for the purpose of monitoring tunnel health.

func (*Controller) Run

func (controller *Controller) Run(shutdownBroadcast <-chan struct{})

Run executes the controller. It launches components and then monitors for a shutdown signal; after receiving the signal it shuts down the controller. The components include: - the periodic remote server list fetcher - the tunnel manager - a local SOCKS proxy that port forwards through the pool of tunnels - a local HTTP proxy that port forwards through the pool of tunnels

func (*Controller) SignalFailure

func (controller *Controller) SignalFailure()

SignalFailure notifies the controller that an associated component has failed. This will terminate the controller.

type CustomTLSConfig

type CustomTLSConfig struct {

	// Dial is the network connection dialer. TLS is layered on
	// top of a new network connection created with dialer.
	Dial Dialer

	// Timeout is and optional timeout for combined network
	// connection dial and TLS handshake.
	Timeout time.Duration

	// FrontingAddr overrides the "addr" input to Dial when specified
	FrontingAddr string

	// SendServerName specifies whether to use SNI
	// (tlsdialer functionality)
	SendServerName bool

	// VerifyLegacyCertificate is a special case self-signed server
	// certificate case. Ignores IP SANs and basic constraints. No
	// certificate chain. Just checks that the server presented the
	// specified certificate.
	VerifyLegacyCertificate *x509.Certificate

	// TlsConfig is a tls.Config to use in the
	// non-verifyLegacyCertificate case.
	TlsConfig *tls.Config
}

CustomTLSConfig contains parameters to determine the behavior of CustomTLSDial.

type DeviceBinder

type DeviceBinder interface {
	// TODO: return 'error'; currently no return value due to
	// Android Library limitation.
	BindToDevice(fileDescriptor int)
}

DeviceBinder defines the interface to the external BindToDevice provider

type DialConfig

type DialConfig struct {

	// UpstreamHttpProxyAddress specifies an HTTP proxy to connect through
	// (the proxy must support HTTP CONNECT). The address may be a hostname
	// or IP address and must include a port number.
	UpstreamHttpProxyAddress string

	ConnectTimeout time.Duration
	ReadTimeout    time.Duration
	WriteTimeout   time.Duration

	// PendingConns is used to interrupt dials in progress.
	// The dial may be interrupted using PendingConns.CloseAll(): on platforms
	// that support this, the new conn is added to pendingConns before the network
	// connect begins and removed from pendingConns once the connect succeeds or fails.
	PendingConns *Conns

	// BindToDevice parameters are used to exclude connections and
	// associated DNS requests from VPN routing.
	// When BindToDeviceProvider is set, any underlying socket is
	// submitted to the device binding servicebefore connecting.
	// The service should bind the socket to a device so that it doesn't route
	// through a VPN interface. This service is also used to bind UDP sockets used
	// for DNS requests, in which case BindToDeviceDnsServer is used as the
	// DNS server.
	BindToDeviceProvider  DeviceBinder
	BindToDeviceDnsServer string
}

DialConfig contains parameters to determine the behavior of a Psiphon dialer (TCPDial, MeekDial, etc.)

type Dialer

type Dialer func(string, string) (net.Conn, error)

Dialer is a custom dialer compatible with http.Transport.Dial.

func NewCustomTLSDialer

func NewCustomTLSDialer(config *CustomTLSConfig) Dialer

func NewTCPDialer

func NewTCPDialer(config *DialConfig) Dialer

NewTCPDialer creates a TCPDialer.

type ExtraParam

type ExtraParam struct {
	// contains filtered or unexported fields
}

type HttpProxy

type HttpProxy struct {
	// contains filtered or unexported fields
}

HttpProxy is a HTTP server that relays HTTP requests through the tunnel SSH client.

func NewHttpProxy

func NewHttpProxy(config *Config, tunneler Tunneler) (proxy *HttpProxy, err error)

NewHttpProxy initializes and runs a new HTTP proxy server.

func (*HttpProxy) Close

func (proxy *HttpProxy) Close()

Close terminates the HTTP server.

func (*HttpProxy) ServeHTTP

func (proxy *HttpProxy) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request)

ServeHTTP receives HTTP requests and proxies them. CONNECT requests are hijacked and all data is relayed. Other HTTP requests are proxied with explicit round trips. In both cases, the tunnel is used for proxied traffic.

Implementation is based on:

https://github.com/justmao945/mallory Copyright (c) 2014 JianjunMao The MIT License (MIT)

https://golang.org/src/pkg/net/http/httputil/reverseproxy.go Copyright 2011 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

type MeekConn

type MeekConn struct {
	// contains filtered or unexported fields
}

MeekConn is a network connection that tunnels TCP over HTTP and supports "fronting". Meek sends client->server flow in HTTP request bodies and receives server->client flow in HTTP response bodies. Polling is used to achieve full duplex TCP.

Fronting is an obfuscation technique in which the connection to a web server, typically a CDN, is indistinguishable from any other HTTPS connection to the generic "fronting domain" -- the HTTP Host header is used to route the requests to the actual destination. See https://trac.torproject.org/projects/tor/wiki/doc/meek for more details.

MeekConn also operates in unfronted mode, in which plain HTTP connections are made without routing through a CDN.

func DialMeek

func DialMeek(
	serverEntry *ServerEntry, sessionId string,
	useFronting bool, config *DialConfig) (meek *MeekConn, err error)

DialMeek returns an initialized meek connection. A meek connection is an HTTP session which does not depend on an underlying socket connection (although persistent HTTP connections are used for performance). This function does not wait for the connection to be "established" before returning. A goroutine is spawned which will eventually start HTTP polling. useFronting assumes caller has already checked server entry capabilities.

func (*MeekConn) Close

func (meek *MeekConn) Close() (err error)

Close terminates the meek connection. Close waits for the relay processing goroutine to stop and releases HTTP transport resources. A mutex is required to support psiphon.Conn.SetClosedSignal concurrency semantics.

func (*MeekConn) LocalAddr

func (meek *MeekConn) LocalAddr() net.Addr

Stub implementation of net.Conn.LocalAddr

func (*MeekConn) Read

func (meek *MeekConn) Read(buffer []byte) (n int, err error)

Read reads data from the connection. net.Conn Deadlines are ignored. net.Conn concurrency semantics are supported.

func (*MeekConn) RemoteAddr

func (meek *MeekConn) RemoteAddr() net.Addr

Stub implementation of net.Conn.RemoteAddr

func (*MeekConn) SetClosedSignal

func (meek *MeekConn) SetClosedSignal(closedSignal chan struct{}) (err error)

SetClosedSignal implements psiphon.Conn.SetClosedSignal

func (*MeekConn) SetDeadline

func (meek *MeekConn) SetDeadline(t time.Time) error

Stub implementation of net.Conn.SetDeadline

func (*MeekConn) SetReadDeadline

func (meek *MeekConn) SetReadDeadline(t time.Time) error

Stub implementation of net.Conn.SetReadDeadline

func (*MeekConn) SetWriteDeadline

func (meek *MeekConn) SetWriteDeadline(t time.Time) error

Stub implementation of net.Conn.SetWriteDeadline

func (*MeekConn) Write

func (meek *MeekConn) Write(buffer []byte) (n int, err error)

Write writes data to the connection. net.Conn Deadlines are ignored. net.Conn concurrency semantics are supported.

type ObfuscatedSshConn

type ObfuscatedSshConn struct {
	net.Conn
	// contains filtered or unexported fields
}

ObfuscatedSshConn wraps a Conn and applies the obfuscated SSH protocol to the traffic on the connection: https://github.com/brl/obfuscated-openssh/blob/master/README.obfuscation ObfuscatedSshConn is used to add obfuscation to go's stock ssh client without modification to that standard library code. The underlying connection must be used for SSH client traffic. This code injects the obfuscated seed message, applies obfuscated stream cipher transformations, and performs minimal parsing of the SSH protocol to determine when to stop obfuscation (after the first SSH_MSG_NEWKEYS is sent by the client and received from the server).

WARNING: doesn't fully conform to net.Conn concurrency semantics: there's no synchronization of access to the read/writeBuffers, so concurrent calls to one of Read or Write will result in undefined behavior.

func NewObfuscatedSshConn

func NewObfuscatedSshConn(conn net.Conn, obfuscationKeyword string) (*ObfuscatedSshConn, error)

NewObfuscatedSshConn creates a new ObfuscatedSshConn. The underlying conn must be used for SSH client traffic and must have transferred no traffic.

func (*ObfuscatedSshConn) Read

func (conn *ObfuscatedSshConn) Read(buffer []byte) (n int, err error)

Read wraps standard Read, transparently applying the obfusation transformations.

func (*ObfuscatedSshConn) Write

func (conn *ObfuscatedSshConn) Write(buffer []byte) (n int, err error)

Write wraps standard Write, transparently applying the obfuscation transformations.

type ObfuscatedSshReadState

type ObfuscatedSshReadState int

type ObfuscatedSshWriteState

type ObfuscatedSshWriteState int

type Obfuscator

type Obfuscator struct {
	// contains filtered or unexported fields
}

Obfuscator implements the seed message, key derivation, and stream ciphers for: https://github.com/brl/obfuscated-openssh/blob/master/README.obfuscation

func NewObfuscator

func NewObfuscator(config *ObfuscatorConfig) (obfuscator *Obfuscator, err error)

NewObfuscator creates a new Obfuscator, initializes it with a seed message, derives client and server keys, and creates RC4 stream ciphers to obfuscate data.

func (*Obfuscator) ConsumeSeedMessage

func (obfuscator *Obfuscator) ConsumeSeedMessage() []byte

ConsumeSeedMessage returns the seed message created in NewObfuscator, removing the reference so that it may be garbage collected.

func (*Obfuscator) ObfuscateClientToServer

func (obfuscator *Obfuscator) ObfuscateClientToServer(buffer []byte)

ObfuscateClientToServer applies the client RC4 stream to the bytes in buffer.

func (*Obfuscator) ObfuscateServerToClient

func (obfuscator *Obfuscator) ObfuscateServerToClient(buffer []byte)

ObfuscateServerToClient applies the server RC4 stream to the bytes in buffer.

type ObfuscatorConfig

type ObfuscatorConfig struct {
	Keyword    string
	MaxPadding int
}

type Regexps

type Regexps []regexpReplace

Regexps holds the regular expressions and replacement strings used for transforming URLs and hostnames into a stats-appropriate forms.

func MakeRegexps

func MakeRegexps(pageViewRegexes, httpsRequestRegexes []map[string]string) *Regexps

MakeRegexps takes the raw string-map form of the regex-replace pairs returned by the server handshake and turns them into a usable object.

type RemoteServerList

type RemoteServerList struct {
	Data                   string `json:"data"`
	SigningPublicKeyDigest string `json:"signingPublicKeyDigest"`
	Signature              string `json:"signature"`
}

RemoteServerList is a JSON record containing a list of Psiphon server entries. As it may be downloaded from various sources, it is digitally signed so that the data may be authenticated.

type ServerEntry

type ServerEntry struct {
	IpAddress                     string   `json:"ipAddress"`
	WebServerPort                 string   `json:"webServerPort"` // not an int
	WebServerSecret               string   `json:"webServerSecret"`
	WebServerCertificate          string   `json:"webServerCertificate"`
	SshPort                       int      `json:"sshPort"`
	SshUsername                   string   `json:"sshUsername"`
	SshPassword                   string   `json:"sshPassword"`
	SshHostKey                    string   `json:"sshHostKey"`
	SshObfuscatedPort             int      `json:"sshObfuscatedPort"`
	SshObfuscatedKey              string   `json:"sshObfuscatedKey"`
	Capabilities                  []string `json:"capabilities"`
	Region                        string   `json:"region"`
	MeekServerPort                int      `json:"meekServerPort"`
	MeekCookieEncryptionPublicKey string   `json:"meekCookieEncryptionPublicKey"`
	MeekObfuscatedKey             string   `json:"meekObfuscatedKey"`
	MeekFrontingDomain            string   `json:"meekFrontingDomain"`
	MeekFrontingHost              string   `json:"meekFrontingHost"`
}

ServerEntry represents a Psiphon server. It contains information about how to estalish a tunnel connection to the server through several protocols. ServerEntry are JSON records downloaded from various sources.

func DecodeServerEntry

func DecodeServerEntry(encodedServerEntry string) (serverEntry *ServerEntry, err error)

DecodeServerEntry extracts server entries from the encoding used by remote server lists and Psiphon server handshake requests.

type ServerEntryIterator

type ServerEntryIterator struct {
	// contains filtered or unexported fields
}

ServerEntryIterator is used to iterate over stored server entries in rank order.

func NewServerEntryIterator

func NewServerEntryIterator(region, protocol string) (iterator *ServerEntryIterator, err error)

NewServerEntryIterator creates a new NewServerEntryIterator

func (*ServerEntryIterator) Close

func (iterator *ServerEntryIterator) Close()

Close cleans up resources associated with a ServerEntryIterator.

func (*ServerEntryIterator) Next

func (iterator *ServerEntryIterator) Next() (serverEntry *ServerEntry, err error)

Next returns the next server entry, by rank, for a ServerEntryIterator. Returns nil with no error when there is no next item.

func (*ServerEntryIterator) Reset

func (iterator *ServerEntryIterator) Reset() error

Reset a NewServerEntryIterator to the start of its cycle. The next call to Next will return the first server entry.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session is a utility struct which holds all of the data associated with a Psiphon session. In addition to the established tunnel, this includes the session ID (used for Psiphon API requests) and a http client configured to make tunneled Psiphon API requests.

func NewSession

func NewSession(config *Config, tunnel *Tunnel) (session *Session, err error)

NewSession makes tunnelled handshake and connected requests to the Psiphon server and returns a Session struct, initialized with the session ID, for use with subsequent Psiphon server API requests (e.g., periodic status requests).

func (*Session) DoStatusRequest

func (session *Session) DoStatusRequest(statsPayload json.Marshaler, final bool) error

DoStatusRequest makes a /status request to the server, sending session stats. final should be true if this is the last such request before disconnecting.

type SocksProxy

type SocksProxy struct {
	// contains filtered or unexported fields
}

SocksProxy is a SOCKS server that accepts local host connections and, for each connection, establishes a port forward through the tunnel SSH client and relays traffic through the port forward.

func NewSocksProxy

func NewSocksProxy(config *Config, tunneler Tunneler) (proxy *SocksProxy, err error)

NewSocksProxy initializes a new SOCKS server. It begins listening for connections, starts a goroutine that runs an accept loop, and returns leaving the accept loop running.

func (*SocksProxy) Close

func (proxy *SocksProxy) Close()

Close terminates the listener and waits for the accept loop goroutine to complete.

type StatsConn

type StatsConn struct {
	net.Conn
	// contains filtered or unexported fields
}

StatsConn is to be used as an intermediate link in a chain of net.Conn objects. It inspects requests and responses and derives stats from them.

func NewStatsConn

func NewStatsConn(nextConn net.Conn, serverID string, regexps *Regexps) *StatsConn

NewStatsConn creates a StatsConn. serverID can be anything that uniquely identifies the server; it will be passed to GetForServer() when retrieving the accumulated stats.

func (*StatsConn) Read

func (conn *StatsConn) Read(buffer []byte) (n int, err error)

Read is called when responses to requests are being read from the remote server.

func (*StatsConn) Write

func (conn *StatsConn) Write(buffer []byte) (n int, err error)

Write is called when requests are being written out through the tunnel to the remote server.

type TCPConn

type TCPConn struct {
	net.Conn
	// contains filtered or unexported fields
}

TCPConn is a customized TCP connection that:

  • can be interrupted while connecting;
  • implements idle read/write timeouts;
  • can be bound to a specific system device (for Android VpnService routing compatibility, for example).
  • implements the psiphon.Conn interface

func DialTCP

func DialTCP(addr string, config *DialConfig) (conn *TCPConn, err error)

TCPConn creates a new, connected TCPConn.

func (*TCPConn) Close

func (conn *TCPConn) Close() (err error)

Close terminates a connected (net.Conn) or connecting (socketFd) TCPConn. A mutex is required to support psiphon.Conn.SetClosedSignal concurrency semantics.

func (*TCPConn) Read

func (conn *TCPConn) Read(buffer []byte) (n int, err error)

Read wraps standard Read to add an idle timeout. The connection is explicitly closed on timeout.

func (*TCPConn) SetClosedSignal

func (conn *TCPConn) SetClosedSignal(closedSignal chan struct{}) (err error)

SetClosedSignal implements psiphon.Conn.SetClosedSignal

func (*TCPConn) SetDeadline

func (conn *TCPConn) SetDeadline(t time.Time) error

Override implementation of net.Conn.SetDeadline

func (*TCPConn) SetReadDeadline

func (conn *TCPConn) SetReadDeadline(t time.Time) error

Override implementation of net.Conn.SetReadDeadline

func (*TCPConn) SetWriteDeadline

func (conn *TCPConn) SetWriteDeadline(t time.Time) error

Override implementation of net.Conn.SetWriteDeadline

func (*TCPConn) Write

func (conn *TCPConn) Write(buffer []byte) (n int, err error)

Write wraps standard Write to add an idle timeout The connection is explicitly closed on timeout.

type Tunnel

type Tunnel struct {
	// contains filtered or unexported fields
}

Tunnel is a connection to a Psiphon server. An established tunnel includes a network connection to the specified server and an SSH session built on top of that transport.

func EstablishTunnel

func EstablishTunnel(
	config *Config, pendingConns *Conns, serverEntry *ServerEntry) (tunnel *Tunnel, err error)

EstablishTunnel first makes a network transport connection to the Psiphon server and then establishes an SSH client session on top of that transport. The SSH server is authenticated using the public key in the server entry. Depending on the server's capabilities, the connection may use plain SSH over TCP, obfuscated SSH over TCP, or obfuscated SSH over HTTP (meek protocol). When requiredProtocol is not blank, that protocol is used. Otherwise, the first protocol in SupportedTunnelProtocols that's also in the server capabilities is used.

func (*Tunnel) Close

func (tunnel *Tunnel) Close()

Close terminates the tunnel.

func (*Tunnel) Dial

func (tunnel *Tunnel) Dial(remoteAddr string) (conn net.Conn, err error)

Dial establishes a port forward connection through the tunnel

func (*Tunnel) IsSessionStarted

func (tunnel *Tunnel) IsSessionStarted() bool

func (*Tunnel) ServerID

func (tunnel *Tunnel) ServerID() string

ServerID provides a unique identifier for the server the tunnel connects to. This ID is consistent between multiple tunnels connected to that server.

func (*Tunnel) SetSessionStarted

func (tunnel *Tunnel) SetSessionStarted()

func (*Tunnel) SetStatsRegexps

func (tunnel *Tunnel) SetStatsRegexps(regexps *Regexps)

SetStatsRegexps sets the Regexps used for the statistics for this tunnel.

func (*Tunnel) SignalFailure

func (tunnel *Tunnel) SignalFailure()

SignalFailure notifies the tunnel that an associated component has failed. This will terminate the tunnel.

func (*Tunnel) StatsRegexps

func (tunnel *Tunnel) StatsRegexps() *Regexps

StatsRegexps gets the Regexps used for the statistics for this tunnel.

type TunneledConn

type TunneledConn struct {
	net.Conn
	// contains filtered or unexported fields
}

TunneledConn implements net.Conn and wraps a port foward connection. It is used to hook into Read and Write to observe I/O errors and report these errors back to the tunnel monitor as port forward failures.

func (*TunneledConn) Read

func (conn *TunneledConn) Read(buffer []byte) (n int, err error)

func (*TunneledConn) Write

func (conn *TunneledConn) Write(buffer []byte) (n int, err error)

type Tunneler

type Tunneler interface {
	Dial(remoteAddr string) (conn net.Conn, err error)
	SignalFailure()
}

Tunneler specifies the interface required by components that use a tunnel. Components which use this interface may be serviced by a single Tunnel instance, or a Controller which manages a pool of tunnels, or any other object which implements Tunneler.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL