/
athenz-conf.go
376 lines (338 loc) · 10.7 KB
/
athenz-conf.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
package main
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"errors"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"strings"
"syscall"
"time"
"golang.org/x/crypto/ssh/terminal"
"golang.org/x/net/proxy"
"github.com/AthenZ/athenz/clients/go/zms"
)
var (
// VERSION gets set by the build script via the LDFLAGS.
VERSION string
// BUILD_DATE gets set by the build script via the LDFLAGS.
BUILD_DATE string
)
func defaultZmsURL() string {
s := os.Getenv("ZMS")
if s != "" {
return s
}
return "https://localhost:4443/"
}
func defaultZtsURL() string {
s := os.Getenv("ZTS")
if s != "" {
return s
}
return "https://localhost:8443/"
}
func defaultIdentity() string {
return "user." + os.Getenv("USER")
}
func defaultSocksProxy() string {
return os.Getenv("SOCKS5_PROXY")
}
// isFreshFile checks the file's last modification time
// and returns true the file was updated within maxAge
// (file is "fresh"), false otherwise (file is "stale").
func isFreshFile(filename string, maxAge float64) bool {
info, err := os.Stat(filename)
if err != nil {
return false
}
delta := time.Since(info.ModTime())
// return false if delta exceeds maxAge
tooOld := delta.Minutes() > maxAge
return !tooOld
}
func getCachedNToken() string {
ntokenFile := os.Getenv("HOME") + "/.ntoken"
if isFreshFile(ntokenFile, 45) {
data, err := os.ReadFile(ntokenFile)
if err == nil {
return strings.TrimSpace(string(data))
}
fmt.Printf("Couldn't read the file, error: %v\n", err)
}
return ""
}
const identityPrefix = "user."
func getAuthNToken(identity, authorizedServices, zmsURL string, tr *http.Transport, timeout time.Duration) (string, error) {
// our identity must be user
if !strings.HasPrefix(identity, identityPrefix) {
return "", errors.New("identity must start with " + identityPrefix)
}
user := identity[5:]
ntoken := getCachedNToken()
if ntoken != "" {
return ntoken, nil
}
fmt.Fprintf(os.Stderr, "Enter password for "+user+": ")
pass, err := terminal.ReadPassword(syscall.Stdin)
if err != nil {
return "", err
}
password := string(pass)
// The user types <return> during terminal.ReadPassword() however
// since echo is turned off the cursor doesn't make it to the next line.
fmt.Fprint(os.Stderr, "\n")
data := []byte(user + ":" + password)
str := base64.StdEncoding.EncodeToString(data)
var authHeader = "Authorization"
var authCreds = "Basic " + str
zmsClient := zms.ZMSClient{
URL: zmsURL,
Transport: tr,
CredsHeaders: make(map[string]string),
Timeout: timeout,
}
zmsClient.AddCredentials(authHeader, authCreds)
tok, err := zmsClient.GetUserToken(zms.SimpleName(user), authorizedServices, nil)
if err != nil {
return "", fmt.Errorf("Cannot get user token for user: %s error: %v", user, err)
}
if tok.Token != "" {
ntokenFile := os.Getenv("HOME") + "/.ntoken"
data := []byte(tok.Token)
os.WriteFile(ntokenFile, data, 0600)
}
return string(tok.Token), nil
}
func usage() string {
var buf bytes.Buffer
buf.WriteString("usage: athenz-conf -z <zms_url> [flags]\n")
buf.WriteString(" flags:\n")
buf.WriteString(" -c cacert_file CA Certificate file path\n")
buf.WriteString(" -svc-cert-file cert_file Service Certificate file path\n")
buf.WriteString(" -f ntoken_file Principal Authority NToken file used for authentication\n")
buf.WriteString(" -i identity User identity to authenticate as if NToken file is not specified\n")
buf.WriteString(" (default=" + defaultIdentity() + ")\n")
buf.WriteString(" -k Disable peer verification of SSL certificates.\n")
buf.WriteString(" -svc-key-file key_file Service Private Key file path\n")
buf.WriteString(" -o Output config filename (default=athenz.conf)\n")
buf.WriteString(" -s host:port The SOCKS5 proxy to route requests through\n")
buf.WriteString(" -t zts_url Base URL of the ZTS server to use\n")
buf.WriteString(" (default ZTS=" + defaultZtsURL() + ")\n")
buf.WriteString(" -z zms_url Base URL of the ZS server to use\n")
buf.WriteString(" (default ZMS=" + defaultZmsURL() + ")\n")
buf.WriteString(" -m timeout Timeout in seconds for connection requests")
buf.WriteString("\n")
return buf.String()
}
func printVersion() {
if VERSION == "" {
fmt.Println("athenz-conf (development version)")
} else {
fmt.Println("athenz-conf " + VERSION + " " + BUILD_DATE)
}
}
func loadNtokenFromFile(fileName string) (string, error) {
buf, err := os.ReadFile(fileName)
if err != nil {
return "", err
}
return strings.TrimSpace(string(buf)), nil
}
func main() {
pZMS := flag.String("z", defaultZmsURL(), "Base URL of the ZMS server to use")
pZTS := flag.String("t", defaultZtsURL(), "Base URL of the ZTS server to use")
pHdr := flag.String("hdr", "Athenz-Principal-Auth", "the authentication header name")
pKey := flag.String("svc-key-file", "", "the service private key file")
pCert := flag.String("svc-cert-file", "", "the service certificate file")
pIdentity := flag.String("i", defaultIdentity(), "the identity to authenticate as")
pNtokenFile := flag.String("f", "", "ntoken file path")
pCACert := flag.String("c", "", "CA Certificate file path")
pOutputFile := flag.String("o", "athenz.conf", "config filename")
pSocks := flag.String("s", defaultSocksProxy(), "The SOCKS5 proxy to route requests through, i.e. 127.0.0.1:1080")
pSkipVerify := flag.Bool("k", false, "Disable peer verification of SSL certificates")
pTimeout := flag.Int("m", 15, "Timeout in seconds for connection requests")
pShowVersion := flag.Bool("version", false, "Show version")
flag.Usage = func() {
fmt.Println(usage())
}
// first we need to parse our arguments based
// on the flags we defined above
flag.Parse()
if *pShowVersion {
printVersion()
return
}
zmsConfURL := normalizeServerURL(*pZMS, "/zms/v1")
ztsConfURL := normalizeServerURL(*pZTS, "/zts/v1")
zmsURL := zmsConfURL + "zms/v1"
if zmsURL == "" {
log.Fatalf("No ZMS Url specified")
}
// now process our request
args := flag.Args()
if len(args) == 1 {
if args[0] == "help" {
fmt.Println(usage())
return
} else if args[0] == "version" {
printVersion()
return
}
}
identity := *pIdentity
if !strings.Contains(identity, ".") {
identity = "user." + identity
}
if *pSocks == "" {
pSocks = nil
}
if *pCACert == "" {
pCACert = nil
}
if *pKey == "" && *pCert == "" {
pKey = nil
pCert = nil
} else if *pKey == "" || *pCert == "" {
log.Fatalf("Both service key and certificate must be provided")
}
tr := getHttpTransport(pSocks, pKey, pCert, pCACert, *pSkipVerify)
var ntoken string
var err error
if *pNtokenFile == "" {
if pKey == nil {
ntoken, err = getAuthNToken(identity, "", zmsURL, tr, time.Duration(time.Duration(*pTimeout)*time.Second))
if err != nil {
log.Fatalf("Unable to get NToken: %v", err)
}
}
} else {
ntoken, err = loadNtokenFromFile(*pNtokenFile)
if err != nil {
log.Fatalf("Unable to load ntoken from file: '%s' err: %v", *pNtokenFile, err)
}
}
zmsClient := zms.NewClient(zmsURL, tr)
zmsClient.Timeout = time.Duration(time.Duration(*pTimeout) * time.Second)
if ntoken != "" {
zmsClient.AddCredentials(*pHdr, ntoken)
}
var buf bytes.Buffer
buf.WriteString("{\n")
buf.WriteString(" \"zmsUrl\": \"" + zmsConfURL + "\",\n")
if ztsConfURL != "" {
buf.WriteString(" \"ztsUrl\": \"" + ztsConfURL + "\",\n")
}
zmsService, err := zmsClient.GetServiceIdentity(zms.DomainName("sys.auth"), zms.SimpleName("zms"))
if err != nil {
log.Fatalf("Unable to retrieve zms service details, err: %v", err)
}
dumpService(&buf, "zmsPublicKeys", zmsService)
ztsService, err := zmsClient.GetServiceIdentity(zms.DomainName("sys.auth"), zms.SimpleName("zts"))
if err == nil {
buf.WriteString(",\n")
dumpService(&buf, "ztsPublicKeys", ztsService)
}
buf.WriteString("\n")
buf.WriteString("}\n")
err = os.WriteFile(*pOutputFile, buf.Bytes(), 0644)
if err != nil {
log.Fatalf("Unable to write athenz.conf file, err: %v", err)
}
os.Exit(0)
}
func dumpService(buf *bytes.Buffer, label string, svc *zms.ServiceIdentity) {
buf.WriteString(" \"" + label + "\": [\n")
for idx, publicKey := range svc.PublicKeys {
buf.WriteString(" {\n")
buf.WriteString(" \"id\": \"" + publicKey.Id + "\",\n")
buf.WriteString(" \"key\": \"" + publicKey.Key + "\"\n")
buf.WriteString(" }")
if idx != len(svc.PublicKeys)-1 {
buf.WriteString(",")
}
buf.WriteString("\n")
}
buf.WriteString(" ]")
}
func getHttpTransport(socksProxy, keyFile, certFile, caCertFile *string, skipVerify bool) *http.Transport {
tr := http.Transport{}
if socksProxy != nil {
dialer := &net.Dialer{}
dialSocksProxy, err := proxy.SOCKS5("tcp", *socksProxy, nil, dialer)
if err == nil {
tr.Dial = dialSocksProxy.Dial
}
}
if keyFile != nil || caCertFile != nil || skipVerify {
config, err := GetTLSConfigFromFiles(certFile, keyFile, caCertFile)
if err != nil {
log.Fatalf("Unable to generate TLS config object, error: %v", err)
}
if skipVerify {
config.InsecureSkipVerify = skipVerify
}
tr.Proxy = http.ProxyFromEnvironment
tr.TLSClientConfig = config
}
return &tr
}
func GetTLSConfigFromFiles(certFile, keyFile, caCertFile *string) (*tls.Config, error) {
var keyPem []byte
var certPem []byte
var caCertPem []byte
var err error
if keyFile != nil {
keyPem, err = os.ReadFile(*keyFile)
if err != nil {
return nil, fmt.Errorf("Unable to read keyfile: %q, error: %v", *keyFile, err)
}
certPem, err = os.ReadFile(*certFile)
if err != nil {
return nil, fmt.Errorf("Unable to read certfile: %q, error: %v", *certFile, err)
}
}
if caCertFile != nil {
caCertPem, err = os.ReadFile(*caCertFile)
if err != nil {
return nil, fmt.Errorf("Unable to read ca certfile: %q, error: %v", *caCertFile, err)
}
}
return GetTLSConfig(certPem, keyPem, caCertPem)
}
func GetTLSConfig(certPem, keyPem, caCertPem []byte) (*tls.Config, error) {
config := &tls.Config{}
if keyPem != nil {
clientCert, err := tls.X509KeyPair(certPem, keyPem)
if err != nil {
return nil, fmt.Errorf("Unable to formulate clientCert from key and cert bytes, error: %v", err)
}
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0] = clientCert
}
if caCertPem != nil {
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(caCertPem) {
return nil, fmt.Errorf("Unable to append CA Certificate to pool")
}
config.RootCAs = certPool
}
return config, nil
}
func normalizeServerURL(url, suffix string) string {
normURL := ""
if strings.HasSuffix(url, suffix) {
normURL = url[:len(url)-len(suffix)] + "/"
} else if last := len(url) - 1; last >= 0 && url[last] == '/' {
normURL = url
} else {
normURL = url + "/"
}
return normURL
}