This repository has been archived by the owner on May 21, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
80 lines (69 loc) · 1.53 KB
/
main.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
package main
import (
"fmt"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"
"strings"
)
func acceptableRequest(r *http.Request) bool {
if r.Header.Get("X-Forwarded-For") != "" {
return false
}
if r.Header.Get("Metadata-Flavor") == "Amazon" {
return true
}
whitelistedUserAgentPrefixes := []string{
"aws-chalice/",
"aws-cli/",
"aws-sdk-",
"Boto3/",
"Botocore/",
"Cloud-Init/",
}
ua := r.UserAgent()
if ua == "" {
// no user-agent header was sent
return false
}
for _, v := range whitelistedUserAgentPrefixes {
if strings.HasPrefix(ua, v) {
return true
}
}
return false
}
func main() {
if val, ok := os.LookupEnv("LOGFLAGS"); ok {
if logflags, err := strconv.Atoi(val); err == nil {
log.SetFlags(logflags)
}
}
remote, err := url.Parse("http://169.254.169.254")
if err != nil {
panic(err)
}
proxy := httputil.NewSingleHostReverseProxy(remote)
handleRequest := func(w http.ResponseWriter, r *http.Request) {
if acceptableRequest(r) {
log.Printf("Proxying request to %s from User-Agent: %s\n", r.URL, r.UserAgent())
proxy.ServeHTTP(w, r)
} else {
log.Printf("Blocked request to %s from User-Agent: %s\n", r.URL, r.UserAgent())
w.WriteHeader(http.StatusBadRequest) // 400
}
}
port, _ := strconv.Atoi(os.Getenv("PORT"))
if port == 0 {
port = 16925
}
log.Printf("Listening on port: %d\n", port)
http.HandleFunc("/", handleRequest)
err = http.ListenAndServe(fmt.Sprintf("localhost:%d", port), nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}