Debian Codegraph @

server/certstore_windows_test.go

raw
1 // Copyright 2022-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 //go:build windows
15
16 package server
17
18 import (
19 "crypto/tls"
20 "fmt"
21 "net/url"
22 "os"
23 "os/exec"
24 "strings"
25 "testing"
26 "time"
27
28 "github.com/nats-io/nats.go"
29 )
30
31 func runPowershellScript(scriptFile string, args []string) error {
32 psExec, _ := exec.LookPath("powershell.exe")
33
34 execArgs := []string{psExec, "-command", fmt.Sprintf("& '%s'", scriptFile)}
35 if len(args) > 0 {
36 execArgs = append(execArgs, args...)
37 }
38
39 cmdImport := &exec.Cmd{
40 Path: psExec,
41 Args: execArgs,
42 Stdout: os.Stdout,
43 Stderr: os.Stderr,
44 }
45 return cmdImport.Run()
46 }
47
48 func runConfiguredLeaf(t *testing.T, hubPort int, certStore string, matchBy string, match string, caMatch string, expectedLeafCount int) {
49
50 // Fire up the leaf
51 u, err := url.Parse(fmt.Sprintf("nats://localhost:%d", hubPort))
52 if err != nil {
53 t.Fatalf("Error parsing url: %v", err)
54 }
55
56 configStr := fmt.Sprintf(`
57 port: -1
58 leaf {
59 remotes [
60 {
61 url: "%s"
62 tls {
63 cert_store: "%s"
64 cert_match_by: "%s"
65 cert_match: "%s"
66 ca_certs_match: %s
67
68 # Test settings that succeed should be equivalent to:
69 # cert_file: "../test/configs/certs/tlsauth/client.pem"
70 # key_file: "../test/configs/certs/tlsauth/client-key.pem"
71 # ca_file: "../test/configs/certs/tlsauth/ca.pem"
72 timeout: 5
73 }
74 }
75 ]
76 }
77 `, u.String(), certStore, matchBy, match, caMatch)
78
79 leafConfig := createConfFile(t, []byte(configStr))
80 defer removeFile(t, leafConfig)
81 leafServer, _ := RunServerWithConfig(leafConfig)
82 defer leafServer.Shutdown()
83
84 // After client verify, hub will match by SAN email, SAN dns, and Subject (in that order)
85 // Our test client specifies Subject only so we should match on that...
86
87 // A little settle time
88 time.Sleep(1 * time.Second)
89 checkLeafNodeConnectedCount(t, leafServer, expectedLeafCount)
90 }
91
92 // TestLeafTLSWindowsCertStore tests the topology of two NATS Servers connected as leaf and hub with authentication of
93 // leaf to hub via mTLS with leaf's certificate and signing key provisioned in the Windows certificate store.
94 func TestLeafTLSWindowsCertStore(t *testing.T) {
95
96 // Client Identity (client.pem)
97 // Issuer: O = NATS CA, OU = NATS.io, CN = localhost
98 // Subject: OU = NATS.io, CN = example.com
99
100 // Make sure windows cert store is reset to avoid conflict with other tests
101 err := runPowershellScript("../test/configs/certs/tlsauth/certstore/delete-cert-from-store.ps1", nil)
102 if err != nil {
103 t.Fatalf("expected powershell cert delete to succeed: %s", err.Error())
104 }
105
106 // Provision Windows cert store with client cert and secret
107 err = runPowershellScript("../test/configs/certs/tlsauth/certstore/import-p12-client.ps1", nil)
108 if err != nil {
109 t.Fatalf("expected powershell provision to succeed: %s", err.Error())
110 }
111
112 err = runPowershellScript("../test/configs/certs/tlsauth/certstore/import-p12-ca.ps1", nil)
113 if err != nil {
114 t.Fatalf("expected powershell provision CA to succeed: %s", err.Error())
115 }
116
117 // Fire up the hub
118 hubConfig := createConfFile(t, []byte(`
119 port: -1
120 leaf {
121 listen: "127.0.0.1:-1"
122 tls {
123 ca_file: "../test/configs/certs/tlsauth/ca.pem"
124 cert_file: "../test/configs/certs/tlsauth/server.pem"
125 key_file: "../test/configs/certs/tlsauth/server-key.pem"
126 timeout: 5
127 verify_and_map: true
128 }
129 }
130
131 accounts: {
132 AcctA: {
133 users: [ {user: "OU = NATS.io, CN = example.com"} ]
134 },
135 AcctB: {
136 users: [ {user: UserB1} ]
137 },
138 SYS: {
139 users: [ {user: System} ]
140 }
141 }
142 system_account: "SYS"
143 `))
144 defer removeFile(t, hubConfig)
145 hubServer, hubOptions := RunServerWithConfig(hubConfig)
146 defer hubServer.Shutdown()
147
148 testCases := []struct {
149 certStore string
150 certMatchBy string
151 certMatch string
152 caCertsMatch string
153 expectedLeafCount int
154 }{
155 // Test subject and issuer
156 {"WindowsCurrentUser", "Subject", "example.com", "\"NATS CA\"", 1},
157 {"WindowsCurrentUser", "Issuer", "NATS CA", "\"NATS CA\"", 1},
158 {"WindowsCurrentUser", "Issuer", "Frodo Baggins, Inc.", "\"NATS CA\"", 0},
159 {"WindowsCurrentUser", "Thumbprint", "7e44f478114a2e29b98b00beb1b3687d8dc0e481", "\"NATS CA\"", 0},
160 // Test CAs, NATS CA is valid, others are missing
161 {"WindowsCurrentUser", "Subject", "example.com", "[\"NATS CA\"]", 1},
162 {"WindowsCurrentUser", "Subject", "example.com", "[\"GlobalSign\"]", 0},
163 {"WindowsCurrentUser", "Subject", "example.com", "[\"Missing NATS Cert\"]", 0},
164 {"WindowsCurrentUser", "Subject", "example.com", "[\"NATS CA\", \"Missing NATS Cert1\"]", 1},
165 {"WindowsCurrentUser", "Subject", "example.com", "[\"Missing Cert2\",\"NATS CA\"]", 1},
166 {"WindowsCurrentUser", "Subject", "example.com", "[\"Missing, Cert3\",\"Missing NATS Cert4\"]", 0},
167 }
168 for _, tc := range testCases {
169 testName := fmt.Sprintf("%s by %s match %s", tc.certStore, tc.certMatchBy, tc.certMatch)
170 t.Run(fmt.Sprintf(testName, tc.certStore, tc.certMatchBy, tc.certMatch, tc.caCertsMatch), func(t *testing.T) {
171 defer func() {
172 if r := recover(); r != nil {
173 if tc.expectedLeafCount != 0 {
174 t.Fatalf("did not expect panic: %s", testName)
175 } else {
176 if !strings.Contains(fmt.Sprintf("%v", r), "Error processing configuration file") {
177 t.Fatalf("did not expect unknown panic: %s", testName)
178 }
179 }
180 }
181 }()
182 runConfiguredLeaf(t, hubOptions.LeafNode.Port,
183 tc.certStore, tc.certMatchBy, tc.certMatch,
184 tc.caCertsMatch, tc.expectedLeafCount)
185 })
186 }
187 }
188
189 // TestServerTLSWindowsCertStore tests the topology of a NATS server requiring TLS and gettings it own server
190 // cert identity (as used when accepting NATS client connections and negotiating TLS) from Windows certificate store.
191 func TestServerTLSWindowsCertStore(t *testing.T) {
192
193 // Server Identity (server.pem)
194 // Issuer: O = NATS CA, OU = NATS.io, CN = localhost
195 // Subject: OU = NATS.io Operators, CN = localhost
196
197 // Make sure windows cert store is reset to avoid conflict with other tests
198 err := runPowershellScript("../test/configs/certs/tlsauth/certstore/delete-cert-from-store.ps1", nil)
199 if err != nil {
200 t.Fatalf("expected powershell cert delete to succeed: %s", err.Error())
201 }
202
203 // Provision Windows cert store with server cert and secret
204 err = runPowershellScript("../test/configs/certs/tlsauth/certstore/import-p12-server.ps1", nil)
205 if err != nil {
206 t.Fatalf("expected powershell provision to succeed: %s", err.Error())
207 }
208
209 err = runPowershellScript("../test/configs/certs/tlsauth/certstore/import-p12-ca.ps1", nil)
210 if err != nil {
211 t.Fatalf("expected powershell provision CA to succeed: %s", err.Error())
212 }
213
214 // Fire up the server
215 srvConfig := createConfFile(t, []byte(`
216 listen: "localhost:-1"
217 tls {
218 cert_store: "WindowsCurrentUser"
219 cert_match_by: "Subject"
220 cert_match: "NATS.io Operators"
221 ca_certs_match: ["NATS CA"]
222 timeout: 5
223 }
224 `))
225 defer removeFile(t, srvConfig)
226 srvServer, _ := RunServerWithConfig(srvConfig)
227 if srvServer == nil {
228 t.Fatalf("expected to be able start server with cert store configuration")
229 }
230 defer srvServer.Shutdown()
231
232 testCases := []struct {
233 clientCA string
234 expect bool
235 }{
236 {"../test/configs/certs/tlsauth/ca.pem", true},
237 {"../test/configs/certs/tlsauth/client.pem", false},
238 }
239 for _, tc := range testCases {
240 t.Run(fmt.Sprintf("Client CA: %s", tc.clientCA), func(t *testing.T) {
241 nc, _ := nats.Connect(srvServer.clientConnectURLs[0], nats.RootCAs(tc.clientCA))
242 err := nc.Publish("foo", []byte("hello TLS server-authenticated server"))
243 if (err != nil) == tc.expect {
244 t.Fatalf("expected publish result %v to TLS authenticated server", tc.expect)
245 }
246 nc.Close()
247
248 for i := 0; i < 5; i++ {
249 nc, _ = nats.Connect(srvServer.clientConnectURLs[0], nats.RootCAs(tc.clientCA))
250 err = nc.Publish("foo", []byte("hello TLS server-authenticated server"))
251 if (err != nil) == tc.expect {
252 t.Fatalf("expected repeated connection result %v to TLS authenticated server", tc.expect)
253 }
254 nc.Close()
255 }
256 })
257 }
258 }
259
260 // TestServerIgnoreExpiredCerts tests if the server skips expired certificates in configuration, and finds non-expired ones
261 func TestServerIgnoreExpiredCerts(t *testing.T) {
262
263 // Server Identities: expired.pem; not-expired.pem
264 // Issuer: OU = NATS.io, CN = localhost
265 // Subject: OU = NATS.io Operators, CN = localhost
266
267 testCases := []struct {
268 certFile string
269 expect bool
270 }{
271 {"expired.p12", false},
272 {"not-expired.p12", true},
273 }
274 for _, tc := range testCases {
275 t.Run(fmt.Sprintf("Server certificate: %s", tc.certFile), func(t *testing.T) {
276 // Make sure windows cert store is reset to avoid conflict with other tests
277 err := runPowershellScript("../test/configs/certs/tlsauth/certstore/delete-cert-from-store.ps1", nil)
278 if err != nil {
279 t.Fatalf("expected powershell cert delete to succeed: %s", err.Error())
280 }
281
282 // Provision Windows cert store with server cert and secret
283 err = runPowershellScript("../test/configs/certs/tlsauth/certstore/import-p12-server.ps1", []string{tc.certFile})
284 if err != nil {
285 t.Fatalf("expected powershell provision to succeed: %s", err.Error())
286 }
287 // Fire up the server
288 srvConfig := createConfFile(t, []byte(`
289 listen: "localhost:-1"
290 tls {
291 cert_store: "WindowsCurrentUser"
292 cert_match_by: "Subject"
293 cert_match: "NATS.io Operators"
294 cert_match_skip_invalid: true
295 timeout: 5
296 }
297 `))
298 defer removeFile(t, srvConfig)
299 cfg, _ := ProcessConfigFile(srvConfig)
300 if (cfg != nil) == tc.expect {
301 return
302 }
303 if tc.expect == false {
304 t.Fatalf("expected server start to fail with expired certificate")
305 } else {
306 t.Fatalf("expected server to start with non expired certificate")
307 }
308 })
309 }
310 }
311
312 func TestWindowsTLS12ECDSA(t *testing.T) {
313 err := runPowershellScript("../test/configs/certs/tlsauth/certstore/import-p12-server.ps1", []string{"ecdsa_server.pfx"})
314 if err != nil {
315 t.Fatalf("expected powershell provision to succeed: %v", err)
316 }
317
318 config := createConfFile(t, []byte(`
319 listen: "localhost:-1"
320 tls {
321 cert_store: "WindowsCurrentUser"
322 cert_match_by: "Thumbprint"
323 cert_match: "4F8AF21756E5DBBD54619BBB6F3CC5D455ED4468"
324 cert_match_skip_invalid: true
325 timeout: 5
326 }
327 `))
328 defer removeFile(t, config)
329
330 srv, _ := RunServerWithConfig(config)
331 if srv == nil {
332 t.Fatalf("expected to be able start server with cert store configuration")
333 }
334 defer srv.Shutdown()
335
336 for name, version := range map[string]uint16{
337 "TLS 1.3": tls.VersionTLS13,
338 "TLS 1.2": tls.VersionTLS12,
339 } {
340 t.Run(name, func(t *testing.T) {
341 tc := &tls.Config{MaxVersion: version, MinVersion: version, InsecureSkipVerify: true}
342
343 if _, err = nats.Connect(srv.clientConnectURLs[0], nats.Secure(tc)); err != nil {
344 t.Fatalf("connection with %s: %v", name, err)
345 }
346
347 t.Logf("successful connection with %s", name)
348 })
349 }
350 }