mirror of
https://github.com/xor-gate/go-socks5-ssh-proxy
synced 2026-03-23 22:36:36 +01:00
Use github.com/awnumar/memguard to protect de-obfuscated embedded ssh private key and write logging to file when VMK is set
This commit is contained in:
23
vendor/github.com/awnumar/memguard/core/auxiliary.go
generated
vendored
Normal file
23
vendor/github.com/awnumar/memguard/core/auxiliary.go
generated
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
// Ascertain and store the system memory page size.
|
||||
pageSize = os.Getpagesize()
|
||||
)
|
||||
|
||||
// Round a length to a multiple of the system page size.
|
||||
func roundToPageSize(length int) int {
|
||||
return (length + (pageSize - 1)) & (^(pageSize - 1))
|
||||
}
|
||||
|
||||
// Convert a pointer and length to a byte slice that describes that memory.
|
||||
func getBytes(ptr *byte, len int) []byte {
|
||||
var sl = reflect.SliceHeader{Data: uintptr(unsafe.Pointer(ptr)), Len: len, Cap: len}
|
||||
return *(*[]byte)(unsafe.Pointer(&sl))
|
||||
}
|
||||
317
vendor/github.com/awnumar/memguard/core/buffer.go
generated
vendored
Normal file
317
vendor/github.com/awnumar/memguard/core/buffer.go
generated
vendored
Normal file
@ -0,0 +1,317 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
|
||||
"github.com/awnumar/memcall"
|
||||
)
|
||||
|
||||
var (
|
||||
buffers = new(bufferList)
|
||||
)
|
||||
|
||||
// ErrNullBuffer is returned when attempting to construct a buffer of size less than one.
|
||||
var ErrNullBuffer = errors.New("<memguard::core::ErrNullBuffer> buffer size must be greater than zero")
|
||||
|
||||
// ErrBufferExpired is returned when attempting to perform an operation on or with a buffer that has been destroyed.
|
||||
var ErrBufferExpired = errors.New("<memguard::core::ErrBufferExpired> buffer has been purged from memory and can no longer be used")
|
||||
|
||||
/*
|
||||
Buffer is a structure that holds raw sensitive data.
|
||||
|
||||
The number of Buffers that can exist at one time is limited by how much memory your system's kernel allows each process to mlock/VirtualLock. Therefore you should call DestroyBuffer on Buffers that you no longer need, ideally defering a Destroy call after creating a new one.
|
||||
*/
|
||||
type Buffer struct {
|
||||
sync.RWMutex // Local mutex lock // TODO: this does not protect 'data' field
|
||||
|
||||
alive bool // Signals that destruction has not come
|
||||
mutable bool // Mutability state of underlying memory
|
||||
|
||||
data []byte // Portion of memory holding the data
|
||||
memory []byte // Entire allocated memory region
|
||||
|
||||
preguard []byte // Guard page addressed before the data
|
||||
inner []byte // Inner region between the guard pages
|
||||
postguard []byte // Guard page addressed after the data
|
||||
|
||||
canary []byte // Value written behind data to detect spillage
|
||||
}
|
||||
|
||||
/*
|
||||
NewBuffer is a raw constructor for the Buffer object.
|
||||
*/
|
||||
func NewBuffer(size int) (*Buffer, error) {
|
||||
var err error
|
||||
|
||||
if size < 1 {
|
||||
return nil, ErrNullBuffer
|
||||
}
|
||||
|
||||
b := new(Buffer)
|
||||
|
||||
// Allocate the total needed memory
|
||||
innerLen := roundToPageSize(size)
|
||||
b.memory, err = memcall.Alloc((2 * pageSize) + innerLen)
|
||||
if err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
|
||||
// Construct slice reference for data buffer.
|
||||
b.data = getBytes(&b.memory[pageSize+innerLen-size], size)
|
||||
|
||||
// Construct slice references for page sectors.
|
||||
b.preguard = getBytes(&b.memory[0], pageSize)
|
||||
b.inner = getBytes(&b.memory[pageSize], innerLen)
|
||||
b.postguard = getBytes(&b.memory[pageSize+innerLen], pageSize)
|
||||
|
||||
// Construct slice reference for canary portion of inner page.
|
||||
b.canary = getBytes(&b.memory[pageSize], len(b.inner)-len(b.data))
|
||||
|
||||
// Lock the pages that will hold sensitive data.
|
||||
if err := memcall.Lock(b.inner); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
|
||||
// Initialise the canary value and reference regions.
|
||||
if err := Scramble(b.canary); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
Copy(b.preguard, b.canary)
|
||||
Copy(b.postguard, b.canary)
|
||||
|
||||
// Make the guard pages inaccessible.
|
||||
if err := memcall.Protect(b.preguard, memcall.NoAccess()); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
if err := memcall.Protect(b.postguard, memcall.NoAccess()); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
|
||||
// Set remaining properties
|
||||
b.alive = true
|
||||
b.mutable = true
|
||||
|
||||
// Append the container to list of active buffers.
|
||||
buffers.add(b)
|
||||
|
||||
// Return the created Buffer to the caller.
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// Data returns a byte slice representing the memory region containing the data.
|
||||
func (b *Buffer) Data() []byte {
|
||||
return b.data
|
||||
}
|
||||
|
||||
// Inner returns a byte slice representing the entire inner memory pages. This should NOT be used unless you have a specific need.
|
||||
func (b *Buffer) Inner() []byte {
|
||||
return b.inner
|
||||
}
|
||||
|
||||
// Freeze makes the underlying memory of a given buffer immutable. This will do nothing if the Buffer has been destroyed.
|
||||
func (b *Buffer) Freeze() {
|
||||
if err := b.freeze(); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Buffer) freeze() error {
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
|
||||
if !b.alive {
|
||||
return nil
|
||||
}
|
||||
|
||||
if b.mutable {
|
||||
if err := memcall.Protect(b.inner, memcall.ReadOnly()); err != nil {
|
||||
return err
|
||||
}
|
||||
b.mutable = false
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Melt makes the underlying memory of a given buffer mutable. This will do nothing if the Buffer has been destroyed.
|
||||
func (b *Buffer) Melt() {
|
||||
if err := b.melt(); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Buffer) melt() error {
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
|
||||
if !b.alive {
|
||||
return nil
|
||||
}
|
||||
|
||||
if !b.mutable {
|
||||
if err := memcall.Protect(b.inner, memcall.ReadWrite()); err != nil {
|
||||
return err
|
||||
}
|
||||
b.mutable = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Scramble attempts to overwrite the data with cryptographically-secure random bytes.
|
||||
func (b *Buffer) Scramble() {
|
||||
if err := b.scramble(); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Buffer) scramble() error {
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
return Scramble(b.Data())
|
||||
}
|
||||
|
||||
/*
|
||||
Destroy performs some security checks, securely wipes the contents of, and then releases a Buffer's memory back to the OS. If a security check fails, the process will attempt to wipe all it can before safely panicking.
|
||||
|
||||
If the Buffer has already been destroyed, the function does nothing and returns nil.
|
||||
*/
|
||||
func (b *Buffer) Destroy() {
|
||||
if err := b.destroy(); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
// Remove this one from global slice.
|
||||
buffers.remove(b)
|
||||
}
|
||||
|
||||
func (b *Buffer) destroy() error {
|
||||
if b == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Attain a mutex lock on this Buffer.
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
|
||||
// Return if it's already destroyed.
|
||||
if !b.alive {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Make all of the memory readable and writable.
|
||||
if err := memcall.Protect(b.memory, memcall.ReadWrite()); err != nil {
|
||||
return err
|
||||
}
|
||||
b.mutable = true
|
||||
|
||||
// Wipe data field.
|
||||
Wipe(b.data)
|
||||
|
||||
// Verify the canary
|
||||
if !Equal(b.preguard, b.postguard) || !Equal(b.preguard[:len(b.canary)], b.canary) {
|
||||
return errors.New("<memguard::core::buffer> canary verification failed; buffer overflow detected")
|
||||
}
|
||||
|
||||
// Wipe the memory.
|
||||
Wipe(b.memory)
|
||||
|
||||
// Unlock pages locked into memory.
|
||||
if err := memcall.Unlock(b.inner); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Free all related memory.
|
||||
if err := memcall.Free(b.memory); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Reset the fields.
|
||||
b.alive = false
|
||||
b.mutable = false
|
||||
b.data = nil
|
||||
b.memory = nil
|
||||
b.preguard = nil
|
||||
b.inner = nil
|
||||
b.postguard = nil
|
||||
b.canary = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// Alive returns true if the buffer has not been destroyed.
|
||||
func (b *Buffer) Alive() bool {
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
return b.alive
|
||||
}
|
||||
|
||||
// Mutable returns true if the buffer is mutable.
|
||||
func (b *Buffer) Mutable() bool {
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
return b.mutable
|
||||
}
|
||||
|
||||
// BufferList stores a list of buffers in a thread-safe manner.
|
||||
type bufferList struct {
|
||||
sync.RWMutex
|
||||
list []*Buffer
|
||||
}
|
||||
|
||||
// Add appends a given Buffer to the list.
|
||||
func (l *bufferList) add(b ...*Buffer) {
|
||||
l.Lock()
|
||||
defer l.Unlock()
|
||||
|
||||
l.list = append(l.list, b...)
|
||||
}
|
||||
|
||||
// Copy returns an instantaneous snapshot of the list.
|
||||
func (l *bufferList) copy() []*Buffer {
|
||||
l.Lock()
|
||||
defer l.Unlock()
|
||||
|
||||
list := make([]*Buffer, len(l.list))
|
||||
copy(list, l.list)
|
||||
|
||||
return list
|
||||
}
|
||||
|
||||
// Remove removes a given Buffer from the list.
|
||||
func (l *bufferList) remove(b *Buffer) {
|
||||
l.Lock()
|
||||
defer l.Unlock()
|
||||
|
||||
for i, v := range l.list {
|
||||
if v == b {
|
||||
l.list = append(l.list[:i], l.list[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Exists checks if a given buffer is in the list.
|
||||
func (l *bufferList) exists(b *Buffer) bool {
|
||||
l.RLock()
|
||||
defer l.RUnlock()
|
||||
|
||||
for _, v := range l.list {
|
||||
if b == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Flush clears the list and returns its previous contents.
|
||||
func (l *bufferList) flush() []*Buffer {
|
||||
l.Lock()
|
||||
defer l.Unlock()
|
||||
|
||||
list := make([]*Buffer, len(l.list))
|
||||
copy(list, l.list)
|
||||
|
||||
l.list = nil
|
||||
|
||||
return list
|
||||
}
|
||||
182
vendor/github.com/awnumar/memguard/core/coffer.go
generated
vendored
Normal file
182
vendor/github.com/awnumar/memguard/core/coffer.go
generated
vendored
Normal file
@ -0,0 +1,182 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Interval of time between each verify & re-key cycle.
|
||||
const interval = 500 * time.Millisecond
|
||||
|
||||
// ErrCofferExpired is returned when a function attempts to perform an operation using a secure key container that has been wiped and destroyed.
|
||||
var ErrCofferExpired = errors.New("<memguard::core::ErrCofferExpired> attempted usage of destroyed key object")
|
||||
|
||||
/*
|
||||
Coffer is a specialized container for securing highly-sensitive, 32 byte values.
|
||||
*/
|
||||
type Coffer struct {
|
||||
sync.Mutex
|
||||
|
||||
left *Buffer
|
||||
right *Buffer
|
||||
|
||||
rand *Buffer
|
||||
}
|
||||
|
||||
// NewCoffer is a raw constructor for the *Coffer object.
|
||||
func NewCoffer() *Coffer {
|
||||
s := new(Coffer)
|
||||
s.left, _ = NewBuffer(32)
|
||||
s.right, _ = NewBuffer(32)
|
||||
s.rand, _ = NewBuffer(32)
|
||||
|
||||
s.Init()
|
||||
|
||||
go func(s *Coffer) {
|
||||
ticker := time.NewTicker(interval)
|
||||
|
||||
for range ticker.C {
|
||||
if err := s.Rekey(); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}(s)
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// Init is used to reset the value stored inside a Coffer to a new random 32 byte value, overwriting the old.
|
||||
func (s *Coffer) Init() error {
|
||||
if s.Destroyed() {
|
||||
return ErrCofferExpired
|
||||
}
|
||||
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
if err := Scramble(s.left.Data()); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := Scramble(s.right.Data()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// left = left XOR hash(right)
|
||||
hr := Hash(s.right.Data())
|
||||
for i := range hr {
|
||||
s.left.Data()[i] ^= hr[i]
|
||||
}
|
||||
Wipe(hr)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/*
|
||||
View returns a snapshot of the contents of a Coffer inside a Buffer. As usual the Buffer should be destroyed as soon as possible after use by calling the Destroy method.
|
||||
*/
|
||||
func (s *Coffer) View() (*Buffer, error) {
|
||||
if s.Destroyed() {
|
||||
return nil, ErrCofferExpired
|
||||
}
|
||||
|
||||
b, _ := NewBuffer(32)
|
||||
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
// data = hash(right) XOR left
|
||||
h := Hash(s.right.Data())
|
||||
|
||||
for i := range b.Data() {
|
||||
b.Data()[i] = h[i] ^ s.left.Data()[i]
|
||||
}
|
||||
Wipe(h)
|
||||
|
||||
return b, nil
|
||||
}
|
||||
|
||||
/*
|
||||
Rekey is used to re-key a Coffer. Ideally this should be done at short, regular intervals.
|
||||
*/
|
||||
func (s *Coffer) Rekey() error {
|
||||
if s.Destroyed() {
|
||||
return ErrCofferExpired
|
||||
}
|
||||
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
if err := Scramble(s.rand.Data()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Hash the current right partition for later.
|
||||
hashRightCurrent := Hash(s.right.Data())
|
||||
|
||||
// new_right = current_right XOR buf32
|
||||
for i := range s.right.Data() {
|
||||
s.right.Data()[i] ^= s.rand.Data()[i]
|
||||
}
|
||||
|
||||
// new_left = current_left XOR hash(current_right) XOR hash(new_right)
|
||||
hashRightNew := Hash(s.right.Data())
|
||||
for i := range s.left.Data() {
|
||||
s.left.Data()[i] ^= hashRightCurrent[i] ^ hashRightNew[i]
|
||||
}
|
||||
Wipe(hashRightNew)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/*
|
||||
Destroy wipes and cleans up all memory related to a Coffer object. Once this method has been called, the Coffer can no longer be used and a new one should be created instead.
|
||||
*/
|
||||
func (s *Coffer) Destroy() error {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
err1 := s.left.destroy()
|
||||
if err1 == nil {
|
||||
buffers.remove(s.left)
|
||||
}
|
||||
err2 := s.right.destroy()
|
||||
if err2 == nil {
|
||||
buffers.remove(s.right)
|
||||
}
|
||||
err3 := s.rand.destroy()
|
||||
if err3 == nil {
|
||||
buffers.remove(s.rand)
|
||||
}
|
||||
|
||||
errS := ""
|
||||
if err1 != nil {
|
||||
errS = errS + err1.Error() + "\n"
|
||||
}
|
||||
if err2 != nil {
|
||||
errS = errS + err2.Error() + "\n"
|
||||
}
|
||||
if err3 != nil {
|
||||
errS = errS + err3.Error() + "\n"
|
||||
}
|
||||
if errS == "" {
|
||||
return nil
|
||||
}
|
||||
return errors.New(errS)
|
||||
}
|
||||
|
||||
// Destroyed returns a boolean value indicating if a Coffer has been destroyed.
|
||||
func (s *Coffer) Destroyed() bool {
|
||||
if s == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
if s.left == nil || s.right == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
return s.left.data == nil || s.right.data == nil
|
||||
}
|
||||
131
vendor/github.com/awnumar/memguard/core/crypto.go
generated
vendored
Normal file
131
vendor/github.com/awnumar/memguard/core/crypto.go
generated
vendored
Normal file
@ -0,0 +1,131 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"errors"
|
||||
"runtime"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/crypto/blake2b"
|
||||
"golang.org/x/crypto/nacl/secretbox"
|
||||
)
|
||||
|
||||
// Overhead is the size by which the ciphertext exceeds the plaintext.
|
||||
const Overhead int = secretbox.Overhead + 24 // auth + nonce
|
||||
|
||||
// ErrInvalidKeyLength is returned when attempting to encrypt or decrypt with a key that is not exactly 32 bytes in size.
|
||||
var ErrInvalidKeyLength = errors.New("<memguard::core::ErrInvalidKeyLength> key must be exactly 32 bytes")
|
||||
|
||||
// ErrBufferTooSmall is returned when the decryption function, Open, is given an output buffer that is too small to hold the plaintext. In practice the plaintext will be Overhead bytes smaller than the ciphertext returned by the encryption function, Seal.
|
||||
var ErrBufferTooSmall = errors.New("<memguard::core::ErrBufferTooSmall> the given buffer is too small to hold the plaintext")
|
||||
|
||||
// ErrDecryptionFailed is returned when the attempted decryption fails. This can occur if the given key is incorrect or if the ciphertext is invalid.
|
||||
var ErrDecryptionFailed = errors.New("<memguard::core::ErrDecryptionFailed> decryption failed: key is wrong or ciphertext is corrupt")
|
||||
|
||||
// Encrypt takes a plaintext message and a 32 byte key and returns an authenticated ciphertext.
|
||||
func Encrypt(plaintext, key []byte) ([]byte, error) {
|
||||
// Check the length of the key is correct.
|
||||
if len(key) != 32 {
|
||||
return nil, ErrInvalidKeyLength
|
||||
}
|
||||
|
||||
// Get a reference to the key's underlying array without making a copy.
|
||||
k := (*[32]byte)(unsafe.Pointer(&key[0]))
|
||||
|
||||
// Allocate space for and generate a nonce value.
|
||||
var nonce [24]byte
|
||||
if err := Scramble(nonce[:]); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
|
||||
// Encrypt m and return the result.
|
||||
return secretbox.Seal(nonce[:], plaintext, &nonce, k), nil
|
||||
}
|
||||
|
||||
/*
|
||||
Decrypt decrypts a given ciphertext with a given 32 byte key and writes the result to the start of a given buffer.
|
||||
|
||||
The buffer must be large enough to contain the decrypted data. This is in practice Overhead bytes less than the length of the ciphertext returned by the Seal function above. This value is the size of the nonce plus the size of the Poly1305 authenticator.
|
||||
|
||||
The size of the decrypted data is returned.
|
||||
*/
|
||||
func Decrypt(ciphertext, key []byte, output []byte) (int, error) {
|
||||
// Check the length of the key is correct.
|
||||
if len(key) != 32 {
|
||||
return 0, ErrInvalidKeyLength
|
||||
}
|
||||
|
||||
// Check the capacity of the given output buffer.
|
||||
if cap(output) < (len(ciphertext) - Overhead) {
|
||||
return 0, ErrBufferTooSmall
|
||||
}
|
||||
|
||||
// Get a reference to the key's underlying array without making a copy.
|
||||
k := (*[32]byte)(unsafe.Pointer(&key[0]))
|
||||
|
||||
// Retrieve and store the nonce value.
|
||||
var nonce [24]byte
|
||||
Copy(nonce[:], ciphertext[:24])
|
||||
|
||||
// Decrypt and return the result.
|
||||
m, ok := secretbox.Open(nil, ciphertext[24:], &nonce, k)
|
||||
if ok { // Decryption successful.
|
||||
Move(output[:cap(output)], m) // Move plaintext to given output buffer.
|
||||
return len(m), nil // Return length of decrypted plaintext.
|
||||
}
|
||||
|
||||
// Decryption unsuccessful. Either the key was wrong or the authentication failed.
|
||||
return 0, ErrDecryptionFailed
|
||||
}
|
||||
|
||||
// Hash implements a cryptographic hash function using Blake2b.
|
||||
func Hash(b []byte) []byte {
|
||||
h := blake2b.Sum256(b)
|
||||
return h[:]
|
||||
}
|
||||
|
||||
// Scramble fills a given buffer with cryptographically-secure random bytes.
|
||||
func Scramble(buf []byte) error {
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// See Wipe
|
||||
runtime.KeepAlive(buf)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Wipe takes a buffer and wipes it with zeroes.
|
||||
func Wipe(buf []byte) {
|
||||
for i := range buf {
|
||||
buf[i] = 0
|
||||
}
|
||||
|
||||
// This should keep buf's backing array live and thus prevent dead store
|
||||
// elimination, according to discussion at
|
||||
// https://github.com/golang/go/issues/33325 .
|
||||
runtime.KeepAlive(buf)
|
||||
}
|
||||
|
||||
// Copy is identical to Go's builtin copy function except the copying is done in constant time. This is to mitigate against side-channel attacks.
|
||||
func Copy(dst, src []byte) {
|
||||
if len(dst) > len(src) {
|
||||
subtle.ConstantTimeCopy(1, dst[:len(src)], src)
|
||||
} else if len(dst) < len(src) {
|
||||
subtle.ConstantTimeCopy(1, dst, src[:len(dst)])
|
||||
} else {
|
||||
subtle.ConstantTimeCopy(1, dst, src)
|
||||
}
|
||||
}
|
||||
|
||||
// Move is identical to Copy except it wipes the source buffer after the copy operation is executed.
|
||||
func Move(dst, src []byte) {
|
||||
Copy(dst, src)
|
||||
Wipe(src)
|
||||
}
|
||||
|
||||
// Equal does a constant-time comparison of two byte slices. This is to mitigate against side-channel attacks.
|
||||
func Equal(x, y []byte) bool {
|
||||
return subtle.ConstantTimeCompare(x, y) == 1
|
||||
}
|
||||
138
vendor/github.com/awnumar/memguard/core/enclave.go
generated
vendored
Normal file
138
vendor/github.com/awnumar/memguard/core/enclave.go
generated
vendored
Normal file
@ -0,0 +1,138 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
key = &Coffer{}
|
||||
keyMtx = sync.Mutex{}
|
||||
)
|
||||
|
||||
func getOrCreateKey() *Coffer {
|
||||
keyMtx.Lock()
|
||||
defer keyMtx.Unlock()
|
||||
|
||||
if key.Destroyed() {
|
||||
key = NewCoffer()
|
||||
}
|
||||
|
||||
return key
|
||||
}
|
||||
|
||||
func getKey() *Coffer {
|
||||
keyMtx.Lock()
|
||||
defer keyMtx.Unlock()
|
||||
|
||||
return key
|
||||
}
|
||||
|
||||
// ErrNullEnclave is returned when attempting to construct an enclave of size less than one.
|
||||
var ErrNullEnclave = errors.New("<memguard::core::ErrNullEnclave> enclave size must be greater than zero")
|
||||
|
||||
/*
|
||||
Enclave is a sealed and encrypted container for sensitive data.
|
||||
*/
|
||||
type Enclave struct {
|
||||
ciphertext []byte
|
||||
}
|
||||
|
||||
/*
|
||||
NewEnclave is a raw constructor for the Enclave object. The given buffer is wiped after the enclave is created.
|
||||
*/
|
||||
func NewEnclave(buf []byte) (*Enclave, error) {
|
||||
// Return an error if length < 1.
|
||||
if len(buf) < 1 {
|
||||
return nil, ErrNullEnclave
|
||||
}
|
||||
|
||||
// Create a new Enclave.
|
||||
e := new(Enclave)
|
||||
|
||||
// Get a view of the key.
|
||||
k, err := getOrCreateKey().View()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Encrypt the plaintext.
|
||||
e.ciphertext, err = Encrypt(buf, k.Data())
|
||||
if err != nil {
|
||||
Panic(err) // key is not 32 bytes long
|
||||
}
|
||||
|
||||
// Destroy our copy of the key.
|
||||
k.Destroy()
|
||||
|
||||
// Wipe the given buffer.
|
||||
Wipe(buf)
|
||||
|
||||
return e, nil
|
||||
}
|
||||
|
||||
/*
|
||||
Seal consumes a given Buffer object and returns its data secured and encrypted inside an Enclave. The given Buffer is destroyed after the Enclave is created.
|
||||
*/
|
||||
func Seal(b *Buffer) (*Enclave, error) {
|
||||
// Check if the Buffer has been destroyed.
|
||||
if !b.Alive() {
|
||||
return nil, ErrBufferExpired
|
||||
}
|
||||
|
||||
b.Melt() // Make the buffer mutable so that we can wipe it.
|
||||
|
||||
// Construct the Enclave from the Buffer's data.
|
||||
e, err := func() (*Enclave, error) {
|
||||
b.RLock() // Attain a read lock.
|
||||
defer b.RUnlock()
|
||||
return NewEnclave(b.Data())
|
||||
}()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Destroy the Buffer object.
|
||||
b.Destroy()
|
||||
|
||||
// Return the newly created Enclave.
|
||||
return e, nil
|
||||
}
|
||||
|
||||
/*
|
||||
Open decrypts an Enclave and puts the contents into a Buffer object. The given Enclave is left untouched and may be reused.
|
||||
|
||||
The Buffer object should be destroyed after the contents are no longer needed.
|
||||
*/
|
||||
func Open(e *Enclave) (*Buffer, error) {
|
||||
// Allocate a secure Buffer to hold the decrypted data.
|
||||
b, err := NewBuffer(len(e.ciphertext) - Overhead)
|
||||
if err != nil {
|
||||
Panic("<memguard:core> ciphertext has invalid length") // ciphertext has invalid length
|
||||
}
|
||||
|
||||
// Grab a view of the key.
|
||||
k, err := getOrCreateKey().View()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Decrypt the enclave into the buffer we created.
|
||||
_, err = Decrypt(e.ciphertext, k.Data(), b.Data())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Destroy our copy of the key.
|
||||
k.Destroy()
|
||||
|
||||
// Return the contents of the Enclave inside a Buffer.
|
||||
return b, nil
|
||||
}
|
||||
|
||||
/*
|
||||
EnclaveSize returns the number of bytes of plaintext data stored inside an Enclave.
|
||||
*/
|
||||
func EnclaveSize(e *Enclave) int {
|
||||
return len(e.ciphertext) - Overhead
|
||||
}
|
||||
87
vendor/github.com/awnumar/memguard/core/exit.go
generated
vendored
Normal file
87
vendor/github.com/awnumar/memguard/core/exit.go
generated
vendored
Normal file
@ -0,0 +1,87 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/awnumar/memcall"
|
||||
)
|
||||
|
||||
/*
|
||||
Purge wipes all sensitive data and keys before reinitialising the session with a fresh encryption key and secure values. Subsequent library operations will use these fresh values and the old data is assumed to be practically unrecoverable.
|
||||
|
||||
The creation of new Enclave objects should wait for this function to return since subsequent Enclave objects will use the newly created key.
|
||||
|
||||
This function should be called before the program terminates, or else the provided Exit or Panic functions should be used to terminate.
|
||||
*/
|
||||
func Purge() {
|
||||
var opErr error
|
||||
|
||||
func() {
|
||||
// Halt the re-key cycle and prevent new enclaves or keys being created.
|
||||
keyMtx.Lock()
|
||||
defer keyMtx.Unlock()
|
||||
if !key.Destroyed() {
|
||||
key.Lock()
|
||||
defer key.Unlock()
|
||||
}
|
||||
|
||||
// Get a snapshot of existing Buffers.
|
||||
snapshot := buffers.flush()
|
||||
|
||||
// Destroy them, performing the usual sanity checks.
|
||||
for _, b := range snapshot {
|
||||
if err := b.destroy(); err != nil {
|
||||
if opErr == nil {
|
||||
opErr = err
|
||||
} else {
|
||||
opErr = fmt.Errorf("%s; %s", opErr.Error(), err.Error())
|
||||
}
|
||||
// buffer destroy failed; wipe instead
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
if !b.mutable {
|
||||
if err := memcall.Protect(b.inner, memcall.ReadWrite()); err != nil {
|
||||
// couldn't change it to mutable; we can't wipe it! (could this happen?)
|
||||
// not sure what we can do at this point, just warn and move on
|
||||
fmt.Fprintf(os.Stderr, "!WARNING: failed to wipe immutable data at address %p", &b.data)
|
||||
continue // wipe in subprocess?
|
||||
}
|
||||
}
|
||||
Wipe(b.data)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// If we encountered an error, panic.
|
||||
if opErr != nil {
|
||||
panic(opErr)
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Exit terminates the process with a specified exit code but securely wipes and cleans up sensitive data before doing so.
|
||||
*/
|
||||
func Exit(c int) {
|
||||
// Wipe the encryption key used to encrypt data inside Enclaves.
|
||||
getKey().Destroy()
|
||||
|
||||
// Get a snapshot of existing Buffers.
|
||||
snapshot := buffers.copy() // copy ensures the buffers stay in the list until they are destroyed.
|
||||
|
||||
// Destroy them, performing the usual sanity checks.
|
||||
for _, b := range snapshot {
|
||||
b.Destroy()
|
||||
}
|
||||
|
||||
// Exit with the specified exit code.
|
||||
os.Exit(c)
|
||||
}
|
||||
|
||||
/*
|
||||
Panic is identical to the builtin panic except it purges the session before calling panic.
|
||||
*/
|
||||
func Panic(v interface{}) {
|
||||
Purge() // creates a new key so it is safe to recover from this panic
|
||||
panic(v)
|
||||
}
|
||||
9
vendor/github.com/awnumar/memguard/core/init.go
generated
vendored
Normal file
9
vendor/github.com/awnumar/memguard/core/init.go
generated
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"github.com/awnumar/memcall"
|
||||
)
|
||||
|
||||
func init() {
|
||||
memcall.DisableCoreDumps()
|
||||
}
|
||||
Reference in New Issue
Block a user