common

package
v0.0.14-beta-ios Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2017 License: GPL-3.0 Imports: 31 Imported by: 285

Documentation

Index

Constants

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 (
	OBFUSCATION_CONN_MODE_CLIENT = iota
	OBFUSCATION_CONN_MODE_SERVER
)
View Source
const (
	OBFUSCATION_READ_STATE_IDENTIFICATION_LINES = iota
	OBFUSCATION_READ_STATE_KEX_PACKETS
	OBFUSCATION_READ_STATE_FLUSH
	OBFUSCATION_READ_STATE_FINISHED
)
View Source
const (
	OBFUSCATION_WRITE_STATE_CLIENT_SEND_SEED_MESSAGE = iota
	OBFUSCATION_WRITE_STATE_SERVER_SEND_IDENTIFICATION_LINE_PADDING
	OBFUSCATION_WRITE_STATE_IDENTIFICATION_LINE
	OBFUSCATION_WRITE_STATE_KEX_PACKETS
	OBFUSCATION_WRITE_STATE_FINISHED
)
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"
)

Variables

This section is empty.

Functions

func Compress

func Compress(data []byte) []byte

Compress returns zlib compressed data

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 and source file line number.

func Decompress

func Decompress(data []byte) ([]byte, error)

Decompress returns zlib decompressed data

func FlipCoin

func FlipCoin() bool

FlipCoin is a helper function that randomly returns true or false. If the underlying random number generator fails, FlipCoin still returns a result.

func GenerateAuthenticatedDataPackageKeys

func GenerateAuthenticatedDataPackageKeys() (string, string, error)

GenerateAuthenticatedDataPackageKeys generates a key pair be used to sign and verify AuthenticatedDataPackages.

func GenerateHostName

func GenerateHostName() string

func GetCurrentTimestamp

func GetCurrentTimestamp() string

GetCurrentTimestamp returns the current time in UTC as an RFC 3339 formatted string.

func GetInterfaceIPAddress

func GetInterfaceIPAddress(listenInterface string) (string, error)

Take in an interface name ("lo", "eth0", "any") passed from either a config setting, by using the -listenInterface flag on client or -interface flag on server from the command line and return the IP address associated with it. If no interface is provided use the default loopback interface (127.0.0.1). If "any" is passed then listen on 0.0.0.0 for client (invalid with server)

func GetParentContext

func GetParentContext() string

GetParentContext returns the parent function name and source file line number.

func IPAddressFromAddr

func IPAddressFromAddr(addr net.Addr) string

IPAddressFromAddr is a helper which extracts an IP address from a net.Addr or returns "" if there is no IP address.

func Jitter

func Jitter(n int64, factor float64) int64

Jitter returns n +/- the given factor. For example, for n = 100 and factor = 0.1, the return value will be in the range [90, 110].

func JitterDuration

func JitterDuration(
	d time.Duration, factor float64) time.Duration

JitterDuration is a helper function that wraps Jitter.

func MakeRandomPeriod

func MakeRandomPeriod(min, max time.Duration) (time.Duration, error)

MakeRandomPeriod returns a random duration, within a given range. In the unlikely case where an underlying MakeRandom functions fails, the period is the minimum.

func MakeRandomStringBase64

func MakeRandomStringBase64(byteLength int) (string, error)

MakeRandomStringBase64 returns a base64 encoded random string. byteLength specifies the pre-encoded data length.

func MakeRandomStringHex

func MakeRandomStringHex(byteLength int) (string, error)

MakeRandomStringHex returns a hex encoded random string. byteLength specifies the pre-encoded data length.

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 MakeSecureRandomInt64.

func MakeSecureRandomInt64

func MakeSecureRandomInt64(max int64) (int64, error)

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

func MakeSecureRandomPadding

func MakeSecureRandomPadding(minLength, maxLength int) ([]byte, error)

