-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcerts.go
175 lines (157 loc) · 4.95 KB
/
certs.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
package fluent
import (
"crypto/rsa"
"crypto"
"crypto/sha512"
"io/ioutil"
"github.com/pkg/errors"
"encoding/pem"
"crypto/x509"
"hash"
"github.com/streadway/amqp"
)
const hashAlgo = x509.SHA512WithRSA
const signerAlgo = crypto.SHA512
func getHasher() hash.Hash {
return sha512.New()
}
func sign(data []byte, key *rsa.PrivateKey, opts crypto.SignerOpts) ([]byte, error) {
h := getHasher()
h.Write(data)
d := h.Sum(nil)
return key.Sign(nil, d, opts)
}
func loadPrivateKeyFile(path string) (*rsa.PrivateKey, error) {
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, errors.Wrap(err, "load content of "+path)
}
key, err := loadPrivateKey(content)
return key, errors.Wrapf(err, "private key from file %v", path)
}
func loadPrivateKey(content []byte) (*rsa.PrivateKey, error) {
var block *pem.Block
tail := content
for {
block, tail = pem.Decode(tail)
if block == nil {
break
}
switch block.Type {
case "PRIVATE KEY":
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, errors.Wrapf(err, "decode private key")
}
rKey, ok := key.(*rsa.PrivateKey)
if !ok {
return nil, errors.Errorf("private key is not RSA PKS#8")
}
return rKey, nil
}
}
return nil, errors.New("private key not found")
}
func loadCertificateFromFile(path string) (*x509.Certificate, error) {
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, errors.Wrap(err, "load content of "+path)
}
cert, err := loadCertificate(content)
return cert, errors.Wrapf(err, "load certificate from file %v", path)
}
func loadCertificate(content []byte) (*x509.Certificate, error) {
var block *pem.Block
tail := content
for {
block, tail = pem.Decode(tail)
if block == nil {
break
}
switch block.Type {
case "CERTIFICATE":
key, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, errors.Wrapf(err, "decode public key")
}
return key, nil
}
}
return nil, errors.New("public key not found")
}
type messageSigner struct {
header string
key *rsa.PrivateKey
}
func (ms *messageSigner) Handle(msg *amqp.Publishing) bool {
idBytes := []byte(msg.MessageId)
var data = make([]byte, len(idBytes)+len(msg.Body))
// by adding message-id into signature we prevent re-use old message by hackers. Of course only if target system
// can correct handle duplicated messages (drop them)
copy(data, idBytes)
copy(data[len(idBytes):], msg.Body)
signature, err := sign(data, ms.key, signerAlgo)
if err != nil {
panic(err) // something really wrong
}
if msg.Headers == nil {
msg.Headers = make(amqp.Table)
}
msg.Headers[ms.header] = signature
return true
}
// Create new PKS#1 1.5 SHA512 signer handler
func NewSigner(privateKey []byte, header string) (SenderHandler, error) {
key, err := loadPrivateKey(privateKey)
return &messageSigner{header: header, key: key}, errors.Wrapf(err, "create signer")
}
// Load private key from PKCS#8 file and create new PKS#1 1.5 SHA512 signer handler. File should contains
// --PRIVATE KEY-- section
func NewSignerFromFile(privateKeyFile string, header string) (SenderHandler, error) {
key, err := loadPrivateKeyFile(privateKeyFile)
return &messageSigner{header: header, key: key}, errors.Wrapf(err, "create signer from file")
}
type messageValidator struct {
logger Logger
header string
cert *x509.Certificate
}
func (mv *messageValidator) Handle(msg *amqp.Delivery) (bool) {
if msg.Headers == nil {
mv.logger.Println("message", msg.MessageId, "has empty headers")
return false
}
sigRaw, ok := msg.Headers[mv.header]
if !ok {
mv.logger.Println("message", msg.MessageId, "has no signature header", mv.header)
return false
}
signature, ok := sigRaw.([]byte)
if !ok {
mv.logger.Println("message", msg.MessageId, "signature header is not a bytes")
return false
}
idBytes := []byte(msg.MessageId)
var data = make([]byte, len(idBytes)+len(msg.Body))
copy(data, idBytes)
copy(data[len(idBytes):], msg.Body)
err := mv.cert.CheckSignature(hashAlgo, data, signature)
if err != nil {
mv.logger.Println("message", msg.MessageId, "signature verification failed:", err)
return false
}
return true
}
// Creates new handler that validates messages against signature header. Important!
// application MUST drop duplicated (by message id) messages by it self or
// it's possible just to resend same messages multiple times.
func NewCertValidator(cert []byte, header string, log Logger) (ReceiverHandler, error) {
key, err := loadCertificate(cert)
return &messageValidator{header: header, cert: key, logger: log}, errors.Wrapf(err, "create validator")
}
// Creates new handler (see NewCertValidator) with key from public ASN.1 DER certificate. Certificate
// should contain --CERTIFICATE-- section
func NewCertValidatorFromFile(certFile string, header string, log Logger) (ReceiverHandler, error) {
key, err := loadCertificateFromFile(certFile)
return &messageValidator{header: header, cert: key, logger: log}, errors.Wrapf(err, "create validator from file")
}