File: tlsconfig.go

package info (click to toggle)
zabbix 1%3A7.0.10%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 272,688 kB
  • sloc: sql: 946,050; ansic: 389,440; php: 292,698; javascript: 83,388; sh: 5,680; makefile: 3,285; java: 1,420; cpp: 694; perl: 64; xml: 56
file content (260 lines) | stat: -rw-r--r-- 7,360 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/*
** Copyright (C) 2001-2025 Zabbix SIA
**
** Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
** documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
** rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
** permit persons to whom the Software is furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in all copies or substantial portions
** of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
** WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
** COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE.
**/

package tlsconfig

import (
	"crypto/tls"
	"crypto/x509"
	"errors"
	"fmt"
	"os"

	"golang.zabbix.com/sdk/errs"
	"golang.zabbix.com/sdk/uri"
)

// Details holds required data for TLS connections
type Details struct {
	SessionName        string
	TlsConnect         string
	TlsCaFile          string
	TlsCertFile        string
	TlsKeyFile         string
	RawUri             string
	AllowedConnections map[string]bool
}

// Validate checks if set TlsConnect type is allowed
// if checkCA is true checks if TLSCAFile is set (does not validate the file)
// if checkCertFile is true checks if TlsCertFile is set (does not validate the file)
// if checkKeyFile is true checks if TlsKeyFile is set (does not validate the file)
func (d *Details) Validate(checkCA, checkCertFile, checkKeyFile bool) error {
	if len(d.AllowedConnections) == 0 {
		return errors.New("no connection types allowed")
	}

	if d.TlsConnect == "" {
		return errors.New("connection type must be set")
	}

	if !d.AllowedConnections[d.TlsConnect] {
		return fmt.Errorf("connection type %s not allowed", d.TlsConnect)
	}

	if checkCA && d.TlsCaFile == "" {
		return fmt.Errorf("TLS CA file must be set with connection type %s", d.TlsConnect)
	}

	if checkCertFile && d.TlsCertFile == "" {
		return fmt.Errorf("TLS certificate file must be set with connection type %s", d.TlsConnect)
	}

	if checkKeyFile && d.TlsKeyFile == "" {
		return fmt.Errorf("TLS key file must be set with connection type %s", d.TlsConnect)
	}

	return nil
}

// GetTLSConfig creates tls.Config from details
func (d *Details) GetTLSConfig(skipVerify bool) (*tls.Config, error) {
	rootCertPool := x509.NewCertPool()

	pem, err := os.ReadFile(d.TlsCaFile)
	if err != nil {
		return nil, errs.Wrap(err, "failed to read TLS CA file")
	}

	if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
		return nil, errs.New("failed to append PEM")
	}

	clientCerts, err := d.LoadCertificates()
	if err != nil {
		return nil, err
	}

	if skipVerify {
		return &tls.Config{RootCAs: rootCertPool, Certificates: clientCerts, InsecureSkipVerify: skipVerify}, nil
	}

	url, err := uri.New(d.RawUri, nil)
	if err != nil {
		return nil, errs.Wrap(err, "failed to parse uri")
	}

	return &tls.Config{
		RootCAs: rootCertPool, Certificates: clientCerts, InsecureSkipVerify: skipVerify, ServerName: url.Host(),
	}, nil
}

// LoadCertificates combines cert and key files
func (d *Details) LoadCertificates() ([]tls.Certificate, error) {
	if d.TlsCertFile == "" || d.TlsKeyFile == "" {
		return nil, nil
	}

	var Certs []tls.Certificate

	certs, err := tls.LoadX509KeyPair(d.TlsCertFile, d.TlsKeyFile)
	if err != nil {
		return nil, errs.Wrap(err, "failed to load tls cert and/or key file")
	}

	Certs = []tls.Certificate{certs}

	return Certs, nil
}

