forked from 99designs/aws-vault
/
server.go
171 lines (143 loc) · 4.57 KB
/
server.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
package server
import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
"runtime"
"time"
"github.com/99designs/aws-vault/vault"
)
const (
metadataBind = "169.254.169.254:80"
awsTimeFormat = "2006-01-02T15:04:05Z"
localServerUrl = "http://127.0.0.1:9099"
localServerBind = "127.0.0.1:9099"
)
func StartMetadataServer() error {
if _, err := installNetworkAlias(); err != nil {
return err
}
router := http.NewServeMux()
router.HandleFunc("/latest/meta-data/iam/security-credentials/", indexHandler)
router.HandleFunc("/latest/meta-data/iam/security-credentials/local-credentials", credentialsHandler)
// The AWS Go SDK checks the instance-id endpoint to validate the existence of EC2 Metadata
router.HandleFunc("/latest/meta-data/instance-id/", instanceIdHandler)
// The AWS .NET SDK checks this endpoint during obtaining credentials/refreshing them
router.HandleFunc("/latest/meta-data/iam/info/", infoHandlerStub)
l, err := net.Listen("tcp", metadataBind)
if err != nil {
return err
}
log.Printf("Local instance role server running on %s", l.Addr())
return http.Serve(l, router)
}
type metadataHandler struct {
http.Handler
}
func infoHandlerStub(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, `{"Code" : "Success"}`)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "local-credentials")
}
func credentialsHandler(w http.ResponseWriter, r *http.Request) {
resp, err := http.Get(localServerUrl)
if err != nil {
http.Error(w, err.Error(), http.StatusGatewayTimeout)
return
}
defer resp.Body.Close()
log.Printf("Fetched credentials from %s", localServerUrl)
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
io.Copy(w, resp.Body)
}
func instanceIdHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "aws-vault")
}
func checkServerRunning(bind string) bool {
_, err := net.DialTimeout("tcp", bind, time.Millisecond*10)
return err == nil
}
func StartCredentialProxyOnWindows() error {
log.Printf("Starting `aws-vault server` in the background")
cmd := exec.Command(os.Args[0], "server")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return err
}
time.Sleep(time.Second * 1)
if !checkServerRunning(metadataBind) {
return errors.New("The credential proxy server isn't running. Run aws-vault server as Administrator in the background and then try this command again")
}
return nil
}
func StartCredentialProxyWithSudo() error {
log.Printf("Starting `aws-vault server` as root in the background")
cmd := exec.Command("sudo", "-b", os.Args[0], "server")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func StartCredentialProxy() error {
if runtime.GOOS == "windows" {
return StartCredentialProxyOnWindows()
}
return StartCredentialProxyWithSudo()
}
func StartCredentialsServer(creds *vault.VaultCredentials) error {
if !checkServerRunning(metadataBind) {
if err := StartCredentialProxy(); err != nil {
return err
}
}
l, err := net.Listen("tcp", localServerBind)
if err != nil {
return err
}
log.Printf("Local instance role server running on %s", l.Addr())
go http.Serve(l, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Must make sure the remote ip is from the loopback, otherwise clients on the same network segment could
// potentially route traffic via 169.254.169.254:80
// See https://developer.apple.com/library/content/qa/qa1357/_index.html
if !net.ParseIP(ip).IsLoopback() {
http.Error(w, "Access denied from non-localhost address", http.StatusUnauthorized)
return
}
log.Printf("RemoteAddr = %v", r.RemoteAddr)
log.Printf("Credentials.IsExpired() = %#v", creds.IsExpired())
val, err := creds.Get()
if err != nil {
http.Error(w, err.Error(), http.StatusGatewayTimeout)
return
}
log.Printf("Serving credentials via http ****************%s, expiration of %s (%s)",
val.AccessKeyID[len(val.AccessKeyID)-4:],
creds.Expires().Format(awsTimeFormat),
creds.Expires().Sub(time.Now()).String())
json.NewEncoder(w).Encode(map[string]interface{}{
"Code": "Success",
"LastUpdated": time.Now().Format(awsTimeFormat),
"Type": "AWS-HMAC",
"AccessKeyId": val.AccessKeyID,
"SecretAccessKey": val.SecretAccessKey,
"Token": val.SessionToken,
"Expiration": creds.Expires().Format(awsTimeFormat),
})
}))
return nil
}