In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "how to use Go to achieve TLS server and client". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Transport layer Security Protocol (Transport Layer Security, abbreviation: TLS) and its predecessor secure socket layer (Secure Sockets Layer, abbreviation: SSL) are security protocols designed to provide security and data integrity for Internet communications.
SSL includes the record layer (Record Layer) and the transport layer, and the record layer protocol determines the encapsulation format of the transport layer data. The transport layer security protocol uses X.509 authentication, then uses asymmetric encryption calculus to authenticate the communicator, and then exchanges the symmetric key as the interview key (Session key). This interview key is used to encrypt the data exchanged between the two parties to ensure the confidentiality and reliability of the communication between the two applications, so that the communication between the client and the server application will not be eavesdropped by the attacker.
This article does not provide an in-depth tutorial on TLS, but provides two simple examples of the Go application TLS to demonstrate the rapid development of secure network transport programs using the go language.
History of TLS
In early 1994, NetScape designed version 1.0 of the SSL protocol (Secure Sockets Layer), but it was not released.
In November 1994, NetScape released SSL version 2. 0 and soon discovered that there were serious vulnerabilities.
In November 1996, SSL 3.0 was published and applied on a large scale.
In January 1999, ISOC, an Internet standardization organization, took over from NetScape and released the upgraded version of SSL, version 1.0 of TLS.
In April 2006 and August 2008, TLS underwent two upgrades, TLS version 1.1 and TLS version 1.2. The latest change is the 2011 revision of TLS 1.2.
Tls 1.3 is now being developed.
Certificate generation
First we create the private key and certificate.
Certificate generation on the server side
Server-side certificates are used to ensure that the server is not fake.
1. Generate the server-side private key
Openssl genrsa-out server.key 2048
2. Generate server-side certificate
Openssl req-new-x509-key server.key-out server.pem-days 3650
Or
Go run $GOROOT/src/crypto/tls/generate_cert.go-certificate generation for host localhost clients
In addition to the "server certificate", the "client certificate" is also involved in some situations. The so-called "client certificate" is used to prove the identity of client visitors.
For example, in the intranet of some financial companies, you must deploy a "client certificate" on your computer in order to open the page of an important server.
I will demonstrate the use of client certificates in later examples.
3. Generate the private key of the client
Openssl genrsa-out client.key 2048
4. Generate the certificate of the client
Openssl req-new-x509-key client.key-out client.pem-days 3650
Or use the following script:
#! / bin/bash# call this script with an email address (valid or not). # like:#. / makecert.sh demo@random.commkdir certsrm certs/*echo "make server cert" openssl req-new-nodes-x509-out certs/server.pem-keyout certs/server.key-days 3650-subj "/ C=DE/ST=NRW/L=Earth/O=Random Company/OU=IT/CN=www.random.com/emailAddress=$1" echo "make client cert" openssl req-new-nodes-x509-out certs/client.pem-keyout certs/client. Key-days 3650-subj "/ C=DE/ST=NRW/L=Earth/O=Random Company/OU=IT/CN=www.random.com/emailAddress=$1"
Golang example
The Go Package tls part implements the function of tls 1.2, which can meet our daily applications. Package crypto/x509 provides operations related to certificate management.
Use of server certificates
The code in this section provides an example of a server using a certificate. The following code is an example of a server:
Package mainimport ("bufio"crypto/tls"log"net") func main () {cert, err: = tls.LoadX509KeyPair ("server.pem", "server.key") if err! = nil {log.Println (err) return} config: = & tls.Config {Certificates: [] tls.Certificate {cert} ln, err: = tls.Listen ("tcp", ": 443") Config) if err! = nil {log.Println (err) return} defer ln.Close () for {conn Err: = ln.Accept () if err! = nil {log.Println (err) continue} go handleConn (conn)}} func handleConn (conn net.Conn) {defer conn.Close () r: = bufio.NewReader (conn) for {msg Err: = r.ReadString ('\ n') if err! = nil {log.Println (err) return} println (msg) n, err: = conn.Write ([] byte ("world\ n")) if err! = nil {log.Println (n, err) return}
First, get the certificate cert from the server private key and pem file we created above, and generate a tls.Config object. This object has multiple fields that can be set, and in this case we use its default value.
Then use tls.Listen to start listening to the client connection, accept and get a net.Conn, the subsequent processing is the same as the ordinary TCP program.
Then, let's take a look at how the client is implemented:
Package mainimport ("crypto/tls"log") func main () {conf: = & tls.Config {InsecureSkipVerify: true,} conn, err: = tls.Dial ("tcp", "127.0.0.1 log 443", conf) if err! = nil {log.Println (err) return} defer conn.Close () n Err: = conn.Write ([] byte ("hello\ n") if err! = nil {log.Println (n, err) return} buf: = make ([] byte, 100) n, err = conn.Read (buf) if err! = nil {log.Println (n, err) return} println (string (buf [: n]))}
InsecureSkipVerify is used to control whether the client is a certificate and the server hostname. If set to true, the certificate and the hostname in the certificate are not verified to match the server hostname.
Because the self-signed certificate is used in our example, it is set to true for testing purposes only.
As you can see, the whole program is not much different from the ordinary TCP program, but the initial need to do some TLS configuration.
You can test this example with go run server.go and go run client.go.
Use of client certificates
In some cases, two-way authentication is required, and the server also needs to verify the authenticity of the client. In this case, we need a little extra configuration from the server and client.
Server side:
Package mainimport ("bufio"crypto/tls"crypto/x509"io/ioutil"log"net") func main () {cert, err: = tls.LoadX509KeyPair ("server.pem", "server.key") if err! = nil {log.Println (err) return} certBytes Err: = ioutil.ReadFile ("client.pem") if err! = nil {panic ("Unable to read cert.pem")} clientCertPool: = x509.NewCertPool () ok: = clientCertPool.AppendCertsFromPEM (certBytes) if! ok {panic ("failed to parse root certificate")} config: = & tls.Config {Certificates: [] tls.Certificate {cert}, ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: clientCertPool } ln, err: = tls.Listen ("tcp", ": 443", config) if err! = nil {log.Println (err) return} defer ln.Close () for {conn Err: = ln.Accept () if err! = nil {log.Println (err) continue} go handleConn (conn)}} func handleConn (conn net.Conn) {defer conn.Close () r: = bufio.NewReader (conn) for {msg Err: = r.ReadString ('\ n') if err! = nil {log.Println (err) return} println (msg) n, err: = conn.Write ([] byte ("world\ n")) if err! = nil {log.Println (n, err) return}
Because we need to validate the client, we need to configure the following two additional fields:
ClientAuth: tls.RequireAndVerifyClientCert,ClientCAs: clientCertPool
Then the client also configures the clientCertPool:
Package mainimport ("crypto/tls"crypto/x509"io/ioutil"log") func main () {cert, err: = tls.LoadX509KeyPair ("client.pem", "client.key") if err! = nil {log.Println (err) return} certBytes Err: = ioutil.ReadFile ("client.pem") if err! = nil {panic ("Unable to read cert.pem")} clientCertPool: = x509.NewCertPool () ok: = clientCertPool.AppendCertsFromPEM (certBytes) if! ok {panic ("failed to parse root certificate")} conf: = & tls.Config {RootCAs: clientCertPool, Certificates: [] tls.Certificate {cert} InsecureSkipVerify: true,} conn, err: = tls.Dial ("tcp", "127.0.0.1 return 443", conf) if err! = nil {log.Println (err) return} defer conn.Close () n, err: = conn.Write ([] byte ("hello\ n") if err! = nil {log.Println (n) Err) return} buf: = make ([] byte, 100) n, err = conn.Read (buf) if err! = nil {log.Println (n, err) return} println (string (buf [: n]))}
Run the two codes go run server2.go and go run client2.go, you can see that the two can communicate normally, if you use the previous client go run client.go, can not communicate normally, because the previous client does not provide a client certificate.
For examples of correcting the use of custom CA, please refer to https://github.com/golang/net/tree/master/http2/h3demo
Make CA:$ openssl genrsa-out rootCA.key 2048$ openssl req-x509-new-nodes-key rootCA.key-days 1024-out rootCA.pem... Install that to FirefoxMake cert:$ openssl genrsa-out server.key 2048$ openssl req-new-key server.key-out server.csr$ openssl x509-req-in server.csr-CA rootCA.pem-CAkey rootCA.key-CAcreateserial-out server.crt-days 500This is the end of how to use Go to implement TLS servers and clients. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.