// Starts listening for client connections. // When a new application connects, launches listeners in a goroutine. // Returns an error when error occurs. func StartListen(port int, useTls bool, crtPath string, keyPath string, sname string) error { // Create a listening address addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf(":%d", port)) if err != nil { return err } // start a new server and listen on the address var l net.Listener l, err = net.ListenTCP("tcp", addr) if err != nil { return err } // wrap with TLS if required if useTls { cert, err := tls.LoadX509KeyPair(crtPath, keyPath) if err != nil { return err } conf := tls.Config{} certs := make([]tls.Certificate, 1) certs[0] = cert conf.Certificates = certs cp := x509.NewCertPool() caCert, err := ioutil.ReadFile(crtPath) if err != nil { return err } if !cp.AppendCertsFromPEM(caCert) { return errors.New("Could not append PEM cert") } conf.RootCAs = cp conf.ServerName = sname conf.ClientAuth = tls.RequireAndVerifyClientCert conf.ClientCAs = cp l = tls.NewListener(l, &conf) } // at the end of this function close the server connection defer l.Close() logging.Debug("Starting listen loop") for { a, err := acceptApp(l) if err != nil { return err } else { logging.Debug("Got connection") go ListenForCommands(a) } } return nil }
func TestTLSConnection(t *testing.T) { reactor := NewReactor() client := reactor.CreateServer("local") initialiseServerConnection(client) // generate a test certificate to use priv, _ := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) duration30Days, _ := time.ParseDuration("-30h") notBefore := time.Now().Add(duration30Days) // valid 30 hours ago duration1Year, _ := time.ParseDuration("90h") notAfter := notBefore.Add(duration1Year) // for 90 hours serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, _ := rand.Int(rand.Reader, serialNumberLimit) template := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ Organization: []string{"gIRC-Go Co"}, }, NotBefore: notBefore, NotAfter: notAfter, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, IsCA: true, } template.IPAddresses = append(template.IPAddresses, net.ParseIP("127.0.0.1")) template.IPAddresses = append(template.IPAddresses, net.ParseIP("::")) template.DNSNames = append(template.DNSNames, "localhost") derBytes, _ := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv) c := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) b, _ := x509.MarshalECPrivateKey(priv) k := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: b}) // we mock up a server connection to test the client listenerKeyPair, _ := tls.X509KeyPair(c, k) var listenerTLSConfig tls.Config listenerTLSConfig.Certificates = make([]tls.Certificate, 0) listenerTLSConfig.Certificates = append(listenerTLSConfig.Certificates, listenerKeyPair) listener, _ := tls.Listen("tcp", ":0", &listenerTLSConfig) // mock up the client side too clientTLSCertPool := x509.NewCertPool() clientTLSCertPool.AppendCertsFromPEM(c) var clientTLSConfig tls.Config clientTLSConfig.RootCAs = clientTLSCertPool clientTLSConfig.ServerName = "localhost" go client.Connect(listener.Addr().String(), true, &clientTLSConfig) go client.ReceiveLoop() testServerConnection(t, reactor, client, listener) }
// StartTLS takes an identity and an authority certificate and upgrades the net.Conn on the protocol to TLS // It returns the CommonName from the peer certitifcate, or an error func (p *Protocol) StartTLS(identity *security.Identity, caCertificate *security.Certificate) (string, error) { var ( err error tlsConn *tls.Conn ) if err = p.WriteBytesWithDeadline([]byte{TLS}); err != nil { return "", err } // Build the config config := new(tls.Config) config.ServerName = p.serverName // Setup the tls connection if err = p.tlsSetup(config, identity, caCertificate); err != nil { return "", err } // Upgrade the connection to TLS // TODO: Add a deadline here? tlsConn = tls.Client(p.conn, config) if err = tlsConn.Handshake(); err != nil { return "", err } // Capture the connection state cs := tlsConn.ConnectionState() // And replace the original connection p.conn = net.Conn(tlsConn) p.setupBuffers() return cs.PeerCertificates[0].Subject.CommonName, nil }
// ClientConfig generates a tls.Config object for use by an HTTP client. func (info TLSInfo) ClientConfig() (*tls.Config, error) { var cfg *tls.Config var err error if !info.Empty() { cfg, err = info.baseConfig() if err != nil { return nil, err } } else { cfg = &tls.Config{ServerName: info.ServerName} } CAFiles := info.cafiles() if len(CAFiles) > 0 { cfg.RootCAs, err = tlsutil.NewCertPool(CAFiles) if err != nil { return nil, err } // if given a CA, trust any host with a cert signed by the CA cfg.ServerName = "" } if info.selfCert { cfg.InsecureSkipVerify = true } return cfg, nil }
func (s *_SmtpSender) SendTo(template_name string, subject string, receivers []mail.Address, args map[string]interface{}) (err error) { var templa *template.Template var ok bool if templa, ok = s.Templates[template_name]; !ok { if templa, err = template.ParseFiles(filepath.Join(*s.Root, template_name)); err == nil { s.Templates[template_name] = templa } else { return } } var c client if *s.Ttl { var config tls.Config config.ServerName = *s.Server if c, err = smtpoverttl.DialTTL(fmt.Sprintf("%s:%d", *s.Server, *s.Port), &config); err == nil { return s.sendMail(c, subject, templa, receivers, args) } } else { if c, err = smtp.Dial(fmt.Sprintf("%s:%d", *s.Server, *s.Port)); err == nil { return s.sendMail(c, subject, templa, receivers, args) } } return }
func (c *Conn) upgradeTLS(tlsConf *tls.Config) error { // create a local copy of the config to set ServerName for this connection var conf tls.Config if tlsConf != nil { conf = *tlsConf } host, _, err := net.SplitHostPort(c.addr) if err != nil { return err } conf.ServerName = host c.tlsConn = tls.Client(c.conn, &conf) err = c.tlsConn.Handshake() if err != nil { return err } c.r = c.tlsConn c.w = c.tlsConn frameType, data, err := ReadUnpackedResponse(c) if err != nil { return err } if frameType != FrameTypeResponse || !bytes.Equal(data, []byte("OK")) { return errors.New("invalid response from TLS upgrade") } return nil }
// performRequest performs an HTTP request r to Synthing API func performRequest(r *http.Request) (*http.Response, error) { request, err := prepareApiRequestForSyncthing(r) if request == nil { return nil, err } var tlsCfg tls.Config if cert != nil { tlsCfg.RootCAs = x509.NewCertPool() tlsCfg.RootCAs.AddCert(cert) // Always use this certificate tlsCfg.ServerName = cert.Subject.CommonName } tr := &http.Transport{ TLSClientConfig: &tlsCfg, ResponseHeaderTimeout: requestTimeout, DisableKeepAlives: true, } client := &http.Client{ Transport: tr, Timeout: requestTimeout, } res, err := client.Do(request) if res != nil && res.StatusCode == 403 { Warning.Printf("Error: HTTP POST forbidden. Missing API key?") return res, errors.New("HTTP POST forbidden") } return res, err }
func (cn *conn) ssl(o values) { tlsConf := tls.Config{} switch mode := o.Get("sslmode"); mode { case "require", "": tlsConf.InsecureSkipVerify = true case "verify-full": tlsConf.ServerName = o.Get("host") case "disable": return default: errorf(`unsupported sslmode %q; only "require" (default), "verify-full", and "disable" supported`, mode) } w := cn.writeBuf(0) w.int32(80877103) cn.send(w) b := cn.scratch[:1] _, err := io.ReadFull(cn.c, b) if err != nil { panic(err) } if b[0] != 'S' { panic(ErrSSLNotSupported) } cn.c = tls.Client(cn.c, &tlsConf) }
func (c *tlsClient) Connect(timeout time.Duration) error { host, _, err := net.SplitHostPort(c.hostport) if err != nil { return err } var tlsconfig tls.Config tlsconfig.MinVersion = c.tls.MinVersion tlsconfig.RootCAs = c.tls.RootCAs tlsconfig.Certificates = c.tls.Certificates tlsconfig.ServerName = host if err := c.tcpClient.Connect(timeout); err != nil { return c.onFail(err) } socket := tls.Client(c.Conn, &tlsconfig) if err := socket.SetDeadline(time.Now().Add(timeout)); err != nil { _ = socket.Close() return c.onFail(err) } if err := socket.Handshake(); err != nil { _ = socket.Close() return c.onFail(err) } c.Conn = socket c.connected = true return nil }
// NewClient initializes a ldap connection to a given URI. if tlsconf is nil, sane // default are used (tls1.2, secure verify, ...). // // * uri is a connection string to the ldap server, eg. `ldaps://example.net:636/dc=example,dc=net` // // * username is a bind user, eg. `uid=bind-bob,ou=logins,dc=mozilla` // // * password is a password for the bind user // // * cacertpath is the path to a file containing trusted root certificates // // * tlsconf is a Go TLS Configuration // // * starttls requires that the LDAP connection is opened insecurely but immediately switched to TLS using the StartTLS protocol. func NewClient(uri, username, password string, tlsconf *tls.Config, starttls bool) (Client, error) { errorPrefix := fmt.Sprintf("mozldap.NewClient(uri=%q, username=%q, password=****, starttls=%v)", uri, username, starttls) cli, err := ParseUri(uri) if err != nil { return Client{}, fmt.Errorf("%s -> %s", errorPrefix, err.Error()) } if tlsconf == nil { // sensible default for TLS configuration tlsconf = &tls.Config{ MinVersion: tls.VersionTLS12, CipherSuites: []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, tls.TLS_RSA_WITH_AES_128_CBC_SHA, tls.TLS_RSA_WITH_AES_256_CBC_SHA, }, InsecureSkipVerify: false, ServerName: cli.Host, } } // if we're secure, we want to check that // the server name matches the uri hostname if !tlsconf.InsecureSkipVerify && tlsconf.ServerName == "" { tlsconf.ServerName = cli.Host } if cli.UseTLS { cli.conn, err = ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", cli.Host, cli.Port), tlsconf) } else { cli.conn, err = ldap.Dial("tcp", fmt.Sprintf("%s:%d", cli.Host, cli.Port)) } if err != nil { return Client{}, fmt.Errorf("%s -> %s", errorPrefix, err.Error()) } // TLS and StartTLS are mutually exclusive if !cli.UseTLS && starttls { cli.UseStartTLS = true err = cli.conn.StartTLS(tlsconf) if err != nil { cli.Close() return Client{}, fmt.Errorf("%s -> %s", errorPrefix, err.Error()) } } // First bind with a read only user err = cli.conn.Bind(username, password) if err != nil { cli.Close() return Client{}, fmt.Errorf("%s -> %s", errorPrefix, err.Error()) } return cli, err }
func (cn *conn) ssl(o values) { verifyCaOnly := false tlsConf := tls.Config{} switch mode := o.Get("sslmode"); mode { // "require" is the default. case "", "require": // We must skip TLS's own verification since it requires full // verification since Go 1.3. tlsConf.InsecureSkipVerify = true // From http://www.postgresql.org/docs/current/static/libpq-ssl.html: // Note: For backwards compatibility with earlier versions of PostgreSQL, if a // root CA file exists, the behavior of sslmode=require will be the same as // that of verify-ca, meaning the server certificate is validated against the // CA. Relying on this behavior is discouraged, and applications that need // certificate validation should always use verify-ca or verify-full. if _, err := os.Stat(o.Get("sslrootcert")); err == nil { verifyCaOnly = true } else { o.Set("sslrootcert", "") } case "verify-ca": // We must skip TLS's own verification since it requires full // verification since Go 1.3. tlsConf.InsecureSkipVerify = true verifyCaOnly = true case "verify-full": tlsConf.ServerName = o.Get("host") case "disable": return default: errorf(`unsupported sslmode %q; only "require" (default), "verify-full", "verify-ca", and "disable" supported`, mode) } cn.setupSSLClientCertificates(&tlsConf, o) cn.setupSSLCA(&tlsConf, o) w := cn.writeBuf(0) w.int32(80877103) cn.sendStartupPacket(w) b := cn.scratch[:1] _, err := io.ReadFull(cn.c, b) if err != nil { panic(err) } if b[0] != 'S' { panic(ErrSSLNotSupported) } client := tls.Client(cn.c, &tlsConf) if verifyCaOnly { cn.verifyCA(client, &tlsConf) } cn.c = client }
func (t *Transport) newTLSConfig(host string) *tls.Config { cfg := new(tls.Config) if t.TLSClientConfig != nil { *cfg = *t.TLSClientConfig } cfg.NextProtos = []string{NextProtoTLS} // TODO: don't override if already in list cfg.ServerName = host return cfg }
// starts a server and will not return func (self *Server) ServerEntry(psignal chan uint32) { var sc *ServerClient var cert tls.Certificate var config tls.Config fmt.Println("Server Started") // signal caller we are ending defer func() { psignal <- 0 }() self.accountConfigsLock = &sync.Mutex{} self.accountConfigs = make(map[string]*AccountConfig) fmt.Printf("loading certificate\n") cert, err := tls.LoadX509KeyPair("cert.pem", "cert.pem") fmt.Printf("creating config\n") config = tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true} config.ServerName = "kmcg3413.net" // create a listening socket fmt.Printf("creating listener\n") ln, err := tls.Listen("tcp", ":4323", &config) if err != nil { fmt.Printf("Error: %s\n", err) return } if ln == nil { fmt.Println("There was an error creating the NET/TLS listener.") return } fmt.Printf("ready for connections\n") // handle connections for { conn, err := ln.Accept() if err != nil { fmt.Printf("accept-error: %s\n", err) continue } if conn == nil { fmt.Printf("accept-error: %s\n", err) continue } fmt.Printf("new client accepted\n") sc = self.NewClient() go sc.ClientEntry(conn) } return }
func initializeDopplerPool(config *config.Config, logger *gosteno.Logger) (*clientpool.DopplerPool, error) { adapter, err := storeAdapterProvider(config.EtcdUrls, config.EtcdMaxConcurrentRequests) if err != nil { return nil, err } err = adapter.Connect() if err != nil { logger.Warnd(map[string]interface{}{ "error": err.Error(), }, "Failed to connect to etcd") } preferInZone := func(relativePath string) bool { return strings.HasPrefix(relativePath, "/"+config.Zone+"/") } var tlsConfig *tls.Config if config.PreferredProtocol == "tls" { c := config.TLSConfig tlsConfig, err = listeners.NewTLSConfig(c.CertFile, c.KeyFile, c.CAFile) if err != nil { return nil, err } tlsConfig.ServerName = "doppler" } clientPool := clientpool.NewDopplerPool(logger, func(logger *gosteno.Logger, url string) (clientpool.Client, error) { client, err := clientpool.NewClient(logger, url, tlsConfig) if err == nil && client.Scheme() != config.PreferredProtocol { logger.Warnd(map[string]interface{}{ "url": url, }, "Doppler advertising UDP only") } return client, err }) onUpdate := func(all map[string]string, preferred map[string]string) { clientPool.Set(all, preferred) } dopplers, err := dopplerservice.NewFinder(adapter, config.PreferredProtocol, preferInZone, onUpdate, logger) if err != nil { return nil, err } dopplers.Start() onLegacyUpdate := func(all map[string]string, preferred map[string]string) { clientPool.SetLegacy(all, preferred) } legacyDopplers := dopplerservice.NewLegacyFinder(adapter, config.LoggregatorDropsondePort, preferInZone, onLegacyUpdate, logger) legacyDopplers.Start() return clientPool, nil }
// Retrieves the configuration from the config json // builds the TaskConfig object and returns it func (t *Tasks) GetConfig() *TaskConfig { if t.Config == nil { configuration := MainConfig{} if _, err := os.Stat(t.ConfigFile); os.IsNotExist(err) == false { log.Printf("Config file found - loading configuration") file, _ := os.Open(t.ConfigFile) decoder := json.NewDecoder(file) err := decoder.Decode(&configuration) if err != nil { log.Printf("Error decoding configuration: %s\n", err) } } else { //setup defaults log.Printf("No config file found, using defaults.") configuration.Cafile = "/vagrant/ssl/cacert.pem" configuration.Keyfile = "/vagrant/ssl/key.pem" configuration.Certfile = "/vagrant/ssl/cert.pem" configuration.Username = "******" configuration.Password = "******" configuration.Host = "proxy" configuration.Port = "5671" configuration.CN = "rabbit" } rootCa, err := ioutil.ReadFile(configuration.Cafile) if err != nil { panic(err) } clientKey, err := ioutil.ReadFile(configuration.Keyfile) if err != nil { panic(err) } clientCert, err := ioutil.ReadFile(configuration.Certfile) if err != nil { panic(err) } cfg := new(tls.Config) cfg.RootCAs = x509.NewCertPool() cfg.RootCAs.AppendCertsFromPEM([]byte(rootCa)) cfg.ServerName = configuration.CN cert, _ := tls.X509KeyPair([]byte(clientCert), []byte(clientKey)) cfg.Certificates = append(cfg.Certificates, cert) result := new(TaskConfig) result.TlsConfig = cfg result.Uri = fmt.Sprintf("amqps://%s:%s@%s:%s/", configuration.Username, configuration.Password, configuration.Host, configuration.Port) t.Config = result } return t.Config }
func (t *Transport) newTLSConfig(host string) *tls.Config { cfg := new(tls.Config) if t.TLSClientConfig != nil { *cfg = *t.TLSClientConfig } if !strSliceContains(cfg.NextProtos, NextProtoTLS) { cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...) } if cfg.ServerName == "" { cfg.ServerName = host } return cfg }
func TestDSNWithCustomTLS(t *testing.T) { baseDSN := "User:[email protected](localhost:5555)/dbname?tls=" tlsCfg := tls.Config{} RegisterTLSConfig("utils_test", &tlsCfg) // Custom TLS is missing tst := baseDSN + "invalid_tls" cfg, err := ParseDSN(tst) if err == nil { t.Errorf("invalid custom TLS in DSN (%s) but did not error. Got config: %#v", tst, cfg) } tst = baseDSN + "utils_test" // Custom TLS with a server name name := "foohost" tlsCfg.ServerName = name cfg, err = ParseDSN(tst) if err != nil { t.Error(err.Error()) } else if cfg.TLS.ServerName != name { t.Errorf("did not get the correct TLS ServerName (%s) parsing DSN (%s).", name, tst) } // Custom TLS without a server name name = "localhost" tlsCfg.ServerName = "" cfg, err = ParseDSN(tst) if err != nil { t.Error(err.Error()) } else if cfg.TLS.ServerName != name { t.Errorf("did not get the correct ServerName (%s) parsing DSN (%s).", name, tst) } DeregisterTLSConfig("utils_test") }
func (tc *tcpChannel) Open() error { dailTimeout := tc.conf.DialTimeout if 0 == dailTimeout { dailTimeout = 5 } var tlscfg *tls.Config hostport := tc.rurl.Host vpsHost, vpsPort, _ := net.SplitHostPort(hostport) if strings.EqualFold(tc.rurl.Scheme, "tls") { tlscfg = &tls.Config{} tlscfg.ServerName = vpsHost if len(tc.conf.SNIProxy) > 0 && vpsPort == "443" && hosts.InHosts(tc.conf.SNIProxy) { hostport = hosts.GetAddr(tc.conf.SNIProxy, "443") vpsHost, _, _ = net.SplitHostPort(hostport) tc.useSNIProxy = true log.Printf("VPS channel select SNIProxy %s to connect", hostport) } } if net.ParseIP(vpsHost) == nil { iphost, err := proxy.DnsGetDoaminIP(vpsHost) if nil != err { return err } hostport = net.JoinHostPort(iphost, vpsPort) } //log.Printf("######%s %s", vpsHost, tc.hostport) timeout := time.Duration(dailTimeout) * time.Second var c net.Conn var err error if len(tc.conf.Proxy) > 0 { c, err = helper.HTTPProxyDial(tc.conf.Proxy, hostport, timeout) } else { c, err = netx.DialTimeout("tcp", hostport, timeout) } if nil != tlscfg && nil == err { c = tls.Client(c, tlscfg) } if err != nil { if tc.rurl.String() != tc.originAddr { tc.rurl, _ = url.Parse(tc.originAddr) tc.proxyChannel.Addr = tc.rurl.String() } log.Printf("###Failed to connect %s with err:%v", hostport, err) return err } tc.conn = c return nil }
func addTLS(server string, conn net.Conn) (*tls.Conn, error) { tlsConfig := tls.Config{} if tr, ok := http.DefaultTransport.(*http.Transport); ok && tr.TLSClientConfig != nil { tlsConfig = *tr.TLSClientConfig } tlsConfig.ServerName = server tlsClient := tls.Client(conn, &tlsConfig) if err := tlsClient.Handshake(); err != nil { return nil, fmt.Errorf("Failed to TLS handshake with XMPP server: %s", err) } if err := tlsClient.VerifyHostname(server); err != nil { return nil, fmt.Errorf("Failed to verify hostname of XMPP server: %s", err) } return tlsClient, nil }
// ssl generates a function to upgrade a net.Conn based on the "sslmode" and // related settings. The function is nil when no upgrade should take place. func ssl(o values) func(net.Conn) net.Conn { verifyCaOnly := false tlsConf := tls.Config{} switch mode := o.Get("sslmode"); mode { // "require" is the default. case "", "require": // We must skip TLS's own verification since it requires full // verification since Go 1.3. tlsConf.InsecureSkipVerify = true // From http://www.postgresql.org/docs/current/static/libpq-ssl.html: // Note: For backwards compatibility with earlier versions of PostgreSQL, if a // root CA file exists, the behavior of sslmode=require will be the same as // that of verify-ca, meaning the server certificate is validated against the // CA. Relying on this behavior is discouraged, and applications that need // certificate validation should always use verify-ca or verify-full. if _, err := os.Stat(o.Get("sslrootcert")); err == nil { verifyCaOnly = true } else { o.Set("sslrootcert", "") } case "verify-ca": // We must skip TLS's own verification since it requires full // verification since Go 1.3. tlsConf.InsecureSkipVerify = true verifyCaOnly = true case "verify-full": tlsConf.ServerName = o.Get("host") case "disable": return nil default: errorf(`unsupported sslmode %q; only "require" (default), "verify-full", "verify-ca", and "disable" supported`, mode) } sslClientCertificates(&tlsConf, o) sslCertificateAuthority(&tlsConf, o) sslRenegotiation(&tlsConf) return func(conn net.Conn) net.Conn { client := tls.Client(conn, &tlsConf) if verifyCaOnly { sslVerifyCertificateAuthority(client, &tlsConf) } return client } }
func (server *Server) ListenAndServeTLS(listenString string, certFile string, keyFile string) error { cert, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { return err } tlsConfig := tls.Config{Certificates: []tls.Certificate{cert}} tlsConfig.ServerName = "localhost" ln, err := tls.Listen("tcp", listenString, &tlsConfig) if err != nil { return err } err = server.serve(ln) if err != nil { return err } return nil }
func NewClient() (*JabberClient, error) { tlsConfig := tls.Config{} tlsConfig.ServerName = "talk.google.com" options := xmpp.Options{ Host: "talk.google.com:443", User: services.Config.Jabber.Jid, Password: services.Config.Jabber.Pass, Debug: false, Session: false, TLSConfig: &tlsConfig, } talk, err := options.NewClient() if err != nil { return nil, err } ret := JabberClient{ talk, make(chan interface{}, 1), make(chan xmpp.Chat, 1), } go recvChannel(talk, ret.recv) // keepalive interval to reconnect, otherwise the connection dies interval := time.Minute * 15 keepalive := time.NewTicker(interval) go func() { for { select { case <-keepalive.C: talk.Close() talk, err = options.NewClient() if err != nil { log.Fatal(err) } go recvChannel(talk, ret.recv) case chat := <-ret.send: talk.Send(chat) } } }() return &ret, nil }
func sendMessage(msg *gomail.Message) error { config := tls.Config{} if *noTls { config.InsecureSkipVerify = true } var auth smtp.Auth if *smtpUser != "" { auth = gomail.LoginAuth(*smtpUser, *smtpPassword, *smtpHost) config.ServerName = *smtpHost } address := fmt.Sprintf("%v:%v", *smtpHost, *smtpPort) mailer := gomail.NewCustomMailer(address, auth, gomail.SetTLSConfig(&config)) if err := mailer.Send(msg); err != nil { log.Printf("Error sending configuration email: %v", err) return errors.New("Failed to send confirmation email") } return nil }
func (cn *conn) ssl(o values) { verifyCaOnly := false tlsConf := tls.Config{} switch mode := o.Get("sslmode"); mode { case "require", "": tlsConf.InsecureSkipVerify = true case "verify-ca": // We must skip TLS's own verification since it requires full // verification since Go 1.3. tlsConf.InsecureSkipVerify = true verifyCaOnly = true case "verify-full": tlsConf.ServerName = o.Get("host") case "disable": return default: errorf(`unsupported sslmode %q; only "require" (default), "verify-full", and "disable" supported`, mode) } cn.setupSSLClientCertificates(&tlsConf, o) cn.setupSSLCA(&tlsConf, o) w := cn.writeBuf(0) w.int32(80877103) cn.sendStartupPacket(w) b := cn.scratch[:1] _, err := io.ReadFull(cn.c, b) if err != nil { panic(err) } if b[0] != 'S' { panic(ErrSSLNotSupported) } client := tls.Client(cn.c, &tlsConf) if verifyCaOnly { cn.verifyCA(client, &tlsConf) } cn.c = client }
func dialServer(addr string, timeout time.Duration, ssl bool, sslconfig *tls.Config) (net.Conn, error) { var nc net.Conn var err error const network = "tcp" if timeout != 0 { if ssl { // unfortunately tls does not provide a DialTimeout // so lets try to replicate the behavior of Dial if nc, err = net.DialTimeout(network, addr, timeout); err != nil { return nil, err } var config *tls.Config if sslconfig != nil { config = sslconfig } else { config = &tls.Config{} } if config.ServerName == "" { idx := strings.LastIndex(addr, ":") if idx == -1 { idx = len(addr) } config.ServerName = addr[:idx] } tc := tls.Client(nc, config) if err = tc.Handshake(); err != nil { nc.Close() return nil, err } nc = tc } else { nc, err = net.DialTimeout(network, addr, timeout) } } else { if ssl { nc, err = tls.Dial(network, addr, sslconfig) } else { nc, err = net.Dial(network, addr) } } return nc, err }
func finalizeTLSConfig(tlsConfig *tls.Config, tlsRemoteCert *x509.Certificate) { // Trusted certificates if tlsRemoteCert != nil { caCertPool := x509.NewCertPool() // Make it a valid RootCA tlsRemoteCert.IsCA = true tlsRemoteCert.KeyUsage = x509.KeyUsageCertSign // Setup the pool caCertPool.AddCert(tlsRemoteCert) tlsConfig.RootCAs = caCertPool // Set the ServerName if tlsRemoteCert.DNSNames != nil { tlsConfig.ServerName = tlsRemoteCert.DNSNames[0] } } tlsConfig.BuildNameToCertificate() }
func (d *dialer) startTLS(c interfaces.Conn, conn net.Conn) error { fmt.Fprintf(c.Out(), "<starttls xmlns='%s'/>", NsTLS) proceed, err := nextStart(c.In()) if err != nil { return err } if proceed.Name.Space != NsTLS || proceed.Name.Local != "proceed" { return errors.New("xmpp: expected <proceed> after <starttls> but got <" + proceed.Name.Local + "> in " + proceed.Name.Space) } l := c.Config().GetLog() io.WriteString(l, "Starting TLS handshake\n") var tlsConfig tls.Config if c.Config().TLSConfig != nil { tlsConfig = *c.Config().TLSConfig } tlsConfig.ServerName = c.OriginDomain() tlsConfig.InsecureSkipVerify = true tlsConn := tls.Client(conn, &tlsConfig) if err := tlsConn.Handshake(); err != nil { return err } tlsState := tlsConn.ConnectionState() printTLSDetails(l, tlsState) if err = d.verifier.Verify(tlsState, tlsConfig, c.OriginDomain()); err != nil { return err } d.bindTransport(c, tlsConn) return nil }
func dial(address string, tlsConfig *tls.Config, fallback bool) (conn *grpc.ClientConn, err error) { ctx := log.Get().WithField("Address", address) opts := DialOptions if tlsConfig != nil { tlsConfig.ServerName = strings.SplitN(address, ":", 2)[0] // trim the port opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig))) } else { opts = append(opts, grpc.WithInsecure()) } conn, err = grpc.Dial( address, opts..., ) if err == nil { return } switch err := err.(type) { case x509.CertificateInvalidError, x509.ConstraintViolationError, x509.HostnameError, x509.InsecureAlgorithmError, x509.SystemRootsError, x509.UnhandledCriticalExtension, x509.UnknownAuthorityError: // Non-temporary error while connecting to a TLS-enabled server return nil, err case tls.RecordHeaderError: if fallback { ctx.WithError(err).Warn("Could not connect to gRPC server with TLS, reconnecting without it...") return dial(address, nil, fallback) } return nil, err } log.Get().WithField("ErrType", fmt.Sprintf("%T", err)).WithError(err).Error("Unhandled dial error [please create issue on Github]") return nil, err }
func (client *Client) dialTcpTLS(network, addr string, cfg *tls.Config) (net.Conn, error) { cfg.ServerName = "server.h2.proxy" cn, err := tls.Dial(network, addr, cfg) if err != nil { return nil, err } if err := cn.Handshake(); err != nil { return nil, err } if !cfg.InsecureSkipVerify { if err := cn.VerifyHostname(cfg.ServerName); err != nil { return nil, err } } state := cn.ConnectionState() if p := state.NegotiatedProtocol; p != http2.NextProtoTLS { return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, http2.NextProtoTLS) } if !state.NegotiatedProtocolIsMutual { return nil, errors.New("http2: could not negotiate protocol mutually") } return cn, nil }
func (client *Client) dialWsTLS(network, addr string, cfg *tls.Config) (net.Conn, error) { ws, _, err := client.Dialer.Dial(client.ServerUrl.String()+"/p", nil) if err != nil { return nil, err } closeWs := ws defer func() { if closeWs != nil { closeWs.Close() } }() pc := NewWs(ws, client.BufSize, client.PingPeriod) u := url.URL{Host: client.ServerUrl.Host} _, hostNoPort := hostPortNoPort(&u) cfg.ServerName = hostNoPort cn := tls.Client(pc, cfg) if err := cn.Handshake(); err != nil { return nil, err } if !cfg.InsecureSkipVerify { if err := cn.VerifyHostname(cfg.ServerName); err != nil { return nil, err } } state := cn.ConnectionState() if p := state.NegotiatedProtocol; p != http2.NextProtoTLS { return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, http2.NextProtoTLS) } if !state.NegotiatedProtocolIsMutual { return nil, errors.New("http2: could not negotiate protocol mutually") } closeWs = nil go client.ping(ws, addr) return cn, nil }