/
section.go
800 lines (707 loc) · 22.1 KB
/
section.go
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
// Copyright 2020, Shulhan <ms@kilabit.info>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package config
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"golang.org/x/crypto/ssh"
"golang.org/x/term"
)
// List of valid keys in Host or Match section.
const (
// List of key in Host or Match with single, string value.
KeyAddKeysToAgent = `addkeystoagent`
KeyAddressFamily = `addressfamily`
KeyBindAddress = `bindaddress`
KeyBindInterface = `bindinterface`
KeyCanonicalizeHostname = `canonicalizehostname`
KeySetEnv = `setenv`
KeyXAuthLocation = `xauthlocation`
// List of key in Host or Match with multiple, string values.
KeyCASignatureAlgorithms = `casignaturealgorithms`
KeyCanonicalDomains = `canonicaldomains`
KeyCertificateFile = `certificatefile`
KeyIdentityFile = `identityfile`
KeySendEnv = `sendenv`
KeyUserKnownHostsFile = `userknownhostsfile`
// List of key in Host or Match with integer value.
KeyCanonicalizeMaxDots = `canonicalizemaxdots`
KeyConnectTimeout = `connecttimeout`
KeyConnectionAttempts = `connectionattempts`
// List of key in Host or Match with boolean value.
KeyBatchMode = `batchmode`
KeyCanonicalizeFallbackLocal = `canonicalizefallbacklocal`
KeyChallengeResponseAuthentication = `challengeresponseauthentication`
KeyCheckHostIP = `checkhostip`
KeyClearAllForwardings = `clearallforwardings`
KeyCompression = `compression`
KeyVisualHostKey = `visualhostkey`
// List of key in Host or Match with value fetched using method.
KeyCanonicalizePermittedCNames = `canonicalizepermittedcnames`
KeyHostname = `hostname`
KeyIdentityAgent = `identityagent`
KeyPort = `port`
KeyUser = `user`
)
// TODO: list of keys that are not implemented yet due to hard or
// unknown how to test it.
// nolint: deadcode,varcheck
const (
keyCiphers = "ciphers"
keyControlMaster = "controlmaster"
keyControlPath = "controlpath"
keyControlPersist = "controlpersist"
keyDynamicForward = "dynamicforward"
keyEnableSSHKeysign = "enablesshkeysign"
keyEscapeChar = "escapechar"
keyExitOnForwardFailure = "keyexitonforwardfailure"
keyFingerprintHash = "fingerprinthash"
keyForwardAgent = "forwardagent"
keyForwardX11 = "forwardx11"
keyForwardX11Timeout = "forwardx11timeout"
keyForwardX11Trusted = "forwardx11trusted"
keyGatewayPorts = "gatewayports"
keyGlobalKnownHostsFile = "globalknownhostsfile"
keyGSSAPIAuthentication = "gssapiauthentication"
keyGSSAPIDelegateCredentials = "gssapidelegatecredentials"
keyHashKnownHosts = "hashknownhosts"
keyHostBasedAuthentication = "hostbasedauthentication"
keyHostBaseKeyTypes = "hostbasedkeytypes"
keyHostKeyAlgorithms = "hostkeyalgorithms"
keyHostKeyAlias = "hostkeyalias"
keyIdentitiesOnly = "identitiesonly"
keyIgnoreUnknown = "ignoreunknown"
keyInclude = "include"
keyIPQoS = "ipqos"
keyKbdInteractiveAuthentication = "kbdinteractiveauthentication"
keyKbdInteractiveDevices = "kbdinteractivedevices"
keyKexAlgorithms = "kexalgorithms"
keyLocalCommand = "localcommand"
keyLocalForward = "localforward"
keyLogLevel = "loglevel"
keyMACs = "macs"
keyNoHostAuthenticationForLocalhost = "nohostauthenticationforlocalhost"
keyNumberOfPasswordPrompts = "numberofpasswordprompts"
keyPasswordAuthentication = "passwordauthentication"
keyPermitLocalCommand = "permitlocalcommand"
keyPKCS11Provider = "pkcs11provider"
keyPreferredAuthentications = "preferredauthentications"
keyProxyCommand = "proxycommand"
keyProxyJump = "proxyjump"
keyProxyUseFdpass = "proxyusefdpass"
keyPubkeyAcceptedKeyTypes = "pubkeyacceptedkeytypes"
keyPubkeyAuthentication = "pubkeyauthentication"
keyRekeyLimit = "rekeylimit"
keyRemoteCommand = "remotecommand"
keyRemoteForward = "remoteforward"
keyRequestTTY = "requesttty"
keyRevokeHostKeys = "revokehostkeys"
keyServerAliveCountMax = "serveralivecountmax"
keyServerAliveInterval = "serveraliveinterval"
keyStreamLocalBindMask = "streamlocalbindmask"
keyStreamLocalBindUnlink = "streamlocalbindunlink"
keyStrictHostKeyChecking = "stricthostkeychecking"
keySyslogFacility = "syslogfacility"
keyTCPKeepAlive = "tcpkeepalive"
keyTunnel = "tunnel"
keyTunnelDevince = "tunneldevice"
keyUpdatehostKeys = "updatehostkeys"
keyUseKeychain = "usekeychain"
keyVerifyHostKeyDNS = "verifyhostkeydns"
)
// Known values for key.
const (
ValueAcceptNew = `accept-new`
ValueAlways = `always`
ValueAsk = `ask`
ValueConfirm = `confirm`
ValueOff = `off`
ValueNo = `no`
ValueNone = `none`
ValueYes = `yes`
)
// Valid values for key AddressFamily.
const (
ValueAny = `any`
ValueInet = `inet`
ValueInet6 = `inet6`
)
// List of default key value.
const (
DefConnectionAttempts = `1`
DefPort = `22`
DefXAuthLocation = `/usr/X11R6/bin/xauth`
)
// defaultFields define default field value for known key.
var defaultFields = map[string]string{
KeyChallengeResponseAuthentication: ValueYes,
KeyCheckHostIP: ValueYes,
KeyConnectionAttempts: DefConnectionAttempts,
KeyPort: DefPort,
KeyXAuthLocation: DefXAuthLocation,
}
// defaultCASignatureAlgorithms return list of default signature algorithms
// that client supported.
func defaultCASignatureAlgorithms() []string {
return []string{
ssh.KeyAlgoECDSA256,
ssh.KeyAlgoECDSA384,
ssh.KeyAlgoECDSA521,
ssh.KeyAlgoED25519,
ssh.KeyAlgoRSA,
}
}
// defaultIdentityFile return list of default IdentityFile.
func defaultIdentityFile() []string {
return []string{
`~/.ssh/id_dsa`,
`~/.ssh/id_ecdsa`,
`~/.ssh/id_ed25519`,
`~/.ssh/id_rsa`,
}
}
// defaultUserKnownHostsFile return list of default KnownHostsFile.
func defaultUserKnownHostsFile() []string {
return []string{
`~/.ssh/known_hosts`,
`~/.ssh/known_hosts2`,
}
}
// Section is the type that represent SSH client Host and Match section in
// configuration.
type Section struct {
// Field store the unpacked key and value of Section.
// For section key that is not expecting string value, one can use
// FieldBool or FieldInt64.
Field map[string]string
// env contains the key and value from SetEnv field.
env map[string]string
// name contains the raw value after Host or Match.
name string
// dir store the path to the "config" directory.
dir string
// WorkingDir contains the directory where the SSH client started.
// This value is required when client want to copy file from/to
// remote.
// This field is optional, default to current working directory from
// os.Getwd() or user's home directory.
WorkingDir string
// User's home directory.
homeDir string
certificateFile []string
IdentityFile []string
knownHostsFile []string
sendEnv []string
// Patterns for Host section.
patterns []*pattern
// Criteria for Match section.
criteria []*matchCriteria
// If true indicated that this is Match section.
useCriteria bool
}
// NewSection create an empty Host or Match section.
//
// The Config parameter is optional, if not set the section will assume that
// any path is relative to current working directory or using absolute path.
func NewSection(cfg *Config, name string) (section *Section) {
name = strings.TrimSpace(name)
if len(name) == 0 {
name = `*`
}
section = &Section{
Field: map[string]string{},
env: map[string]string{},
name: name,
}
if cfg != nil {
section.dir = cfg.dir
section.homeDir = cfg.homeDir
section.WorkingDir = cfg.workDir
}
return section
}
func newSectionHost(cfg *Config, rawPattern string) (host *Section) {
host = NewSection(cfg, rawPattern)
var (
patterns = strings.Fields(rawPattern)
s string
pat *pattern
)
for _, s = range patterns {
pat = newPattern(s)
host.patterns = append(host.patterns, pat)
}
return host
}
// CASignatureAlgorithms return list of signature algorithms set from
// KeyCASignatureAlgorithms.
// If not set it will return the default CA signature algorithms.
func (section *Section) CASignatureAlgorithms() []string {
var value = section.Field[KeyCASignatureAlgorithms]
if len(value) == 0 {
return defaultCASignatureAlgorithms()
}
return strings.Split(value, `,`)
}
// CanonicalDomains return list CanonicalDomains set in Section.
func (section *Section) CanonicalDomains() []string {
var value = section.Field[KeyCanonicalDomains]
if len(value) == 0 {
return nil
}
return strings.Fields(value)
}
// CanonicalizePermittedCNames return the permitted CNAMEs set in Section,
// from KeyCanonicalizePermittedCNames.
func (section *Section) CanonicalizePermittedCNames() (pcnames *PermittedCNAMEs, err error) {
var value = section.Field[KeyCanonicalizePermittedCNames]
if len(value) == 0 {
return nil, nil
}
pcnames, err = parseCanonicalizePermittedCNames(value)
if err != nil {
return nil, err
}
return pcnames, nil
}
// CertificateFile return list of certificate file, if its set in Host or
// Match configuration.
func (section *Section) CertificateFile() []string {
return section.certificateFile
}
// Environments return system and/or custom environment that will be passed
// to remote machine.
// The key and value is derived from "SendEnv" and "SetEnv".
func (section *Section) Environments(sysEnv map[string]string) (env map[string]string) {
var (
key string
val string
sendPattern string
ok bool
)
env = make(map[string]string, len(section.sendEnv)+len(section.env))
for key, val = range sysEnv {
for _, sendPattern = range section.sendEnv {
ok, _ = filepath.Match(sendPattern, key)
if ok {
env[key] = val
}
}
}
for key, val = range section.env {
env[key] = val
}
return env
}
// FieldBool get the Field value as boolean.
// It will return false if key is not exist or value is invalid.
func (section *Section) FieldBool(key string) (vbool bool) {
var vstr = section.Field[key]
if len(vstr) == 0 {
return false
}
vbool, _ = parseBool(key, vstr)
return vbool
}
// FieldInt64 get the Field value as int64.
// If the value is unparseable as int64 it will return 0.
func (section *Section) FieldInt64(key string) (val int64) {
var vstr = section.Field[key]
if len(vstr) == 0 {
return 0
}
val, _ = strconv.ParseInt(vstr, 10, 64)
return val
}
// Hostname return the hostname of this section.
func (section *Section) Hostname() string {
return section.Field[KeyHostname]
}
// IdentityAgent get the identity agent either from section config variable
// "IdentityAgent" or from environment variable SSH_AUTH_SOCK.
//
// There are four possible value: SSH_AUTH_SOCK, <$STRING>, <PATH>, or
// "none".
// If SSH_AUTH_SOCK, the socket path is read from the environment variable
// SSH_AUTH_SOCK.
// If value start with "$", then the socket path is set based on value of
// that environment variable.
// Other string beside "none" will be considered as path to socket.
//
// It will return empty string if IdentityAgent set to "none" or
// SSH_AUTH_SOCK is empty.
func (section *Section) IdentityAgent() string {
var value = section.Field[KeyIdentityAgent]
if value == `none` {
return ``
}
if len(value) == 0 || value == envSSHAuthSock {
return os.Getenv(envSSHAuthSock)
}
if value[0] == '$' {
// Read the socket from environment variable defined by
// value.
return os.Getenv(value[1:])
}
// IdentityAgent set to path to socket.
return value
}
// Port return the remote machine port of this section.
func (section *Section) Port() string {
return section.Field[KeyPort]
}
// Signers convert the IdentityFile to ssh.Signer for authentication using
// PublicKey.
//
// This method will ask for passphrase from terminal, if one of IdentityFile
// is protected.
// Unless the value of IdentityFile changes, this method should be called
// only once, otherwise it will ask passphrase on every call.
func (section *Section) Signers() (signers []ssh.Signer, err error) {
var (
logp = `Signers`
pkeyFile string
pkeyPem []byte
pass []byte
signer ssh.Signer
pkey any
isMissingPass bool
)
for _, pkeyFile = range section.IdentityFile {
pkeyPem, err = os.ReadFile(pkeyFile)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
continue
}
return nil, fmt.Errorf(`%s: %w`, logp, err)
}
pkey, err = ssh.ParseRawPrivateKey(pkeyPem)
if err != nil {
_, isMissingPass = err.(*ssh.PassphraseMissingError)
if !isMissingPass {
return nil, fmt.Errorf(`%s: %w`, logp, err)
}
fmt.Printf("Enter passphrase for %s:", pkeyFile)
pass, err = term.ReadPassword(0)
if err != nil {
return nil, fmt.Errorf(`%s: %w`, logp, err)
}
pkey, err = ssh.ParseRawPrivateKeyWithPassphrase(pkeyPem, pass)
if err != nil {
return nil, fmt.Errorf(`%s: %w`, logp, err)
}
}
signer, err = ssh.NewSignerFromKey(pkey)
if err != nil {
return nil, fmt.Errorf(`%s: %w`, logp, err)
}
signers = append(signers, signer)
}
return signers, nil
}
// isMatch will return true if the string "s" match with one of Host or Match
// section.
func (section *Section) isMatch(s string) bool {
if section.useCriteria {
for _, criteria := range section.criteria {
if criteria.isMatch(s) {
return true
}
}
} else {
for _, pat := range section.patterns {
if pat.isMatch(s) {
return true
}
}
}
return false
}
// setDefaults set and expand all of the fields values if its not set.
func (section *Section) setDefaults() {
if len(section.IdentityFile) == 0 {
section.IdentityFile = defaultIdentityFile()
}
var (
file string
x int
)
for x, file = range section.IdentityFile {
section.IdentityFile[x] = section.pathUnfold(file)
}
// Set and expand the UserKnownHostsFile.
if len(section.knownHostsFile) == 0 {
section.knownHostsFile = defaultUserKnownHostsFile()
}
for x, file = range section.knownHostsFile {
section.knownHostsFile[x] = section.pathUnfold(file)
}
var (
key string
val string
exist bool
)
for key, val = range defaultFields {
_, exist = section.Field[key]
if !exist {
section.Field[key] = val
}
}
}
// merge the other Section.
func (section *Section) merge(other *Section) {
var (
key string
value string
)
for key, value = range other.Field {
// The key and value in other should be valid, so no need to
// check for error.
section.Field[key] = value
}
section.certificateFile = append(section.certificateFile, other.certificateFile...)
section.IdentityFile = append(section.IdentityFile, other.IdentityFile...)
section.knownHostsFile = append(section.knownHostsFile, other.knownHostsFile...)
section.sendEnv = append(section.sendEnv, other.sendEnv...)
}
// Set the section field by raw key and value.
func (section *Section) Set(key, value string) (err error) {
switch key {
case KeyAddKeysToAgent:
err = validateAddKeysToAgent(value)
case KeyAddressFamily:
err = validateAddressFamily(value)
case KeyBatchMode:
_, err = parseBool(key, value)
case KeyBindAddress:
case KeyBindInterface:
case KeyCanonicalDomains:
case KeyCanonicalizeFallbackLocal:
_, err = parseBool(key, value)
case KeyCanonicalizeHostname:
err = validateCanonicalizeHostname(value)
case KeyCanonicalizeMaxDots:
_, err = strconv.Atoi(value)
case KeyCanonicalizePermittedCNames:
_, err = parseCanonicalizePermittedCNames(value)
case KeyCASignatureAlgorithms:
value = strings.ToLower(value)
case KeyCertificateFile:
section.certificateFile = append(section.certificateFile, value)
case KeyChallengeResponseAuthentication:
_, err = parseBool(key, value)
case KeyCheckHostIP:
_, err = parseBool(key, value)
case KeyClearAllForwardings:
_, err = parseBool(key, value)
case KeyCompression:
_, err = parseBool(key, value)
case KeyConnectionAttempts:
_, err = strconv.Atoi(value)
case KeyConnectTimeout:
_, err = strconv.Atoi(value)
case KeyIdentityAgent:
case KeyIdentityFile:
section.IdentityFile = append(section.IdentityFile, value)
case KeyHostname:
value = strings.ToLower(value)
case KeyPort:
_, err = strconv.Atoi(value)
case KeySendEnv:
section.sendEnv = append(section.sendEnv, value)
case KeySetEnv:
section.setEnv(value)
case KeyUser:
// User name is case sensitive.
case KeyUserKnownHostsFile:
section.setUserKnownHostsFile(value)
case KeyVisualHostKey:
_, err = parseBool(key, value)
case KeyXAuthLocation:
default:
// Store the unknown key into Field.
}
if err != nil {
return err
}
section.Field[key] = value
return nil
}
// User return the user value of this section.
func (section *Section) User() string {
return section.Field[KeyUser]
}
// UserKnownHostsFile return list of user known_hosts file set in this
// Section.
func (section *Section) UserKnownHostsFile() []string {
return section.knownHostsFile
}
// MarshalText encode the Section back to ssh_config format.
// The key is indented by two spaces.
func (section *Section) MarshalText() (text []byte, err error) {
var buf bytes.Buffer
if section.useCriteria {
buf.WriteString(`Match`)
var criteria *matchCriteria
for _, criteria = range section.criteria {
buf.WriteByte(' ')
criteria.WriteTo(&buf)
}
} else {
buf.WriteString(`Host`)
if len(section.patterns) == 0 {
buf.WriteByte(' ')
buf.WriteString(section.name)
} else {
var pat *pattern
for _, pat = range section.patterns {
buf.WriteByte(' ')
pat.WriteTo(&buf)
}
}
}
buf.WriteByte('\n')
var (
listKey = make([]string, 0, len(section.Field))
key string
val string
)
for key = range section.Field {
listKey = append(listKey, key)
}
sort.Strings(listKey)
for _, key = range listKey {
if key == KeyIdentityFile {
for _, val = range section.IdentityFile {
buf.WriteString(` `)
buf.WriteString(key)
buf.WriteByte(' ')
buf.WriteString(section.pathFold(val))
buf.WriteByte('\n')
}
continue
}
if key == KeyUserKnownHostsFile {
for _, val = range section.knownHostsFile {
buf.WriteString(` `)
buf.WriteString(key)
buf.WriteByte(' ')
buf.WriteString(section.pathFold(val))
buf.WriteByte('\n')
}
continue
}
buf.WriteString(` `)
buf.WriteString(key)
buf.WriteByte(' ')
buf.WriteString(section.Field[key])
buf.WriteByte('\n')
}
return buf.Bytes(), nil
}
// WriteTo marshal the Section into text and write it to w.
func (section *Section) WriteTo(w io.Writer) (n int64, err error) {
var text []byte
text, _ = section.MarshalText()
var c int
c, err = w.Write(text)
return int64(c), err
}
// pathFold remove the path prefix from input file "in", start from the
// "config" directory and then the user's home directory.
func (section *Section) pathFold(in string) (out string) {
if filepath.HasPrefix(in, section.dir) {
out, _ = filepath.Rel(section.dir, in)
return out
}
if filepath.HasPrefix(in, section.homeDir) {
out, _ = filepath.Rel(section.homeDir, in)
return `~/` + out
}
return in
}
// pathUnfold expand the file to make it absolute.
// If the file prefixed with '~', it will expanded into home directory.
// If the file is relative (does not start with '/'), it will expanded based
// on the "config" directory.
func (section *Section) pathUnfold(in string) string {
if len(in) == 0 {
return in
}
if in[0] == '/' {
return in
}
if in[0] == '~' {
return filepath.Join(section.homeDir, in[1:])
}
// The path in is relative to the "config" directory.
return filepath.Join(section.dir, in)
}
// setEnv set the Environments with key and value of format "KEY=VALUE".
func (section *Section) setEnv(env string) {
kv := strings.SplitN(env, "=", 2)
if len(kv) == 2 {
section.env[kv[0]] = kv[1]
}
}
func (section *Section) setUserKnownHostsFile(val string) {
var list = strings.Fields(val)
if len(list) > 0 {
section.knownHostsFile = append(section.knownHostsFile, list...)
}
}
func validateAddKeysToAgent(val string) (err error) {
switch val {
case ValueAlways, ValueAsk, ValueConfirm, ValueNo, ValueYes:
default:
return fmt.Errorf(`%s: invalid value %q`, KeyAddKeysToAgent, val)
}
return nil
}
func validateAddressFamily(val string) (err error) {
switch val {
case ValueAny, ValueInet, ValueInet6:
default:
return fmt.Errorf(`%s: invalid value %q`, KeyAddressFamily, val)
}
return nil
}
func validateCanonicalizeHostname(val string) (err error) {
switch val {
case ValueNo, ValueAlways, ValueYes:
default:
return fmt.Errorf(`%s: invalid value %q`, KeyCanonicalizeHostname, val)
}
return nil
}
func parseCanonicalizePermittedCNames(val string) (pcnames *PermittedCNAMEs, err error) {
sourceTarget := strings.Split(val, ":")
if len(sourceTarget) != 2 {
return nil, fmt.Errorf(`%s: invalid rule`, KeyCanonicalizePermittedCNames)
}
listSource := strings.Split(sourceTarget[0], ",")
sources := make([]*pattern, 0, len(listSource))
for _, domain := range listSource {
src := newPattern(domain)
sources = append(sources, src)
}
listTarget := strings.Split(sourceTarget[1], ",")
targets := make([]*pattern, 0, len(listTarget))
for _, domain := range listTarget {
target := newPattern(domain)
targets = append(targets, target)
}
pcnames = &PermittedCNAMEs{
sources: sources,
targets: targets,
}
return pcnames, nil
}