本文整理汇总了Golang中crypto/tls.Config.ServerName方法的典型用法代码示例。如果您正苦于以下问题:Golang Config.ServerName方法的具体用法?Golang Config.ServerName怎么用?Golang Config.ServerName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类crypto/tls.Config
的用法示例。
在下文中一共展示了Config.ServerName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: StartListen
// 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
}
示例2: StartTLS
// 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
}
示例3: ClientConfig
// 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
}
示例4: upgradeTLS
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
}
示例5: SendTo
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
}
示例6: TestTLSConnection
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)
}
示例7: performRequest
// 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
}
示例8: ssl
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)
}
示例9: Connect
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
}
示例10: NewClient
// 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
}
示例11: ssl
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
}
示例12: newTLSConfig
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
}
示例13: ServerEntry
// 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
}
示例14: initializeDopplerPool
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
}
示例15: GetConfig
// 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 = "admin"
configuration.Password = "admin"
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:%[email protected]%s:%s/", configuration.Username, configuration.Password, configuration.Host, configuration.Port)
t.Config = result
}
return t.Config
}