• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang psiphon.ContextError函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon.ContextError函数的典型用法代码示例。如果您正苦于以下问题:Golang ContextError函数的具体用法?Golang ContextError怎么用?Golang ContextError使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了ContextError函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
}
开发者ID:code-mx,项目名称:psiphon-tunnel-core,代码行数:29,代码来源:trafficRules.go


示例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
}
开发者ID:code-mx,项目名称:psiphon-tunnel-core,代码行数:34,代码来源:webServer.go


示例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
}
开发者ID:yangguangyu,项目名称:psiphon-tunnel-core,代码行数:62,代码来源:redis.go


示例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
}
开发者ID:code-mx,项目名称:psiphon-tunnel-core,代码行数:15,代码来源:meek.go


示例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
}
开发者ID:code-mx,项目名称:psiphon-tunnel-core,代码行数:49,代码来源:tunnelServer.go


示例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
}
开发者ID:code-mx,项目名称:psiphon-tunnel-core,代码行数:27,代码来源:meek.go


示例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
}
开发者ID:code-mx,项目名称:psiphon-tunnel-core,代码行数:51,代码来源:meek.go


示例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
}
开发者ID:yangguangyu,项目名称:psiphon-tunnel-core,代码行数:49,代码来源:log.go


示例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
}
开发者ID:yangguangyu,项目名称:psiphon-tunnel-core,代码行数:39,代码来源:sshService.go


示例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
}
开发者ID:yangguangyu,项目名称:psiphon-tunnel-core,代码行数:17,代码来源:geoip.go


示例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
}
开发者ID:code-mx,项目名称:psiphon-tunnel-core,代码行数:24,代码来源:tunnelServer.go


示例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
}
开发者ID:code-mx,项目名称:psiphon-tunnel-core,代码行数:25,代码来源:services.go


示例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
}
开发者ID:code-mx,项目名称:psiphon-tunnel-core,代码行数:17,代码来源:tunnelServer.go


示例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
}
开发者ID:yangguangyu,项目名称:psiphon-tunnel-core,代码行数:48,代码来源:config.go


示例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
}
开发者ID:code-mx,项目名称:psiphon-tunnel-core,代码行数:52,代码来源:meek.go


示例16: copyWithThrottle

func copyWithThrottle(dst io.Writer, src io.Reader, throttleSleepMilliseconds int) (int64, error) {
	// TODO: use a low-memory io.Copy?
	if throttleSleepMilliseconds <= 0 {
		// No throttle
		return io.Copy(dst, src)
	}
	var totalBytes int64
	for {
		bytes, err := io.CopyN(dst, src, SSH_THROTTLED_PORT_FORWARD_MAX_COPY)
		totalBytes += bytes
		if err == io.EOF {
			err = nil
			break
		}
		if err != nil {
			return totalBytes, psiphon.ContextError(err)
		}
		time.Sleep(time.Duration(throttleSleepMilliseconds) * time.Millisecond)
	}
	return totalBytes, nil
}
开发者ID:yangguangyu,项目名称:psiphon-tunnel-core,代码行数:21,代码来源:sshService.go


示例17: generateWebServerCertificate

func generateWebServerCertificate() (string, string, error) {

	// Based on https://golang.org/src/crypto/tls/generate_cert.go

	// TODO: use other key types: anti-fingerprint by varying params

	rsaKey, err := rsa.GenerateKey(rand.Reader, WEB_SERVER_CERTIFICATE_RSA_KEY_BITS)
	if err != nil {
		return "", "", psiphon.ContextError(err)
	}

	notBefore := time.Now()
	notAfter := notBefore.Add(WEB_SERVER_CERTIFICATE_VALIDITY_PERIOD)

	// TODO: psi_ops_install sets serial number to 0?
	// TOSO: psi_ops_install sets RSA exponent to 3, digest type to 'sha1', and version to 2?

	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return "", "", psiphon.ContextError(err)
	}

	template := x509.Certificate{

		// TODO: psi_ops_install leaves subject blank?
		/*
			Subject: pkix.Name{
				Organization: []string{""},
			},
			IPAddresses: ...
		*/

		SerialNumber:          serialNumber,
		NotBefore:             notBefore,
		NotAfter:              notAfter,
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
		IsCA: true,
	}

	derCert, err := x509.CreateCertificate(rand.Reader, &template, &template, rsaKey.Public(), rsaKey)
	if err != nil {
		return "", "", psiphon.ContextError(err)
	}

	webServerCertificate := pem.EncodeToMemory(
		&pem.Block{
			Type:  "CERTIFICATE",
			Bytes: derCert,
		},
	)

	webServerPrivateKey := pem.EncodeToMemory(
		&pem.Block{
			Type:  "RSA PRIVATE KEY",
			Bytes: x509.MarshalPKCS1PrivateKey(rsaKey),
		},
	)

	return string(webServerCertificate), string(webServerPrivateKey), nil
}
开发者ID:yangguangyu,项目名称:psiphon-tunnel-core,代码行数:63,代码来源:config.go