func VerifyPeerCertificateFunc(
	dnsName string, rootCAPool *x509.CertPool,
) func(certificates [][]byte, _ [][]*x509.Certificate) error {
	return func(certificates [][]byte, _ [][]*x509.Certificate) error {
		if len(certificates) == 0 {
			return errs.New("no TLS certificates found")
		}

		certs := make([]*x509.Certificate, 0, len(certificates))

		for _, c := range certificates {
			cert, err := x509.ParseCertificate(c)
			if err != nil {
				return errs.New("no TLS certificates found")
			}

			certs = append(certs, cert)
		}

		opts := x509.VerifyOptions{
			DNSName:       dnsName,
			Roots:         rootCAPool,
			Intermediates: x509.NewCertPool(),
		}

		for i, cert := range certs {
			if i == 0 {
				continue
			}

			opts.Intermediates.AddCert(cert)
		}

		_, err := certs[0].Verify(opts)
		if err != nil {
			return errs.Wrap(err, "failed to verify certificate")
		}

		return nil
	}
}

// CreateConfig (deprecated) creates tls.Config from details
func CreateConfig(details Details, skipVerify bool) (*tls.Config, error) {
	rootCertPool := x509.NewCertPool()

	pem, err := os.ReadFile(details.TlsCaFile)
	if err != nil {
		return nil, err
	}

	if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
		return nil, errs.New("failed to append PEM")
	}

	clientCerts := make([]tls.Certificate, 0, 1)

	certs, err := tls.LoadX509KeyPair(details.TlsCertFile, details.TlsKeyFile)
	if err != nil {
		return nil, err
	}

	clientCerts = append(clientCerts, certs)

	if skipVerify {
		return &tls.Config{RootCAs: rootCertPool, Certificates: clientCerts, InsecureSkipVerify: skipVerify}, nil
	}

	url, err := uri.New(details.RawUri, nil)
	if err != nil {
		return nil, err
	}

	return &tls.Config{
		RootCAs: rootCertPool, Certificates: clientCerts, InsecureSkipVerify: skipVerify, ServerName: url.Host(),
	}, nil
}

// NewDetails creates new Details struct with no validation
func NewDetails(session, dbConnect, caFile, certFile, keyFile, uri string, connectionTypes ...string) Details {
	connTypes := make(map[string]bool)
	for _, v := range connectionTypes {
		connTypes[v] = true
	}

	return Details{session, dbConnect, caFile, certFile, keyFile, uri, connTypes}
}

// CreateDetails (deprecated) creates details with validation
func CreateDetails(session, dbConnect, caFile, certFile, keyFile, uri string) (Details, error) {
	if dbConnect != "" && dbConnect != "required" {
		if err := validateSetTLSFiles(caFile, certFile, keyFile); err != nil {
			return Details{}, fmt.Errorf("%s uri %s, with session %s", err.Error(), uri, session)
		}
	} else {
		if err := validateUnsetTLSFiles(caFile, certFile, keyFile); err != nil {
			return Details{}, fmt.Errorf("%s uri %s, with session %s", err.Error(), uri, session)
		}
	}

	return Details{session, dbConnect, caFile, certFile, keyFile, uri, nil}, nil
}

func validateSetTLSFiles(caFile, certFile, keyFile string) error {
	if caFile == "" {
		return errors.New("missing TLS CA file")
	}

	if certFile == "" {
		return errors.New("missing TLS certificate file")
	}

	if keyFile == "" {
		return errors.New("missing TLS key file")
	}

	return nil
}

func validateUnsetTLSFiles(caFile, certFile, keyFile string) error {
	errTmpl := "TLS %s file must not be set, when unencrypted connection or TLS without identity checks is configured"

	if caFile != "" {
		return fmt.Errorf(errTmpl, "CA")
	}

	if certFile != "" {
		return fmt.Errorf(errTmpl, "certificate")
	}

	if keyFile != "" {
		return fmt.Errorf(errTmpl, "key")
	}

	return nil
}