forked from writeas/httpsignatures-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
signature.go
220 lines (178 loc) · 4.95 KB
/
signature.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
// httpsignatures is a golang implementation of the http-signatures spec
// found at https://tools.ietf.org/html/draft-cavage-http-signatures
package httpsignatures
import (
"crypto/ecdsa"
"crypto/rsa"
"encoding/base64"
"errors"
"fmt"
"net/http"
"regexp"
"strings"
)
const (
headerSignature = "Signature"
headerAuthorization = "Authorization"
RequestTarget = "(request-target)"
authScheme = "Signature "
)
var (
ErrorNoSignatureHeader = errors.New("No Signature header found in request")
signatureRegex = regexp.MustCompile(`(\w+)="([^"]*)"`)
)
// Signature is the hashed key + headers, either from a request or a signer
type Signature struct {
KeyID string
Algorithm *Algorithm
Headers HeaderList
Signature string
}
// FromRequest creates a new Signature from the Request
// both Signature and Authorization http headers are supported.
func FromRequest(r *http.Request) (*Signature, error) {
if s, ok := r.Header[headerSignature]; ok {
return FromString(s[0])
}
if a, ok := r.Header[headerAuthorization]; ok {
return FromString(strings.TrimPrefix(a[0], authScheme))
}
return nil, ErrorNoSignatureHeader
}
// FromString creates a new Signature from its encoded form,
// eg `keyId="a",algorithm="b",headers="c",signature="d"`
func FromString(in string) (*Signature, error) {
var res Signature = Signature{}
var key string
var value string
for _, m := range signatureRegex.FindAllStringSubmatch(in, -1) {
key = m[1]
value = m[2]
if key == "keyId" {
res.KeyID = value
} else if key == "algorithm" {
alg, err := algorithmFromString(value)
if err != nil {
return nil, err
}
res.Algorithm = alg
} else if key == "headers" {
res.Headers = headerListFromString(value)
} else if key == "signature" {
res.Signature = value
} else {
return nil, errors.New(fmt.Sprintf("Unexpected key in signature '%s'", key))
}
}
if len(res.Signature) == 0 {
return nil, errors.New("Missing signature")
}
if len(res.KeyID) == 0 {
return nil, errors.New("Missing keyId")
}
if res.Algorithm == nil {
return nil, errors.New("Missing algorithm")
}
return &res, nil
}
// String returns the encoded form of the Signature
func (s Signature) String() string {
str := fmt.Sprintf(
`keyId="%s",algorithm="%s",signature="%s"`,
s.KeyID,
s.Algorithm.name,
s.Signature,
)
if len(s.Headers) > 0 {
str += fmt.Sprintf(`,headers="%s"`, s.Headers.String())
}
return str
}
func (s Signature) calculateSignature(key interface{}, r *http.Request) (string, error) {
signingString, err := s.Headers.signingString(r)
if err != nil {
return "", err
}
b, err := s.Algorithm.sign(key, []byte(signingString))
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(b), nil
}
// Sign this signature using the given key
func (s *Signature) sign(key interface{}, r *http.Request) error {
sig, err := s.calculateSignature(key, r)
if err != nil {
return err
}
s.Signature = sig
return nil
}
// IsValid validates this signature for the given key
func (s Signature) IsValid(key interface{}, r *http.Request) bool {
if !s.Headers.hasDate() {
return false
}
signingString, err := s.Headers.signingString(r)
if err != nil {
return false
}
signature, err := base64.StdEncoding.DecodeString(s.Signature)
if err != nil {
return false
}
return s.Algorithm.verify(key, []byte(signingString), signature)
}
// IsValidRSA validates that the request was signed by an RSA private key, using
// the public key for verification.
func (s Signature) IsValidRSA(key *rsa.PublicKey, r *http.Request) bool {
return s.IsValid(key, r)
}
// IsValidECDSA validates that the request was signed by an ECDSA private key,
// using the public key for verification.
func (s Signature) IsValidECDSA(key *ecdsa.PublicKey, r *http.Request) bool {
return s.IsValid(key, r)
}
type HeaderList []string
func headerListFromString(list string) HeaderList {
return strings.Split(strings.ToLower(string(list)), " ")
}
func (h HeaderList) String() string {
return strings.ToLower(strings.Join(h, " "))
}
func (h HeaderList) hasDate() bool {
for _, header := range h {
if header == "date" {
return true
}
}
return false
}
func (h HeaderList) signingString(req *http.Request) (string, error) {
lines := []string{}
for _, header := range h {
if header == RequestTarget {
lines = append(lines, requestTargetLine(req))
} else {
line, err := headerLine(req, header)
if err != nil {
return "", err
}
lines = append(lines, line)
}
}
return strings.Join(lines, "\n"), nil
}
func requestTargetLine(req *http.Request) string {
var url string = ""
if req.URL != nil {
url = req.URL.RequestURI()
}
return fmt.Sprintf("%s: %s %s", RequestTarget, strings.ToLower(req.Method), url)
}
func headerLine(req *http.Request, header string) (string, error) {
if value := req.Header.Get(header); value != "" {
return fmt.Sprintf("%s: %s", header, value), nil
}
return "", errors.New(fmt.Sprintf("Missing required header '%s'", header))
}