示例18: GenerateConfig

// GenerateConfig create a new Psiphon server config. It returns a JSON
// encoded config and a client-compatible "server entry" for the server. It
// generates all necessary secrets and key material, which are emitted in
// the config file and server entry as necessary.
func GenerateConfig(params *GenerateConfigParams) ([]byte, []byte, error) {

	// TODO: support disabling web server or a subset of protocols

	serverIPaddress := params.ServerIPAddress
	if serverIPaddress == "" {
		serverIPaddress = DEFAULT_SERVER_IP_ADDRESS
	}

	// Web server config

	webServerPort := params.WebServerPort
	if webServerPort == 0 {
		webServerPort = DEFAULT_WEB_SERVER_PORT
	}

	webServerSecret, err := psiphon.MakeRandomString(WEB_SERVER_SECRET_BYTE_LENGTH)
	if err != nil {
		return nil, nil, psiphon.ContextError(err)
	}

	webServerCertificate, webServerPrivateKey, err := generateWebServerCertificate()
	if err != nil {
		return nil, nil, psiphon.ContextError(err)
	}

	// SSH config

	sshServerPort := params.SSHServerPort
	if sshServerPort == 0 {
		sshServerPort = DEFAULT_SSH_SERVER_PORT
	}

	// TODO: use other key types: anti-fingerprint by varying params

	rsaKey, err := rsa.GenerateKey(rand.Reader, SSH_RSA_HOST_KEY_BITS)
	if err != nil {
		return nil, nil, psiphon.ContextError(err)
	}

	sshPrivateKey := pem.EncodeToMemory(
		&pem.Block{
			Type:  "RSA PRIVATE KEY",
			Bytes: x509.MarshalPKCS1PrivateKey(rsaKey),
		},
	)

	signer, err := ssh.NewSignerFromKey(rsaKey)
	if err != nil {
		return nil, nil, psiphon.ContextError(err)
	}

	sshPublicKey := signer.PublicKey()

	sshUserNameSuffix, err := psiphon.MakeRandomString(SSH_USERNAME_SUFFIX_BYTE_LENGTH)
	if err != nil {
		return nil, nil, psiphon.ContextError(err)
	}

	sshUserName := "psiphon_" + sshUserNameSuffix

	sshPassword, err := psiphon.MakeRandomString(SSH_PASSWORD_BYTE_LENGTH)
	if err != nil {
		return nil, nil, psiphon.ContextError(err)
	}

	// TODO: vary version string for anti-fingerprint
	sshServerVersion := "SSH-2.0-Psiphon"

	// Obfuscated SSH config

	obfuscatedSSHServerPort := params.ObfuscatedSSHServerPort
	if obfuscatedSSHServerPort == 0 {
		obfuscatedSSHServerPort = DEFAULT_OBFUSCATED_SSH_SERVER_PORT
	}

	obfuscatedSSHKey, err := psiphon.MakeRandomString(SSH_OBFUSCATED_KEY_BYTE_LENGTH)
	if err != nil {
		return nil, nil, psiphon.ContextError(err)
	}

	// Assemble config and server entry

	config := &Config{
		LogLevel:                DEFAULT_LOG_LEVEL,
		SyslogFacility:          "",
		SyslogTag:               DEFAULT_SYSLOG_TAG,
		Fail2BanFormat:          "",
		DiscoveryValueHMACKey:   "",
		GeoIPDatabaseFilename:   DEFAULT_GEO_IP_DATABASE_FILENAME,
		ServerIPAddress:         serverIPaddress,
		WebServerPort:           webServerPort,
		WebServerSecret:         webServerSecret,
		WebServerCertificate:    webServerCertificate,
		WebServerPrivateKey:     webServerPrivateKey,
		SSHPrivateKey:           string(sshPrivateKey),
//.........这里部分代码省略.........
开发者ID:yangguangyu,项目名称:psiphon-tunnel-core,代码行数:101,代码来源:config.go


示例19: RunServices

// RunServices initializes support functions including logging, GeoIP service, and
// redis connection pooling; and then starts the server components and runs them
// until os.Interrupt or os.Kill signals are received. The config determines
// which components are run.
func RunServices(encodedConfigs [][]byte) error {

	config, err := LoadConfig(encodedConfigs)
	if err != nil {
		log.WithContextFields(LogFields{"error": err}).Error("load config failed")
		return psiphon.ContextError(err)
	}

	err = InitLogging(config)
	if err != nil {
		log.WithContextFields(LogFields{"error": err}).Error("init logging failed")
		return psiphon.ContextError(err)
	}

	err = InitGeoIP(config)
	if err != nil {
		log.WithContextFields(LogFields{"error": err}).Error("init GeoIP failed")
		return psiphon.ContextError(err)
	}

	if config.UseRedis() {
		err = InitRedis(config)
		if err != nil {
			log.WithContextFields(LogFields{"error": err}).Error("init redis failed")
			return psiphon.ContextError(err)
		}
	}

	waitGroup := new(sync.WaitGroup)
	shutdownBroadcast := make(chan struct{})
	errors := make(chan error)

	if config.RunWebServer() {
		waitGroup.Add(1)
		go func() {
			defer waitGroup.Done()
			err := RunWebServer(config, shutdownBroadcast)
			select {
			case errors <- err:
			default:
			}
		}()
	}

	if config.RunSSHServer() {
		waitGroup.Add(1)
		go func() {
			defer waitGroup.Done()
			err := RunSSHServer(config, shutdownBroadcast)
			select {
			case errors <- err:
			default:
			}
		}()
	}

	if config.RunObfuscatedSSHServer() {
		waitGroup.Add(1)
		go func() {
			defer waitGroup.Done()
			err := RunObfuscatedSSHServer(config, shutdownBroadcast)
			select {
			case errors <- err:
			default:
			}
		}()
	}

	// An OS signal triggers an orderly shutdown
	systemStopSignal := make(chan os.Signal, 1)
	signal.Notify(systemStopSignal, os.Interrupt, os.Kill)

	err = nil

	select {
	case <-systemStopSignal:
		log.WithContext().Info("shutdown by system")
	case err = <-errors:
		log.WithContextFields(LogFields{"error": err}).Error("service failed")
	}

	close(shutdownBroadcast)
	waitGroup.Wait()

	return err
}
开发者ID:yangguangyu,项目名称:psiphon-tunnel-core,代码行数:90,代码来源:services.go


示例20: runSSHServer

// runSSHServer runs an SSH or Obfuscated SSH server. In the Obfuscated SSH case, an
// ObfuscatedSSHConn is layered in front of the client TCP connection; otherwise, both
// modes are identical.
//
// runSSHServer listens on the designated port and spawns new goroutines to handle
// each client connection. It halts when shutdownBroadcast is signaled. A list of active
// clients is maintained, and when halting all clients are first shutdown.
//
// Each client goroutine handles its own obfuscation (optional), SSH handshake, SSH
// authentication, and then looping on client new channel requests. At this time, only
// "direct-tcpip" channels, dynamic port fowards, are expected and supported.
//
// A new goroutine is spawned to handle each port forward. Each port forward tracks its
// bytes transferred. Overall per-client stats for connection duration, GeoIP, number of
// port forwards, and bytes transferred are tracked and logged when the client shuts down.
func runSSHServer(
	config *Config, useObfuscation bool, shutdownBroadcast <-chan struct{}) error {

	privateKey, err := ssh.ParseRawPrivateKey([]byte(config.SSHPrivateKey))
	if err != nil {
		return psiphon.ContextError(err)
	}

	// TODO: use cert (ssh.NewCertSigner) for anti-fingerprint?
	signer, err := ssh.NewSignerFromKey(privateKey)
	if err != nil {
		return psiphon.ContextError(err)
	}

	sshServer := &sshServer{
		config:            config,
		useObfuscation:    useObfuscation,
		shutdownBroadcast: shutdownBroadcast,
		sshHostKey:        signer,
		nextClientID:      1,
		clients:           make(map[sshClientID]*sshClient),
	}

	var serverPort int
	if useObfuscation {
		serverPort = config.ObfuscatedSSHServerPort
	} else {
		serverPort = config.SSHServerPort
	}

	listener, err := net.Listen(
		"tcp", fmt.Sprintf("%s:%d", config.ServerIPAddress, serverPort))
	if err != nil {
		return psiphon.ContextError(err)
	}

	log.WithContextFields(
		LogFields{
			"useObfuscation": useObfuscation,
			"port":           serverPort,
		}).Info("starting")

	err = nil
	errors := make(chan error)
	waitGroup := new(sync.WaitGroup)

	waitGroup.Add(1)
	go func() {
		defer waitGroup.Done()

	loop:
		for {
			conn, err := listener.Accept()

			select {
			case <-shutdownBroadcast:
				if err == nil {
					conn.Close()
				}
				break loop
			default:
			}

			if err != nil {
				if e, ok := err.(net.Error); ok && e.Temporary() {
					log.WithContextFields(LogFields{"error": err}).Error("accept failed")
					// Temporary error, keep running
					continue
				}

				select {
				case errors <- psiphon.ContextError(err):
				default:
				}

				break loop
			}

			// process each client connection concurrently
			go sshServer.handleClient(conn.(*net.TCPConn))
		}

		sshServer.stopClients()

		log.WithContextFields(
//.........这里部分代码省略.........
开发者ID:yangguangyu,项目名称:psiphon-tunnel-core,代码行数:101,代码来源:sshService.go



注:本文中的github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon.ContextError函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang common.Contains函数代码示例发布时间:2022-05-28
下一篇:
Golang monotime.Now函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap