本文整理汇总了Golang中crypto/tls.Config类的典型用法代码示例。如果您正苦于以下问题:Golang Config类的具体用法?Golang Config怎么用?Golang Config使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Config类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ServerTLSListen
func ServerTLSListen(service string, f func(conn net.Conn)) {
// Load x509 certificates for our private/public key, makecert.sh will
// generate them for you.
cert, err := tls.LoadX509KeyPair("certs/server.pem", "certs/server.key")
if err != nil {
log.Fatalf("server: loadkeys: %s", err)
}
// Note if we don't tls.RequireAnyClientCert client side certs are ignored.
config := tls.Config{Certificates: []tls.Certificate{cert}, ClientAuth: tls.RequireAnyClientCert}
config.Rand = rand.Reader
listener, err := tls.Listen("tcp", service, &config)
if err != nil {
log.Fatalf("server: listen: %s", err)
}
log.Print("server: listening")
// Keep this loop simple/fast as to be able to handle new connections
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("server: accept: %s", err)
break
}
log.Printf("server: accepted from %s", conn.RemoteAddr())
// Fire off go routing to handle rest of connection.
go handleClient(conn, f)
}
}
示例2: NewTLSServer
// NewTLSServer creates and starts a TLS-enabled testing server.
func NewTLSServer(bind string, containerChan chan<- *docker.Container, hook func(*http.Request), tlsConfig TLSConfig) (*DockerServer, error) {
listener, err := net.Listen("tcp", bind)
if err != nil {
return nil, err
}
defaultCertificate, err := tls.LoadX509KeyPair(tlsConfig.CertPath, tlsConfig.CertKeyPath)
if err != nil {
return nil, err
}
tlsServerConfig := new(tls.Config)
tlsServerConfig.Certificates = []tls.Certificate{defaultCertificate}
if tlsConfig.RootCAPath != "" {
rootCertPEM, err := ioutil.ReadFile(tlsConfig.RootCAPath)
if err != nil {
return nil, err
}
certsPool := x509.NewCertPool()
certsPool.AppendCertsFromPEM(rootCertPEM)
tlsServerConfig.RootCAs = certsPool
}
tlsListener := tls.NewListener(listener, tlsServerConfig)
server := buildDockerServer(tlsListener, containerChan, hook)
go http.Serve(tlsListener, server)
return server, nil
}
示例3: ssl
func (cn *conn) ssl(o values) {
tlsConf := tls.Config{}
switch mode := o.Get("sslmode"); mode {
case "require", "":
tlsConf.InsecureSkipVerify = true
case "verify-full":
// fall out
case "disable":
return
default:
errorf(`unsupported sslmode %q; only "require" (default), "verify-full", and "disable" supported`, mode)
}
cn.setupSSLCertKey(&tlsConf, o)
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)
}
示例4: DialTablet
// DialTablet creates and initializes TabletBson.
func DialTablet(context context.Context, endPoint topo.EndPoint, keyspace, shard string, timeout time.Duration) (tabletconn.TabletConn, error) {
var addr string
var config *tls.Config
if *tabletBsonEncrypted {
addr = fmt.Sprintf("%v:%v", endPoint.Host, endPoint.NamedPortMap["_vts"])
config = &tls.Config{}
config.InsecureSkipVerify = true
} else {
addr = fmt.Sprintf("%v:%v", endPoint.Host, endPoint.NamedPortMap["_vtocc"])
}
conn := &TabletBson{endPoint: endPoint}
var err error
if *tabletBsonUsername != "" {
conn.rpcClient, err = bsonrpc.DialAuthHTTP("tcp", addr, *tabletBsonUsername, *tabletBsonPassword, timeout, config)
} else {
conn.rpcClient, err = bsonrpc.DialHTTP("tcp", addr, timeout, config)
}
if err != nil {
return nil, tabletError(err)
}
var sessionInfo tproto.SessionInfo
if err = conn.rpcClient.Call("SqlQuery.GetSessionId", tproto.SessionParams{Keyspace: keyspace, Shard: shard}, &sessionInfo); err != nil {
conn.rpcClient.Close()
return nil, tabletError(err)
}
conn.sessionID = sessionInfo.SessionId
return conn, nil
}
示例5: DialTablet
// DialTablet creates and initializes TabletBson.
func DialTablet(ctx context.Context, endPoint topo.EndPoint, keyspace, shard string, timeout time.Duration) (tabletconn.TabletConn, error) {
var addr string
var config *tls.Config
if *tabletBsonEncrypted {
addr = netutil.JoinHostPort(endPoint.Host, endPoint.NamedPortMap["vts"])
config = &tls.Config{}
config.InsecureSkipVerify = true
} else {
addr = netutil.JoinHostPort(endPoint.Host, endPoint.NamedPortMap["vt"])
}
conn := &TabletBson{endPoint: endPoint}
var err error
if *tabletBsonUsername != "" {
conn.rpcClient, err = bsonrpc.DialAuthHTTP("tcp", addr, *tabletBsonUsername, *tabletBsonPassword, timeout, config)
} else {
conn.rpcClient, err = bsonrpc.DialHTTP("tcp", addr, timeout, config)
}
if err != nil {
return nil, tabletError(err)
}
var sessionInfo tproto.SessionInfo
if err = conn.rpcClient.Call(ctx, "SqlQuery.GetSessionId", tproto.SessionParams{Keyspace: keyspace, Shard: shard}, &sessionInfo); err != nil {
conn.rpcClient.Close()
return nil, tabletError(err)
}
// SqlQuery.GetSessionId might return an application error inside the SessionInfo
if err = vterrors.FromRPCError(sessionInfo.Err); err != nil {
conn.rpcClient.Close()
return nil, tabletError(err)
}
conn.sessionID = sessionInfo.SessionId
return conn, nil
}
示例6: runServer
func runServer(transportFactory thrift.TTransportFactory, protocolFactory thrift.TProtocolFactory, addr string, secure bool) error {
var transport thrift.TServerTransport
var err error
if secure {
cfg := new(tls.Config)
if cert, err := tls.LoadX509KeyPair("server.crt", "server.key"); err == nil {
cfg.Certificates = append(cfg.Certificates, cert)
} else {
return err
}
transport, err = thrift.NewTSSLServerSocket(addr, cfg)
} else {
transport, err = thrift.NewTServerSocket(addr)
}
if err != nil {
return err
}
fmt.Printf("%T\n", transport)
handler := NewCalculatorHandler()
processor := tutorial.NewCalculatorProcessor(handler)
server := thrift.NewTSimpleServer4(processor, transport, transportFactory, protocolFactory)
fmt.Println("Starting the simple server... on ", addr)
return server.Serve()
}
示例7: main
func main() {
random, _ := os.Open("/dev/urandom", os.O_RDONLY, 0)
pembytes := readEntireFile("/home/kris/SSL/gr0g.crt")
cert, _ := pem.Decode(pembytes)
keybytes := readEntireFile("/home/kris/SSL/gr0g.key")
pk, _ := pem.Decode(keybytes)
privatekey, _ := x509.ParsePKCS1PrivateKey(pk.Bytes)
config := new(tls.Config)
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0].Certificate = [][]byte{cert.Bytes}
config.Certificates[0].PrivateKey = privatekey
config.Rand = random
//config.RootCAs = caset
config.Time = time.Seconds
listener, err := tls.Listen("tcp", "0.0.0.0:8443", config)
fmt.Printf("%s\n", err)
for {
conn, _ := listener.Accept()
go func() {
for {
buf := make([]byte, 1024)
_, err := conn.Read(buf)
if err != nil {
return
}
fmt.Printf("%s", buf)
}
}()
}
}
示例8: 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
}
示例9: 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{}
}
CAFiles := info.cafiles()
if len(CAFiles) > 0 {
cfg.RootCAs, err = tlsutil.NewCertPool(CAFiles)
if err != nil {
return nil, err
}
}
if info.selfCert {
cfg.InsecureSkipVerify = true
}
return cfg, nil
}
示例10: newH2Transport
func (client *Client) newH2Transport() http.RoundTripper {
tlsConfig := tls.Config{
InsecureSkipVerify: os.Getenv("TEST_MODE") == "1",
}
if client.ServerUrl.Scheme == "tcp" {
// 1. LoadClientCert
cert, err := tls.LoadX509KeyPair("client.crt", "client.key")
if err != nil {
log.WithError(err).Fatal("loading server certificate")
}
// 2. LoadCACert
caCert, err := ioutil.ReadFile("chain.pem")
if err != nil {
log.WithError(err).Fatal("loading CA certificate")
}
caPool := x509.NewCertPool()
caPool.AppendCertsFromPEM(caCert)
tlsConfig.RootCAs = caPool
tlsConfig.Certificates = []tls.Certificate{cert}
}
return &http2.Transport{
TLSClientConfig: &tlsConfig,
DialTLS: client.DialProxyTLS,
}
}
示例11: ClientConfig
// Generates a tls.Config object for a client from the given files.
func (info TLSInfo) ClientConfig() (*tls.Config, error) {
var cfg tls.Config
if info.KeyFile == "" || info.CertFile == "" {
return &cfg, nil
}
tlsCert, err := tls.LoadX509KeyPair(info.CertFile, info.KeyFile)
if err != nil {
return nil, err
}
cfg.Certificates = []tls.Certificate{tlsCert}
if info.CAFile != "" {
cp, err := newCertPool(info.CAFile)
if err != nil {
return nil, err
}
cfg.RootCAs = cp
}
return &cfg, nil
}
示例12: HandleStartTLS
// HandleStartTLS is the companion to StartTLS, and will do the connection upgrade. It assumes
// that the TLS command byte has already been read. Like StartTLS it returns the peer name, or
// an error
func (p *Protocol) HandleStartTLS(identity *security.Identity, caCertificate *security.Certificate) (string, error) {
var (
err error
tlsConn *tls.Conn
)
// Build the config
config := new(tls.Config)
config.ClientAuth = tls.RequireAndVerifyClientCert
// 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.Server(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()
// Send an Ack
p.Ack()
return cs.PeerCertificates[0].Subject.CommonName, nil
}
示例13: 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
}
示例14: NewETCDMetrics
func NewETCDMetrics(logger lager.Logger, etcdOptions *ETCDOptions) (*ETCDMetrics, error) {
var tlsConfig *tls.Config
if etcdOptions.CertFile != "" && etcdOptions.KeyFile != "" {
var err error
tlsConfig, err = cfhttp.NewTLSConfig(etcdOptions.CertFile, etcdOptions.KeyFile, etcdOptions.CAFile)
if err != nil {
return nil, err
}
tlsConfig.ClientSessionCache = tls.NewLRUClientSessionCache(etcdOptions.ClientSessionCacheSize)
}
client := cfhttp.NewClient()
client.CheckRedirect = func(*http.Request, []*http.Request) error {
return errRedirected
}
if tr, ok := client.Transport.(*http.Transport); ok {
tr.TLSClientConfig = tlsConfig
} else {
return nil, errors.New("Invalid transport")
}
return &ETCDMetrics{
logger: logger,
etcdCluster: etcdOptions.ClusterUrls,
client: client,
}, nil
}
示例15: SecureServe
// SecureListen obtains a listener that accepts
// secure connections
func SecureServe(addr string, certFile, keyFile, caFile string) {
config := tls.Config{}
// load the server cert / key
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
log.Fatalf("%s", err)
}
config.Certificates = []tls.Certificate{cert}
// load the ca if necessary
// FIXME(alainjobart) this doesn't quite work yet, have
// to investigate
if caFile != "" {
config.ClientCAs = x509.NewCertPool()
pemCerts, err := ioutil.ReadFile(caFile)
if err != nil {
log.Fatalf("%s", err)
}
if !config.ClientCAs.AppendCertsFromPEM(pemCerts) {
log.Fatalf("%s", err)
}
config.ClientAuth = tls.RequireAndVerifyClientCert
}
l, err := tls.Listen("tcp", addr, &config)
if err != nil {
log.Fatalf("%s", err)
}
throttled := NewThrottledListener(l, *secureThrottle, *secureMaxBuffer)
cl := proc.Published(throttled, "SecureConnections", "SecureAccepts")
go http.Serve(cl, nil)
}