-
Notifications
You must be signed in to change notification settings - Fork 6
/
hmacurl.go
234 lines (199 loc) · 7.46 KB
/
hmacurl.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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/jessevdk/go-flags"
"github.com/udryan10/hmacurl/canonicalRequest"
"github.com/udryan10/hmacurl/signString"
"github.com/udryan10/hmacurl/signature"
"github.com/udryan10/hmacurl/utilities"
"github.com/udryan10/hmacurl/validation"
)
// positional argument
type Url struct {
Url string `positional-arg-name:"url"`
}
// setup flags
var opts struct {
Request string `short:"X" long:"request" default:"GET" description:"the http method to use" value-name:"GET|POST"`
Data string `short:"d" long:"data" default:"" description:"for POST requests, the data to be uploaded as the body. Used if -f is not provided." value-name:"'my string body'"`
File string `short:"f" long:"file" default:"" description:"for POST requests, the file to be uploaded as the body. Used if -d is not provided" value-name:"./file.txt"`
Headers map[string]string `short:"H" optional:"true" long:"header" description:"Extra header(s) to include in the request when sending HTTP to a server. You may specify any number of extra headers. "value-name:"'Content-Type: application/json'"`
CurlOnly bool `long:"curl-only" default:"false" description:"If specified, will only print out a curl command - not actually run a request"`
AccessKey string `short:"a" long:"access-key" default:"" description:"The access Key to use in HMAC signing. Can also be specified as an environment variable(export HMACURL_ACCESS_KEY='fasdf')"`
SecretKey string `short:"s" long:"secret-key" default:"" description:"The secret Key to use in HMAC signing. Can also be specified as an environment variable(export HMACURL_SECRET_KEY='fasdf')"`
CredentialScope string `short:"c" long:"credential-scope" default:"" description:"The credential scope (aka Service Name) for the request. Defaults to short host name."`
Region string `short:"r" long:"region" default:"us-east-1" description:"The region to use in the credential scope."`
SkipHost bool `short:"" long:"skip-host" default:"false" description:"Do not sign the Host header (useful for non-standard HMAC implementations)"`
Proxy string `short:"p" long:"proxy" default:"" description:"Proxy server to use if not set via environment variable."`
Debug bool `long:"debug" default:"false" description:"Whether to output debug information"`
// remaining positional args
Args Url `positional-args:"true" required:"true"`
}
// will run before main() used to parse our flags
func init() {
_, err := flags.Parse(&opts)
// help call
if err != nil {
os.Exit(0)
}
}
func main() {
var accessKey string
var secretKey string
// if we werent provided these arguments, pull from environment
if opts.AccessKey == "" {
if os.Getenv("HMACURL_ACCESS_KEY") == "" {
fmt.Println("Please provide access key via argument or environment variable HMACURL_ACCESS_KEY")
os.Exit(3)
} else {
accessKey = os.Getenv("HMACURL_ACCESS_KEY")
}
} else {
accessKey = opts.AccessKey
}
if opts.SecretKey == "" {
if os.Getenv("HMACURL_SECRET_KEY") == "" {
fmt.Println("Please provide secret key via argument or environment variable HMACURL_SECRET_KEY")
os.Exit(3)
} else {
secretKey = os.Getenv("HMACURL_SECRET_KEY")
}
} else {
secretKey = opts.SecretKey
}
if validation.Method(opts.Request) == false {
fmt.Printf("method %s is invalid\n", opts.Request)
os.Exit(1)
}
urlString, err := url.Parse(opts.Args.Url)
if err != nil {
fmt.Printf("Invalid url %s\n", opts.Args.Url)
os.Exit(2)
}
var payload string
if opts.Request == "POST" {
if opts.Data != "" {
payload = opts.Data
} else if opts.File != "" {
fileContents, err := ioutil.ReadFile(opts.File)
if err != nil {
panic(err)
}
// reading from file seems to put a newline at end - trim this
payload = strings.TrimSuffix(string(fileContents[:]), "\n")
}
}
requestTime := time.Now().UTC()
host, _, err := net.SplitHostPort(urlString.Host)
// likely no port
if err != nil {
host = urlString.Host
}
credentialScope := opts.CredentialScope
if opts.CredentialScope == "" {
credentialScope = strings.Split(host, ".")[0]
}
// setup headers
headerMap := map[string]string{"x-amz-date": requestTime.Format("20060102T150405Z")}
if opts.SkipHost == false {
headerMap["host"] = urlString.Host
}
// add headers passed in from -H options to headerMap
for k, v := range opts.Headers {
headerMap[strings.ToLower(k)] = strings.ToLower(v)
}
// if we were not given a Content-Type, use the default standard
if _, ok := headerMap["content-type"]; !ok {
headerMap["content-type"] = "application/octet-stream"
}
// where we start the signing process - pass in http method, url, headers and payload. for GET requests payload should be ""
canonicalString := canonicalRequest.FormatCanonicalString(opts.Request, urlString, headerMap, payload)
if opts.Debug == true {
fmt.Println("Canonical String:")
fmt.Println(canonicalString)
fmt.Println("================")
}
canonicalStringHashed := utilities.DataToSha256Encoded([]byte(canonicalString))
if opts.Debug == true {
fmt.Println("Canonical String Hashed:")
fmt.Println(canonicalStringHashed)
fmt.Println("================")
}
stringToSign := signString.StringToSign(requestTime, canonicalStringHashed, opts.Region, credentialScope)
if opts.Debug == true {
fmt.Println("String to sign:")
fmt.Println(stringToSign)
fmt.Println("================")
}
signature := signature.CalculateSignature(requestTime, stringToSign, opts.Region, credentialScope, secretKey)
headerMap["Authorization"] = utilities.GenerateSignedHeader(accessKey, signature, opts.Region, credentialScope, requestTime.Format("20060102"), canonicalRequest.FormatSignedHeaders(headerMap))
if opts.Debug == true {
fmt.Println("signature:")
fmt.Println(headerMap["Authorization"])
fmt.Println("================")
}
// signing process is complete start http calls
// if we had a flag to only output the curl command, dump that and be done
if opts.CurlOnly == true {
headerStringBuild := ""
for k, v := range headerMap {
headerStringBuild += fmt.Sprintf(" %s '%s:%s'", "-H", k, v)
}
if opts.Request == "POST" {
fmt.Printf("curl -X%s %s '%s' -v -d'%s'", opts.Request, headerStringBuild, urlString, payload)
} else if opts.Request == "GET" {
fmt.Printf("curl -X%s %s '%s' -v", opts.Request, headerStringBuild, urlString)
}
fmt.Println()
os.Exit(0)
}
var client *http.Client
if len(opts.Proxy) > 0 {
proxyURL, err := url.Parse(opts.Proxy)
if err != nil {
fmt.Println("Error parsing proxy: " + err.Error())
os.Exit(1)
}
client = &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}}
} else {
client = &http.Client{}
}
// make either a GET Request or POST Request
if opts.Request == "GET" {
req, err := http.NewRequest("GET", urlString.String(), nil)
// add headers to request
for k, v := range headerMap {
req.Header.Add(k, v)
}
resp, err := client.Do(req)
if err != nil {
fmt.Println("error in http call")
os.Exit(4)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(body[:]))
} else if opts.Request == "POST" {
req, err := http.NewRequest("POST", urlString.String(), bytes.NewBufferString(payload))
// add headers to request
for k, v := range headerMap {
req.Header.Add(k, v)
}
resp, err := client.Do(req)
if err != nil {
fmt.Println("error in http call")
os.Exit(4)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(body[:]))
}
}