-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpanos_init.go
More file actions
202 lines (177 loc) · 5.33 KB
/
panos_init.go
File metadata and controls
202 lines (177 loc) · 5.33 KB
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
package main
import (
"fmt"
"io"
"io/ioutil"
"os"
"regexp"
"strings"
"time"
"golang.org/x/crypto/ssh"
)
// Various prompts.
var (
P1 *regexp.Regexp
P2 *regexp.Regexp
P3 *regexp.Regexp
)
func init() {
P1 = regexp.MustCompile(`[a-zA-Z][a-zA-Z0-9\._\-]+@[a-zA-Z][a-zA-Z0-9\._\-]+> `)
P2 = regexp.MustCompile(`[a-zA-Z][a-zA-Z0-9\._\-]+@[a-zA-Z][a-zA-Z0-9\._\-]+# `)
P3 = regexp.MustCompile(`(Enter|Confirm) password\s+:\s+?`)
}
// Globals to handle I/O.
var (
stdin io.Writer
stdout io.Reader
buf [65 * 1024]byte
)
// ReadTo reads from stdout until the desired prompt is encountered.
func ReadTo(prompt *regexp.Regexp) (string, error) {
var i int
for {
n, err := stdout.Read(buf[i:])
if n > 0 {
os.Stdout.Write(buf[i:i + n])
}
if err != nil {
return "", err
}
i += n
if prompt.Find(buf[:i]) != nil {
return string(buf[:i]), nil
}
}
}
// Perform user initialization.
func panosInit() error {
var err error
// Load environment variables.
hostname := os.Getenv("PANOS_HOSTNAME")
username := os.Getenv("PANOS_USERNAME")
password := os.Getenv("PANOS_PASSWORD")
// Sanity check input.
if len(os.Args) == 1 || os.Args[1] == "-h" || os.Args[1] == "--help" || hostname == "" || username == "" || password == "" {
u := []string{
fmt.Sprintf("Usage: %s <key_file>", os.Args[0]),
"",
"This will connect to a PAN-OS NGFW and perform initial config:",
"",
" * Adds the user as a superuser (if not the admin user)",
" * Sets the user's password",
" * Commit",
"",
"The following environment variables are required:",
"",
" * PANOS_HOSTNAME",
" * PANOS_USERNAME",
" * PANOS_PASSWORD",
}
for i := range u {
fmt.Printf("%s\n", u[i])
}
os.Exit(0)
}
// Read in the ssh key file.
data, err := ioutil.ReadFile(os.Args[1])
if err != nil {
return fmt.Errorf("Failed to read SSH key file %q: %s", os.Args[1], err)
}
signer, err := ssh.ParsePrivateKey(data)
if err != nil {
return fmt.Errorf("Failed to parse private key: %s", err)
}
useSshKey := ssh.PublicKeys(signer)
// Configure and open the ssh connection.
config := &ssh.ClientConfig{
User: "admin",
Auth: []ssh.AuthMethod{
useSshKey,
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", fmt.Sprintf("%s:22", hostname), config)
if err != nil {
return fmt.Errorf("Failed dial: %s", err)
}
defer client.Close()
session, err := client.NewSession()
if err != nil {
return fmt.Errorf("Failed to create session: %s", err)
}
defer session.Close()
modes := ssh.TerminalModes{
ssh.ECHO: 0,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
}
if err = session.RequestPty("vt100", 80, 80, modes); err != nil {
return fmt.Errorf("pty request failed: %s", err)
}
// Get input/output pipes for the ssh connection.
stdin, err = session.StdinPipe()
if err != nil {
return fmt.Errorf("setup stdin err: %s", err)
}
stdout, err = session.StdoutPipe()
if err != nil {
return fmt.Errorf("setup stdout err: %s", err)
}
// Invoke a shell on the remote host.
if err = session.Start("/bin/sh"); err != nil {
return fmt.Errorf("failed session.Start: %s", err)
}
// Perform initial config.
ok := true
commands := []struct{
Send string
Expect *regexp.Regexp
Validation string
OmitIfAdmin bool
}{
{"", P1, "", false},
{"set cli pager off", P1, "", false},
{"show system info", P1, "", false},
{"configure", P2, "", false},
{fmt.Sprintf("set mgt-config users %s permissions role-based superuser yes", username), P2, "", true},
{fmt.Sprintf("set mgt-config users %s password", username), P3, "", false},
{password, P3, "", false},
{password, P2, "", false},
{"commit description 'initial config'", P2, "Configuration committed successfully", false},
{"exit", P1, "", false},
{"exit", nil, "", false},
}
for _, cmd := range commands {
if cmd.OmitIfAdmin && username == "admin" {
continue
}
if cmd.Send != "" {
stdin.Write([]byte(cmd.Send + "\n"))
}
if cmd.Expect != nil {
out, err := ReadTo(cmd.Expect)
if err != nil {
return fmt.Errorf("Error in %q: %s", cmd.Send, err)
}
if cmd.Validation != "" {
ok = ok && strings.Contains(out, cmd.Validation)
}
// Delay slightly before sending passwords.
if cmd.Expect == P3 {
time.Sleep(1 * time.Second)
}
} else {
fmt.Printf("exit\n")
session.Wait()
}
}
// Completed successfully.
return nil
}
func main() {
if err := panosInit(); err != nil {
fmt.Printf("\nFailed initial config: %s\n", err)
os.Exit(1)
}
fmt.Printf("\nConfig initialization successful")
}