本文整理汇总了Golang中github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon.ContextError函数的典型用法代码示例。如果您正苦于以下问题:Golang ContextError函数的具体用法?Golang ContextError怎么用?Golang ContextError使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ContextError函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Reload
// Reload [re]initializes the TrafficRulesSet with the rules data
// in the specified file. This function obtains a write lock on
// the database, blocking all readers. When Reload fails, the previous
// state is retained.
func (set *TrafficRulesSet) Reload(ruleSetFilename string) error {
set.Lock()
defer set.Unlock()
if ruleSetFilename == "" {
// No traffic rules filename in the config
return nil
}
configJSON, err := ioutil.ReadFile(ruleSetFilename)
if err != nil {
return psiphon.ContextError(err)
}
var newSet TrafficRulesSet
err = json.Unmarshal(configJSON, &newSet)
if err != nil {
return psiphon.ContextError(err)
}
set.DefaultRules = newSet.DefaultRules
set.RegionalRules = newSet.RegionalRules
return nil
}
示例2: convertHTTPRequestToAPIRequest
// convertHTTPRequestToAPIRequest converts the HTTP request query
// parameters and request body to the JSON object import format
// expected by the API request handlers.
func convertHTTPRequestToAPIRequest(
w http.ResponseWriter,
r *http.Request,
requestBodyName string) (requestJSONObject, error) {
params := make(requestJSONObject)
for name, values := range r.URL.Query() {
for _, value := range values {
params[name] = value
// Note: multiple values per name are ignored
break
}
}
if requestBodyName != "" {
r.Body = http.MaxBytesReader(w, r.Body, MAX_API_PARAMS_SIZE)
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, psiphon.ContextError(err)
}
var bodyParams requestJSONObject
err = json.Unmarshal(body, &bodyParams)
if err != nil {
return nil, psiphon.ContextError(err)
}
params[requestBodyName] = bodyParams
}
return params, nil
}
示例3: UpdateRedisForLegacyPsiWeb
// UpdateRedisForLegacyPsiWeb sets the Psiphon session and discovery records for
// a new SSH connection following the conventions of the legacy psi_web component.
// This facility is used so psi_web can use the GeoIP values the SSH server has
// resolved for the user connection.
// The redis database indexes, expiry values, and record schemas all match the
// legacy psi_web configuration.
func UpdateRedisForLegacyPsiWeb(psiphonSessionID string, geoIPData GeoIPData) error {
redisSessionDBIndex := 0
// Discard sessions older than 60 minutes
sessionExpireSeconds := 60 * 60
sessionRecord, err := json.Marshal(
struct {
Country string `json:"region"`
City string `json:"city"`
ISP string `json:"isp"`
}{geoIPData.Country, geoIPData.City, geoIPData.ISP})
if err != nil {
return psiphon.ContextError(err)
}
redisDiscoveryDBIndex := 1
// Discard discovery records older than 5 minutes
discoveryExpireSeconds := 60 * 5
discoveryRecord, err := json.Marshal(
struct {
DiscoveryValue int `json:"client_ip_address_strategy_value"`
}{geoIPData.DiscoveryValue})
if err != nil {
return psiphon.ContextError(err)
}
conn := redisPool.Get()
// Note: using SET with NX (set if not exists) so as to not clobber
// any existing records set by an upstream connection server (i.e.,
// meek server). We allow expiry deadline extension unconditionally.
conn.Send("MULTI")
conn.Send("SELECT", redisSessionDBIndex)
// http://redis.io/commands/set -- NX/EX options require Redis 2.6.12
//conn.Send("SET", psiphonSessionID, string(sessionRecord), "NX", "EX", sessionExpireSeconds)
conn.Send("SETNX", psiphonSessionID, string(sessionRecord))
conn.Send("EXPIRE", psiphonSessionID, sessionExpireSeconds)
conn.Send("SELECT", redisDiscoveryDBIndex)
//conn.Send("SET", psiphonSessionID, string(discoveryRecord), "NX", "EX", discoveryExpireSeconds)
conn.Send("SETNX", psiphonSessionID, string(discoveryRecord))
conn.Send("EXPIRE", psiphonSessionID, discoveryExpireSeconds)
_, err = conn.Do("EXEC")
if err != nil {
return psiphon.ContextError(err)
}
return nil
}
示例4: makeMeekSessionID
// makeMeekSessionID creates a new session ID. The variable size is intended to
// frustrate traffic analysis of both plaintext and TLS meek traffic.
func makeMeekSessionID() (string, error) {
size := MEEK_MIN_SESSION_ID_LENGTH
n, err := psiphon.MakeSecureRandomInt(MEEK_MAX_SESSION_ID_LENGTH - MEEK_MIN_SESSION_ID_LENGTH)
if err != nil {
return "", psiphon.ContextError(err)
}
size += n
sessionID, err := psiphon.MakeRandomStringBase64(size)
if err != nil {
return "", psiphon.ContextError(err)
}
return sessionID, nil
}
示例5: passwordCallback
func (sshClient *sshClient) passwordCallback(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
var sshPasswordPayload struct {
SessionId string `json:"SessionId"`
SshPassword string `json:"SshPassword"`
}
err := json.Unmarshal(password, &sshPasswordPayload)
if err != nil {
// Backwards compatibility case: instead of a JSON payload, older clients
// send the hex encoded session ID prepended to the SSH password.
// Note: there's an even older case where clients don't send any session ID,
// but that's no longer supported.
if len(password) == 2*psiphon.PSIPHON_API_CLIENT_SESSION_ID_LENGTH+2*SSH_PASSWORD_BYTE_LENGTH {
sshPasswordPayload.SessionId = string(password[0 : 2*psiphon.PSIPHON_API_CLIENT_SESSION_ID_LENGTH])
sshPasswordPayload.SshPassword = string(password[2*psiphon.PSIPHON_API_CLIENT_SESSION_ID_LENGTH : len(password)])
} else {
return nil, psiphon.ContextError(fmt.Errorf("invalid password payload for %q", conn.User()))
}
}
if !isHexDigits(sshClient.sshServer.support, sshPasswordPayload.SessionId) {
return nil, psiphon.ContextError(fmt.Errorf("invalid session ID for %q", conn.User()))
}
userOk := (subtle.ConstantTimeCompare(
[]byte(conn.User()), []byte(sshClient.sshServer.support.Config.SSHUserName)) == 1)
passwordOk := (subtle.ConstantTimeCompare(
[]byte(sshPasswordPayload.SshPassword), []byte(sshClient.sshServer.support.Config.SSHPassword)) == 1)
if !userOk || !passwordOk {
return nil, psiphon.ContextError(fmt.Errorf("invalid password for %q", conn.User()))
}
psiphonSessionID := sshPasswordPayload.SessionId
sshClient.Lock()
sshClient.psiphonSessionID = psiphonSessionID
geoIPData := sshClient.geoIPData
sshClient.Unlock()
// Store the GeoIP data associated with the session ID. This makes the GeoIP data
// available to the web server for web transport Psiphon API requests.
sshClient.sshServer.support.GeoIPService.SetSessionCache(
psiphonSessionID, geoIPData)
return nil, nil
}
示例6: NewMeekServer
// NewMeekServer initializes a new meek server.
func NewMeekServer(
support *SupportServices,
listener net.Listener,
useTLS bool,
clientHandler func(clientConn net.Conn),
stopBroadcast <-chan struct{}) (*MeekServer, error) {
meekServer := &MeekServer{
support: support,
listener: listener,
clientHandler: clientHandler,
openConns: new(psiphon.Conns),
stopBroadcast: stopBroadcast,
sessions: make(map[string]*meekSession),
}
if useTLS {
tlsConfig, err := makeMeekTLSConfig(support)
if err != nil {
return nil, psiphon.ContextError(err)
}
meekServer.tlsConfig = tlsConfig
}
return meekServer, nil
}
示例7: makeMeekTLSConfig
// makeMeekTLSConfig creates a TLS config for a meek HTTPS listener.
// Currently, this config is optimized for fronted meek where the nature
// of the connection is non-circumvention; it's optimized for performance
// assuming the peer is an uncensored CDN.
func makeMeekTLSConfig(support *SupportServices) (*tls.Config, error) {
certificate, privateKey, err := GenerateWebServerCertificate(
support.Config.MeekCertificateCommonName)
if err != nil {
return nil, psiphon.ContextError(err)
}
tlsCertificate, err := tls.X509KeyPair(
[]byte(certificate), []byte(privateKey))
if err != nil {
return nil, psiphon.ContextError(err)
}
return &tls.Config{
Certificates: []tls.Certificate{tlsCertificate},
NextProtos: []string{"http/1.1"},
MinVersion: tls.VersionTLS10,
// This is a reordering of the supported CipherSuites in golang 1.6. Non-ephemeral key
// CipherSuites greatly reduce server load, and we try to select these since the meek
// protocol is providing obfuscation, not privacy/integrity (this is provided by the
// tunneled SSH), so we don't benefit from the perfect forward secrecy property provided
// by ephemeral key CipherSuites.
// https://github.com/golang/go/blob/1cb3044c9fcd88e1557eca1bf35845a4108bc1db/src/crypto/tls/cipher_suites.go#L75
CipherSuites: []uint16{
tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_RSA_WITH_RC4_128_SHA,
tls.TLS_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
},
PreferServerCipherSuites: true,
}, nil
}
示例8: InitLogging
// InitLogging configures a logger according to the specified
// config params. If not called, the default logger set by the
// package init() is used.
// When configured, InitLogging also establishes a local syslog
// logger specifically for fail2ban integration.
// Concurrenty note: should only be called from the main
// goroutine.
func InitLogging(config *Config) error {
level, err := logrus.ParseLevel(config.LogLevel)
if err != nil {
return psiphon.ContextError(err)
}
hooks := make(logrus.LevelHooks)
var syslogHook *logrus_syslog.SyslogHook
if config.SyslogFacility != "" {
syslogHook, err = logrus_syslog.NewSyslogHook(
"", "", getSyslogPriority(config), config.SyslogTag)
if err != nil {
return psiphon.ContextError(err)
}
hooks.Add(syslogHook)
}
log = &ContextLogger{
&logrus.Logger{
Out: os.Stderr,
Formatter: new(logrus.TextFormatter),
Hooks: hooks,
Level: level,
},
}
if config.Fail2BanFormat != "" {
fail2BanFormat = config.Fail2BanFormat
fail2BanWriter, err = syslog.Dial(
"", "", syslog.LOG_AUTH|syslog.LOG_INFO, config.SyslogTag)
if err != nil {
return psiphon.ContextError(err)
}
}
return nil
}
示例9: passwordCallback
func (sshClient *sshClient) passwordCallback(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
var sshPasswordPayload struct {
SessionId string `json:"SessionId"`
SshPassword string `json:"SshPassword"`
}
err := json.Unmarshal(password, &sshPasswordPayload)
if err != nil {
return nil, psiphon.ContextError(fmt.Errorf("invalid password payload for %q", conn.User()))
}
userOk := (subtle.ConstantTimeCompare(
[]byte(conn.User()), []byte(sshClient.sshServer.config.SSHUserName)) == 1)
passwordOk := (subtle.ConstantTimeCompare(
[]byte(sshPasswordPayload.SshPassword), []byte(sshClient.sshServer.config.SSHPassword)) == 1)
if !userOk || !passwordOk {
return nil, psiphon.ContextError(fmt.Errorf("invalid password for %q", conn.User()))
}
psiphonSessionID := sshPasswordPayload.SessionId
sshClient.Lock()
sshClient.psiphonSessionID = psiphonSessionID
geoIPData := sshClient.geoIPData
sshClient.Unlock()
if sshClient.sshServer.config.UseRedis() {
err = UpdateRedisForLegacyPsiWeb(psiphonSessionID, geoIPData)
if err != nil {
log.WithContextFields(LogFields{
"psiphonSessionID": psiphonSessionID,
"error": err}).Warning("UpdateRedisForLegacyPsiWeb failed")
// Allow the connection to proceed; legacy psi_web will not get accurate GeoIP values.
}
}
return nil, nil
}
示例10: InitGeoIP
// InitGeoIP opens a GeoIP2/GeoLite2 MaxMind database and prepares
// it for lookups.
func InitGeoIP(config *Config) error {
discoveryValueHMACKey = config.DiscoveryValueHMACKey
if config.GeoIPDatabaseFilename != "" {
var err error
geoIPReader, err = maxminddb.Open(config.GeoIPDatabaseFilename)
if err != nil {
return psiphon.ContextError(err)
}
log.WithContext().Info("GeoIP initialized")
}
return nil
}
示例11: newSSHServer
func newSSHServer(
support *SupportServices,
shutdownBroadcast <-chan struct{}) (*sshServer, error) {
privateKey, err := ssh.ParseRawPrivateKey([]byte(support.Config.SSHPrivateKey))
if err != nil {
return nil, psiphon.ContextError(err)
}
// TODO: use cert (ssh.NewCertSigner) for anti-fingerprint?
signer, err := ssh.NewSignerFromKey(privateKey)
if err != nil {
return nil, psiphon.ContextError(err)
}
return &sshServer{
support: support,
shutdownBroadcast: shutdownBroadcast,
sshHostKey: signer,
nextClientID: 1,
acceptedClientCounts: make(map[string]int64),
clients: make(map[sshClientID]*sshClient),
}, nil
}
示例12: NewSupportServices
// NewSupportServices initializes a new SupportServices.
func NewSupportServices(config *Config) (*SupportServices, error) {
trafficRulesSet, err := NewTrafficRulesSet(config.TrafficRulesFilename)
if err != nil {
return nil, psiphon.ContextError(err)
}
psinetDatabase, err := psinet.NewDatabase(config.PsinetDatabaseFilename)
if err != nil {
return nil, psiphon.ContextError(err)
}
geoIPService, err := NewGeoIPService(
config.GeoIPDatabaseFilename, config.DiscoveryValueHMACKey)
if err != nil {
return nil, psiphon.ContextError(err)
}
return &SupportServices{
Config: config,
TrafficRulesSet: trafficRulesSet,
PsinetDatabase: psinetDatabase,
GeoIPService: geoIPService,
}, nil
}
示例13: NewTunnelServer
// NewTunnelServer initializes a new tunnel server.
func NewTunnelServer(
support *SupportServices,
shutdownBroadcast <-chan struct{}) (*TunnelServer, error) {
sshServer, err := newSSHServer(support, shutdownBroadcast)
if err != nil {
return nil, psiphon.ContextError(err)
}
return &TunnelServer{
runWaitGroup: new(sync.WaitGroup),
listenerError: make(chan error),
shutdownBroadcast: shutdownBroadcast,
sshServer: sshServer,
}, nil
}
示例14: LoadConfig
// LoadConfig loads and validates a JSON encoded server config. If more than one
// JSON config is specified, then all are loaded and values are merged together,
// in order. Multiple configs allows for use cases like storing static, server-specific
// values in a base config while also deploying network-wide throttling settings
// in a secondary file that can be paved over on all server hosts.
func LoadConfig(configJSONs [][]byte) (*Config, error) {
// Note: default values are set in GenerateConfig
var config Config
for _, configJSON := range configJSONs {
err := json.Unmarshal(configJSON, &config)
if err != nil {
return nil, psiphon.ContextError(err)
}
}
if config.Fail2BanFormat != "" && strings.Count(config.Fail2BanFormat, "%s") != 1 {
return nil, errors.New("Fail2BanFormat must have one '%%s' placeholder")
}
if config.ServerIPAddress == "" {
return nil, errors.New("ServerIPAddress is missing from config file")
}
if config.WebServerPort > 0 && (config.WebServerSecret == "" || config.WebServerCertificate == "" ||
config.WebServerPrivateKey == "") {
return nil, errors.New(
"web server requires WebServerSecret, WebServerCertificate, WebServerPrivateKey")
}
if config.SSHServerPort > 0 && (config.SSHPrivateKey == "" || config.SSHServerVersion == "" ||
config.SSHUserName == "" || config.SSHPassword == "") {
return nil, errors.New(
"SSH server requires SSHPrivateKey, SSHServerVersion, SSHUserName, SSHPassword")
}
if config.ObfuscatedSSHServerPort > 0 && (config.SSHPrivateKey == "" || config.SSHServerVersion == "" ||
config.SSHUserName == "" || config.SSHPassword == "" || config.ObfuscatedSSHKey == "") {
return nil, errors.New(
"Obfuscated SSH server requires SSHPrivateKey, SSHServerVersion, SSHUserName, SSHPassword, ObfuscatedSSHKey")
}
return &config, nil
}
示例15: getMeekCookiePayload
// getMeekCookiePayload extracts the payload from a meek cookie. The cookie
// paylod is base64 encoded, obfuscated, and NaCl encrypted.
func getMeekCookiePayload(support *SupportServices, cookieValue string) ([]byte, error) {
decodedValue, err := base64.StdEncoding.DecodeString(cookieValue)
if err != nil {
return nil, psiphon.ContextError(err)
}
// The data consists of an obfuscated seed message prepended
// to the obfuscated, encrypted payload. The server obfuscator
// will read the seed message, leaving the remaining encrypted
// data in the reader.
reader := bytes.NewReader(decodedValue[:])
obfuscator, err := psiphon.NewServerObfuscator(
reader,
&psiphon.ObfuscatorConfig{Keyword: support.Config.MeekObfuscatedKey})
if err != nil {
return nil, psiphon.ContextError(err)
}
offset, err := reader.Seek(0, 1)
if err != nil {
return nil, psiphon.ContextError(err)
}
encryptedPayload := decodedValue[offset:]
obfuscator.ObfuscateClientToServer(encryptedPayload)
var nonce [24]byte
var privateKey, ephemeralPublicKey [32]byte
decodedPrivateKey, err := base64.StdEncoding.DecodeString(
support.Config.MeekCookieEncryptionPrivateKey)
if err != nil {
return nil, psiphon.ContextError(err)
}
copy(privateKey[:], decodedPrivateKey)
if len(encryptedPayload) < 32 {
return nil, psiphon.ContextError(errors.New("unexpected encrypted payload size"))
}
copy(ephemeralPublicKey[0:32], encryptedPayload[0:32])
payload, ok := box.Open(nil, encryptedPayload[32:], &nonce, &ephemeralPublicKey, &privateKey)
if !ok {
return nil, psiphon.ContextError(errors.New("open box failed"))
}
return payload, nil
}