Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cookies.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"net/http"
"time"

"github.com/divoxx/goRailsYourself/crypto"
"github.com/doximity/cookies/goRailsYourself/crypto"
)

// CookieEncryptor implements cookie encryption and signing to allow securely storing sensitive
Expand Down
21 changes: 21 additions & 0 deletions goRailsYourself/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Matt Aimonetti

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
27 changes: 27 additions & 0 deletions goRailsYourself/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
goRailsYourself
===============

[![GoDoc](http://godoc.org/github.com/mattetti/goRailsYourself?status.png)](https://pkg.go.dev/github.com/mattetti/goRailsYourself)


A suite of packages useful when you have to deal with Go and Rails apps
or when migrating from Ruby to Go.

The crypto package allows for shared authentication cookie support with Rails, included version 5.2+.


See the [documentation](http://godoc.org/github.com/mattetti/goRailsYourself) and/or the test suite for more examples.

## Dependencies:

The inflector package relies on:
[unidecode](http://godoc.org/github.com/fiam/gounidecode/unidecode) to handle the transliteration.

The crypto package relies on:
[pbkdf2](http://golang.org/x/crypto/pbkdf2) to handle the
generation of derived keys.

The test suite uses
[Goblin](http://tech.gilt.com/post/64409561192/goblin-a-minimal-and-beautiful-testing-framework-for)


21 changes: 21 additions & 0 deletions goRailsYourself/crypto/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Matt Aimonetti

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
100 changes: 100 additions & 0 deletions goRailsYourself/crypto/aes_cbc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package crypto

import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"io"
"strings"
)

func (crypt *MessageEncryptor) aesCbcEncrypt(value interface{}) (string, error) {
// TODO: check the crypt is properly initiated
k := crypt.Key
// The longest accepted key is 32 byte long,
// instead of rejecting a long key, we truncate it.
// This is how openssl in Ruby works.
if len(k) > 32 {
k = crypt.Key[:32]
}
block, err := aes.NewCipher(k)
if err != nil {
return "", err
}

// Set a default serializer if not already set
if crypt.Serializer == nil {
crypt.Serializer = JsonMsgSerializer{}
}
splaintext, err := crypt.Serializer.Serialize(value)
if err != nil {
return "", err
}
plaintext := []byte(splaintext)

// CBC mode works on blocks so plaintexts may need to be padded to the
// next whole block. See
// http://tools.ietf.org/html/rfc5652#section-6.3
plaintext = PKCS7Pad(plaintext)

// The IV needs to be unique, but not secure, it is included in the
// cypher text.
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}

// generate the cipher text
mode := cipher.NewCBCEncrypter(block, iv)
ciphertext := make([]byte, len(plaintext))
mode.CryptBlocks(ciphertext, plaintext)

// base64 the cipher text + the iv and join by "--"
output := base64.StdEncoding.EncodeToString(ciphertext) + "--" + base64.StdEncoding.EncodeToString(iv)
return output, nil
}

func (crypt *MessageEncryptor) aesCbcDecrypt(encryptedMsg string, target interface{}) error {
k := crypt.Key
// The longest accepted key is 32 byte long,
// instead of rejecting a long key, we truncate it.
// This is how openssl in Ruby works.
if len(k) > 32 {
k = crypt.Key[:32]
}

block, err := aes.NewCipher(k)
if err != nil {
return err
}

// split the msg and decode each part
splitMsg := strings.Split(encryptedMsg, "--")
if len(splitMsg) != 2 {
return errors.New("bad data (--)")
}

ciphertext, err := base64.StdEncoding.DecodeString(splitMsg[0])
if err != nil {
return err
}
iv, err := base64.StdEncoding.DecodeString(splitMsg[1])
if err != nil {
return err
}

if len(ciphertext) < aes.BlockSize {
return errors.New("bad data, ciphertext too short")
}
if len(ciphertext)%aes.BlockSize != 0 {
return errors.New("bad data, ciphertext is not a multiple of the block size")
}

mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
unPaddedCiphertext := PKCS7Unpad(ciphertext)

return crypt.Serializer.Unserialize(string(unPaddedCiphertext), target)
}
109 changes: 109 additions & 0 deletions goRailsYourself/crypto/aes_gcm.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package crypto

import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)

func (crypt *MessageEncryptor) aesGCMEncrypt(value interface{}) (string, error) {
// TODO: check the crypt is properly initiated
k := crypt.Key
// The longest accepted key is 32 byte long,
// instead of rejecting a long key, we truncate it.
// This is how openssl in Ruby works.
if len(k) > 32 {
k = crypt.Key[:32]
}
block, err := aes.NewCipher(k)
if err != nil {
return "", err
}

aesgcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}

// Set a default serializer if not already set
if crypt.Serializer == nil {
crypt.Serializer = JsonMsgSerializer{}
}
splaintext, err := crypt.Serializer.Serialize(value)
if err != nil {
return "", err
}
plaintext := []byte(splaintext)

iv := make([]byte, aesgcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}

ciphertext := aesgcm.Seal(nil, iv, plaintext, nil)

// Rails stores the GCM auth tag separately from the encrypted data,
// unlike the cipher package, so a little munging is required.
// Luckily aesgcm.Overhead() is the tag size (which is 16).
tagStart := len(ciphertext) - aesgcm.Overhead()
tag := ciphertext[tagStart:]
enc := ciphertext[:tagStart]

vectors := [][]byte{enc, iv, tag}
for i, vec := range vectors {
dst := make([]byte, base64.StdEncoding.EncodedLen(len(vec)))
base64.StdEncoding.Encode(dst, vec)
vectors[i] = dst
}

output := string(bytes.Join(vectors, []byte("--")))
return output, nil
}

func (crypt *MessageEncryptor) aesGCMDecrypt(encryptedMsg string, target interface{}) error {
k := crypt.Key
// The longest accepted key is 32 byte long,
// instead of rejecting a long key, we truncate it.
// This is how openssl in Ruby works.
if len(k) > 32 {
k = crypt.Key[:32]
}

block, err := aes.NewCipher(k)
if err != nil {
return err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return err
}

vectors := bytes.SplitN([]byte(encryptedMsg), []byte("--"), 3)
if len(vectors) != 3 {
return fmt.Errorf("missing vectors, want 3, got %d", len(vectors))
}
for i, vec := range vectors {
dst := make([]byte, base64.StdEncoding.DecodedLen(len(vec)))
n, err := base64.StdEncoding.Decode(dst, vec)
if err != nil {
return fmt.Errorf("bad base64 encoding")
}
vectors[i] = dst[:n]
}

enc := vectors[0]
// Rails splits the auth tag into a separate vector, which is unnecessary really, but fine.
enc = append(enc, vectors[2]...)
nonce := vectors[1]

plain, err := aesgcm.Open(nil, nonce, enc, nil)
if err != nil {
return err
}

return crypt.Serializer.Unserialize(string(plain), target)
}
21 changes: 21 additions & 0 deletions goRailsYourself/crypto/crypto.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package crypto

import (
"crypto/rand"
"io"
)

type MsgSerializer interface {
Serialize(v interface{}) (string, error)
Unserialize(data string, v interface{}) error
}

// Generates a random key of the passed length.
// As a reminder, for AES keys of length 16, 24, or 32 bytes are expected for AES-128, AES-192, or AES-256.
func GenerateRandomKey(strength int) []byte {
k := make([]byte, strength)
if _, err := io.ReadFull(rand.Reader, k); err != nil {
return nil
}
return k
}
Loading