MakeSecureRandomPadding selects a random padding length in the indicated range and returns a random byte array of the selected length. In the unlikely case where an underlying MakeRandom functions fails, the padding is length 0.

func ReadAuthenticatedDataPackage

func ReadAuthenticatedDataPackage(
	packageJSON []byte, signingPublicKey string) (string, error)

ReadAuthenticatedDataPackage extracts and verifies authenticated data from an AuthenticatedDataPackage. The package must have been signed with the given key.

func RegisterHostNameGenerator

func RegisterHostNameGenerator(generator func() string)

func TruncateTimestampToHour

func TruncateTimestampToHour(timestamp string) string

TruncateTimestampToHour truncates an RFC 3339 formatted string to hour granularity. If the input is not a valid format, the result is "".

func WriteAuthenticatedDataPackage

func WriteAuthenticatedDataPackage(
	data string, signingPublicKey, signingPrivateKey string) ([]byte, error)

WriteAuthenticatedDataPackage creates an AuthenticatedDataPackage containing the specified data and signed by the given key. The output conforms with the legacy format here: https://bitbucket.org/psiphon/psiphon-circumvention-system/src/c25d080f6827b141fe637050ce0d5bd0ae2e9db5/Automation/psi_ops_crypto_tools.py

Types

type ActivityMonitoredConn

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

ActivityMonitoredConn wraps a net.Conn, adding logic to deal with events triggered by I/O activity.

When an inactivity timeout is specified, the network I/O will timeout after the specified period of read inactivity. Optionally, for the purpose of inactivity only, ActivityMonitoredConn will also consider the connection active when data is written to it.

When a LRUConnsEntry is specified, then the LRU entry is promoted on either a successful read or write.

When an ActivityUpdater is set, then its UpdateActivity method is called on each read and write with the number of bytes transferred. The durationNanoseconds, which is the time since the last read, is reported only on reads.

func NewActivityMonitoredConn

func NewActivityMonitoredConn(
	conn net.Conn,
	inactivityTimeout time.Duration,
	activeOnWrite bool,
	activityUpdater ActivityUpdater,
	lruEntry *LRUConnsEntry) (*ActivityMonitoredConn, error)

NewActivityMonitoredConn creates a new ActivityMonitoredConn.

func (*ActivityMonitoredConn) GetActiveDuration

func (conn *ActivityMonitoredConn) GetActiveDuration() time.Duration

GetActiveDuration returns the time elapsed between the initialization of the ActivityMonitoredConn and the last Read. Only reads are used for this calculation since writes may succeed locally due to buffering.

func (*ActivityMonitoredConn) GetLastActivityMonotime

func (conn *ActivityMonitoredConn) GetLastActivityMonotime() monotime.Time

GetLastActivityTime returns the arbitrary monotonic time of the last Read.

func (*ActivityMonitoredConn) GetStartTime

func (conn *ActivityMonitoredConn) GetStartTime() time.Time

GetStartTime gets the time when the ActivityMonitoredConn was initialized. Reported time is UTC.

func (*ActivityMonitoredConn) IsClosed

func (conn *ActivityMonitoredConn) IsClosed() bool

IsClosed implements the Closer iterface. The return value indicates whether the underlying conn has been closed.

func (*ActivityMonitoredConn) Read

func (conn *ActivityMonitoredConn) Read(buffer []byte) (int, error)

func (*ActivityMonitoredConn) Write

func (conn *ActivityMonitoredConn) Write(buffer []byte) (int, error)

type ActivityUpdater

type ActivityUpdater interface {
	UpdateProgress(bytesRead, bytesWritten int64, durationNanoseconds int64)
}

ActivityUpdater defines an interface for receiving updates for ActivityMonitoredConn activity. Values passed to UpdateProgress are bytes transferred and conn duration since the previous UpdateProgress.

type AuthenticatedDataPackage

type AuthenticatedDataPackage struct {
	Data                   string `json:"data"`
	SigningPublicKeyDigest []byte `json:"signingPublicKeyDigest"`
	Signature              []byte `json:"signature"`
}

