pax_global_header 0000666 0000000 0000000 00000000064 14601340762 0014515 g ustar 00root root 0000000 0000000 52 comment=4ed2841e9041c2c37e455b05446477445c0eaf07
memguard-0.22.5/ 0000775 0000000 0000000 00000000000 14601340762 0013404 5 ustar 00root root 0000000 0000000 memguard-0.22.5/.cirrus.yml 0000664 0000000 0000000 00000003673 14601340762 0015525 0 ustar 00root root 0000000 0000000 linux_task:
container:
image: golang:latest
env:
GO111MODULE: on
GOPATH: /tmp/go
CIRRUS_WORKING_DIR: /tmp/go/src/github.com/${CIRRUS_REPO_FULL_NAME}
build_script:
- go version
- go get ./...
- go build -race -v ./...
test_script:
- go test -race -v ./...
bench_script:
- go test -run=XXX -bench=. ./...
osx_task:
macos_instance:
image: ghcr.io/cirruslabs/macos-ventura-base:latest
env:
GO111MODULE: on
GOPATH: /tmp/go
PATH: ${GOPATH}/bin:${PATH}
CIRRUS_WORKING_DIR: /tmp/go/src/github.com/${CIRRUS_REPO_FULL_NAME}
install_script:
- brew install go
build_script:
- go version
- go get ./...
- go build -race -v ./...
test_script:
- go test -race -v ./...
bench_script:
- go test -run=XXX -bench=. ./...
windows_task:
windows_container:
image: cirrusci/windowsservercore:2019
env:
GO111MODULE: on
GOPATH: C:\golang
PATH: ${GOPATH}\bin;C:\Program Files\Go\bin;C:\Users\ContainerAdministrator\go\bin;${PATH}
CIRRUS_WORKING_DIR: C:\golang\src\github.com\${CIRRUS_REPO_FULL_NAME}
install_script:
- choco install -y golang
- choco install -y mingw # This installs MinGW which includes gcc
- refreshenv
- gcc --version
build_script:
- go version
- go get ./...
- env CGO_ENABLED=1 go build -race -v ./...
test_script:
- echo $PATH
- refreshenv
- echo $PATH
- env CGO_ENABLED=1 go test -race -v ./...
bench_script:
- go test -run=XXX -bench=. ./...
freebsd_task:
freebsd_instance:
image: freebsd-14-0-release-amd64-ufs
env:
GO111MODULE: on
GOPATH: /tmp/go
PATH: ${GOPATH}/bin:${PATH}
CIRRUS_WORKING_DIR: /tmp/go/src/github.com/${CIRRUS_REPO_FULL_NAME}
install_script:
- pkg install -y go git
build_script:
- go version
- go get ./...
- go build -race -v ./...
test_script:
- go test -race -v ./...
bench_script:
- go test -run=XXX -bench=. ./...
memguard-0.22.5/.github/ 0000775 0000000 0000000 00000000000 14601340762 0014744 5 ustar 00root root 0000000 0000000 memguard-0.22.5/.github/ISSUE_TEMPLATE/ 0000775 0000000 0000000 00000000000 14601340762 0017127 5 ustar 00root root 0000000 0000000 memguard-0.22.5/.github/ISSUE_TEMPLATE/bug_report.md 0000664 0000000 0000000 00000001174 14601340762 0021624 0 ustar 00root root 0000000 0000000 ---
name: Bug report
about: Create a report to help us improve
labels: bug
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behaviour:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behaviour**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**System (please complete the following information):**
- OS and Kernel Versions:
- Memguard Version:
- Go Version:
**Additional context**
Add any other context about the problem here.
memguard-0.22.5/.github/ISSUE_TEMPLATE/proposal.md 0000664 0000000 0000000 00000001071 14601340762 0021307 0 ustar 00root root 0000000 0000000 ---
name: Proposal
about: Suggest an idea for this project
labels: proposal
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
memguard-0.22.5/.github/ISSUE_TEMPLATE/question.md 0000664 0000000 0000000 00000000126 14601340762 0021317 0 ustar 00root root 0000000 0000000 ---
name: Question
about: Get help with something
labels: question
---
*Ask away...*
memguard-0.22.5/AUTHORS 0000664 0000000 0000000 00000000656 14601340762 0014463 0 ustar 00root root 0000000 0000000 # Entries should be added alphabetically in the form:
# Name or Organization
Andrew LeFevre
Awn Umar
Carlo Alberto Ferraris
dotcppfile
Fedor Korotkov
Jam Adams
Joseph Richey
Neven Sajko
Paul Zeinlinger
memguard-0.22.5/LICENSE 0000664 0000000 0000000 00000026135 14601340762 0014420 0 ustar 00root root 0000000 0000000 Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
memguard-0.22.5/README.md 0000664 0000000 0000000 00000005565 14601340762 0014676 0 ustar 00root root 0000000 0000000
MemGuard
Software enclave for storage of sensitive information in memory.
---
This package attempts to reduce the likelihood of sensitive data being exposed when in memory. It aims to support all major operating systems and is written in pure Go.
## Features
* Sensitive data is encrypted and authenticated in memory with XSalsa20Poly1305. The [scheme](https://spacetime.dev/encrypting-secrets-in-memory) used also [defends against cold-boot attacks](https://spacetime.dev/memory-retention-attacks).
* Memory allocation bypasses the language runtime by [using system calls](https://github.com/awnumar/memcall) to query the kernel for resources directly. This avoids interference from the garbage-collector.
* Buffers that store plaintext data are fortified with guard pages and canary values to detect spurious accesses and overflows.
* Effort is taken to prevent sensitive data from touching the disk. This includes locking memory to prevent swapping and handling core dumps.
* Kernel-level immutability is implemented so that attempted modification of protected regions results in an access violation.
* Multiple endpoints provide session purging and safe termination capabilities as well as signal handling to prevent remnant data being left behind.
* Side-channel attacks are mitigated against by making sure that the copying and comparison of data is done in constant-time.
* Accidental memory leaks are mitigated against by harnessing the garbage-collector to automatically destroy containers that have become unreachable.
Some features were inspired by [libsodium](https://github.com/jedisct1/libsodium), so credits to them.
Full documentation and a complete overview of the API can be found [here](https://godoc.org/github.com/awnumar/memguard). Interesting and useful code samples can be found within the [examples](examples) subpackage.
## Installation
```
$ go get github.com/awnumar/memguard
```
API is experimental and may have unstable changes. You should pin a version. [[modules](https://github.com/golang/go/wiki/Modules)]
## Contributing
* Submitting program samples to [`./examples`](examples).
* Reporting bugs, vulnerabilities, and any difficulties in using the API.
* Writing useful security and crypto libraries that utilise memguard.
* Implementing kernel-specific/cpu-specific protections.
* Submitting performance improvements.
Issues are for reporting bugs and for discussion on proposals. Pull requests should be made against master.
memguard-0.22.5/buffer.go 0000664 0000000 0000000 00000042121 14601340762 0015204 0 ustar 00root root 0000000 0000000 package memguard
import (
"bytes"
"io"
"os"
"unsafe"
"github.com/awnumar/memguard/core"
)
/*
LockedBuffer is a structure that holds raw sensitive data.
The number of LockedBuffers that you are able to create is limited by how much memory your system's kernel allows each process to mlock/VirtualLock. Therefore you should call Destroy on LockedBuffers that you no longer need or defer a Destroy call after creating a new LockedBuffer.
*/
type LockedBuffer struct {
*core.Buffer
}
// Constructs a LockedBuffer object from a core.Buffer while also setting up the finalizer for it.
func newBuffer(buf *core.Buffer) *LockedBuffer {
return &LockedBuffer{buf}
}
// Constructs a quasi-destroyed LockedBuffer with size zero.
func newNullBuffer() *LockedBuffer {
return &LockedBuffer{new(core.Buffer)}
}
/*
NewBuffer creates a mutable data container of the specified size.
*/
func NewBuffer(size int) *LockedBuffer {
// Construct a Buffer of the specified size.
buf, err := core.NewBuffer(size)
if err != nil {
return newNullBuffer()
}
// Construct and return the wrapped container object.
return newBuffer(buf)
}
/*
NewBufferFromBytes constructs an immutable buffer from a byte slice. The source buffer is wiped after the value has been copied over to the created container.
*/
func NewBufferFromBytes(src []byte) *LockedBuffer {
// Construct a buffer of the correct size.
b := NewBuffer(len(src))
if b.Size() == 0 {
return b
}
// Move the data over.
b.Move(src)
// Make the buffer immutable.
b.Freeze()
// Return the created Buffer object.
return b
}
/*
NewBufferFromReader reads some number of bytes from an io.Reader into an immutable LockedBuffer.
An error is returned precisely when the number of bytes read is less than the requested amount. Any data read is returned in either case.
*/
func NewBufferFromReader(r io.Reader, size int) (*LockedBuffer, error) {
// Construct a buffer of the provided size.
b := NewBuffer(size)
if b.Size() == 0 {
return b, nil
}
// Attempt to fill it with data from the Reader.
if n, err := io.ReadFull(r, b.Bytes()); err != nil {
if n == 0 {
// nothing was read
b.Destroy()
return newNullBuffer(), err
}
// partial read
d := NewBuffer(n)
d.Copy(b.Bytes()[:n])
d.Freeze()
b.Destroy()
return d, err
}
// success
b.Freeze()
return b, nil
}
/*
NewBufferFromReaderUntil constructs an immutable buffer containing data sourced from an io.Reader object.
If an error is encountered before the delimiter value, the error will be returned along with the data read up until that point.
*/
func NewBufferFromReaderUntil(r io.Reader, delim byte) (*LockedBuffer, error) {
// Construct a buffer with a data page that fills an entire memory page.
b := NewBuffer(os.Getpagesize())
// Loop over the buffer a byte at a time.
for i := 0; ; i++ {
// If we have filled this buffer...
if i == b.Size() {
// Construct a new buffer that is a page size larger.
c := NewBuffer(b.Size() + os.Getpagesize())
// Copy the data over.
c.Copy(b.Bytes())
// Destroy the old one and reassign its variable.
b.Destroy()
b = c
}
// Attempt to read a single byte.
n, err := r.Read(b.Bytes()[i : i+1])
if n != 1 { // if we did not read a byte
if err == nil { // and there was no error
i-- // try again
continue
}
// if instead there was an error, we're done early
if i == 0 { // no data read
b.Destroy()
return newNullBuffer(), err
}
d := NewBuffer(i)
d.Copy(b.Bytes()[:i])
d.Freeze()
b.Destroy()
return d, err
}
// we managed to read a byte, check if it was the delimiter
// note that errors are ignored in this case where we got data
if b.Bytes()[i] == delim {
if i == 0 {
// if first byte was delimiter, there's no data to return
b.Destroy()
return newNullBuffer(), nil
}
d := NewBuffer(i)
d.Copy(b.Bytes()[:i])
d.Freeze()
b.Destroy()
return d, nil
}
}
}
/*
NewBufferFromEntireReader reads from an io.Reader into an immutable buffer. It will continue reading until EOF.
A nil error is returned precisely when we managed to read all the way until EOF. Any data read is returned in either case.
*/
func NewBufferFromEntireReader(r io.Reader) (*LockedBuffer, error) {
// Create a buffer with a data region of one page size.
b := NewBuffer(os.Getpagesize())
for read := 0; ; {
// Attempt to read some data from the reader.
n, err := r.Read(b.Bytes()[read:])
// Nothing read but no error, try again.
if n == 0 && err == nil {
continue
}
// 1) so either have data and no error
// 2) or have error and no data
// 3) or both have data and have error
// Increment the read count by the number of bytes that we just read.
read += n
if err != nil {
// Suppress EOF error
if err == io.EOF {
err = nil
}
// We're done, return the data.
if read == 0 {
// No data read.
b.Destroy()
return newNullBuffer(), err
}
d := NewBuffer(read)
d.Copy(b.Bytes()[:read])
d.Freeze()
b.Destroy()
return d, err
}
// If we've filled this buffer, grow it by another page size.
if len(b.Bytes()[read:]) == 0 {
d := NewBuffer(b.Size() + os.Getpagesize())
d.Copy(b.Bytes())
b.Destroy()
b = d
}
}
}
/*
NewBufferRandom constructs an immutable buffer filled with cryptographically-secure random bytes.
*/
func NewBufferRandom(size int) *LockedBuffer {
// Construct a buffer of the specified size.
b := NewBuffer(size)
if b.Size() == 0 {
return b
}
// Fill the buffer with random bytes.
b.Scramble()
// Make the buffer immutable.
b.Freeze()
// Return the created Buffer object.
return b
}
// Freeze makes a LockedBuffer's memory immutable. The call can be reversed with Melt.
func (b *LockedBuffer) Freeze() {
b.Buffer.Freeze()
}
// Melt makes a LockedBuffer's memory mutable. The call can be reversed with Freeze.
func (b *LockedBuffer) Melt() {
b.Buffer.Melt()
}
/*
Seal takes a LockedBuffer object and returns its contents encrypted inside a sealed Enclave object. The LockedBuffer is subsequently destroyed and its contents wiped.
If Seal is called on a destroyed buffer, a nil enclave is returned.
*/
func (b *LockedBuffer) Seal() *Enclave {
e, err := core.Seal(b.Buffer)
if err != nil {
if err == core.ErrBufferExpired {
return nil
}
core.Panic(err)
}
return &Enclave{e}
}
/*
Copy performs a time-constant copy into a LockedBuffer. Move is preferred if the source is not also a LockedBuffer or if the source is no longer needed.
*/
func (b *LockedBuffer) Copy(src []byte) {
b.CopyAt(0, src)
}
/*
CopyAt performs a time-constant copy into a LockedBuffer at an offset. Move is preferred if the source is not also a LockedBuffer or if the source is no longer needed.
*/
func (b *LockedBuffer) CopyAt(offset int, src []byte) {
if !b.IsAlive() {
return
}
b.Lock()
defer b.Unlock()
core.Copy(b.Bytes()[offset:], src)
}
/*
Move performs a time-constant move into a LockedBuffer. The source is wiped after the bytes are copied.
*/
func (b *LockedBuffer) Move(src []byte) {
b.MoveAt(0, src)
}
/*
MoveAt performs a time-constant move into a LockedBuffer at an offset. The source is wiped after the bytes are copied.
*/
func (b *LockedBuffer) MoveAt(offset int, src []byte) {
if !b.IsAlive() {
return
}
b.Lock()
defer b.Unlock()
core.Move(b.Bytes()[offset:], src)
}
/*
Scramble attempts to overwrite the data with cryptographically-secure random bytes.
*/
func (b *LockedBuffer) Scramble() {
if !b.IsAlive() {
return
}
b.Buffer.Scramble()
}
/*
Wipe attempts to overwrite the data with zeros.
*/
func (b *LockedBuffer) Wipe() {
if !b.IsAlive() {
return
}
b.Lock()
defer b.Unlock()
core.Wipe(b.Bytes())
}
/*
Size gives you the length of a given LockedBuffer's data segment. A destroyed LockedBuffer will have a size of zero.
*/
func (b *LockedBuffer) Size() int {
return len(b.Bytes())
}
/*
Destroy wipes and frees the underlying memory of a LockedBuffer. The LockedBuffer will not be accessible or usable after this calls is made.
*/
func (b *LockedBuffer) Destroy() {
b.Buffer.Destroy()
}
/*
IsAlive returns a boolean value indicating if a LockedBuffer is alive, i.e. that it has not been destroyed.
*/
func (b *LockedBuffer) IsAlive() bool {
return b.Buffer.Alive()
}
/*
IsMutable returns a boolean value indicating if a LockedBuffer is mutable.
*/
func (b *LockedBuffer) IsMutable() bool {
return b.Buffer.Mutable()
}
/*
EqualTo performs a time-constant comparison on the contents of a LockedBuffer with a given buffer. A destroyed LockedBuffer will always return false.
*/
func (b *LockedBuffer) EqualTo(buf []byte) bool {
b.RLock()
defer b.RUnlock()
return core.Equal(b.Bytes(), buf)
}
/*
Functions for representing the memory region as various data types.
*/
/*
Bytes returns a byte slice referencing the protected region of memory.
*/
func (b *LockedBuffer) Bytes() []byte {
return b.Buffer.Data()
}
/*
Reader returns a Reader object referencing the protected region of memory.
*/
func (b *LockedBuffer) Reader() *bytes.Reader {
return bytes.NewReader(b.Bytes())
}
/*
String returns a string representation of the protected region of memory.
*/
func (b *LockedBuffer) String() string {
slice := b.Bytes()
return *(*string)(unsafe.Pointer(&slice))
}
/*
Uint16 returns a slice pointing to the protected region of memory with the data represented as a sequence of unsigned 16 bit integers. Its length will be half that of the byte slice, excluding any remaining part that doesn't form a complete uint16 value.
If called on a destroyed LockedBuffer, a nil slice will be returned.
*/
func (b *LockedBuffer) Uint16() []uint16 {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Compute size of new slice representation.
size := b.Size() / 2
if size < 1 {
return nil
}
// Construct the new slice representation.
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
// Cast the representation to the correct type and return it.
return *(*[]uint16)(unsafe.Pointer(&sl))
}
/*
Uint32 returns a slice pointing to the protected region of memory with the data represented as a sequence of unsigned 32 bit integers. Its length will be one quarter that of the byte slice, excluding any remaining part that doesn't form a complete uint32 value.
If called on a destroyed LockedBuffer, a nil slice will be returned.
*/
func (b *LockedBuffer) Uint32() []uint32 {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Compute size of new slice representation.
size := b.Size() / 4
if size < 1 {
return nil
}
// Construct the new slice representation.
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
// Cast the representation to the correct type and return it.
return *(*[]uint32)(unsafe.Pointer(&sl))
}
/*
Uint64 returns a slice pointing to the protected region of memory with the data represented as a sequence of unsigned 64 bit integers. Its length will be one eighth that of the byte slice, excluding any remaining part that doesn't form a complete uint64 value.
If called on a destroyed LockedBuffer, a nil slice will be returned.
*/
func (b *LockedBuffer) Uint64() []uint64 {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Compute size of new slice representation.
size := b.Size() / 8
if size < 1 {
return nil
}
// Construct the new slice representation.
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
// Cast the representation to the correct type and return it.
return *(*[]uint64)(unsafe.Pointer(&sl))
}
/*
Int8 returns a slice pointing to the protected region of memory with the data represented as a sequence of signed 8 bit integers. If called on a destroyed LockedBuffer, a nil slice will be returned.
*/
func (b *LockedBuffer) Int8() []int8 {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Construct the new slice representation.
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), b.Size(), b.Size()}
// Cast the representation to the correct type and return it.
return *(*[]int8)(unsafe.Pointer(&sl))
}
/*
Int16 returns a slice pointing to the protected region of memory with the data represented as a sequence of signed 16 bit integers. Its length will be half that of the byte slice, excluding any remaining part that doesn't form a complete int16 value.
If called on a destroyed LockedBuffer, a nil slice will be returned.
*/
func (b *LockedBuffer) Int16() []int16 {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Compute size of new slice representation.
size := b.Size() / 2
if size < 1 {
return nil
}
// Construct the new slice representation.
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
// Cast the representation to the correct type and return it.
return *(*[]int16)(unsafe.Pointer(&sl))
}
/*
Int32 returns a slice pointing to the protected region of memory with the data represented as a sequence of signed 32 bit integers. Its length will be one quarter that of the byte slice, excluding any remaining part that doesn't form a complete int32 value.
If called on a destroyed LockedBuffer, a nil slice will be returned.
*/
func (b *LockedBuffer) Int32() []int32 {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Compute size of new slice representation.
size := b.Size() / 4
if size < 1 {
return nil
}
// Construct the new slice representation.
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
// Cast the representation to the correct type and return it.
return *(*[]int32)(unsafe.Pointer(&sl))
}
/*
Int64 returns a slice pointing to the protected region of memory with the data represented as a sequence of signed 64 bit integers. Its length will be one eighth that of the byte slice, excluding any remaining part that doesn't form a complete int64 value.
If called on a destroyed LockedBuffer, a nil slice will be returned.
*/
func (b *LockedBuffer) Int64() []int64 {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Compute size of new slice representation.
size := b.Size() / 8
if size < 1 {
return nil
}
// Construct the new slice representation.
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
// Cast the representation to the correct type and return it.
return *(*[]int64)(unsafe.Pointer(&sl))
}
/*
ByteArray8 returns a pointer to some 8 byte array. Care must be taken not to dereference the pointer and instead pass it around as-is.
The length of the buffer must be at least 8 bytes in size and the LockedBuffer should not be destroyed. In either of these cases a nil value is returned.
*/
func (b *LockedBuffer) ByteArray8() *[8]byte {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Check if the length is large enough.
if len(b.Bytes()) < 8 {
return nil
}
// Cast the representation to the correct type.
return (*[8]byte)(unsafe.Pointer(&b.Bytes()[0]))
}
/*
ByteArray16 returns a pointer to some 16 byte array. Care must be taken not to dereference the pointer and instead pass it around as-is.
The length of the buffer must be at least 16 bytes in size and the LockedBuffer should not be destroyed. In either of these cases a nil value is returned.
*/
func (b *LockedBuffer) ByteArray16() *[16]byte {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Check if the length is large enough.
if len(b.Bytes()) < 16 {
return nil
}
// Cast the representation to the correct type.
return (*[16]byte)(unsafe.Pointer(&b.Bytes()[0]))
}
/*
ByteArray32 returns a pointer to some 32 byte array. Care must be taken not to dereference the pointer and instead pass it around as-is.
The length of the buffer must be at least 32 bytes in size and the LockedBuffer should not be destroyed. In either of these cases a nil value is returned.
*/
func (b *LockedBuffer) ByteArray32() *[32]byte {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Check if the length is large enough.
if len(b.Bytes()) < 32 {
return nil
}
// Cast the representation to the correct type.
return (*[32]byte)(unsafe.Pointer(&b.Bytes()[0]))
}
/*
ByteArray64 returns a pointer to some 64 byte array. Care must be taken not to dereference the pointer and instead pass it around as-is.
The length of the buffer must be at least 64 bytes in size and the LockedBuffer should not be destroyed. In either of these cases a nil value is returned.
*/
func (b *LockedBuffer) ByteArray64() *[64]byte {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Check if the length is large enough.
if len(b.Bytes()) < 64 {
return nil
}
// Cast the representation to the correct type.
return (*[64]byte)(unsafe.Pointer(&b.Bytes()[0]))
}
memguard-0.22.5/buffer_test.go 0000664 0000000 0000000 00000064220 14601340762 0016247 0 ustar 00root root 0000000 0000000 package memguard
import (
"bytes"
"crypto/rand"
"errors"
"io"
mrand "math/rand"
"os"
"runtime"
"testing"
"unsafe"
)
func TestPtrSafetyWithGC(t *testing.T) {
dataToLock := []byte(`abcdefgh`)
b := NewBufferFromBytes(dataToLock)
dataPtr := b.Bytes()
finalizerCalledChan := make(chan bool)
runtime.SetFinalizer(b, func(_ *LockedBuffer) {
finalizerCalledChan <- true
})
// b is now unreachable
runtime.GC()
finalizerCalled := <-finalizerCalledChan
if finalizerCalled == false {
t.Error("this should never occur")
}
// Check that data hasn't been garbage collected
if !bytes.Equal(dataPtr, []byte(`abcdefgh`)) {
t.Error("data does not have the value we set")
}
}
func TestNewBuffer(t *testing.T) {
b := NewBuffer(32)
if b == nil {
t.Error("buffer should not be nil")
}
if len(b.Bytes()) != 32 || cap(b.Bytes()) != 32 {
t.Error("buffer sizes incorrect")
}
if !bytes.Equal(b.Bytes(), make([]byte, 32)) {
t.Error("buffer is not zeroed")
}
if !b.IsMutable() {
t.Error("buffer should be mutable")
}
if !b.IsAlive() {
t.Error("buffer should not be destroyed")
}
b.Destroy()
b = NewBuffer(0)
if b.Bytes() != nil {
t.Error("data slice should be nil")
}
if b.Size() != 0 {
t.Error("size should be zero", b.Size())
}
if b.IsAlive() {
t.Error("buffer should be destroyed")
}
if b.IsMutable() {
t.Error("buffer should be immutable")
}
}
func TestNewBufferFromBytes(t *testing.T) {
data := []byte("yellow submarine")
b := NewBufferFromBytes(data)
if b == nil {
t.Error("buffer should not be nil")
}
if len(b.Bytes()) != 16 || cap(b.Bytes()) != 16 {
t.Error("buffer sizes invalid")
}
if !bytes.Equal(b.Bytes(), []byte("yellow submarine")) {
t.Error("data does not match\n", b.Bytes(), "\n", data)
}
if !bytes.Equal(data, make([]byte, 16)) {
t.Error("source buffer not wiped")
}
if b.IsMutable() {
t.Error("buffer should be immutable")
}
if !b.IsAlive() {
t.Error("buffer should not be destroyed")
}
b.Destroy()
b = NewBufferFromBytes([]byte{})
if b.Bytes() != nil {
t.Error("data slice should be nil")
}
if b.Size() != 0 {
t.Error("size should be zero", b.Size())
}
if b.IsAlive() {
t.Error("buffer should be destroyed")
}
if b.IsMutable() {
t.Error("buffer should be immutable")
}
}
func TestNewBufferFromReader(t *testing.T) {
b, err := NewBufferFromReader(rand.Reader, 4096)
if err != nil {
t.Error(err)
}
if b.Size() != 4096 {
t.Error("buffer of incorrect size")
}
if bytes.Equal(b.Bytes(), make([]byte, 4096)) {
t.Error("didn't read from reader")
}
if b.IsMutable() {
t.Error("expected buffer to be immutable")
}
b.Destroy()
r := bytes.NewReader([]byte("yellow submarine"))
b, err = NewBufferFromReader(r, 16)
if err != nil {
t.Error(err)
}
if b.Size() != 16 {
t.Error("buffer of incorrect size")
}
if !bytes.Equal(b.Bytes(), []byte("yellow submarine")) {
t.Error("incorrect data")
}
if b.IsMutable() {
t.Error("expected buffer to be immutable")
}
b.Destroy()
r = bytes.NewReader([]byte("yellow submarine"))
b, err = NewBufferFromReader(r, 17)
if err == nil {
t.Error("expected error got nil;", err)
}
if b.Size() != 16 {
t.Error("incorrect size")
}
if !bytes.Equal(b.Bytes(), []byte("yellow submarine")) {
t.Error("incorrect data")
}
if b.IsMutable() {
t.Error("expected buffer to be immutable")
}
b.Destroy()
r = bytes.NewReader([]byte(""))
b, err = NewBufferFromReader(r, 32)
if err == nil {
t.Error("expected error got nil")
}
if b.IsAlive() {
t.Error("expected destroyed buffer")
}
if b.IsMutable() {
t.Error("expected immutable buffer")
}
if b.Size() != 0 {
t.Error("expected nul sized buffer")
}
r = bytes.NewReader([]byte("yellow submarine"))
b, err = NewBufferFromReader(r, 0)
if err != nil {
t.Error(err)
}
if b.Bytes() != nil {
t.Error("data slice should be nil")
}
if b.Size() != 0 {
t.Error("size should be zero", b.Size())
}
if b.IsAlive() {
t.Error("buffer should be destroyed")
}
if b.IsMutable() {
t.Error("buffer should be immutable")
}
}
type s struct {
count int
}
func (reader *s) Read(p []byte) (n int, err error) {
if mrand.Intn(2) == 0 {
return 0, nil
}
reader.count++
if reader.count == 5000 {
copy(p, []byte{1})
return 1, nil
}
copy(p, []byte{0})
return 1, nil
}
func TestNewBufferFromReaderUntil(t *testing.T) {
data := make([]byte, 5000)
data[4999] = 1
r := bytes.NewReader(data)
b, err := NewBufferFromReaderUntil(r, 1)
if err != nil {
t.Error(err)
}
if b.Size() != 4999 {
t.Error("buffer has incorrect size")
}
for i := range b.Bytes() {
if b.Bytes()[i] != 0 {
t.Error("incorrect data")
}
}
if b.IsMutable() {
t.Error("expected buffer to be immutable")
}
b.Destroy()
r = bytes.NewReader(data[:32])
b, err = NewBufferFromReaderUntil(r, 1)
if err == nil {
t.Error("expected error got nil")
}
if b.Size() != 32 {
t.Error("invalid size")
}
for i := range b.Bytes() {
if b.Bytes()[i] != 0 {
t.Error("incorrect data")
}
}
if b.IsMutable() {
t.Error("expected buffer to be immutable")
}
b.Destroy()
r = bytes.NewReader([]byte{'x'})
b, err = NewBufferFromReaderUntil(r, 'x')
if err != nil {
t.Error(err)
}
if b.Size() != 0 {
t.Error("expected no data")
}
if b.IsAlive() {
t.Error("expected dead buffer")
}
r = bytes.NewReader([]byte(""))
b, err = NewBufferFromReaderUntil(r, 1)
if err == nil {
t.Error("expected error got nil")
}
if b.IsAlive() {
t.Error("expected destroyed buffer")
}
if b.IsMutable() {
t.Error("expected immutable buffer")
}
if b.Size() != 0 {
t.Error("expected nul sized buffer")
}
rr := new(s)
b, err = NewBufferFromReaderUntil(rr, 1)
if err != nil {
t.Error(err)
}
if b.Size() != 4999 {
t.Error("invalid size")
}
for i := range b.Bytes() {
if b.Bytes()[i] != 0 {
t.Error("invalid data")
}
}
if b.IsMutable() {
t.Error("expected buffer to be immutable")
}
b.Destroy()
}
type ss struct {
count int
}
func (reader *ss) Read(p []byte) (n int, err error) {
if mrand.Intn(2) == 0 {
return 0, nil
}
reader.count++
if reader.count == 5000 {
return 0, io.EOF
}
copy(p, []byte{0})
return 1, nil
}
type se struct {
count int
}
func (reader *se) Read(p []byte) (n int, err error) {
copy(p, []byte{0})
reader.count++
if reader.count == 5000 {
return 1, errors.New("shut up bro")
}
return 1, nil
}
func TestNewBufferFromEntireReader(t *testing.T) {
r := bytes.NewReader([]byte("yellow submarine"))
b, err := NewBufferFromEntireReader(r)
if err != nil {
t.Error(err)
}
if b.Size() != 16 {
t.Error("incorrect size", b.Size())
}
if !b.EqualTo([]byte("yellow submarine")) {
t.Error("incorrect data", b.String())
}
if b.IsMutable() {
t.Error("buffer should be immutable")
}
b.Destroy()
data := make([]byte, 16000)
ScrambleBytes(data)
r = bytes.NewReader(data)
b, err = NewBufferFromEntireReader(r)
if err != nil {
t.Error(err)
}
if b.Size() != len(data) {
t.Error("incorrect size", b.Size())
}
if !b.EqualTo(data) {
t.Error("incorrect data")
}
if b.IsMutable() {
t.Error("buffer should be immutable")
}
b.Destroy()
r = bytes.NewReader([]byte{})
b, err = NewBufferFromEntireReader(r)
if err != nil {
t.Error(err)
}
if b.Size() != 0 {
t.Error("buffer should be nil size")
}
if b.IsAlive() {
t.Error("buffer should appear destroyed")
}
rr := new(ss)
b, err = NewBufferFromEntireReader(rr)
if err != nil {
t.Error(err)
}
if b.Size() != 4999 {
t.Error("incorrect size", b.Size())
}
if !b.EqualTo(make([]byte, 4999)) {
t.Error("incorrect data")
}
if b.IsMutable() {
t.Error("buffer should be immutable")
}
b.Destroy()
re := new(se)
b, err = NewBufferFromEntireReader(re)
if err == nil {
t.Error("expected error got nil")
}
if b.Size() != 5000 {
t.Error(b.Size())
}
if !b.EqualTo(make([]byte, 5000)) {
t.Error("incorrect data")
}
if b.IsMutable() {
t.Error("buffer should be immutable")
}
b.Destroy()
// real world test
f, err := os.Open("LICENSE")
if err != nil {
t.Error(err)
}
data, err = io.ReadAll(f)
if err != nil {
t.Error(err)
}
_, err = f.Seek(0, 0)
if err != nil {
t.Error(err)
}
b, err = NewBufferFromEntireReader(f)
if err != nil {
t.Error(err)
}
if !b.EqualTo(data) {
t.Error("incorrect data")
}
if b.IsMutable() {
t.Error("buffer should be immutable")
}
b.Destroy()
f.Close()
}
func TestNewBufferRandom(t *testing.T) {
b := NewBufferRandom(32)
if b == nil {
t.Error("buffer is nil")
}
if len(b.Bytes()) != 32 || cap(b.Bytes()) != 32 {
t.Error("buffer sizes incorrect")
}
if bytes.Equal(b.Bytes(), make([]byte, 32)) {
t.Error("buffer is zeroed")
}
if b.IsMutable() {
t.Error("buffer should be immutable")
}
if !b.IsAlive() {
t.Error("buffer should not be destroyed")
}
b.Destroy()
b = NewBufferRandom(0)
if b.Bytes() != nil {
t.Error("data slice should be nil")
}
if b.Size() != 0 {
t.Error("size should be zero", b.Size())
}
if b.IsAlive() {
t.Error("buffer should be destroyed")
}
if b.IsMutable() {
t.Error("buffer should be immutable")
}
}
func TestFreeze(t *testing.T) {
b := NewBuffer(8)
if b == nil {
t.Error("buffer is nil")
}
if !b.IsMutable() {
t.Error("buffer isn't mutable")
}
b.Freeze()
if b.IsMutable() {
t.Error("buffer did not change to immutable")
}
if !bytes.Equal(b.Bytes(), make([]byte, 8)) {
t.Error("buffer changed value") // also tests readability
}
b.Freeze() // Test idempotency
if b.IsMutable() {
t.Error("buffer should be immutable")
}
if !bytes.Equal(b.Bytes(), make([]byte, 8)) {
t.Error("buffer changed value") // also tests readability
}
b.Destroy()
b.Freeze()
if b.IsMutable() {
t.Error("buffer is mutable")
}
if b.IsAlive() {
t.Error("buffer should be destroyed")
}
b = newNullBuffer()
b.Freeze()
if b.IsMutable() {
t.Error("buffer should be immutable")
}
}
func TestMelt(t *testing.T) {
b := NewBuffer(8)
if b == nil {
t.Error("buffer is nil")
}
b.Freeze()
if b.IsMutable() {
t.Error("buffer is mutable")
}
b.Melt()
if !b.IsMutable() {
t.Error("buffer did not become mutable")
}
if !bytes.Equal(b.Bytes(), make([]byte, 8)) {
t.Error("buffer changed value") // also tests readability
}
b.Bytes()[0] = 0x1 // test writability
if b.Bytes()[0] != 0x1 {
t.Error("buffer value not changed")
}
b.Melt() // Test idempotency
if !b.IsMutable() {
t.Error("buffer should be mutable")
}
b.Bytes()[0] = 0x2
if b.Bytes()[0] != 0x2 {
t.Error("buffer value not changed")
}
b.Destroy()
b.Melt()
if b.IsMutable() {
t.Error("buffer shouldn't be mutable")
}
if b.IsAlive() {
t.Error("buffer should be destroyed")
}
b = newNullBuffer()
b.Melt()
if b.IsMutable() {
t.Error("buffer should be immutable")
}
}
func TestSeal(t *testing.T) {
b := NewBufferRandom(32)
if b == nil {
t.Error("buffer is nil")
}
data := make([]byte, 32)
copy(data, b.Bytes())
e := b.Seal()
if e == nil {
t.Error("got nil enclave")
}
if b.IsAlive() {
t.Error("buffer should be destroyed")
}
b, err := e.Open()
if err != nil {
t.Error("unexpected error;", err)
}
if !bytes.Equal(b.Bytes(), data) {
t.Error("data does not match")
}
b.Destroy()
e = b.Seal() // call on destroyed buffer
if e != nil {
t.Error("expected nil enclave")
}
}
func TestCopy(t *testing.T) {
b := NewBuffer(16)
if b == nil {
t.Error("buffer is nil")
}
b.Copy([]byte("yellow submarine"))
if !bytes.Equal(b.Bytes(), []byte("yellow submarine")) {
t.Error("copy unsuccessful")
}
b.Destroy()
b.Copy([]byte("yellow submarine"))
if b.Bytes() != nil {
t.Error("buffer should be destroyed")
}
b = newNullBuffer()
b.Copy([]byte("yellow submarine"))
}
func TestCopyAt(t *testing.T) {
b := NewBuffer(8)
if b == nil {
t.Error("got nil buffer")
}
b.CopyAt(0, []byte("1234"))
if !bytes.Equal(b.Bytes()[:4], []byte("1234")) {
t.Error("copy unsuccessful")
}
if !bytes.Equal(b.Bytes()[4:], []byte{0, 0, 0, 0}) {
t.Error("copy overflow")
}
b.CopyAt(4, []byte("5678"))
if !bytes.Equal(b.Bytes(), []byte("12345678")) {
t.Error("copy unsuccessful")
}
b.Destroy()
b.CopyAt(4, []byte("hmmm"))
if b.Bytes() != nil {
t.Error("buffer should be destroyed")
}
b = newNullBuffer()
b.CopyAt(4, []byte("yellow submarine"))
}
func TestMove(t *testing.T) {
b := NewBuffer(16)
if b == nil {
t.Error("buffer is nil")
}
b.Move([]byte("yellow submarine"))
if !bytes.Equal(b.Bytes(), []byte("yellow submarine")) {
t.Error("copy unsuccessful")
}
data := []byte("yellow submarine")
b.Move(data)
for b := range data {
if data[b] != 0x0 {
t.Error("buffer was not wiped", b)
}
}
b.Destroy()
b.Move(data)
if b.Bytes() != nil {
t.Error("buffer should be destroyed")
}
b = newNullBuffer()
b.Move([]byte("yellow submarine"))
}
func TestMoveAt(t *testing.T) {
b := NewBuffer(8)
if b == nil {
t.Error("got nil buffer")
}
data := []byte("12345678")
b.MoveAt(0, data[:4])
if !bytes.Equal(b.Bytes()[:4], []byte("1234")) {
t.Error("copy unsuccessful")
}
if !bytes.Equal(b.Bytes()[4:], []byte{0, 0, 0, 0}) {
t.Error("copy overflow")
}
b.MoveAt(4, data[4:])
if !bytes.Equal(b.Bytes(), []byte("12345678")) {
t.Error("copy unsuccessful")
}
if !bytes.Equal(data, make([]byte, 8)) {
t.Error("buffer not wiped")
}
b.Destroy()
b.MoveAt(4, []byte("hmmm"))
if b.Bytes() != nil {
t.Error("buffer should be destroyed")
}
b = newNullBuffer()
b.MoveAt(4, []byte("yellow submarine"))
}
func TestScramble(t *testing.T) {
b := NewBuffer(32)
if b == nil {
t.Error("buffer is nil")
}
b.Scramble()
if bytes.Equal(b.Bytes(), make([]byte, 32)) {
t.Error("buffer was not randomised")
}
one := make([]byte, 32)
copy(one, b.Bytes())
b.Scramble()
if bytes.Equal(b.Bytes(), make([]byte, 32)) {
t.Error("buffer was not randomised")
}
if bytes.Equal(b.Bytes(), one) {
t.Error("buffer did not change")
}
b.Destroy()
b.Scramble()
if b.Bytes() != nil {
t.Error("buffer should be destroyed")
}
b = newNullBuffer()
b.Scramble()
}
func TestWipe(t *testing.T) {
b := NewBufferRandom(32)
if b == nil {
t.Error("got nil buffer")
}
b.Melt()
if bytes.Equal(b.Bytes(), make([]byte, 32)) {
t.Error("buffer was not randomised")
}
b.Wipe()
for i := range b.Bytes() {
if b.Bytes()[i] != 0 {
t.Error("buffer was not wiped; index", i)
}
}
b.Destroy()
b.Wipe()
if b.Bytes() != nil {
t.Error("buffer should be destroyed")
}
b = newNullBuffer()
b.Wipe()
}
func TestSize(t *testing.T) {
b := NewBuffer(1234)
if b == nil {
t.Error("got nil buffer")
}
if b.Size() != 1234 {
t.Error("size does not match expected")
}
b.Destroy()
if b.Size() != 0 {
t.Error("destroyed buffer size should be zero")
}
b = newNullBuffer()
if b.Size() != 0 {
t.Error("size should be zero")
}
}
func TestDestroy(t *testing.T) {
b := NewBuffer(32)
if b == nil {
t.Error("got nil buffer")
}
if b.Bytes() == nil {
t.Error("expected buffer to not be nil")
}
if len(b.Bytes()) != 32 || cap(b.Bytes()) != 32 {
t.Error("buffer sizes incorrect")
}
if !b.IsAlive() {
t.Error("buffer should be alive")
}
if !b.IsMutable() {
t.Error("buffer should be mutable")
}
b.Destroy()
if b.Bytes() != nil {
t.Error("expected buffer to be nil")
}
if len(b.Bytes()) != 0 || cap(b.Bytes()) != 0 {
t.Error("buffer sizes incorrect")
}
if b.IsAlive() {
t.Error("buffer should be destroyed")
}
if b.IsMutable() {
t.Error("buffer should be immutable")
}
b.Destroy()
if b.Bytes() != nil {
t.Error("expected buffer to be nil")
}
if len(b.Bytes()) != 0 || cap(b.Bytes()) != 0 {
t.Error("buffer sizes incorrect")
}
if b.IsAlive() {
t.Error("buffer should be destroyed")
}
if b.IsMutable() {
t.Error("buffer should be immutable")
}
b = newNullBuffer()
b.Destroy()
if b.IsAlive() {
t.Error("buffer should be dead")
}
}
func TestIsAlive(t *testing.T) {
b := NewBuffer(8)
if b == nil {
t.Error("got nil buffer")
}
if !b.IsAlive() {
t.Error("invalid state")
}
if b.IsAlive() != b.IsAlive() {
t.Error("states don't match")
}
b.Destroy()
if b.IsAlive() {
t.Error("invalid state")
}
if b.IsAlive() != b.IsAlive() {
t.Error("states don't match")
}
b = newNullBuffer()
if b.IsAlive() {
t.Error("buffer should be dead")
}
}
func TestIsMutable(t *testing.T) {
b := NewBuffer(8)
if b == nil {
t.Error("got nil buffer")
}
if !b.IsMutable() {
t.Error("invalid state")
}
if b.IsMutable() != b.IsMutable() {
t.Error("states don't match")
}
b.Freeze()
if b.IsMutable() {
t.Error("invalid state")
}
if b.IsMutable() != b.IsMutable() {
t.Error("states don't match")
}
b.Destroy()
if b.IsMutable() {
t.Error("invalid state")
}
if b.IsMutable() != b.IsMutable() {
t.Error("states don't match")
}
b = newNullBuffer()
if b.IsMutable() {
t.Error("buffer should be immutable")
}
}
func TestEqualTo(t *testing.T) {
b := NewBufferFromBytes([]byte("yellow submarine"))
if !b.EqualTo([]byte("yellow submarine")) {
t.Error("comparison incorrect")
}
if b.EqualTo([]byte("yellow")) {
t.Error("comparison incorrect")
}
b.Destroy()
if b.EqualTo([]byte("yellow submarine")) {
t.Error("comparison with destroyed should be false")
}
b = newNullBuffer()
if !b.EqualTo([]byte{}) {
t.Error("buffer should be size zero")
}
}
func TestBytes(t *testing.T) {
b := NewBufferFromBytes([]byte("yellow submarine"))
if b == nil {
t.Error("got nil buffer")
}
if !bytes.Equal(b.Bytes(), []byte("yellow submarine")) {
t.Error("not equal contents")
}
b.Melt()
b.Bytes()[8] = ^b.Bytes()[8]
if !bytes.Equal(b.Buffer.Data(), b.Bytes()) {
t.Error("methods disagree")
}
b.Destroy()
if b.Bytes() != nil {
t.Error("expected nil buffer")
}
b = newNullBuffer()
if b.Bytes() != nil {
t.Error("buffer should be nil")
}
}
func TestReader(t *testing.T) {
b := NewBufferRandom(32)
c, err := NewBufferFromReader(b.Reader(), 32)
if err != nil {
t.Error(err)
}
if !bytes.Equal(b.Bytes(), c.Bytes()) {
t.Error("data not equal")
}
b.Destroy()
c.Destroy()
if c.Reader().Size() != 0 {
t.Error("expected nul reader")
}
b = newNullBuffer()
if c.Reader().Size() != 0 {
t.Error("expected nul reader")
}
}
func TestString(t *testing.T) {
b := NewBufferRandom(32)
b.Melt()
s := b.String()
for i := range b.Bytes() {
b.Bytes()[i] = 'x'
if string(b.Bytes()) != s {
t.Error("string does not map same memory")
}
}
b.Destroy()
s = b.String()
if s != "" {
t.Error("string should be empty")
}
b = newNullBuffer()
if s != "" {
t.Error("string should be empty")
}
}
func TestUint16(t *testing.T) {
b := NewBuffer(32)
if b == nil {
t.Error("got nil buffer")
}
u16 := b.Uint16()
if len(u16) != 16 || cap(u16) != 16 {
t.Error("sizes incorrect")
}
if uintptr(unsafe.Pointer(&u16[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(3)
if b == nil {
t.Error("got nil buffer")
}
u16 = b.Uint16()
if len(u16) != 1 || cap(u16) != 1 {
t.Error("sizes should be 1")
}
if uintptr(unsafe.Pointer(&u16[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(1)
if b == nil {
t.Error("got nil buffer")
}
u16 = b.Uint16()
if u16 != nil {
t.Error("expected nil slice")
}
b.Destroy()
if b.Uint16() != nil {
t.Error("expected nil slice as buffer destroyed")
}
b = newNullBuffer()
if b.Uint16() != nil {
t.Error("should be nil")
}
}
func TestUint32(t *testing.T) {
b := NewBuffer(32)
if b == nil {
t.Error("got nil buffer")
}
u32 := b.Uint32()
if len(u32) != 8 || cap(u32) != 8 {
t.Error("sizes incorrect")
}
if uintptr(unsafe.Pointer(&u32[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(5)
if b == nil {
t.Error("got nil buffer")
}
u32 = b.Uint32()
if len(u32) != 1 || cap(u32) != 1 {
t.Error("sizes should be 1")
}
if uintptr(unsafe.Pointer(&u32[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(3)
if b == nil {
t.Error("got nil buffer")
}
u32 = b.Uint32()
if u32 != nil {
t.Error("expected nil slice")
}
b.Destroy()
if b.Uint32() != nil {
t.Error("expected nil slice as buffer destroyed")
}
b = newNullBuffer()
if b.Uint32() != nil {
t.Error("should be nil")
}
}
func TestUint64(t *testing.T) {
b := NewBuffer(32)
if b == nil {
t.Error("got nil buffer")
}
u64 := b.Uint64()
if len(u64) != 4 || cap(u64) != 4 {
t.Error("sizes incorrect")
}
if uintptr(unsafe.Pointer(&u64[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(9)
if b == nil {
t.Error("got nil buffer")
}
u64 = b.Uint64()
if len(u64) != 1 || cap(u64) != 1 {
t.Error("sizes should be 1")
}
if uintptr(unsafe.Pointer(&u64[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(7)
if b == nil {
t.Error("got nil buffer")
}
u64 = b.Uint64()
if u64 != nil {
t.Error("expected nil slice")
}
b.Destroy()
if b.Uint64() != nil {
t.Error("expected nil slice as buffer destroyed")
}
b = newNullBuffer()
if b.Uint64() != nil {
t.Error("should be nil")
}
}
func TestInt8(t *testing.T) {
b := NewBuffer(32)
if b == nil {
t.Error("got nil buffer")
}
i8 := b.Int8()
if len(i8) != 32 || cap(i8) != 32 {
t.Error("sizes incorrect")
}
if uintptr(unsafe.Pointer(&i8[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
if b.Int8() != nil {
t.Error("expected nil slice as buffer destroyed")
}
b = newNullBuffer()
if b.Int8() != nil {
t.Error("should be nil")
}
}
func TestInt16(t *testing.T) {
b := NewBuffer(32)
if b == nil {
t.Error("got nil buffer")
}
i16 := b.Int16()
if len(i16) != 16 || cap(i16) != 16 {
t.Error("sizes incorrect")
}
if uintptr(unsafe.Pointer(&i16[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(3)
if b == nil {
t.Error("got nil buffer")
}
i16 = b.Int16()
if len(i16) != 1 || cap(i16) != 1 {
t.Error("sizes should be 1")
}
if uintptr(unsafe.Pointer(&i16[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(1)
if b == nil {
t.Error("got nil buffer")
}
i16 = b.Int16()
if i16 != nil {
t.Error("expected nil slice")
}
b.Destroy()
if b.Int16() != nil {
t.Error("expected nil slice as buffer destroyed")
}
b = newNullBuffer()
if b.Int16() != nil {
t.Error("should be nil")
}
}
func TestInt32(t *testing.T) {
b := NewBuffer(32)
if b == nil {
t.Error("got nil buffer")
}
i32 := b.Int32()
if len(i32) != 8 || cap(i32) != 8 {
t.Error("sizes incorrect")
}
if uintptr(unsafe.Pointer(&i32[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(5)
if b == nil {
t.Error("got nil buffer")
}
i32 = b.Int32()
if len(i32) != 1 || cap(i32) != 1 {
t.Error("sizes should be 1")
}
if uintptr(unsafe.Pointer(&i32[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(3)
if b == nil {
t.Error("got nil buffer")
}
i32 = b.Int32()
if i32 != nil {
t.Error("expected nil slice")
}
b.Destroy()
if b.Int32() != nil {
t.Error("expected nil slice as buffer destroyed")
}
b = newNullBuffer()
if b.Int32() != nil {
t.Error("should be nil")
}
}
func TestInt64(t *testing.T) {
b := NewBuffer(32)
if b == nil {
t.Error("got nil buffer")
}
i64 := b.Int64()
if len(i64) != 4 || cap(i64) != 4 {
t.Error("sizes incorrect")
}
if uintptr(unsafe.Pointer(&i64[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(9)
if b == nil {
t.Error("got nil buffer")
}
i64 = b.Int64()
if len(i64) != 1 || cap(i64) != 1 {
t.Error("sizes should be 1")
}
if uintptr(unsafe.Pointer(&i64[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(7)
if b == nil {
t.Error("got nil buffer")
}
i64 = b.Int64()
if i64 != nil {
t.Error("expected nil slice")
}
b.Destroy()
if b.Int64() != nil {
t.Error("expected nil slice as buffer destroyed")
}
b = newNullBuffer()
if b.Int32() != nil {
t.Error("should be nil")
}
}
func TestByteArray8(t *testing.T) {
b := NewBuffer(8)
if b == nil {
t.Error("got nil buffer")
}
if uintptr(unsafe.Pointer(&b.ByteArray8()[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(7)
if b == nil {
t.Error("got nil buffer")
}
if b.ByteArray8() != nil {
t.Error("expected nil byte array")
}
b.Destroy()
if b.ByteArray8() != nil {
t.Error("expected nil byte array from destroyed buffer")
}
b = newNullBuffer()
if b.ByteArray8() != nil {
t.Error("should be nil")
}
}
func TestByteArray16(t *testing.T) {
b := NewBuffer(16)
if b == nil {
t.Error("got nil buffer")
}
if uintptr(unsafe.Pointer(&b.ByteArray16()[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(15)
if b == nil {
t.Error("got nil buffer")
}
if b.ByteArray16() != nil {
t.Error("expected nil byte array")
}
b.Destroy()
if b.ByteArray16() != nil {
t.Error("expected nil byte array from destroyed buffer")
}
b = newNullBuffer()
if b.ByteArray16() != nil {
t.Error("should be nil")
}
}
func TestByteArray32(t *testing.T) {
b := NewBuffer(32)
if b == nil {
t.Error("got nil buffer")
}
if uintptr(unsafe.Pointer(&b.ByteArray32()[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(31)
if b == nil {
t.Error("got nil buffer")
}
if b.ByteArray32() != nil {
t.Error("expected nil byte array")
}
b.Destroy()
if b.ByteArray32() != nil {
t.Error("expected nil byte array from destroyed buffer")
}
b = newNullBuffer()
if b.ByteArray32() != nil {
t.Error("should be nil")
}
}
func TestByteArray64(t *testing.T) {
b := NewBuffer(64)
if b == nil {
t.Error("got nil buffer")
}
if uintptr(unsafe.Pointer(&b.ByteArray64()[0])) != uintptr(unsafe.Pointer(&b.Bytes()[0])) {
t.Error("pointer locations differ")
}
b.Destroy()
b = NewBuffer(63)
if b == nil {
t.Error("got nil buffer")
}
if b.ByteArray64() != nil {
t.Error("expected nil byte array")
}
b.Destroy()
if b.ByteArray64() != nil {
t.Error("expected nil byte array from destroyed buffer")
}
b = newNullBuffer()
if b.ByteArray64() != nil {
t.Error("should be nil")
}
}
memguard-0.22.5/core/ 0000775 0000000 0000000 00000000000 14601340762 0014334 5 ustar 00root root 0000000 0000000 memguard-0.22.5/core/auxiliary.go 0000664 0000000 0000000 00000001040 14601340762 0016665 0 ustar 00root root 0000000 0000000 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))
}
memguard-0.22.5/core/auxiliary_test.go 0000664 0000000 0000000 00000002347 14601340762 0017737 0 ustar 00root root 0000000 0000000 package core
import (
"bytes"
"fmt"
"testing"
"unsafe"
)
func TestRoundToPageSize(t *testing.T) {
fmt.Println("System page size:", pageSize, "bytes")
if roundToPageSize(0) != 0 {
t.Error("failed with test input 0")
}
if roundToPageSize(1) != pageSize {
t.Error("failed with test input 1")
}
if roundToPageSize(pageSize) != pageSize {
t.Error("failed with test input page_size")
}
if roundToPageSize(pageSize+1) != 2*pageSize {
t.Error("failed with test input page_size + 1")
}
}
func TestGetBytes(t *testing.T) {
// Allocate an ordinary buffer.
buffer := make([]byte, 32)
// Get am alternate reference to it using our slice builder.
derived := getBytes(&buffer[0], len(buffer))
// Check for naive equality.
if !bytes.Equal(buffer, derived) {
t.Error("naive equality check failed")
}
// Modify and check if the change was reflected in both.
buffer[0] = 1
buffer[31] = 1
if !bytes.Equal(buffer, derived) {
t.Error("modified equality check failed")
}
// Do a deep comparison.
if uintptr(unsafe.Pointer(&buffer[0])) != uintptr(unsafe.Pointer(&derived[0])) {
t.Error("pointer values differ")
}
if len(buffer) != len(derived) || cap(buffer) != cap(derived) {
t.Error("length or capacity values differ")
}
}
memguard-0.22.5/core/buffer.go 0000664 0000000 0000000 00000016166 14601340762 0016146 0 ustar 00root root 0000000 0000000 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(" 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(" 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(" 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
}
memguard-0.22.5/core/buffer_test.go 0000664 0000000 0000000 00000014265 14601340762 0017203 0 ustar 00root root 0000000 0000000 package core
import (
"bytes"
"testing"
"unsafe"
)
func TestNewBuffer(t *testing.T) {
// Check the error case with zero length.
b, err := NewBuffer(0)
if err != ErrNullBuffer {
t.Error("expected ErrNullBuffer; got", err)
}
if b != nil {
t.Error("expected nil buffer; got", b)
}
// Check the error case with negative length.
b, err = NewBuffer(-1)
if err != ErrNullBuffer {
t.Error("expected ErrNullBuffer; got", err)
}
if b != nil {
t.Error("expected nil buffer; got", b)
}
// Test normal execution.
b, err = NewBuffer(32)
if err != nil {
t.Error("expected nil err; got", err)
}
if !b.alive {
t.Error("did not expect destroyed buffer")
}
if len(b.Data()) != 32 || cap(b.Data()) != 32 {
t.Errorf("buffer has invalid length (%d) or capacity (%d)", len(b.Data()), cap(b.Data()))
}
if !b.mutable {
t.Error("buffer is not marked mutable")
}
if len(b.memory) != roundToPageSize(32)+(2*pageSize) {
t.Error("allocated incorrect length of memory")
}
if !bytes.Equal(b.Data(), make([]byte, 32)) {
t.Error("container is not zero-filled")
}
// Check if the buffer was added to the buffers list.
if !buffers.exists(b) {
t.Error("buffer not in buffers list")
}
// Destroy the buffer.
b.Destroy()
}
func TestLotsOfAllocs(t *testing.T) {
for i := 1; i <= 16385; i++ {
b, err := NewBuffer(i)
if err != nil {
t.Error(err)
}
if !b.alive || !b.mutable {
t.Error("invalid metadata")
}
if len(b.data) != i {
t.Error("invalid data length")
}
if len(b.memory) != roundToPageSize(i)+2*pageSize {
t.Error("memory length invalid")
}
if len(b.preguard) != pageSize || len(b.postguard) != pageSize {
t.Error("guard pages length invalid")
}
if len(b.canary) != len(b.inner)-i {
t.Error("canary length invalid")
}
if len(b.inner)%pageSize != 0 {
t.Error("inner length is not multiple of page size")
}
for j := range b.data {
b.data[j] = 1
}
for j := range b.data {
if b.data[j] != 1 {
t.Error("region rw test failed")
}
}
b.Destroy()
}
}
func TestData(t *testing.T) {
b, err := NewBuffer(32)
if err != nil {
t.Error(err)
}
datasegm := b.data
datameth := b.Data()
// Check for naive equality.
if !bytes.Equal(datasegm, datameth) {
t.Error("naive equality check failed")
}
// Modify and check if the change was reflected in both.
datameth[0] = 1
datameth[31] = 1
if !bytes.Equal(datasegm, datameth) {
t.Error("modified equality check failed")
}
// Do a deep comparison.
if uintptr(unsafe.Pointer(&datameth[0])) != uintptr(unsafe.Pointer(&datasegm[0])) {
t.Error("pointer values differ")
}
if len(datameth) != len(datasegm) || cap(datameth) != cap(datasegm) {
t.Error("length or capacity values differ")
}
b.Destroy()
if b.Data() != nil {
t.Error("expected nil data slice for destroyed buffer")
}
}
func TestBufferState(t *testing.T) {
b, err := NewBuffer(32)
if err != nil {
t.Error("expected nil err; got", err)
}
if b.Mutable() != true {
t.Error("state mismatch: mutability")
}
if b.Alive() != true {
t.Error("state mismatch: alive")
}
b.Freeze()
if b.Mutable() != false {
t.Error("state mismatch: mutability")
}
if b.Alive() != true {
t.Error("state mismatch: alive")
}
b.Melt()
if b.Mutable() != true {
t.Error("state mismatch: mutability")
}
if b.Alive() != true {
t.Error("state mismatch: alive")
}
b.Destroy()
if b.Mutable() != false {
t.Error("state mismatch: mutability")
}
if b.Alive() != false {
t.Error("state mismatch: alive")
}
}
func TestDestroy(t *testing.T) {
// Allocate a new buffer.
b, err := NewBuffer(32)
if err != nil {
t.Error("expected nil err; got", err)
}
// Destroy it.
b.Destroy()
// Pick apart the destruction.
if b.Data() != nil {
t.Error("expected bytes buffer to be nil; got", b.Data())
}
if b.memory != nil {
t.Error("expected memory to be nil; got", b.memory)
}
if b.mutable || b.alive {
t.Error("buffer should be dead and immutable")
}
if b.preguard != nil || b.postguard != nil {
t.Error("guard page slice references are not nil")
}
if b.inner != nil {
t.Error("inner pages slice reference not nil")
}
if b.canary != nil {
t.Error("canary slice reference not nil")
}
// Check if the buffer was removed from the buffers list.
if buffers.exists(b) {
t.Error("buffer is still in buffers list")
}
// Call destroy again to check idempotency.
b.Destroy()
// Verify that it didn't come back to life.
if b.Data() != nil {
t.Error("expected bytes buffer to be nil; got", b.Data())
}
if b.memory != nil {
t.Error("expected memory to be nil; got", b.memory)
}
if b.mutable || b.alive {
t.Error("buffer should be dead and immutable")
}
if b.preguard != nil || b.postguard != nil {
t.Error("guard page slice references are not nil")
}
if b.inner != nil {
t.Error("inner pages slice reference not nil")
}
if b.canary != nil {
t.Error("canary slice reference not nil")
}
}
func TestBufferList(t *testing.T) {
// Create a new BufferList for testing with.
l := new(bufferList)
// Create some example buffers to test with.
a := new(Buffer)
b := new(Buffer)
// Check what Exists is saying.
if l.exists(a) || l.exists(b) {
t.Error("list is empty yet contains buffers?!")
}
// Add our two buffers to the list.
l.add(a)
if len(l.list) != 1 || l.list[0] != a {
t.Error("buffer was not added correctly")
}
l.add(b)
if len(l.list) != 2 || l.list[1] != b {
t.Error("buffer was not added correctly")
}
// Now check that they exist.
if !l.exists(a) || !l.exists(b) {
t.Error("expected buffers to be in list")
}
// Remove the buffers from the list.
l.remove(a)
if len(l.list) != 1 || l.list[0] != b {
t.Error("buffer was not removed correctly")
}
l.remove(b)
if len(l.list) != 0 {
t.Error("item was not removed correctly")
}
// Check what exists is saying now.
if l.exists(a) || l.exists(b) {
t.Error("list is empty yet contains buffers?!")
}
// Add the buffers again to test Empty.
l.add(a)
l.add(b)
bufs := l.flush()
if l.list != nil {
t.Error("list was not nullified")
}
if len(bufs) != 2 || bufs[0] != a || bufs[1] != b {
t.Error("buffers dump incorrect")
}
// Try appending again.
l.add(a)
if !l.exists(a) || l.exists(b) {
t.Error("list is in invalid state")
}
l.remove(a)
}
memguard-0.22.5/core/coffer.go 0000664 0000000 0000000 00000007052 14601340762 0016133 0 ustar 00root root 0000000 0000000 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(" 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
}
memguard-0.22.5/core/coffer_test.go 0000664 0000000 0000000 00000006750 14601340762 0017176 0 ustar 00root root 0000000 0000000 package core
import (
"bytes"
"testing"
)
func TestNewCoffer(t *testing.T) {
s := NewCoffer()
// Attain a lock to halt the verify & rekey cycle.
s.Lock()
// Verify that fields are not nil.
if s.left == nil || s.right == nil {
t.Error("one or more fields are not initialised")
}
// Verify that fields are the expected sizes.
if len(s.left.Data()) != 32 {
t.Error("left side has unexpected lengths")
}
if len(s.right.Data()) != 32 {
t.Error("right size has unexpected lengths")
}
// Verify that the data fields are not zeroed.
if bytes.Equal(s.left.Data(), make([]byte, 32)) {
t.Error("left side is zeroed")
}
if bytes.Equal(s.right.Data(), make([]byte, 32)) {
t.Error("right side is zeroed")
}
s.Unlock() // Release mutex to allow destruction.
s.Destroy()
}
func TestCofferInit(t *testing.T) {
s := NewCoffer()
// Get the value stored inside.
view, err := s.View()
if err != nil {
t.Error("unexpected error")
}
value := make([]byte, 32)
copy(value, view.Data())
view.Destroy()
// Re-init the buffer with a new value.
if err := s.Init(); err != nil {
t.Error("unexpected error;", err)
}
// Get the new value stored inside.
view, err = s.View()
if err != nil {
t.Error("unexpected error")
}
newValue := make([]byte, 32)
copy(newValue, view.Data())
view.Destroy()
// Compare them.
if bytes.Equal(value, newValue) {
t.Error("value was not refreshed")
}
s.Destroy()
// Check error condition.
if err := s.Init(); err != ErrCofferExpired {
t.Error("expected ErrCofferExpired; got", err)
}
}
func TestCofferView(t *testing.T) {
s := NewCoffer()
// Get the value stored inside.
view, err := s.View()
if err != nil {
t.Error("unexpected error")
}
if view == nil {
t.Error("returned object is nil")
}
// Some sanity checks on the inner value.
if view.Data() == nil || len(view.Data()) != 32 {
t.Error("unexpected data; got", view.Data())
}
if bytes.Equal(view.Data(), make([]byte, 32)) {
t.Error("value inside coffer is zero")
}
// Destroy our temporary view of the coffer's contents.
view.Destroy()
s.Destroy()
// Check error condition.
view, err = s.View()
if err != ErrCofferExpired {
t.Error("expected ErrCofferExpired; got", err)
}
if view != nil {
t.Error("expected nil buffer object")
}
}
func TestCofferRekey(t *testing.T) {
s := NewCoffer()
// remember the value stored inside
view, err := s.View()
if err != nil {
t.Error("unexpected error;", err)
}
orgValue := make([]byte, 32)
copy(orgValue, view.Data())
view.Destroy()
// remember the value of the partitions
left := make([]byte, 32)
right := make([]byte, 32)
s.Lock() // halt re-key cycle
copy(left, s.left.Data())
copy(right, s.right.Data())
s.Unlock() // un-halt re-key cycle
s.Rekey() // force a re-key
view, err = s.View()
if err != nil {
t.Error("unexpected error;", err)
}
newValue := make([]byte, 32)
copy(newValue, view.Data())
view.Destroy()
if !bytes.Equal(orgValue, newValue) {
t.Error("value inside coffer changed!!")
}
if bytes.Equal(left, s.left.Data()) || bytes.Equal(right, s.right.Data()) {
t.Error("partition values did not change")
}
s.Destroy()
if err := s.Rekey(); err != ErrCofferExpired {
t.Error("expected ErrCofferExpired; got", err)
}
}
func TestCofferDestroy(t *testing.T) {
s := NewCoffer()
s.Destroy()
// Check metadata flags.
if !s.Destroyed() {
t.Error("expected destroyed")
}
// Check both partitions are destroyed.
if s.left.alive || s.right.alive {
t.Error("some partition not destroyed")
}
}
memguard-0.22.5/core/crypto.go 0000664 0000000 0000000 00000010655 14601340762 0016212 0 ustar 00root root 0000000 0000000 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(" 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(" 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(" 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
}
memguard-0.22.5/core/crypto_test.go 0000664 0000000 0000000 00000011004 14601340762 0017236 0 ustar 00root root 0000000 0000000 package core
import (
"bytes"
"encoding/base64"
"testing"
)
func TestCopy(t *testing.T) {
a := make([]byte, 8)
Scramble(a)
b := make([]byte, 16)
Scramble(b)
c := make([]byte, 32)
Scramble(c)
// dst > src
Copy(b, a)
if !bytes.Equal(b[:8], a) {
t.Error("incorrect copying")
}
// dst < src
Copy(b, c)
if !bytes.Equal(b, c[:16]) {
t.Error("incorrect copying")
}
// dst = src
b2 := make([]byte, 16)
Scramble(b2)
Copy(b, b2)
if !bytes.Equal(b, b2) {
t.Error("incorrect copying")
}
}
func TestMove(t *testing.T) {
a := make([]byte, 32)
Scramble(a)
b := make([]byte, 32)
Scramble(b)
Move(a, b)
if !bytes.Equal(b, make([]byte, 32)) {
t.Error("src buffer was not wiped")
}
}
func TestCompare(t *testing.T) {
a := make([]byte, 8)
Scramble(a)
b := make([]byte, 16)
Scramble(b)
c := make([]byte, 16)
copy(c, b)
// not equal
if Equal(a, b) {
t.Error("expected not equal")
}
// equal
if !Equal(b, c) {
t.Error("expected equal")
}
c[8] = ^c[8]
// not equal
if Equal(b, c) {
t.Error("expected not equal")
}
}
func TestScramble(t *testing.T) {
b := make([]byte, 32)
Scramble(b)
if bytes.Equal(b, make([]byte, 32)) {
t.Error("buffer not scrambled")
}
c := make([]byte, 32)
Scramble(c)
if bytes.Equal(b, make([]byte, 32)) {
t.Error("buffer not scrambled")
}
if bytes.Equal(b, c) {
t.Error("random repeated")
}
}
func TestHash(t *testing.T) {
known := make(map[string]string)
known[""] = "DldRwCblQ7Loqy6wYJnaodHl30d3j3eH+qtFzfEv46g="
known["hash"] = "l+2qaVlkOBNtzRKFU+kEvAP1JkJvcn0nC2mEH7bPUNM="
known["test"] = "kosgNmlD4q/RHrwOri5TqTvxd6T881vMZNUDcE5l4gI="
for k, v := range known {
if base64.StdEncoding.EncodeToString(Hash([]byte(k))) != v {
t.Error("digest doesn't match known values")
}
}
}
func TestWipe(t *testing.T) {
b := make([]byte, 32)
Scramble(b)
Wipe(b)
for i := range b {
if b[i] != 0 {
t.Error("wipe unsuccessful")
}
}
}
func TestEncryptDecrypt(t *testing.T) {
// Declare the plaintext and the key.
m := make([]byte, 64)
Scramble(m)
k := make([]byte, 32)
Scramble(k)
// Encrypt the message.
x, err := Encrypt(m, k)
if err != nil {
t.Error("expected no errors; got", err)
}
// Decrypt the message.
dm := make([]byte, len(x)-Overhead)
length, err := Decrypt(x, k, dm)
if err != nil {
t.Error("expected no errors; got", err)
}
if length != len(x)-Overhead {
t.Error("unexpected plaintext length; got", length)
}
// Verify that the plaintexts match.
if !bytes.Equal(m, dm) {
t.Error("decrypted plaintext does not match original")
}
// Attempt decryption /w buffer that is too small to hold the output.
out := make([]byte, len(x)-Overhead-1)
length, err = Decrypt(x, k, out)
if err != ErrBufferTooSmall {
t.Error("expected error; got", err)
}
if length != 0 {
t.Error("expected zero length; got", length)
}
// Construct a buffer that has the correct capacity but a smaller length.
out = make([]byte, len(x)-Overhead)
smallOut := out[:2]
if len(smallOut) != 2 || cap(smallOut) != len(x)-Overhead {
t.Error("invalid construction for test")
}
length, err = Decrypt(x, k, smallOut)
if err != nil {
t.Error("unexpected error:", err)
}
if length != len(x)-Overhead {
t.Error("unexpected length; got", length)
}
if !bytes.Equal(m, smallOut[:len(x)-Overhead]) {
t.Error("decrypted plaintext does not match original")
}
// Generate an incorrect key.
ik := make([]byte, 32)
Scramble(ik)
// Attempt decryption with the incorrect key.
length, err = Decrypt(x, ik, dm)
if length != 0 {
t.Error("expected length = 0; got", length)
}
if err != ErrDecryptionFailed {
t.Error("expected error with incorrect key; got", err)
}
// Modify the ciphertext somewhat.
for i := range x {
if i%32 == 0 {
x[i] = 0xdb
}
}
// Attempt decryption of the invalid ciphertext with the correct key.
length, err = Decrypt(x, k, dm)
if length != 0 {
t.Error("expected length = 0; got", length)
}
if err != ErrDecryptionFailed {
t.Error("expected error with modified ciphertext; got", err)
}
// Generate a key of an invalid length.
ik = make([]byte, 16)
Scramble(ik)
// Attempt encryption with the invalid key.
ix, err := Encrypt(m, ik)
if err != ErrInvalidKeyLength {
t.Error("expected error with invalid key; got", err)
}
if ix != nil {
t.Error("expected nil ciphertext; got", dm)
}
// Attempt decryption with the invalid key.
length, err = Decrypt(x, ik, dm)
if length != 0 {
t.Error("expected length = 0; got", length)
}
if err != ErrInvalidKeyLength {
t.Error("expected error with invalid key; got", err)
}
}
memguard-0.22.5/core/enclave.go 0000664 0000000 0000000 00000005573 14601340762 0016312 0 ustar 00root root 0000000 0000000 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(" 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(" 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
}
memguard-0.22.5/core/enclave_test.go 0000664 0000000 0000000 00000005015 14601340762 0017340 0 ustar 00root root 0000000 0000000 package core
import (
"bytes"
"testing"
)
func TestNewEnclave(t *testing.T) {
// Initialise some sample plaintext.
data := []byte("yellow submarine")
// Create the Enclave object from this data.
e, err := NewEnclave(data)
if err != nil {
t.Error(err)
}
// Check that the buffer has been wiped.
if !bytes.Equal(data, make([]byte, 16)) {
t.Error("data buffer was not wiped")
}
// Verify the length of the ciphertext is correct.
if len(e.ciphertext) != len(data)+Overhead {
t.Error("ciphertext has unexpected length;", len(e.ciphertext))
}
// Attempt with an empty data slice.
data = make([]byte, 0)
_, err = NewEnclave(data)
if err != ErrNullEnclave {
t.Error("expected ErrNullEnclave; got", err)
}
}
func TestSeal(t *testing.T) {
// Create a new buffer for testing with.
b, err := NewBuffer(32)
if err != nil {
t.Error(err)
}
// Encrypt it into an Enclave.
e, err := Seal(b)
if err != nil {
t.Error(err)
}
// Do a sanity check on the length of the ciphertext.
if len(e.ciphertext) != 32+Overhead {
t.Error("ciphertext has unexpected length:", len(e.ciphertext))
}
// Check that the buffer was destroyed.
if b.alive {
t.Error("buffer was not consumed")
}
// Decrypt the enclave into a new buffer.
buf, err := Open(e)
if err != nil {
t.Error(err)
}
// Check that the decrypted data is correct.
if !bytes.Equal(buf.Data(), make([]byte, 32)) {
t.Error("decrypted data does not match original")
}
// Attempt sealing the destroyed buffer.
e, err = Seal(b)
if err != ErrBufferExpired {
t.Error("expected ErrBufferExpired; got", err)
}
if e != nil {
t.Error("expected nil enclave in error case")
}
// Destroy the hanging buffer.
buf.Destroy()
}
func TestOpen(t *testing.T) {
// Initialise an enclave to test on.
data := []byte("yellow submarine")
e, err := NewEnclave(data)
if err != nil {
t.Error(err)
}
// Open it.
buf, err := Open(e)
if err != nil {
t.Error(err)
}
// Sanity check the output.
if !bytes.Equal(buf.Data(), []byte("yellow submarine")) {
t.Error("decrypted data does not match original")
}
buf.Destroy()
// Modify the ciphertext to trigger an error case.
for i := range e.ciphertext {
e.ciphertext[i] = 0xdb
}
// Check for the error.
buf, err = Open(e)
if err != ErrDecryptionFailed {
t.Error("expected decryption error; got", err)
}
if buf != nil {
t.Error("expected nil buffer in error case")
}
}
func TestEnclaveSize(t *testing.T) {
if EnclaveSize(&Enclave{make([]byte, 1234)}) != 1234-Overhead {
t.Error("invalid enclave size")
}
}
memguard-0.22.5/core/exit.go 0000664 0000000 0000000 00000004621 14601340762 0015637 0 ustar 00root root 0000000 0000000 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)
}
memguard-0.22.5/core/exit_test.go 0000664 0000000 0000000 00000003552 14601340762 0016700 0 ustar 00root root 0000000 0000000 package core
import (
"bytes"
"testing"
)
func TestPurge(t *testing.T) {
// Create a bunch of things to simulate a working environment.
enclave, err := NewEnclave([]byte("yellow submarine"))
if err != nil {
t.Error(err)
}
buffer, err := NewBuffer(32)
if err != nil {
t.Error(err)
}
oldKey := getOrCreateKey()
Purge()
key := getOrCreateKey()
// Verify that the buffers list contains only the important buffers.
buffers.RLock()
if len(buffers.list) != 3 {
t.Error("buffers list was not flushed", buffers.list)
}
for i := range buffers.list {
if !buffers.list[i].Alive() {
t.Error("should not have destroyed excluded buffers")
}
}
if !key.right.Alive() || !key.left.Alive() || !key.rand.Alive() {
t.Error("buffers left in list aren't the right ones")
}
buffers.RUnlock()
// Verify that the buffer was destroyed.
if buffer.alive {
t.Error("buffer was not destroyed")
}
// Verify that the old key was destroyed.
if oldKey.left.alive || oldKey.right.alive {
t.Error("old key was not destroyed")
}
// Verify that the new key is not destroyed.
if !key.left.alive || !key.right.alive {
t.Error("current key is destroyed")
}
// Verify that the key changed by decrypting the Enclave.
if _, err := Open(enclave); err != ErrDecryptionFailed {
t.Error("expected decryption failed; got", err)
}
// Create a buffer with invalid canary.
b, err := NewBuffer(32)
if err != nil {
t.Error(err)
}
Scramble(b.inner)
b.Freeze()
if !panics(func() {
Purge()
}) {
t.Error("did not panic")
}
if !bytes.Equal(b.data, make([]byte, 32)) {
t.Error("data not wiped")
}
buffers.remove(b)
}
func TestPanic(t *testing.T) {
// Call Panic and check if it panics.
if !panics(func() {
Panic("test")
}) {
t.Error("did not panic")
}
}
func panics(fn func()) (panicked bool) {
defer func() {
panicked = (recover() != nil)
}()
fn()
return
}
memguard-0.22.5/core/init.go 0000664 0000000 0000000 00000000144 14601340762 0015625 0 ustar 00root root 0000000 0000000 package core
import (
"github.com/awnumar/memcall"
)
func init() {
memcall.DisableCoreDumps()
}
memguard-0.22.5/docs.go 0000664 0000000 0000000 00000005765 14601340762 0014700 0 ustar 00root root 0000000 0000000 /*
Package memguard implements a secure software enclave for the storage of sensitive information in memory.
package main
import (
"fmt"
"os"
"github.com/awnumar/memguard"
)
func main() {
// Safely terminate in case of an interrupt signal
memguard.CatchInterrupt()
// Purge the session when we return
defer memguard.Purge()
// Generate a key sealed inside an encrypted container
key := memguard.NewEnclaveRandom(32)
// Passing the key off to another function
key = invert(key)
// Decrypt the result returned from invert
keyBuf, err := key.Open()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
defer keyBuf.Destroy()
// Um output it
fmt.Println(keyBuf.Bytes())
}
func invert(key *memguard.Enclave) *memguard.Enclave {
// Decrypt the key into a local copy
b, err := key.Open()
if err != nil {
memguard.SafePanic(err)
}
defer b.Destroy() // Destroy the copy when we return
// Open returns the data in an immutable buffer, so make it mutable
b.Melt()
// Set every element to its complement
for i := range b.Bytes() {
b.Bytes()[i] = ^b.Bytes()[i]
}
// Return the new data in encrypted form
return b.Seal() // <- sealing also destroys b
}
There are two main container objects exposed in this API. Enclave objects encrypt data and store the ciphertext whereas LockedBuffers are more like guarded memory allocations. There is a limit on the maximum number of LockedBuffer objects that can exist at any one time, imposed by the system's mlock limits. There is no limit on Enclaves.
The general workflow is to store sensitive information in Enclaves when it is not immediately needed and decrypt it when and where it is. After use, the LockedBuffer should be destroyed.
If you need access to the data inside a LockedBuffer in a type not covered by any methods provided by this API, you can type-cast the allocation's memory to whatever type you want.
key := memguard.NewBuffer(32)
keyArrayPtr := (*[32]byte)(unsafe.Pointer(&key.Bytes()[0])) // do not dereference
This is of course an unsafe operation and so care must be taken to ensure that the cast is valid and does not result in memory unsafety. Further examples of code and interesting use-cases can be found in the examples subpackage.
Several functions exist to make the mass purging of data very easy. It is recommended to make use of them when appropriate.
// Start an interrupt handler that will clean up memory before exiting
memguard.CatchInterrupt()
// Purge the session when returning from the main function of your program
defer memguard.Purge()
// Use the safe variants of exit functions provided in the stdlib
memguard.SafeExit(1)
memguard.SafePanic(err)
// Destroy LockedBuffers as soon as possible after using them
b, err := enclave.Open()
if err != nil {
memguard.SafePanic(err)
}
defer b.Destroy()
Core dumps are disabled by default. If you absolutely require them, you can enable them by using unix.Setrlimit to set RLIMIT_CORE to an appropriate value.
*/
package memguard
memguard-0.22.5/enclave.go 0000664 0000000 0000000 00000002773 14601340762 0015361 0 ustar 00root root 0000000 0000000 package memguard
import (
"github.com/awnumar/memguard/core"
)
/*
Enclave is a sealed and encrypted container for sensitive data.
*/
type Enclave struct {
*core.Enclave
}
/*
NewEnclave seals up some data into an encrypted enclave object. The buffer is wiped after the data is copied. If the length of the buffer is zero, the function will return nil.
A LockedBuffer may alternatively be converted into an Enclave object using its Seal method. This will also have the effect of destroying the LockedBuffer.
*/
func NewEnclave(src []byte) *Enclave {
e, err := core.NewEnclave(src)
if err != nil {
if err == core.ErrNullEnclave {
return nil
}
core.Panic(err)
}
return &Enclave{e}
}
/*
NewEnclaveRandom generates and seals arbitrary amounts of cryptographically-secure random bytes into an encrypted enclave object. If size is not strictly positive the function will return nil.
*/
func NewEnclaveRandom(size int) *Enclave {
// todo: stream data into enclave
b := NewBufferRandom(size)
return b.Seal()
}
/*
Open decrypts an Enclave object and places its contents into an immutable LockedBuffer. An error will be returned if decryption failed.
*/
func (e *Enclave) Open() (*LockedBuffer, error) {
b, err := core.Open(e.Enclave)
if err != nil {
if err != core.ErrDecryptionFailed {
core.Panic(err)
}
return nil, err
}
b.Freeze()
return newBuffer(b), nil
}
/*
Size returns the number of bytes of data stored within an Enclave.
*/
func (e *Enclave) Size() int {
return core.EnclaveSize(e.Enclave)
}
memguard-0.22.5/enclave_test.go 0000664 0000000 0000000 00000003373 14601340762 0016415 0 ustar 00root root 0000000 0000000 package memguard
import (
"bytes"
"testing"
"github.com/awnumar/memguard/core"
)
func TestNewEnclave(t *testing.T) {
e := NewEnclave([]byte("yellow submarine"))
if e == nil {
t.Error("got nil enclave")
}
data, err := e.Open()
if err != nil {
t.Error("unexpected error:", err)
}
if !bytes.Equal(data.Bytes(), []byte("yellow submarine")) {
t.Error("data doesn't match input")
}
data.Destroy()
e = NewEnclave([]byte{})
if e != nil {
t.Error("enclave should be nil")
}
}
func TestNewEnclaveRandom(t *testing.T) {
e := NewEnclaveRandom(32)
if e == nil {
t.Error("got nil enclave")
}
data, err := e.Open()
if err != nil {
t.Error("unexpected error:", err)
}
if len(data.Bytes()) != 32 || cap(data.Bytes()) != 32 {
t.Error("buffer sizes incorrect")
}
if bytes.Equal(data.Bytes(), make([]byte, 32)) {
t.Error("buffer not randomised")
}
data.Destroy()
e = NewEnclaveRandom(0)
if e != nil {
t.Error("should be nil")
}
}
func TestOpen(t *testing.T) {
e := NewEnclave([]byte("yellow submarine"))
if e == nil {
t.Error("got nil enclave")
}
b, err := e.Open()
if err != nil {
t.Error("unexpected error;", err)
}
if b == nil {
t.Error("buffer should not be nil")
}
if e.Size() != b.Size() {
t.Error("sizes don't match")
}
if !bytes.Equal(b.Bytes(), []byte("yellow submarine")) {
t.Error("data does not match")
}
Purge() // reset the session
b, err = e.Open()
if err != core.ErrDecryptionFailed {
t.Error("expected decryption error; got", err)
}
if b != nil {
t.Error("buffer should be nil")
}
e = NewEnclaveRandom(0)
if !panics(func() {
e.Open()
}) {
t.Error("func should panic on nil enclave")
}
}
func panics(fn func()) (panicked bool) {
defer func() {
panicked = (recover() != nil)
}()
fn()
return
}
memguard-0.22.5/examples/ 0000775 0000000 0000000 00000000000 14601340762 0015222 5 ustar 00root root 0000000 0000000 memguard-0.22.5/examples/README.md 0000664 0000000 0000000 00000003232 14601340762 0016501 0 ustar 00root root 0000000 0000000 # Examples
In this directory are some useful and interesting code samples both for writing effective code using the library and for learning or exploratory purposes. Exploits and proof-of-concepts are also welcome.
Packages are able to import one another. This allows us to build up modules of functionality that work together to create more complex systems.
## Adding a package
1. Create a directory for your program and populate it with code. Check an existing module for guidance if needed.
2. Add test code and benchmarks.
The programs can then be run individually with
```bash
go test -v -race ./examples/module_name
```
or one after the other
```bash
go test -v -race ./examples/...
```
3. Add your program to the end of the [packages](#packages) section of this document.
## Licencing
You own your intellectual property and so you are free to choose any licence for your program. To do this, add a licence header to the top of your source files.
## Packages
0. [`Apache-2.0`] [socketkey](socketkey) :: Streaming multi-threaded client->server transfer of secure data over a socket.
1. [`Apache-2.0`] [casting](casting) :: Some examples of representing the data in allocated buffers as different types.
2. [`Apache-2.0`] [stdin](stdin) :: Reading from standard input directly into a guarded memory region and then sealing it.
3. [`Apache-2.0`] [stream](stream) :: Some examples of working with Stream objects which encrypt data in memory.
4. [[`#132`](https://github.com/awnumar/memguard/issues/132)] [deadlock](deadlock) :: Some conditions causing crashes.
5. [`Apache-2.0`] [streams](streams) :: Multi-threaded test of streams objects.
memguard-0.22.5/examples/casting/ 0000775 0000000 0000000 00000000000 14601340762 0016652 5 ustar 00root root 0000000 0000000 memguard-0.22.5/examples/casting/casting.go 0000664 0000000 0000000 00000006276 14601340762 0020644 0 ustar 00root root 0000000 0000000 /*
Copyright 2019 Awn Umar
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package casting
import (
"unsafe"
"github.com/awnumar/memguard"
)
// Secure is some generic example struct containing sensitive information.
type Secure struct {
Key [32]byte
Salt [2]uint64
Counter uint64
Something bool
}
// ByteArray10 allocates and returns a region of memory represented as a fixed-size 10 byte array.
func ByteArray10() (*memguard.LockedBuffer, *[10]byte) {
// Allocate 10 bytes of memory
b := memguard.NewBuffer(10)
// Return the LockedBuffer along with the cast pointer
return b, (*[10]byte)(unsafe.Pointer(&b.Bytes()[0]))
}
// Uint64Array4 allocates a 32 byte memory region and returns it represented as a sequence of four unsigned 64 bit integer values.
func Uint64Array4() (*memguard.LockedBuffer, *[4]uint64) {
// Allocate the correct amount of memory
b := memguard.NewBuffer(32)
// Return the LockedBuffer along with the cast pointer
return b, (*[4]uint64)(unsafe.Pointer(&b.Bytes()[0]))
}
// SecureStruct allocates a region of memory the size of a struct type and returns a pointer to that memory represented as that struct type.
func SecureStruct() (*memguard.LockedBuffer, *Secure) {
// Initialise an instance of the struct type
s := new(Secure)
// Allocate a LockedBuffer of the correct size
b := memguard.NewBuffer(int(unsafe.Sizeof(*s)))
// Return the LockedBuffer along with the initialised struct
return b, (*Secure)(unsafe.Pointer(&b.Bytes()[0]))
}
// SecureStructArray allocates enough memory to hold an array of Secure structs and returns them.
func SecureStructArray() (*memguard.LockedBuffer, *[2]Secure) {
// Initialise an instance of the struct type
s := new(Secure)
// Allocate a LockedBuffer of four times the size of the struct type
b := memguard.NewBuffer(int(unsafe.Sizeof(*s)) * 2)
// Cast a pointer to the start of the memory into a pointer of a fixed size array of Secure structs of length four
secureArray := (*[2]Secure)(unsafe.Pointer(&b.Bytes()[0]))
// Return the LockedBuffer along with the array
return b, secureArray
}
// SecureStructSlice takes a length and returns a slice of Secure struct values of that length.
func SecureStructSlice(size int) (*memguard.LockedBuffer, []Secure) {
if size < 1 {
return nil, nil
}
// Initialise an instance of the struct type
s := new(Secure)
// Allocate the enough memory to store the struct values
b := memguard.NewBuffer(int(unsafe.Sizeof(*s)) * size)
// Construct the slice from its parameters
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
// Return the LockedBuffer along with the constructed slice
return b, *(*[]Secure)(unsafe.Pointer(&sl))
}
memguard-0.22.5/examples/casting/casting_test.go 0000664 0000000 0000000 00000003236 14601340762 0021674 0 ustar 00root root 0000000 0000000 package casting
import (
"bytes"
"testing"
"unsafe"
"github.com/awnumar/memguard"
)
func TestByteArray10(t *testing.T) {
b, a := ByteArray10()
memguard.ScrambleBytes(a[:])
if !bytes.Equal(b.Bytes(), a[:]) {
t.Error("array describes incorrect memory region")
}
b.Destroy()
}
func TestUint64Array4(t *testing.T) {
b, a := Uint64Array4()
if uintptr(unsafe.Pointer(&b.Bytes()[0])) != uintptr(unsafe.Pointer(&a[0])) {
t.Error("start pointer does not match")
}
b.Bytes()[24] = 1
if a[3] != 1 {
t.Error("incorrect alignment", b.Bytes(), a)
}
b.Destroy()
}
func testSecureStruct(b *memguard.LockedBuffer, s *Secure, offset int, t *testing.T) {
if uintptr(unsafe.Pointer(&b.Bytes()[offset])) != uintptr(unsafe.Pointer(s)) {
t.Error("pointers don't match")
}
memguard.ScrambleBytes(b.Bytes()[offset : offset+32])
if !bytes.Equal(b.Bytes()[offset:offset+32], s.Key[:]) {
t.Error("key doesn't match")
}
b.Bytes()[offset+32] = 1
b.Bytes()[offset+40] = 1
if s.Salt[0] != 1 || s.Salt[1] != 1 {
t.Error("salt doesn't match")
}
b.Bytes()[offset+48] = 1
if s.Counter != 1 {
t.Error("counter doesn't match")
}
b.Bytes()[offset+56] = 1
if !s.Something {
t.Error("bool flag Something doesn't match")
}
}
func TestSecureStruct(t *testing.T) {
b, s := SecureStruct()
testSecureStruct(b, s, 0, t)
b.Destroy()
}
func TestSecureStructArray(t *testing.T) {
b, a := SecureStructArray()
testSecureStruct(b, &a[0], 0, t)
testSecureStruct(b, &a[1], 64, t)
b.Destroy()
}
func TestSecureStructSlice(t *testing.T) {
b, s := SecureStructSlice(3)
testSecureStruct(b, &s[0], 0, t)
testSecureStruct(b, &s[1], 64, t)
testSecureStruct(b, &s[2], 128, t)
b.Destroy()
}
memguard-0.22.5/examples/deadlock/ 0000775 0000000 0000000 00000000000 14601340762 0016770 5 ustar 00root root 0000000 0000000 memguard-0.22.5/examples/deadlock/x01/ 0000775 0000000 0000000 00000000000 14601340762 0017400 5 ustar 00root root 0000000 0000000 memguard-0.22.5/examples/deadlock/x01/poc.go 0000664 0000000 0000000 00000002575 14601340762 0020521 0 ustar 00root root 0000000 0000000 package x01
import (
"bytes"
"context"
"crypto/rand"
"errors"
"fmt"
"io"
"time"
"github.com/awnumar/memguard"
"lukechampine.com/frand"
)
func OpenEnclave(ctx context.Context) {
n := 10
data := make([][]byte, n)
enclaves := make([]*memguard.Enclave, n)
for i := range data {
data[i] = make([]byte, 32)
buf := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, buf); err != nil {
panic("failed to read random data")
}
copy(data[i], buf)
enclaves[i] = memguard.NewEnclave(buf)
}
threads := 20
for i := 0; i < threads; i++ {
go func(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
j := frand.Intn(n)
immediateOpen(ctx, enclaves[j], data[j])
}
}
}(ctx)
}
<-ctx.Done()
time.Sleep(time.Second)
// buf := make([]byte, 1<<20)
// fmt.Println(string(buf[:runtime.Stack(buf, true)]))
}
func openVerify(lock *memguard.Enclave, exp []byte) error {
lb, err := lock.Open()
if err != nil {
return err
}
defer lb.Destroy()
if !bytes.Equal(lb.Bytes(), exp) {
fmt.Println(lb.Bytes(), exp)
return errors.New("open verify fail")
}
return nil
}
func immediateOpen(ctx context.Context, lock *memguard.Enclave, exp []byte) {
c1 := make(chan error, 1)
go func() {
err := openVerify(lock, exp)
c1 <- err
}()
select {
case err := <-c1:
if err != nil {
panic(err)
}
case <-ctx.Done():
}
}
memguard-0.22.5/examples/deadlock/x01/poc_test.go 0000664 0000000 0000000 00000013052 14601340762 0021550 0 ustar 00root root 0000000 0000000 package x01
import (
"context"
"os"
"os/signal"
"syscall"
"testing"
"time"
)
const duration = 10 * time.Second
func TestPanicsPoC(t *testing.T) {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
ctx, cancel := context.WithTimeout(context.Background(), duration)
go func() {
select {
case <-sigs:
cancel()
}
}()
OpenEnclave(ctx)
}
// #############
// panic: runtime error: index out of range [0] with length 0
// goroutine 2060 [running]:
// github.com/awnumar/memguard/core.(*Coffer).View(0xc0000962a0, 0x0, 0x0, 0x0)
// /home/awn/src/go/src/github.com/awnumar/memguard/core/coffer.go:112 +0x3a9
// github.com/awnumar/memguard/core.Open(0xc00000e0e0, 0xc00001c290, 0xc00007a591, 0xc00007a590)
// /home/awn/src/go/src/github.com/awnumar/memguard/core/enclave.go:101 +0xa5
// github.com/awnumar/memguard.(*Enclave).Open(0xc000010040, 0xc000070770, 0x1, 0x1)
// /home/awn/src/go/src/github.com/awnumar/memguard/enclave.go:43 +0x50
// github.com/awnumar/memguard/examples/panics.openVerify(0xc000010040, 0xc000016600, 0x20, 0x20, 0x0, 0x0)
// /home/awn/src/go/src/github.com/awnumar/memguard/examples/panics/poc.go:55 +0x5c
// github.com/awnumar/memguard/examples/panics.immediateOpen.func1(0xc000010040, 0xc000016600, 0x20, 0x20, 0xc00024af60)
// /home/awn/src/go/src/github.com/awnumar/memguard/examples/panics/poc.go:70 +0x5b
// created by github.com/awnumar/memguard/examples/panics.immediateOpen
// /home/awn/src/go/src/github.com/awnumar/memguard/examples/panics/poc.go:69 +0xdf
// FAIL github.com/awnumar/memguard/examples/panics 0.835s
// FAIL
// #############
// WARNING: DATA RACE
// Write at 0x0000007aa588 by goroutine 114:
// github.com/awnumar/memguard/core.Purge()
// /home/awn/src/go/src/github.com/awnumar/memguard/core/exit.go:54 +0x82
// github.com/awnumar/memguard/core.Panic()
// /home/awn/src/go/src/github.com/awnumar/memguard/core/exit.go:85 +0x2f
// github.com/awnumar/memguard/core.NewBuffer()
// /home/awn/src/go/src/github.com/awnumar/memguard/core/buffer.go:75 +0x8ce
// github.com/awnumar/memguard/core.Open()
// /home/awn/src/go/src/github.com/awnumar/memguard/core/enclave.go:95 +0x6b
// github.com/awnumar/memguard.(*Enclave).Open()
// /home/awn/src/go/src/github.com/awnumar/memguard/enclave.go:43 +0x4f
// github.com/awnumar/memguard/examples/unsound.openVerify()
// /home/awn/src/go/src/github.com/awnumar/memguard/examples/unsound/poc.go:55 +0x5b
// github.com/awnumar/memguard/examples/unsound.immediateOpen.func1()
// /home/awn/src/go/src/github.com/awnumar/memguard/examples/unsound/poc.go:70 +0x5a
// Previous read at 0x0000007aa588 by goroutine 50:
// github.com/awnumar/memguard/core.Purge.func1()
// /home/awn/src/go/src/github.com/awnumar/memguard/core/exit.go:22 +0x52
// github.com/awnumar/memguard/core.Purge()
// /home/awn/src/go/src/github.com/awnumar/memguard/core/exit.go:50 +0x44
// github.com/awnumar/memguard/core.Panic()
// /home/awn/src/go/src/github.com/awnumar/memguard/core/exit.go:85 +0x2f
// github.com/awnumar/memguard.(*Enclave).Open()
// /home/awn/src/go/src/github.com/awnumar/memguard/enclave.go:46 +0xa7
// github.com/awnumar/memguard/examples/unsound.openVerify()
// /home/awn/src/go/src/github.com/awnumar/memguard/examples/unsound/poc.go:55 +0x5b
// github.com/awnumar/memguard/examples/unsound.immediateOpen.func1()
// /home/awn/src/go/src/github.com/awnumar/memguard/examples/unsound/poc.go:70 +0x5a
// Goroutine 114 (running) created at:
// github.com/awnumar/memguard/examples/unsound.immediateOpen()
// /home/awn/src/go/src/github.com/awnumar/memguard/examples/unsound/poc.go:69 +0xde
// github.com/awnumar/memguard/examples/unsound.OpenEnclave.func1()
// /home/awn/src/go/src/github.com/awnumar/memguard/examples/unsound/poc.go:40 +0x238
// Goroutine 50 (running) created at:
// github.com/awnumar/memguard/examples/unsound.immediateOpen()
// /home/awn/src/go/src/github.com/awnumar/memguard/examples/unsound/poc.go:69 +0xde
// github.com/awnumar/memguard/examples/unsound.OpenEnclave.func1()
// /home/awn/src/go/src/github.com/awnumar/memguard/examples/unsound/poc.go:40 +0x238
// #############
// panic: could not acquire lock on 0x7f7ef201d000, limit reached? [Err: cannot allocate memory]
// goroutine 1992 [running]:
// github.com/awnumar/memguard/core.Panic(0x607140, 0xc000223a10)
// /home/awn/src/go/src/github.com/awnumar/memguard/core/exit.go:86 +0x48
// github.com/awnumar/memguard/core.NewBuffer(0x20, 0x7d61c0, 0x64, 0xd)
// /home/awn/src/go/src/github.com/awnumar/memguard/core/buffer.go:75 +0x8cf
// github.com/awnumar/memguard/core.Open(0xc0000b80c0, 0xc000016520, 0xc0000783f1, 0xc0000783f0)
// /home/awn/src/go/src/github.com/awnumar/memguard/core/enclave.go:95 +0x6c
// github.com/awnumar/memguard.(*Enclave).Open(0xc0000a6048, 0xc0000eef70, 0x1, 0x1)
// /home/awn/src/go/src/github.com/awnumar/memguard/enclave.go:43 +0x50
// github.com/awnumar/memguard/examples/unsound.openVerify(0xc0000a6048, 0xc0000da080, 0x20, 0x20, 0x0, 0x0)
// /home/awn/src/go/src/github.com/awnumar/memguard/examples/unsound/poc.go:55 +0x5c
// github.com/awnumar/memguard/examples/unsound.immediateOpen.func1(0xc0000a6048, 0xc0000da080, 0x20, 0x20, 0xc000236a80)
// /home/awn/src/go/src/github.com/awnumar/memguard/examples/unsound/poc.go:70 +0x5b
// created by github.com/awnumar/memguard/examples/unsound.immediateOpen
// /home/awn/src/go/src/github.com/awnumar/memguard/examples/unsound/poc.go:69 +0xdf
// FAIL github.com/awnumar/memguard/examples/unsound 0.853s
// FAIL
memguard-0.22.5/examples/deadlock/x02/ 0000775 0000000 0000000 00000000000 14601340762 0017401 5 ustar 00root root 0000000 0000000 memguard-0.22.5/examples/deadlock/x02/poc.go 0000664 0000000 0000000 00000000737 14601340762 0020520 0 ustar 00root root 0000000 0000000 //go:build linux
package x02
import (
"fmt"
"github.com/awnumar/memguard"
"golang.org/x/sys/unix"
)
func POC() {
key := memguard.NewEnclaveRandom(32)
var oldLimit unix.Rlimit
zeroLimit := unix.Rlimit{Cur: 0, Max: oldLimit.Max}
if err := unix.Prlimit(0, unix.RLIMIT_MEMLOCK, &zeroLimit, &oldLimit); err != nil {
panic(fmt.Errorf("error lowering memlock rlimit: %s", err))
}
keyBytes, err := key.Open()
if err != nil {
panic(err)
}
defer keyBytes.Destroy()
}
memguard-0.22.5/examples/deadlock/x02/poc_test.go 0000664 0000000 0000000 00000000310 14601340762 0021542 0 ustar 00root root 0000000 0000000 //go:build linux
package x02
import (
"log"
"testing"
)
func TestPOC(t *testing.T) {
defer func() {
if err := recover(); err != nil {
log.Println("panic occurred:", err)
}
}()
POC()
}
memguard-0.22.5/examples/socketkey/ 0000775 0000000 0000000 00000000000 14601340762 0017223 5 ustar 00root root 0000000 0000000 memguard-0.22.5/examples/socketkey/socketkey.go 0000664 0000000 0000000 00000006011 14601340762 0021551 0 ustar 00root root 0000000 0000000 /*
Copyright 2019 Awn Umar
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package socketkey
import (
"bytes"
"fmt"
"net"
"os"
"github.com/awnumar/memguard"
)
// Save the data here so we can compare it later. Obviously this leaks the secret.
var data []byte
// NOTE: Some lines are commented out for the sake of tests.
/*
SocketKey is a streaming multi-threaded client->server transfer of secure data over a socket.
*/
func SocketKey(size int) {
// Create a server to listen on.
listener, err := net.Listen("tcp", "127.0.0.1:4128")
if err != nil {
memguard.SafePanic(err)
}
defer listener.Close()
// Catch signals and close the listener before terminating safely.
memguard.CatchSignal(func(s os.Signal) {
fmt.Println("Received signal:", s.String())
listener.Close()
}, os.Interrupt, os.Kill)
// Purge the session before returning.
defer memguard.Purge()
// Create a client to connect to our server.
go func() {
// Connect to our server
addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:4128")
if err != nil {
memguard.SafePanic(err)
}
conn, err := net.DialTCP("tcp", nil, addr)
if err != nil {
memguard.SafePanic(err)
}
defer conn.Close()
// Create a buffer filled with random bytes
buf := memguard.NewBufferRandom(size)
defer buf.Destroy()
// Save a copy of the key for comparison later.
data = make([]byte, buf.Size())
copy(data, buf.Bytes())
// fmt.Printf("Sending key: %#v\n", buf.Bytes())
// Send the data to the server
var total, written int
for total = 0; total < size; total += written {
written, err = conn.Write(buf.Bytes()[total:])
if err != nil {
memguard.SafePanic(err)
}
}
}()
// Accept connections from clients
conn, err := listener.Accept()
if err != nil {
memguard.SafePanic(err)
}
// Read the data directly into a guarded memory region
buf, err := memguard.NewBufferFromReader(conn, size)
if err != nil {
memguard.SafePanic(err)
}
defer buf.Destroy()
conn.Close()
// fmt.Printf("Received key: %#v\n", buf.Bytes())
// Compare the key to make sure it wasn't corrupted.
if !bytes.Equal(data, buf.Bytes()) {
memguard.SafePanic(fmt.Sprint("sent != received ::", data, buf.Bytes()))
}
// Seal the key into an encrypted Enclave object.
key := buf.Seal()
// <-- buf is destroyed by this point
// fmt.Printf("Encrypted key: %#v\n", key)
// Decrypt the key into a new buffer.
buf, err = key.Open()
if err != nil {
memguard.SafePanic(err)
}
// fmt.Printf("Decrypted key: %#v\n", buf.Bytes())
// Destroy the buffer.
buf.Destroy()
}
memguard-0.22.5/examples/socketkey/socketkey_test.go 0000664 0000000 0000000 00000000311 14601340762 0022605 0 ustar 00root root 0000000 0000000 package socketkey
import "testing"
func TestSocketKey(t *testing.T) {
SocketKey(4096)
}
func BenchmarkSocketKey32(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
SocketKey(32)
}
}
memguard-0.22.5/examples/stdin/ 0000775 0000000 0000000 00000000000 14601340762 0016343 5 ustar 00root root 0000000 0000000 memguard-0.22.5/examples/stdin/stdin.go 0000664 0000000 0000000 00000002041 14601340762 0020010 0 ustar 00root root 0000000 0000000 /*
Copyright 2019 Awn Umar
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package stdin
import (
"errors"
"os"
"github.com/awnumar/memguard"
)
// ReadKeyFromStdin reads a key from standard inputs and returns it sealed inside an Enclave object.
func ReadKeyFromStdin() (*memguard.Enclave, error) {
key, err := memguard.NewBufferFromReaderUntil(os.Stdin, '\n')
if err != nil {
// error encountered before '\n' was reached
return nil, err
}
if key.Size() == 0 {
return nil, errors.New("no input received")
}
return key.Seal(), nil
}
memguard-0.22.5/examples/stream/ 0000775 0000000 0000000 00000000000 14601340762 0016515 5 ustar 00root root 0000000 0000000 memguard-0.22.5/examples/stream/cpuprof1.svg 0000664 0000000 0000000 00000442657 14601340762 0021017 0 ustar 00root root 0000000 0000000