Encrypt session communication

This commit is contained in:
Milos Gajdos 2019-11-25 15:34:41 +00:00
parent 61fe552ac4
commit f82c267d81
No known key found for this signature in database
GPG Key ID: 8B31058CC55DFD4F
2 changed files with 33 additions and 4 deletions

View File

@ -8,7 +8,7 @@ import (
"io"
)
// Encrypt encrypts data and returns encrypted payload
// Encrypt encrypts data and returns the encrypted data
func Encrypt(data []byte, key string) ([]byte, error) {
// generate a new AES cipher using our 32 byte key
c, err := aes.NewCipher(hash(key))
@ -37,7 +37,7 @@ func Encrypt(data []byte, key string) ([]byte, error) {
return gcm.Seal(nonce, nonce, data, nil), nil
}
// Decrypt decrypts the payload and returns decrypted data
// Decrypt decrypts the payload and returns the decrypted data
func Decrypt(data []byte, key string) ([]byte, error) {
// generate AES cipher for decrypting the message
c, err := aes.NewCipher(hash(key))
@ -64,7 +64,7 @@ func Decrypt(data []byte, key string) ([]byte, error) {
}
// hash hahes the data into 32 bytes key and returns it
// hash uses sha256 to hash the passed in string.
// hash uses sha256 underneath to hash the supplied key
func hash(key string) []byte {
hasher := sha256.New()
hasher.Write([]byte(key))

View File

@ -301,13 +301,27 @@ func (s *session) Send(m *transport.Message) error {
// no op
}
// get the token
token, ok := m.Header["Micro-Tunnel-Token"]
if !ok {
// TODO: should we continue or return error
log.Debugf("no token found, insecure channel")
}
// encrypt the transport message payload
body, err := Encrypt(m.Body, token+s.channel+s.session)
if err != nil {
return err
}
// make copy
data := &transport.Message{
Header: make(map[string]string),
Body: m.Body,
Body: body,
}
for k, v := range m.Header {
// TODO: should we also encrypt headers?
data.Header[k] = v
}
@ -352,7 +366,22 @@ func (s *session) Recv(m *transport.Message) error {
default:
}
// TODO: if we encrypt headers we will have to decrypt them here
token, ok := msg.data.Header["Micro-Tunnel-Token"]
if !ok {
// TODO: should we continue or return error
log.Debugf("no token found, insecure channel")
}
log.Tracef("Received %+v from recv backlog", msg)
// decrypt the received payload using the token
body, err := Decrypt(msg.data.Body, token+s.channel+s.session)
if err != nil {
return err
}
msg.data.Body = body
// set message
*m = *msg.data
// return nil