AuthenticatedDataPackage is a JSON record containing some Psiphon data payload, such as 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 BuildInfo

type BuildInfo struct {
	BuildDate       string          `json:"buildDate"`
	BuildRepo       string          `json:"buildRepo"`
	BuildRev        string          `json:"buildRev"`
	GoVersion       string          `json:"goVersion"`
	GomobileVersion string          `json:"gomobileVersion,omitempty"`
	Dependencies    json.RawMessage `json:"dependencies"`
}

Capture relevant build information here for use in clients or servers

func GetBuildInfo

func GetBuildInfo() *BuildInfo

Return an instance of the BuildInfo struct

func (*BuildInfo) ToMap

func (bi *BuildInfo) ToMap() *map[string]interface{}

Convert 'BuildInfo' struct to 'map[string]interface{}'

type Closer

type Closer interface {
	IsClosed() bool
}

Closer defines the interface to a type, typically a net.Conn, that can be closed.

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. Once the list is closed, no more items may be added to the list (unless it is reset).

func (*Conns) Add

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

func (*Conns) CloseAll

func (conns *Conns) CloseAll()

func (*Conns) Remove

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

func (*Conns) Reset

func (conns *Conns) Reset()

type LRUConns

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

LRUConns is a concurrency-safe list of net.Conns ordered by recent activity. Its purpose is to facilitate closing the oldest connection in a set of connections.

New connections added are referenced by a LRUConnsEntry, which is used to Touch() active connections, which promotes them to the front of the order and to Remove() connections that are no longer LRU candidates.

CloseOldest() will remove the oldest connection from the list and call net.Conn.Close() on the connection.

After an entry has been removed, LRUConnsEntry Touch() and Remove() will have no effect.

func NewLRUConns

func NewLRUConns() *LRUConns

NewLRUConns initializes a new LRUConns.

func (*LRUConns) Add

func (conns *LRUConns) Add(conn net.Conn) *LRUConnsEntry

Add inserts a net.Conn as the freshest connection in a LRUConns and returns an LRUConnsEntry to be used to freshen the connection or remove the connection from the LRU list.

func (*LRUConns) CloseOldest

func (conns *LRUConns) CloseOldest()

CloseOldest closes the oldest connection in a LRUConns. It calls net.Conn.Close() on the connection.

type LRUConnsEntry

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

LRUConnsEntry is an entry in a LRUConns list.

func (*LRUConnsEntry) Remove

func (entry *LRUConnsEntry) Remove()

Remove deletes the connection referenced by the LRUConnsEntry from the associated LRUConns. Has no effect if the entry was not initialized or previously removed.

func (*LRUConnsEntry) Touch

func (entry *LRUConnsEntry) Touch()

Touch promotes the connection referenced by the LRUConnsEntry to the front of the associated LRUConns. Has no effect if the entry was not initialized or previously removed.

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 golang's stock ssh client and server without modification to that standard library code. The underlying connection must be used for SSH 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 and received).

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(
	mode ObfuscatedSshConnMode,
	conn net.Conn,
	obfuscationKeyword string) (*ObfuscatedSshConn, error)

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

In client mode, NewObfuscatedSshConn does not block or initiate network I/O. The obfuscation seed message is sent when Write() is first called.

In server mode, NewObfuscatedSshConn cannot completely initialize itself without the seed message from the client to derive obfuscation keys. So NewObfuscatedSshConn blocks on reading the client seed message from the underlying conn.

func (*ObfuscatedSshConn) Read

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

Read wraps standard Read, transparently applying the obfuscation transformations.

func (*ObfuscatedSshConn) Write

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

Write wraps standard Write, transparently applying the obfuscation transformations.

type ObfuscatedSshConnMode

type ObfuscatedSshConnMode int

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 NewClientObfuscator

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

