-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
netconf.go
379 lines (327 loc) · 10.8 KB
/
netconf.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
package junos
import (
"context"
"encoding/xml"
"errors"
"fmt"
"log"
"net"
"os"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/jeremmfr/go-netconf/netconf"
"golang.org/x/crypto/ssh"
)
const (
errorSeverity string = "error"
rpcCommand = "<command format=\"text\">%s</command>"
rpcConfigStringSet = "<load-configuration action=\"set\" format=\"text\">" +
"<configuration-set>%s</configuration-set></load-configuration>"
rpcSystemInfo = "<get-system-information/>"
rpcCommit = "<commit-configuration><log>%s</log></commit-configuration>"
rpcCandidateLock = "<lock><target><candidate/></target></lock>"
rpcCandidateUnlock = "<unlock><target><candidate/></target></unlock>"
rpcClearCandidate = "<delete-config><target><candidate/></target></delete-config>"
rpcClose = "<close-session/>"
rpcGetInterfacesInformationTerse = `<get-interface-information><terse/></get-interface-information>`
rpcGetInterfaceInformationTerse = `<get-interface-information>%s<terse/></get-interface-information>`
xmlStartTagConfigOut = "<configuration-output>"
xmlEndTagConfigOut = "</configuration-output>"
)
// junosSession : store Junos device info and session.
type junosSession struct {
session *netconf.Session
SystemInformation sysInfo `xml:"system-information"`
}
type sysInfo struct {
HardwareModel string `xml:"hardware-model"`
OsName string `xml:"os-name"`
OsVersion string `xml:"os-version"`
SerialNumber string `xml:"serial-number"`
HostName string `xml:"host-name"`
ClusterNode *bool `xml:"cluster-node"`
}
type commandXMLConfig struct {
Config string `xml:",innerxml"`
}
type netconfAuthMethod struct {
Password string
Username string
PrivateKeyPEM string
PrivateKeyFile string
Passphrase string
Ciphers []string
Timeout int
}
type commitResults struct {
XMLName xml.Name `xml:"commit-results"`
Errors []netconf.RPCError `xml:"rpc-error"`
}
type getPhysicalInterfaceTerseReply struct {
InterfaceInfo struct {
PhysicalInterface []struct {
Name string `xml:"name"`
AdminStatus string `xml:"admin-status"`
OperStatus string `xml:"oper-status"`
} `xml:"physical-interface"`
} `xml:"interface-information"`
}
type getLogicalInterfaceTerseReply struct {
InterfaceInfo struct {
LogicalInterface []struct {
Name string `xml:"name"`
AdminStatus string `xml:"admin-status"`
OperStatus string `xml:"oper-status"`
AddressFamily []struct {
Name string `xml:"address-family-name"`
Address []struct {
Local string `xml:"ifa-local"`
} `xml:"interface-address"`
} `xml:"address-family"`
} `xml:"logical-interface"`
} `xml:"interface-information"`
}
// netconfNewSession establishes a new connection to a Junos device that we will use
// to run our commands against.
// Authentication methods are defined using the netconfAuthMethod struct, and are as follows:
// username and password, SSH private key (with or without passphrase).
func netconfNewSession(ctx context.Context, host string, auth *netconfAuthMethod) (*junosSession, error) {
clientConfig, err := genSSHClientConfig(auth)
if err != nil {
return nil, err
}
return netconfNewSessionWithConfig(ctx, host, clientConfig)
}
// netconfNewSessionWithConfig establishes a new connection to a Junos device that we will use
// to run our commands against.
func netconfNewSessionWithConfig(ctx context.Context, host string, clientConfig *ssh.ClientConfig,
) (*junosSession, error) {
netDialer := net.Dialer{
Timeout: clientConfig.Timeout,
}
conn, err := netDialer.DialContext(ctx, "tcp", host)
if err != nil {
return nil, fmt.Errorf("error connecting to %s: %w", host, err)
}
s, err := netconf.NewSSHSession(conn, clientConfig)
if err != nil {
return nil, fmt.Errorf("error initializing SSH session to %s: %w", host, err)
}
return newSessionFromNetconf(s)
}
// newSessionFromNetconf uses an existing netconf.Session to run our commands against.
func newSessionFromNetconf(s *netconf.Session) (*junosSession, error) {
n := &junosSession{
session: s,
}
return n, n.gatherFacts()
}
// genSSHClientConfig is a wrapper function based around the auth method defined
// (user/password or private key) which returns the SSH client configuration used to
// connect.
func genSSHClientConfig(auth *netconfAuthMethod) (*ssh.ClientConfig, error) {
configs := make([]*ssh.ClientConfig, 0)
configs = append(configs, &ssh.ClientConfig{})
// keys method
switch {
case len(auth.PrivateKeyPEM) > 0:
config, err := netconf.SSHConfigPubKeyPem(auth.Username, []byte(auth.PrivateKeyPEM), auth.Passphrase)
if err != nil {
return config, fmt.Errorf("failed to create new SSHConfig with PEM private key: %w", err)
}
configs = append(configs, config)
case len(auth.PrivateKeyFile) > 0:
config, err := netconf.SSHConfigPubKeyFile(auth.Username, auth.PrivateKeyFile, auth.Passphrase)
if err != nil {
return config, fmt.Errorf("failed to create new SSHConfig with file private key: %w", err)
}
configs = append(configs, config)
case os.Getenv("SSH_AUTH_SOCK") != "":
config, err := netconf.SSHConfigPubKeyAgent(auth.Username)
if err != nil {
log.Printf("failed to communicate with SSH agent: %s", err.Error())
} else {
configs = append(configs, config)
}
}
if len(auth.Password) > 0 {
config := netconf.SSHConfigPassword(auth.Username, auth.Password)
configs = append(configs, config)
}
if len(configs) == 1 {
return configs[0], errors.New("no credentials/keys available")
}
configs[0] = configs[1]
configs[0].Ciphers = auth.Ciphers
configs[0].HostKeyCallback = ssh.InsecureIgnoreHostKey()
for _, v := range configs[2:] {
configs[0].Auth = append(configs[0].Auth, v.Auth...)
}
configs[0].Timeout = time.Duration(auth.Timeout) * time.Second
return configs[0], nil
}
func defaultSSHCiphers() schema.SchemaDefaultFunc {
return func() (interface{}, error) {
return []interface{}{
"aes128-gcm@openssh.com", "chacha20-poly1305@openssh.com",
"aes128-ctr", "aes192-ctr", "aes256-ctr",
"aes128-cbc",
}, nil
}
}
// gatherFacts gathers basic information about the device.
func (j *junosSession) gatherFacts() error {
// Get info for get-system-information and populate SystemInformation Struct
val, err := j.session.Exec(netconf.RawMethod(rpcSystemInfo))
if err != nil {
return fmt.Errorf("failed to netconf get-system-information: %w", err)
}
if val.Errors != nil {
var errorsMsg []string
for _, m := range val.Errors {
errorsMsg = append(errorsMsg, fmt.Sprintf("%v", m))
}
return fmt.Errorf(strings.Join(errorsMsg, "\n"))
}
err = xml.Unmarshal([]byte(val.RawReply), &j)
if err != nil {
return fmt.Errorf("failed to xml unmarshal reply: %w", err)
}
return nil
}
// netconfCommand (show, execute) on Junos device.
func (j *junosSession) netconfCommand(cmd string) (string, error) {
command := fmt.Sprintf(rpcCommand, cmd)
reply, err := j.session.Exec(netconf.RawMethod(command))
if err != nil {
return "", fmt.Errorf("failed to netconf command exec: %w", err)
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return "", errors.New(m.Error())
}
}
if reply.Data == "" || strings.Count(reply.Data, "") <= 2 {
return emptyW, errors.New("no output available - please check the syntax of your command")
}
var output commandXMLConfig
if err := xml.Unmarshal([]byte(reply.Data), &output); err != nil {
return "", fmt.Errorf("failed to xml unmarshal reply: %w", err)
}
return output.Config, nil
}
func (j *junosSession) netconfCommandXML(cmd string) (string, error) {
reply, err := j.session.Exec(netconf.RawMethod(cmd))
if err != nil {
return "", fmt.Errorf("failed to netconf xml command exec: %w", err)
}
if reply.Errors != nil {
for _, m := range reply.Errors {
return "", errors.New(m.Error())
}
}
return reply.Data, nil
}
func (j *junosSession) netconfConfigSet(cmd []string) (string, error) {
command := fmt.Sprintf(rpcConfigStringSet, strings.Join(cmd, "\n"))
reply, err := j.session.Exec(netconf.RawMethod(command))
if err != nil {
return "", fmt.Errorf("failed to netconf set/delete command exec: %w", err)
}
// logFile("netconfConfigSet.Reply:" + reply.RawReply)
message := ""
if reply.Errors != nil {
for _, m := range reply.Errors {
message += m.Message
}
return message, nil
}
return "", nil
}
// netConfConfigLock locks the candidate configuration.
func (j *junosSession) netconfConfigLock() bool {
reply, err := j.session.Exec(netconf.RawMethod(rpcCandidateLock))
if err != nil {
return false
}
if reply.Errors != nil {
return false
}
return true
}
// Unlock unlocks the candidate configuration.
func (j *junosSession) netconfConfigUnlock() []error {
reply, err := j.session.Exec(netconf.RawMethod(rpcCandidateUnlock))
if err != nil {
return []error{fmt.Errorf("failed to netconf config unlock: %w", err)}
}
if reply.Errors != nil {
errs := make([]error, 0)
for _, m := range reply.Errors {
errs = append(errs, errors.New("config unlock: "+m.Message))
}
return errs
}
return []error{}
}
func (j *junosSession) netconfConfigClear() []error {
reply, err := j.session.Exec(netconf.RawMethod(rpcClearCandidate))
if err != nil {
return []error{fmt.Errorf("failed to netconf config clear: %w", err)}
}
if reply.Errors != nil {
errs := make([]error, 0)
for _, m := range reply.Errors {
errs = append(errs, errors.New("config clear: "+m.Message))
}
return errs
}
return []error{}
}
// netconfCommit commits the configuration.
func (j *junosSession) netconfCommit(logMessage string) (_warn []error, _err error) {
reply, err := j.session.Exec(netconf.RawMethod(fmt.Sprintf(rpcCommit, logMessage)))
if err != nil {
return []error{}, fmt.Errorf("failed to netconf commit: %w", err)
}
if reply.Errors != nil {
warnings := make([]error, 0)
for _, m := range reply.Errors {
if m.Severity == errorSeverity {
return warnings, errors.New(m.Error())
}
warnings = append(warnings, errors.New(m.Error()))
}
return warnings, nil
}
var errs commitResults
if strings.Contains(reply.Data, "<commit-results>") {
err = xml.Unmarshal([]byte(reply.Data), &errs)
if err != nil {
return []error{}, fmt.Errorf("failed to xml unmarshal reply '%s': %w", reply.Data, err)
}
if errs.Errors != nil {
warnings := make([]error, 0)
for _, m := range errs.Errors {
if m.Severity == errorSeverity {
return []error{}, errors.New(m.Error())
}
warnings = append(warnings, errors.New(m.Error()))
}
return warnings, nil
}
}
return []error{}, nil
}
// Close disconnects our session to the device.
func (j *junosSession) close(sleepClosed int) error {
_, err := j.session.Exec(netconf.RawMethod(rpcClose))
j.session.Transport.Close()
if err != nil {
sleep(sleepClosed)
return fmt.Errorf("failed to netconf close: %w", err)
}
sleep(sleepClosed)
return nil
}