本文整理汇总了Golang中crypto/tls.Config.ClientAuth方法的典型用法代码示例。如果您正苦于以下问题:Golang Config.ClientAuth方法的具体用法?Golang Config.ClientAuth怎么用?Golang Config.ClientAuth使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类crypto/tls.Config
的用法示例。
在下文中一共展示了Config.ClientAuth方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ServerConfig
// Generates a tls.Config object for a server from the given files.
func (info TLSInfo) ServerConfig() (*tls.Config, error) {
// Both the key and cert must be present.
if info.KeyFile == "" || info.CertFile == "" {
return nil, fmt.Errorf("KeyFile and CertFile must both be present[key: %v, cert: %v]", info.KeyFile, info.CertFile)
}
var cfg tls.Config
tlsCert, err := tls.LoadX509KeyPair(info.CertFile, info.KeyFile)
if err != nil {
return nil, err
}
cfg.Certificates = []tls.Certificate{tlsCert}
if info.CAFile != "" {
cfg.ClientAuth = tls.RequireAndVerifyClientCert
cp, err := newCertPool(info.CAFile)
if err != nil {
return nil, err
}
cfg.RootCAs = cp
cfg.ClientCAs = cp
} else {
cfg.ClientAuth = tls.NoClientCert
}
return &cfg, nil
}
示例2: setupClientAuth
// setupClientAuth sets up TLS client authentication only if
// any of the TLS configs specified at least one cert file.
func setupClientAuth(tlsConfigs []TLSConfig, config *tls.Config) error {
whatClientAuth := tls.NoClientCert
for _, cfg := range tlsConfigs {
if whatClientAuth < cfg.ClientAuth { // Use the most restrictive.
whatClientAuth = cfg.ClientAuth
}
}
if whatClientAuth != tls.NoClientCert {
pool := x509.NewCertPool()
for _, cfg := range tlsConfigs {
if len(cfg.ClientCerts) == 0 {
continue
}
for _, caFile := range cfg.ClientCerts {
caCrt, err := ioutil.ReadFile(caFile) // Anyone that gets a cert from this CA can connect
if err != nil {
return err
}
if !pool.AppendCertsFromPEM(caCrt) {
return fmt.Errorf("error loading client certificate '%s': no certificates were successfully parsed", caFile)
}
}
}
config.ClientCAs = pool
config.ClientAuth = whatClientAuth
}
return nil
}
示例3: 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
}
示例4: GetServerTLSConfig
// GetServerTLSConfig returns a TLS config for using with ListenAndServeTLS
// This sets up the Root and Client CAs for verification
func GetServerTLSConfig(caCert, serverCert, serverKey []byte, allowInsecure bool) (*tls.Config, error) {
// TLS config
var tlsConfig tls.Config
tlsConfig.InsecureSkipVerify = allowInsecure
certPool := x509.NewCertPool()
// load system certs
if err := loadSystemCertificates(certPool); err != nil {
return nil, err
}
// append custom CA
certPool.AppendCertsFromPEM(caCert)
tlsConfig.RootCAs = certPool
tlsConfig.ClientCAs = certPool
log.Debugf("tls root CAs: %d", len(tlsConfig.RootCAs.Subjects()))
// require client auth
tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
// server cert
keypair, err := tls.X509KeyPair(serverCert, serverKey)
if err != nil {
return &tlsConfig, err
}
tlsConfig.Certificates = []tls.Certificate{keypair}
return &tlsConfig, nil
}
示例5: setupClientAuth
// setupClientAuth sets up TLS client authentication only if
// any of the TLS configs specified at least one cert file.
func setupClientAuth(tlsConfigs []TLSConfig, config *tls.Config) error {
var clientAuth bool
for _, cfg := range tlsConfigs {
if len(cfg.ClientCerts) > 0 {
clientAuth = true
break
}
}
if clientAuth {
pool := x509.NewCertPool()
for _, cfg := range tlsConfigs {
for _, caFile := range cfg.ClientCerts {
caCrt, err := ioutil.ReadFile(caFile) // Anyone that gets a cert from Matt Holt can connect
if err != nil {
return err
}
if !pool.AppendCertsFromPEM(caCrt) {
return fmt.Errorf("error loading client certificate '%s': no certificates were successfully parsed", caFile)
}
}
}
config.ClientCAs = pool
config.ClientAuth = tls.RequireAndVerifyClientCert
}
return nil
}
示例6: 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)
}
示例7: NewTLSConfig
// NewTLSConfig returns an initialized TLS configuration suitable for client
// authentication. If caFile is non-empty, it will be loaded.
func NewTLSConfig(caFile string, mutualTLS bool) (*tls.Config, error) {
var c tls.Config
// TLS 1.0 at a minimum (for mysql)
c.MinVersion = tls.VersionTLS10
c.PreferServerCipherSuites = true
if mutualTLS {
log.Info("MutualTLS requested, client certificates will be verified")
c.ClientAuth = tls.VerifyClientCertIfGiven
}
if caFile != "" {
data, err := ioutil.ReadFile(caFile)
if err != nil {
return &c, err
}
c.ClientCAs = x509.NewCertPool()
if !c.ClientCAs.AppendCertsFromPEM(data) {
return &c, errors.New("No certificates parsed")
}
log.Info("Read in CA file:", caFile)
}
c.BuildNameToCertificate()
return &c, nil
}
示例8: 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
}
示例9: NewTestServer
// NewTestServer wraps a Service as an httptest.Server.
func NewTestServer(s Service, cert, key, caCert []byte) (*httptest.Server, error) {
var tlsConfig *tls.Config
if cert != nil {
cert, err := tls.X509KeyPair(cert, key)
if err != nil {
return nil, err
}
tlsConfig = &tls.Config{Certificates: []tls.Certificate{cert}}
}
if caCert != nil {
rootCAs := x509.NewCertPool()
rootCAs.AppendCertsFromPEM(caCert)
if tlsConfig == nil {
tlsConfig = &tls.Config{}
}
tlsConfig.ClientCAs = rootCAs
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
}
serveHTTP := func(w http.ResponseWriter, r *http.Request) {
var review v1beta1.TokenReview
if err := json.NewDecoder(r.Body).Decode(&review); err != nil {
http.Error(w, fmt.Sprintf("failed to decode body: %v", err), http.StatusBadRequest)
return
}
s.Review(&review)
type userInfo struct {
Username string `json:"username"`
UID string `json:"uid"`
Groups []string `json:"groups"`
}
type status struct {
Authenticated bool `json:"authenticated"`
User userInfo `json:"user"`
}
resp := struct {
APIVersion string `json:"apiVersion"`
Status status `json:"status"`
}{
APIVersion: v1beta1.SchemeGroupVersion.String(),
Status: status{
review.Status.Authenticated,
userInfo{
Username: review.Status.User.Username,
UID: review.Status.User.UID,
Groups: review.Status.User.Groups,
},
},
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
server := httptest.NewUnstartedServer(http.HandlerFunc(serveHTTP))
server.TLS = tlsConfig
server.StartTLS()
return server, nil
}
示例10: ServeSecurePort
// ServerSecurePort obtains a listener that accepts secure connections.
// If the provided port is zero, the listening is disabled.
func ServeSecurePort(securePort int, certFile, keyFile, caCertFile string) {
if securePort == 0 {
log.Info("Not listening on secure port")
return
}
config := tls.Config{}
// load the server cert / key
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
log.Fatalf("SecureServe.LoadX509KeyPair(%v, %v) failed: %v", certFile, keyFile, err)
}
config.Certificates = []tls.Certificate{cert}
// load the ca if necessary
// FIXME(alainjobart) this doesn't quite work yet, have
// to investigate
if caCertFile != "" {
config.ClientCAs = x509.NewCertPool()
pemCerts, err := ioutil.ReadFile(caCertFile)
if err != nil {
log.Fatalf("SecureServe: cannot read ca file %v: %v", caCertFile, err)
}
if !config.ClientCAs.AppendCertsFromPEM(pemCerts) {
log.Fatalf("SecureServe: AppendCertsFromPEM failed: %v", err)
}
config.ClientAuth = tls.RequireAndVerifyClientCert
}
l, err := tls.Listen("tcp", fmt.Sprintf(":%d", securePort), &config)
if err != nil {
log.Fatalf("Error listening on secure port %v: %v", securePort, err)
}
log.Infof("Listening on secure port %v", securePort)
throttled := NewThrottledListener(l, *secureThrottle, *secureMaxBuffer)
cl := proc.Published(throttled, "SecureConnections", "SecureAccepts")
// rpc.HandleHTTP registers the default GOB handler at /_goRPC_
// and the debug RPC service at /debug/rpc (it displays a list
// of registered services and their methods).
if ServiceMap["gob-vts"] {
log.Infof("Registering GOB handler and /debug/rpc URL for vts port")
secureRpcServer.HandleHTTP(rpcwrap.GetRpcPath("gob", false), rpcplus.DefaultDebugPath)
}
if ServiceMap["gob-auth-vts"] {
log.Infof("Registering GOB handler and /debug/rpcs URL for SASL vts port")
authenticatedSecureRpcServer.HandleHTTP(rpcwrap.GetRpcPath("gob", true), rpcplus.DefaultDebugPath+"s")
}
handler := http.NewServeMux()
bsonrpc.ServeCustomRPC(handler, secureRpcServer, false)
bsonrpc.ServeCustomRPC(handler, authenticatedSecureRpcServer, true)
httpServer := http.Server{
Handler: handler,
}
go httpServer.Serve(cl)
}
示例11: ListenAnonymous
// ListenAnonymous returns a new Tao-based net.Listener that does not require
// its peer to attest to its identity.
func ListenAnonymous(network, laddr string, config *tls.Config, g Guard, v *Verifier, del *Attestation) (net.Listener, error) {
config.ClientAuth = tls.NoClientCert
inner, err := tls.Listen(network, laddr, config)
if err != nil {
return nil, err
}
return &anonymousListener{listener{inner, g, v, del}}, nil
}
示例12: Init
func Init(messageQueue chan *bl.Message, conf map[string]interface{}) bl.Input {
var tlsConfig tls.Config
tag := bl.GString("tag", conf)
bind := bl.GString("bind", conf)
timeout := int64(bl.GInt("timeout", conf))
if timeout <= 0 {
log.Fatalf("[ERROR] [%s] You must specify right timeout (%d)", module, timeout)
}
SSLCertificate := bl.GString("ssl_cert", conf)
SSLKey := bl.GString("ssl_key", conf)
SSLCA := bl.GString("ssl_ca", conf)
if len(SSLCertificate) > 0 && len(SSLKey) > 0 {
tlsConfig.MinVersion = tls.VersionTLS12
log.Printf("[INFO] [%s] Loading server ssl certificate and key from \"%s\" and \"%s\"", tag,
SSLCertificate, SSLKey)
cert, err := tls.LoadX509KeyPair(SSLCertificate, SSLKey)
if err != nil {
log.Fatalf("[ERROR] [%s] Failed loading server ssl certificate: %s", tag, err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
if len(SSLCA) > 0 {
log.Printf("[INFO] [%s] Loading CA certificate from file: %s\n", tag, SSLCA)
tlsConfig.ClientCAs = x509.NewCertPool()
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
pemdata, err := ioutil.ReadFile(SSLCA)
if err != nil {
log.Fatalf("[ERROR] [%s] Failure reading CA certificate: %s\n", tag, err)
}
block, _ := pem.Decode(pemdata)
if block == nil {
log.Fatalf("[ERROR] [%s] Failed to decode PEM data of CA certificate from \"%s\"\n", tag, SSLCA)
}
if block.Type != "CERTIFICATE" {
log.Fatalf("[ERROR] [%s] This is not a certificate file: %s\n", tag, SSLCA)
}
cacert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
log.Fatalf("[ERROR] [%s] Failed to parse CA certificate: %s\n", tag, SSLCA)
}
tlsConfig.ClientCAs.AddCert(cacert)
}
v := &In_logear_forwarder{tag: tag,
messageQueue: messageQueue,
tlsConfig: tlsConfig,
bind: bind,
timeout: time.Second * time.Duration(timeout)}
return v
} else {
log.Fatalf("[ERROR] [%s] You must specify ssl_cert and ssl_key", module)
}
return nil
}
示例13: NewTestServer
// NewTestServer wraps a Service as an httptest.Server.
func NewTestServer(s Service, cert, key, caCert []byte) (*httptest.Server, error) {
var tlsConfig *tls.Config
if cert != nil {
cert, err := tls.X509KeyPair(cert, key)
if err != nil {
return nil, err
}
tlsConfig = &tls.Config{Certificates: []tls.Certificate{cert}}
}
if caCert != nil {
rootCAs := x509.NewCertPool()
rootCAs.AppendCertsFromPEM(caCert)
if tlsConfig == nil {
tlsConfig = &tls.Config{}
}
tlsConfig.ClientCAs = rootCAs
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
}
serveHTTP := func(w http.ResponseWriter, r *http.Request) {
var review v1alpha1.ImageReview
if err := json.NewDecoder(r.Body).Decode(&review); err != nil {
http.Error(w, fmt.Sprintf("failed to decode body: %v", err), http.StatusBadRequest)
return
}
if s.HTTPStatusCode() < 200 || s.HTTPStatusCode() >= 300 {
http.Error(w, "HTTP Error", s.HTTPStatusCode())
return
}
s.Review(&review)
type status struct {
Allowed bool `json:"allowed"`
Reason string `json:"reason"`
}
resp := struct {
APIVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Status status `json:"status"`
}{
APIVersion: v1alpha1.SchemeGroupVersion.String(),
Kind: "ImageReview",
Status: status{review.Status.Allowed, review.Status.Reason},
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
server := httptest.NewUnstartedServer(http.HandlerFunc(serveHTTP))
server.TLS = tlsConfig
server.StartTLS()
return server, nil
}
示例14: TLSConfig
func (c Config) TLSConfig() *tls.Config {
certs := []tls.Certificate{c.TLSCertificate()}
tlsConfig := tls.Config{
Certificates: certs,
}
if c.TLSClientAuthEnabled() {
tlsConfig.ClientCAs = c.ClientCAsPool()
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
}
return &tlsConfig
}
示例15: tlsConfig
func tlsConfig() *tls.Config {
cfg := new(tls.Config)
cfg.ClientCAs = x509.NewCertPool()
cfg.ClientCAs.AppendCertsFromPEM([]byte(caCert))
cert, err := tls.X509KeyPair([]byte(serverCert), []byte(serverKey))
if err != nil {
panic(err)
}
cfg.Certificates = append(cfg.Certificates, cert)
cfg.ClientAuth = tls.RequireAndVerifyClientCert
return cfg
}