NewClientObfuscator creates a new Obfuscator, staging a seed message to be sent to the server (by the caller) and initializing stream ciphers to obfuscate data.

func NewServerObfuscator

func NewServerObfuscator(
	clientReader io.Reader, config *ObfuscatorConfig) (obfuscator *Obfuscator, err error)

NewServerObfuscator creates a new Obfuscator, reading a seed message directly from the clientReader and initializing stream ciphers to obfuscate data.

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.

func (*Obfuscator) SendSeedMessage

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

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

type ObfuscatorConfig

type ObfuscatorConfig struct {
	Keyword    string
	MaxPadding int
}

type RateLimits

type RateLimits struct {

	// ReadUnthrottledBytes specifies the number of bytes to
	// read, approximately, before starting rate limiting.
	ReadUnthrottledBytes int64

	// ReadBytesPerSecond specifies a rate limit for read
	// data transfer. The default, 0, is no limit.
	ReadBytesPerSecond int64

	// WriteUnthrottledBytes specifies the number of bytes to
	// write, approximately, before starting rate limiting.
	WriteUnthrottledBytes int64

	// WriteBytesPerSecond specifies a rate limit for write
	// data transfer. The default, 0, is no limit.
	WriteBytesPerSecond int64

	// CloseAfterExhausted indicates that the underlying
	// net.Conn should be closed once either the read or
	// write unthrottled bytes have been exhausted. In this
	// case, throttling is never applied.
	CloseAfterExhausted bool
}

RateLimits specify the rate limits for a ThrottledConn.

type ReloadableFile

type ReloadableFile struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

ReloadableFile is a file-backed Reloader. This type is intended to be embedded in other types that add the actual reloadable data structures.

ReloadableFile has a multi-reader mutex for synchronization. Its Reload() function will obtain a write lock before reloading the data structures. The actual reloading action is to be provided via the reloadAction callback, which receives the content of reloaded files and must process the new data (for example, unmarshall the contents into data structures). All read access to the data structures should be guarded by RLocks on the ReloadableFile mutex.

reloadAction must ensure that data structures revert to their previous state when a reload fails.

func NewReloadableFile

func NewReloadableFile(
	fileName string,
	reloadAction func([]byte) error) ReloadableFile

NewReloadableFile initializes a new ReloadableFile

func (*ReloadableFile) LogDescription

func (reloadable *ReloadableFile) LogDescription() string

func (*ReloadableFile) Reload

func (reloadable *ReloadableFile) Reload() (bool, error)

Reload checks if the underlying file has changed and, when changed, invokes the reloadAction callback which should reload the in-memory data structures.

In some case (e.g., traffic rules and OSL), there are penalties associated with proceeding with reload, so care is taken to not invoke the reload action unless the contents have changed.

The file content is loaded and a checksum is taken to determine whether it has changed. Neither file size (may not change when content changes) nor modified date (may change when identical file is repaved) is a sufficient indicator.

All data structure readers should be blocked by the ReloadableFile mutex.

Reload must not be called from multiple concurrent goroutines.

func (*ReloadableFile) WillReload

func (reloadable *ReloadableFile) WillReload() bool

WillReload indicates whether the ReloadableFile is capable of reloading.

type Reloader

type Reloader interface {

	// Reload reloads the data object. Reload returns a flag indicating if the
	// reloadable target has changed and reloaded or remains unchanged. By
	// convention, when reloading fails the Reloader should revert to its previous
	// in-memory state.
	Reload() (bool, error)

	// WillReload indicates if the data object is capable of reloading.
	WillReload() bool

	// LogDescription returns a description to be used for logging
	// events related to the Reloader.
	LogDescription() string
}

Reloader represents a read-only, in-memory reloadable data object. For example, a JSON data file that is loaded into memory and accessed for read-only lookups; and from time to time may be reloaded from the same file, updating the memory copy.

type SubnetLookup

type SubnetLookup []net.IPNet

