Improve tls certificate verification
This commit is contained in:
		@@ -4,6 +4,8 @@ import (
 | 
				
			|||||||
	"MQTTLogger/config"
 | 
						"MQTTLogger/config"
 | 
				
			||||||
	"crypto/tls"
 | 
						"crypto/tls"
 | 
				
			||||||
	"crypto/x509"
 | 
						"crypto/x509"
 | 
				
			||||||
 | 
						"fmt"
 | 
				
			||||||
 | 
						"net/url"
 | 
				
			||||||
	"os"
 | 
						"os"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"go.uber.org/zap"
 | 
						"go.uber.org/zap"
 | 
				
			||||||
@@ -24,11 +26,25 @@ func NewTLSConfig(logger *zap.Logger, config *config.Config) *tls.Config {
 | 
				
			|||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	return &tls.Config{
 | 
						return &tls.Config{
 | 
				
			||||||
		RootCAs: certpool,
 | 
							RootCAs:            certpool,
 | 
				
			||||||
		// We use the provided cert not the one server sends.
 | 
							InsecureSkipVerify: true,
 | 
				
			||||||
		ClientAuth:         tls.NoClientCert,
 | 
							Certificates:       nil,
 | 
				
			||||||
		ClientCAs:          nil,
 | 
							VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error {
 | 
				
			||||||
		InsecureSkipVerify: true, // I know
 | 
								cert, err := x509.ParseCertificate(rawCerts[0])
 | 
				
			||||||
		Certificates: nil,
 | 
								if err != nil {
 | 
				
			||||||
 | 
									return fmt.Errorf("failed to parse certificate: %w", err)
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								opts := x509.VerifyOptions{Roots: certpool}
 | 
				
			||||||
 | 
								if _, err := cert.Verify(opts); err != nil {
 | 
				
			||||||
 | 
									return fmt.Errorf("failed to verify chain: %w", err)
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
								expectedCN, _ := url.Parse(config.URI)
 | 
				
			||||||
 | 
								if cert.Subject.CommonName != expectedCN.Hostname() {
 | 
				
			||||||
 | 
									return fmt.Errorf("unexpected CN, expected %s but got %s", expectedCN.Host, cert.Subject.CommonName)
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
								return nil
 | 
				
			||||||
 | 
							},
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
		Reference in New Issue
	
	Block a user