SubnetLookup provides an efficient lookup for individual IP addresses within a list of subnets.

func NewSubnetLookup

func NewSubnetLookup(CIDRs []string) (SubnetLookup, error)

NewSubnetLookup creates a SubnetLookup from a list of subnet CIDRs.

func NewSubnetLookupFromRoutes

func NewSubnetLookupFromRoutes(routesData []byte) (SubnetLookup, error)

NewSubnetLookup creates a SubnetLookup from text routes data. The input format is expected to be text lines where each line is, e.g., "1.2.3.0\t255.255.255.0\n"

func (SubnetLookup) ContainsIPAddress

func (lookup SubnetLookup) ContainsIPAddress(addr net.IP) bool

ContainsIPAddress performs a binary search on the sorted subnet list to find a network containing the candidate IP address.

func (SubnetLookup) Len

func (lookup SubnetLookup) Len() int

Len implements Sort.Interface

func (SubnetLookup) Less

func (lookup SubnetLookup) Less(i, j int) bool

Less implements Sort.Interface

func (SubnetLookup) Swap

func (lookup SubnetLookup) Swap(i, j int)

Swap implements Sort.Interface

type ThrottledConn

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

ThrottledConn wraps a net.Conn with read and write rate limiters. Rates are specified as bytes per second. Optional unlimited byte counts allow for a number of bytes to read or write before applying rate limiting. Specify limit values of 0 to set no rate limit (unlimited counts are ignored in this case). The underlying rate limiter uses the token bucket algorithm to calculate delay times for read and write operations.

func NewThrottledConn

func NewThrottledConn(conn net.Conn, limits RateLimits) *ThrottledConn

NewThrottledConn initializes a new ThrottledConn.

func (*ThrottledConn) Read

func (conn *ThrottledConn) Read(buffer []byte) (int, error)

func (*ThrottledConn) SetLimits

func (conn *ThrottledConn) SetLimits(limits RateLimits)

SetLimits modifies the rate limits of an existing ThrottledConn. It is safe to call SetLimits while other goroutines are calling Read/Write. This function will not block, and the new rate limits will be applied within Read/Write, but not necessarily until some futher I/O at previous rates.

func (*ThrottledConn) Write

func (conn *ThrottledConn) Write(buffer []byte) (int, error)

Directories

Path Synopsis
osl
Package osl implements the Obfuscated Server List (OSL) mechanism.
Package osl implements the Obfuscated Server List (OSL) mechanism.
tls
Package tls partially implements TLS 1.2, as specified in RFC 5246.
Package tls partially implements TLS 1.2, as specified in RFC 5246.
cipherhw
Package cipherhw exposes common functions for detecting whether hardware support for certain ciphers and authenticators is present.
Package cipherhw exposes common functions for detecting whether hardware support for certain ciphers and authenticators is present.
crypto/chacha20poly1305
Package chacha20poly1305 implements the ChaCha20-Poly1305 AEAD as specified in RFC 7539.
Package chacha20poly1305 implements the ChaCha20-Poly1305 AEAD as specified in RFC 7539.
crypto/chacha20poly1305/internal/chacha20
Package ChaCha20 implements the core ChaCha20 function as specified in https://tools.ietf.org/html/rfc7539#section-2.3.
Package ChaCha20 implements the core ChaCha20 function as specified in https://tools.ietf.org/html/rfc7539#section-2.3.
crypto/curve25519
Package curve25519 provides an implementation of scalar multiplication on the elliptic curve known as curve25519.
Package curve25519 provides an implementation of scalar multiplication on the elliptic curve known as curve25519.
crypto/poly1305
Package poly1305 implements Poly1305 one-time message authentication code as specified in http://cr.yp.to/mac/poly1305-20050329.pdf.
Package poly1305 implements Poly1305 one-time message authentication code as specified in http://cr.yp.to/mac/poly1305-20050329.pdf.

Jump to

Keyboard shortcuts

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