pax_global_header00006660000000000000000000000064146013407620014515gustar00rootroot0000000000000052 comment=4ed2841e9041c2c37e455b05446477445c0eaf07 memguard-0.22.5/000077500000000000000000000000001460134076200134045ustar00rootroot00000000000000memguard-0.22.5/.cirrus.yml000066400000000000000000000036731460134076200155250ustar00rootroot00000000000000linux_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/000077500000000000000000000000001460134076200147445ustar00rootroot00000000000000memguard-0.22.5/.github/ISSUE_TEMPLATE/000077500000000000000000000000001460134076200171275ustar00rootroot00000000000000memguard-0.22.5/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000011741460134076200216240ustar00rootroot00000000000000--- 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.md000066400000000000000000000010711460134076200213070ustar00rootroot00000000000000--- 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.md000066400000000000000000000001261460134076200213170ustar00rootroot00000000000000--- name: Question about: Get help with something labels: question --- *Ask away...* memguard-0.22.5/AUTHORS000066400000000000000000000006561460134076200144630ustar00rootroot00000000000000# 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/LICENSE000066400000000000000000000261351460134076200144200ustar00rootroot00000000000000 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.md000066400000000000000000000055651460134076200146760ustar00rootroot00000000000000

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.go000066400000000000000000000421211460134076200152040ustar00rootroot00000000000000package 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.go000066400000000000000000000642201460134076200162470ustar00rootroot00000000000000package 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/000077500000000000000000000000001460134076200143345ustar00rootroot00000000000000memguard-0.22.5/core/auxiliary.go000066400000000000000000000010401460134076200166650ustar00rootroot00000000000000package 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.go000066400000000000000000000023471460134076200177370ustar00rootroot00000000000000package 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.go000066400000000000000000000161661460134076200161460ustar00rootroot00000000000000package 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.go000066400000000000000000000142651460134076200172030ustar00rootroot00000000000000package 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.go000066400000000000000000000070521460134076200161330ustar00rootroot00000000000000package 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.go000066400000000000000000000067501460134076200171760ustar00rootroot00000000000000package 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.go000066400000000000000000000106551460134076200162120ustar00rootroot00000000000000package 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.go000066400000000000000000000110041460134076200172360ustar00rootroot00000000000000package 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.go000066400000000000000000000055731460134076200163120ustar00rootroot00000000000000package 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.go000066400000000000000000000050151460134076200173400ustar00rootroot00000000000000package 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.go000066400000000000000000000046211460134076200156370ustar00rootroot00000000000000package 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.go000066400000000000000000000035521460134076200167000ustar00rootroot00000000000000package 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.go000066400000000000000000000001441460134076200156250ustar00rootroot00000000000000package core import ( "github.com/awnumar/memcall" ) func init() { memcall.DisableCoreDumps() } memguard-0.22.5/docs.go000066400000000000000000000057651460134076200147000ustar00rootroot00000000000000/* 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.go000066400000000000000000000027731460134076200153610ustar00rootroot00000000000000package 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.go000066400000000000000000000033731460134076200164150ustar00rootroot00000000000000package 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/000077500000000000000000000000001460134076200152225ustar00rootroot00000000000000memguard-0.22.5/examples/README.md000066400000000000000000000032321460134076200165010ustar00rootroot00000000000000# 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/000077500000000000000000000000001460134076200166525ustar00rootroot00000000000000memguard-0.22.5/examples/casting/casting.go000066400000000000000000000062761460134076200206440ustar00rootroot00000000000000/* 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.go000066400000000000000000000032361460134076200216740ustar00rootroot00000000000000package 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/000077500000000000000000000000001460134076200167705ustar00rootroot00000000000000memguard-0.22.5/examples/deadlock/x01/000077500000000000000000000000001460134076200174005ustar00rootroot00000000000000memguard-0.22.5/examples/deadlock/x01/poc.go000066400000000000000000000025751460134076200205210ustar00rootroot00000000000000package 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.go000066400000000000000000000130521460134076200215500ustar00rootroot00000000000000package 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/000077500000000000000000000000001460134076200174015ustar00rootroot00000000000000memguard-0.22.5/examples/deadlock/x02/poc.go000066400000000000000000000007371460134076200205200ustar00rootroot00000000000000//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.go000066400000000000000000000003101460134076200215420ustar00rootroot00000000000000//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/000077500000000000000000000000001460134076200172235ustar00rootroot00000000000000memguard-0.22.5/examples/socketkey/socketkey.go000066400000000000000000000060111460134076200215510ustar00rootroot00000000000000/* 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.go000066400000000000000000000003111460134076200226050ustar00rootroot00000000000000package 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/000077500000000000000000000000001460134076200163435ustar00rootroot00000000000000memguard-0.22.5/examples/stdin/stdin.go000066400000000000000000000020411460134076200200100ustar00rootroot00000000000000/* 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/000077500000000000000000000000001460134076200165155ustar00rootroot00000000000000memguard-0.22.5/examples/stream/cpuprof1.svg000066400000000000000000004426571460134076200210170ustar00rootroot00000000000000 memguard.test cluster_L File: memguard.test File: memguard.test Type: cpu Time: May 20, 2020 at 10:43pm (BST) Duration: 1.27mins, Total samples = 79.90s (105.12%) Showing nodes accounting for 71.55s, 89.55% of 79.90s total Dropped 272 nodes (cum <= 0.40s) Dropped 27 edges (freq <= 0.08s) Showing top 80 nodes out of 111 N1 syscall Syscall 21.91s (27.42%) of 22.35s (27.97%) N2 testing (*B) runN 0.01s (0.013%) of 61.27s (76.68%) N6 memguard BenchmarkStreamRead 0.19s (0.24%) of 47.15s (59.01%) N2->N6 47.15s N12 memguard (*Stream) Write 0 of 27.35s (34.23%) N2->N12 14.09s N3 testing (*B) launch 0 of 59.45s (74.41%) N3->N2 59.45s N4 core NewBuffer 0.01s (0.013%) of 23.92s (29.94%) N20 core Copy 0.01s (0.013%) of 6.30s (7.88%) N4->N20 3.08s N21 memcall Protect 0.05s (0.063%) of 4.12s (5.16%) N4->N21 1.75s N24 runtime newobject 0.44s (0.55%) of 13.16s (16.47%) N4->N24 0.09s N32 memcall Alloc 0.01s (0.013%) of 4.31s (5.39%) N4->N32 4.31s N37 core Scramble 0 of 12.97s (16.23%) N4->N37 12.57s (inline) N80 memcall Lock 0.01s (0.013%) of 2.10s (2.63%) N4->N80 2.10s N5 runtime mallocgc 3.35s (4.19%) of 14.22s (17.80%) N8 runtime systemstack 0.03s (0.038%) of 9.33s (11.68%) N5->N8 1.97s N13 runtime memclrNoHeapPointers 7.38s (9.24%) N5->N13 0.19s N30 runtime heapBitsSetType 1.89s (2.37%) of 2.32s (2.90%) N5->N30 2.32s N41 runtime nextFreeFast 1.26s (1.58%) N5->N41 1.26s (inline) N55 runtime gcmarknewobject 0.47s (0.59%) of 0.83s (1.04%) N5->N55 0.83s N69 runtime (*mcache) refill 0.08s (0.1%) of 3.38s (4.23%) N5->N69 3.38s N9 memguard (*Stream) Read 1.08s (1.35%) of 33.70s (42.18%) N6->N9 33.70s N6->N12 13.26s N7 core NewEnclave 0.03s (0.038%) of 27.19s (34.03%) N16 core (*Coffer) View 0.04s (0.05%) of 22.01s (27.55%) N7->N16 16.44s N17 core (*Buffer) Destroy 0.01s (0.013%) of 11.08s (13.87%) N7->N17 6.22s N44 core Encrypt 0 of 4.31s (5.39%) N7->N44 4.31s N53 core Wipe 0.03s (0.038%) of 1.86s (2.33%) N7->N53 0.18s N25 runtime gcDrain 0.31s (0.39%) of 4.38s (5.48%) N8->N25 4.38s N47 runtime gcDrainN 0.07s (0.088%) of 1.52s (1.90%) N8->N47 1.52s N52 runtime (*mheap) allocSpan 0.16s (0.2%) of 0.85s (1.06%) N8->N52 0.85s N65 runtime (*mheap) freeSpan func1 0.05s (0.063%) of 0.94s (1.18%) N8->N65 0.94s N70 runtime wbBufFlush1 0.06s (0.075%) of 0.40s (0.5%) N8->N70 0.36s N11 memguard (*Stream) next 0.12s (0.15%) of 27.65s (34.61%) N9->N11 27.65s N9->N17 2.56s N9->N20 1.49s N45 sync (*Mutex) Unlock 0.93s (1.16%) N9->N45 0.92s N10 salsa salsa2020XORKeyStream 9.95s (12.45%) N26 memguard newNullBuffer 0.30s (0.38%) of 13.67s (17.11%) N11->N26 13.67s (inline) N28 memguard (*Enclave) Open 0.01s (0.013%) of 13.72s (17.17%) N11->N28 13.72s N62 memguard NewEnclave 0.01s (0.013%) of 27.28s (34.14%) N12->N62 27.28s N14 core Open 0 of 13.13s (16.43%) N14->N4 2.07s N14->N16 5.57s N14->N17 2.28s N31 core Decrypt 0 of 3.21s (4.02%) N14->N31 3.21s N15 core (*Buffer) destroy 0.06s (0.075%) of 11.05s (13.83%) N15->N21 1.58s N22 subtle ConstantTimeCompare 3.66s (4.58%) of 3.67s (4.59%) N15->N22 3.67s N34 memcall Free 0.01s (0.013%) of 3.12s (3.90%) N15->N34 3.12s N15->N53 1.64s N16->N4 21.85s N17->N15 11.05s N18 subtle ConstantTimeCopy 6.26s (7.83%) of 6.29s (7.87%) N19 runtime scanobject 2.69s (3.37%) of 3.88s (4.86%) N40 runtime findObject 0.66s (0.83%) of 0.80s (1.00%) N19->N40 0.43s N64 runtime greyobject 0.17s (0.21%) of 0.43s (0.54%) N19->N64 0.38s N20->N18 6.29s N77 unix Mprotect 0.02s (0.025%) of 4.07s (5.09%) N21->N77 4.07s N23 poly1305 update 3.62s (4.53%) N24->N5 12.72s N25->N19 2.90s N39 runtime markroot 0.16s (0.2%) of 1.38s (1.73%) N25->N39 0.95s N26->N24 12.90s N66 runtime gcWriteBarrier 0.14s (0.18%) of 0.50s (0.63%) N26->N66 0.47s N27 runtime gcBgMarkWorker 0 of 4.63s (5.79%) N27->N8 4.58s N28->N14 13.13s N29 secretbox Seal 0.02s (0.025%) of 3.89s (4.87%) N33 poly1305 Sum 0 of 3.65s (4.57%) N29->N33 2.67s (inline) N56 secretbox sliceForAppend 0 of 1.54s (1.93%) N29->N56 1.13s (inline) N61 runtime heapBitsForAddr 0.36s (0.45%) of 0.43s (0.54%) N30->N61 0.40s (inline) N54 secretbox Open 0.01s (0.013%) of 1.45s (1.81%) N31->N54 1.45s N76 core Move 0 of 1.73s (2.17%) N31->N76 1.73s N58 memcall wipe 0.02s (0.025%) of 3.59s (4.49%) N32->N58 3.42s N73 unix (*mmapper) Mmap 0.03s (0.038%) of 0.88s (1.10%) N32->N73 0.88s N78 poly1305 (*mac) Write 0.02s (0.025%) of 3.64s (4.56%) N33->N78 3.64s N34->N21 0.48s N34->N58 0.17s N74 unix Munmap 0.03s (0.038%) of 2.46s (3.08%) N34->N74 2.46s (inline) N35 runtime (*mheap) alloc 0.06s (0.075%) of 2.59s (3.24%) N35->N8 0.85s N35->N13 1.68s N36 runtime (*mcentral) cacheSpan 0.11s (0.14%) of 3.30s (4.13%) N42 runtime lock 0.42s (0.53%) of 0.53s (0.66%) N36->N42 0.11s N50 runtime (*mspan) sweep 0.18s (0.23%) of 1.61s (2.02%) N36->N50 0.10s N59 runtime (*mcentral) grow 0.07s (0.088%) of 2.81s (3.52%) N36->N59 2.81s N75 io ReadAtLeast 0.02s (0.025%) of 12.97s (16.23%) N37->N75 12.97s N38 runtime sweepone 0.41s (0.51%) of 1.97s (2.47%) N38->N50 1.51s N60 runtime scanblock 0.45s (0.56%) of 0.59s (0.74%) N39->N60 0.59s N43 runtime mcall 0 of 1.10s (1.38%) N71 runtime goschedImpl 0 of 0.76s (0.95%) N43->N71 0.62s N44->N29 3.89s N44->N37 0.40s (inline) N46 runtime bgsweep 0 of 1.88s (2.35%) N46->N38 1.87s N47->N19 0.98s N47->N39 0.43s N48 runtime schedule 0.08s (0.1%) of 1.07s (1.34%) N68 runtime findrunnable 0.07s (0.088%) of 0.70s (0.88%) N48->N68 0.70s N49 testing (*B) run1 func1 0 of 1.82s (2.28%) N49->N2 1.82s N63 runtime (*mcentral) freeSpan 0.06s (0.075%) of 1.16s (1.45%) N50->N63 1.16s N51 syscall Syscall6 0.72s (0.9%) of 0.81s (1.01%) N67 runtime (*pageAlloc) update 0.04s (0.05%) of 0.71s (0.89%) N52->N67 0.13s N53->N13 1.83s N54->N33 0.98s (inline) N54->N56 0.41s (inline) N56->N5 1.50s N57 runtime (*pallocBits) summarize 0.57s (0.71%) of 0.63s (0.79%) N58->N13 3.57s N59->N35 2.59s N60->N40 0.09s N62->N7 27.19s N62->N24 0.08s N63->N42 0.09s N79 runtime (*mheap) freeSpan 0.02s (0.025%) of 0.96s (1.20%) N63->N79 0.96s N65->N42 0.09s N72 runtime (*mheap) freeSpanLocked 0.07s (0.088%) of 0.73s (0.91%) N65->N72 0.73s N66->N8 0.36s N67->N57 0.63s N69->N36 3.30s N70->N40 0.28s N71->N42 0.10s N71->N48 0.60s N72->N67 0.58s N73->N51 0.81s N74->N1 2.36s N75->N1 12.93s N76->N20 1.70s N77->N1 4.04s N78->N23 3.62s N79->N8 0.94s N80->N1 2.07s memguard-0.22.5/examples/stream/memprof1.svg000066400000000000000000001204101460134076200207620ustar00rootroot00000000000000 memguard.test cluster_L File: memguard.test File: memguard.test Type: alloc_space Time: May 20, 2020 at 10:44pm (BST) Showing nodes accounting for 23970.57MB, 99.42% of 24111.31MB total Dropped 27 nodes (cum <= 120.56MB) N1 memguard newNullBuffer 15049.17MB (62.42%) NN1_0 176B N1->NN1_0 12720.13MB NN1_1 16B N1->NN1_1 2329.04MB N2 secretbox sliceForAppend 8884.37MB (36.85%) NN2_0 18kB N2->NN2_0 6795.57MB NN2_1 16kB N2->NN2_1 2088.80MB N3 testing (*B) launch 0 of 23752.61MB (98.51%) N4 testing (*B) runN 0 of 24106.09MB (100%) N3->N4 23752.61MB N5 memguard BenchmarkStreamRead 1.52MB (0.0063%) of 20340.85MB (84.36%) N4->N5 20340.85MB N12 memguard BenchmarkStreamWrite 0.51MB (0.0021%) of 3765.23MB (15.62%) N4->N12 3765.23MB NN5_0 16kB N5->NN5_0 1.52MB N7 memguard (*Stream) Write 0 of 6912.58MB (28.67%) N5->N7 3147.85MB N14 memguard (*Stream) Read 0 of 17191.48MB (71.30%) N5->N14 17191.48MB N6 memguard (*Stream) next 0 of 17191.48MB (71.30%) N6->N1 15049.17MB (inline) N13 memguard (*Enclave) Open 0 of 2142.31MB (8.89%) N6->N13 2142.31MB N11 memguard NewEnclave 4MB (0.017%) of 6893.08MB (28.59%) N7->N11 6893.08MB N8 testing (*B) run1 func1 0 of 353.48MB (1.47%) N8->N4 353.48MB N9 core NewEnclave 15.50MB (0.064%) of 6889.08MB (28.57%) N10 core Encrypt 15.50MB (0.064%) of 6811.07MB (28.25%) N9->N10 6811.07MB N18 secretbox Seal 0 of 6795.57MB (28.18%) N10->N18 6795.57MB N11->N9 6889.08MB N12->N7 3764.73MB N16 core Open 0 of 2137.31MB (8.86%) N13->N16 2137.31MB N14->N6 17191.48MB N15 core Decrypt 0 of 2088.80MB (8.66%) N17 secretbox Open 0 of 2088.80MB (8.66%) N15->N17 2088.80MB N16->N15 2088.80MB N17->N2 2088.80MB (inline) N18->N2 6795.57MB (inline) memguard-0.22.5/examples/stream/stream.go000066400000000000000000000035761460134076200203520ustar00rootroot00000000000000/* 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 stream import ( "io" "os" "github.com/awnumar/memguard" ) // SlowRandByte writes 16KiB of random data to a stream and then operates on it in chunks, returning a random number between 0 and 255. func SlowRandByte() byte { // Get 16KiB bytes of random data. // In the real world we might be reading from a socket instead. // Also we are free to write data in arbitrarily sized chunks. data := memguard.NewBufferRandom(1024 * 16) data.Melt() // Allow mutation so stream writer can wipe source buffer. // Create a stream object. s := memguard.NewStream() // Implements io.Reader and io.Writer interfaces. // Write the data to it. _, _ = s.Write(data.Bytes()) // Should never error or write less data. data.Destroy() // No longer need the source buffer. (Has been wiped.) // Create a buffer to work on this data in chunks. buf := memguard.NewBuffer(os.Getpagesize()) defer buf.Destroy() // Read the data back in chunks. var parity byte for { n, err := s.Read(buf.Bytes()) // Reads directly into guarded allocation. if err != nil { if err == io.EOF { break // end of data } memguard.SafePanic(err) // other error } // Do some example computation on this data. for i := 0; i < n; i++ { parity = parity ^ buf.Bytes()[i] } } // Return the result. return parity } memguard-0.22.5/examples/stream/stream_test.go000066400000000000000000000002311460134076200213720ustar00rootroot00000000000000package stream import ( "fmt" "testing" ) func TestSlowRandByte(t *testing.T) { randByte := SlowRandByte() fmt.Println("Random byte:", randByte) } memguard-0.22.5/examples/streams/000077500000000000000000000000001460134076200167005ustar00rootroot00000000000000memguard-0.22.5/examples/streams/streams.go000066400000000000000000000001621460134076200207040ustar00rootroot00000000000000package streams // MakeStreams ... func MakeStreams() { //concurrent stream access over multiple streams test } memguard-0.22.5/go.mod000066400000000000000000000004241460134076200145120ustar00rootroot00000000000000module github.com/awnumar/memguard go 1.18 require ( github.com/awnumar/memcall v0.2.0 golang.org/x/crypto v0.16.0 lukechampine.com/frand v1.4.2 ) require ( github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da // indirect golang.org/x/sys v0.15.0 // indirect ) memguard-0.22.5/go.sum000066400000000000000000000020731460134076200145410ustar00rootroot00000000000000github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da h1:KjTM2ks9d14ZYCvmHS9iAKVt9AyzRSqNU1qabPih5BY= github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da/go.mod h1:eHEWzANqSiWQsof+nXEI9bUVUyV6F53Fp89EuCh2EAA= github.com/awnumar/memcall v0.2.0 h1:sRaogqExTOOkkNwO9pzJsL8jrOV29UuUW7teRMfbqtI= github.com/awnumar/memcall v0.2.0/go.mod h1:S911igBPR9CThzd/hYQQmTc9SWNu3ZHIlCGaWsWsoJo= golang.org/x/crypto v0.16.0 h1:mMMrFzRSCF0GvB7Ne27XVtVAaXLrPmgPC7/v0tkwHaY= golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= lukechampine.com/frand v1.4.2 h1:RzFIpOvkMXuPMBb9maa4ND4wjBn71E1Jpf8BzJHMaVw= lukechampine.com/frand v1.4.2/go.mod h1:4S/TM2ZgrKejMcKMbeLjISpJMO+/eZ1zu3vYX9dtj3s= memguard-0.22.5/logo.svg000066400000000000000000000010441460134076200150640ustar00rootroot00000000000000memguard-0.22.5/memguard.go000066400000000000000000000015351460134076200155400ustar00rootroot00000000000000package memguard import ( "github.com/awnumar/memguard/core" ) /* Enhancement: check for low memory locking limit and print warning?*/ /* ScrambleBytes overwrites an arbitrary buffer with cryptographically-secure random bytes. */ func ScrambleBytes(buf []byte) { if err := core.Scramble(buf); err != nil { core.Panic(err) } } /* WipeBytes overwrites an arbitrary buffer with zeroes. */ func WipeBytes(buf []byte) { core.Wipe(buf) } /* Purge resets the session key to a fresh value and destroys all existing LockedBuffers. Existing Enclave objects will no longer be decryptable. */ func Purge() { core.Purge() } /* SafePanic wipes all it can before calling panic(v). */ func SafePanic(v interface{}) { core.Panic(v) } /* SafeExit destroys everything sensitive before exiting with a specified status code. */ func SafeExit(c int) { core.Exit(c) } memguard-0.22.5/memguard_test.go000066400000000000000000000013671460134076200166020ustar00rootroot00000000000000package memguard import ( "bytes" "testing" "github.com/awnumar/memguard/core" ) func TestScrambleBytes(t *testing.T) { buf := make([]byte, 32) ScrambleBytes(buf) if bytes.Equal(buf, make([]byte, 32)) { t.Error("buffer not scrambled") } } func TestWipeBytes(t *testing.T) { buf := make([]byte, 32) ScrambleBytes(buf) WipeBytes(buf) if !bytes.Equal(buf, make([]byte, 32)) { t.Error("buffer not wiped") } } func TestPurge(t *testing.T) { key := NewEnclaveRandom(32) buf, err := key.Open() if err != nil { t.Error(err) } Purge() if buf.IsAlive() { t.Error("buffer not destroyed") } buf, err = key.Open() if err != core.ErrDecryptionFailed { t.Error(buf.Bytes(), err) } if buf != nil { t.Error("buffer not nil:", buf) } } memguard-0.22.5/signals.go000066400000000000000000000030731460134076200153760ustar00rootroot00000000000000package memguard import ( "os" "os/signal" "sync" "github.com/awnumar/memguard/core" ) var ( // Ensure we only start a single signal handling instance create sync.Once // Channel for updating the signal handler sigfunc = make(chan func(os.Signal), 1) // Channel that caught signals are sent to by the runtime listener = make(chan os.Signal, 4) ) /* CatchSignal assigns a given function to be run in the event of a signal being received by the process. If no signals are provided all signals will be caught. 1. Signal is caught by the process 2. Interrupt handler is executed 3. Secure session state is wiped 4. Process terminates with exit code 1 This function can be called multiple times with the effect that only the last call will have any effect. */ func CatchSignal(f func(os.Signal), signals ...os.Signal) { create.Do(func() { // Start a goroutine to listen on the channels. go func() { var handler func(os.Signal) for { select { case signal := <-listener: handler(signal) core.Exit(1) case handler = <-sigfunc: } } }() }) // Update the handler function. sigfunc <- f // Notify the channel if we receive a signal. signal.Reset() signal.Notify(listener, signals...) } /* CatchInterrupt is a wrapper around CatchSignal that makes it easy to safely handle receiving interrupt signals. If an interrupt is received, the process will wipe sensitive data in memory before terminating. A subsequent call to CatchSignal will override this call. */ func CatchInterrupt() { CatchSignal(func(_ os.Signal) {}, os.Interrupt) } memguard-0.22.5/signals_test.go000066400000000000000000000040731460134076200164360ustar00rootroot00000000000000//go:build !windows // +build !windows package memguard import ( "net" "os" "os/exec" "testing" ) func TestCatchSignal(t *testing.T) { // If we're within the testing subprocess, run test. if os.Getenv("WITHIN_SUBPROCESS") == "1" { // Start a listener object listener, err := net.Listen("tcp", "127.0.0.1:") if err != nil { SafePanic(err) } defer listener.Close() // Spawn a handler to catch interrupts CatchSignal(func(s os.Signal) { listener.Close() }) // Grab a handle on the running process process, err := os.FindProcess(os.Getpid()) if err != nil { t.Error(err) } // Send it an interrupt signal if err := process.Signal(os.Interrupt); err != nil { t.Error(err) } } // Construct the subprocess with its initial state cmd := exec.Command(os.Args[0], "-test.run=TestCatchSignal") cmd.Env = append(os.Environ(), "WITHIN_SUBPROCESS=1") // Execute the subprocess and inspect its exit code err := cmd.Run().(*exec.ExitError) if err.ExitCode() != 1 { // if exit code is -1 it was likely killed by the signal t.Error("Wanted exit code 1, got", err.ExitCode(), "err:", err) } // Todo: catch this violation (segfault) // // b := NewBuffer(32) // bA := (*[64]byte)(unsafe.Pointer(&b.Bytes()[0])) // bA[42] = 0x69 // write to guard page region } func TestCatchInterrupt(t *testing.T) { if os.Getenv("WITHIN_SUBPROCESS") == "1" { // Start the interrupt handler CatchInterrupt() // Grab a handle on the running process process, err := os.FindProcess(os.Getpid()) if err != nil { t.Error(err) } // Send it an interrupt signal if err := process.Signal(os.Interrupt); err != nil { t.Error(err) } } // Construct the subprocess with its initial state cmd := exec.Command(os.Args[0], "-test.run=TestCatchInterrupt") cmd.Env = append(os.Environ(), "WITHIN_SUBPROCESS=1") // Execute the subprocess and inspect its exit code err := cmd.Run().(*exec.ExitError) if err.ExitCode() != 1 { // if exit code is -1 it was likely killed by the signal t.Error("Wanted exit code 1, got", err.ExitCode(), "err:", err) } } memguard-0.22.5/stream.go000066400000000000000000000074411460134076200152340ustar00rootroot00000000000000package memguard import ( "container/list" "io" "os" "sync" "github.com/awnumar/memguard/core" ) var ( // StreamChunkSize is the maximum amount of data that is locked into memory at a time. // If you get error allocating memory, increase your system's mlock limits. // Use 'ulimit -l' to see mlock limit on unix systems. StreamChunkSize = c c = os.Getpagesize() * 4 ) type queue struct { *list.List } // add data to back of queue func (q *queue) join(e *Enclave) { q.PushBack(e) } // add data to front of queue func (q *queue) push(e *Enclave) { q.PushFront(e) } // pop data off front of queue // returns nil if queue is empty func (q *queue) pop() *Enclave { e := q.Front() // get element at front of queue if e == nil { return nil // no data } q.Remove(e) // success => remove value return e.Value.(*Enclave) // unwrap and return (potential panic) } /* Stream is an in-memory encrypted container implementing the reader and writer interfaces. It is most useful when you need to store lots of data in memory and are able to work on it in chunks. */ type Stream struct { sync.Mutex *queue } // NewStream initialises a new empty Stream object. func NewStream() *Stream { return &Stream{queue: &queue{List: list.New()}} } /* Write encrypts and writes some given data to a Stream object. The data is broken down into chunks and added to the stream in order. The last thing to be written to the stream is the last thing that will be read back. */ func (s *Stream) Write(data []byte) (int, error) { s.Lock() defer s.Unlock() for i := 0; i < len(data); i += c { if i+c > len(data) { s.join(NewEnclave(data[len(data)-(len(data)%c):])) } else { s.join(NewEnclave(data[i : i+c])) } } return len(data), nil } /* Read decrypts and places some data from a Stream object into a provided buffer. If there is no data, the call will return an io.EOF error. If the caller provides a buffer that is too small to hold the next chunk of data, the remaining bytes are re-encrypted and added to the front of the queue to be returned in the next call. To be performant, have */ func (s *Stream) Read(buf []byte) (int, error) { s.Lock() defer s.Unlock() // Grab the next chunk of data from the stream. b, err := s.next() if err != nil { return 0, err } defer b.Destroy() // Copy the contents into the given buffer. core.Copy(buf, b.Bytes()) // Check if there is data left over. if len(buf) < b.Size() { // Re-encrypt it and push onto the front of the list. c := NewBuffer(b.Size() - len(buf)) c.Copy(b.Bytes()[len(buf):]) s.push(c.Seal()) return len(buf), nil } // Not enough data or perfect amount of data. // Either way we copied the entire buffer. return b.Size(), nil } // Size returns the number of bytes of data currently stored within a Stream object. func (s *Stream) Size() int { s.Lock() defer s.Unlock() var n int for e := s.Front(); e != nil; e = e.Next() { n += e.Value.(*Enclave).Size() } return n } // Next grabs the next chunk of data from the Stream and returns it decrypted inside a LockedBuffer. Any error from the stream is forwarded. func (s *Stream) Next() (*LockedBuffer, error) { s.Lock() defer s.Unlock() return s.next() } // does not acquire mutex lock func (s *Stream) next() (*LockedBuffer, error) { // Pop data from the front of the list. e := s.pop() if e == nil { return newNullBuffer(), io.EOF } // Decrypt the data into a guarded allocation. b, err := e.Open() if err != nil { return newNullBuffer(), err } return b, nil } // Flush reads all of the data from a Stream and returns it inside a LockedBuffer. If an error is encountered before all the data could be read, it is returned along with any data read up until that point. func (s *Stream) Flush() (*LockedBuffer, error) { return NewBufferFromEntireReader(s) } memguard-0.22.5/stream_test.go000066400000000000000000000112511460134076200162650ustar00rootroot00000000000000package memguard import ( "bytes" "io" "os" "runtime" "testing" "github.com/awnumar/memguard/core" ) func write(t *testing.T, s *Stream, b []byte) { n, err := s.Write(b) if err != nil { t.Error("write should always succeed", err) } if n != len(b) { t.Error("not all data was written") } if !bytes.Equal(b, make([]byte, len(b))) { t.Error("buffer not wiped") } } func read(t *testing.T, s *Stream, ref []byte, expectedErr error) { b := make([]byte, len(ref)) n, err := s.Read(b) if err != expectedErr { t.Error("Expected", expectedErr, "got;", err) } if n != len(b) { t.Error("not enough data read") } if !bytes.Equal(ref, b) { t.Error("data mismatch") } } func TestStreamNextFlush(t *testing.T) { s := NewStream() size := 2*StreamChunkSize + 1024 b := make([]byte, size) ScrambleBytes(b) ref := make([]byte, len(b)) copy(ref, b) write(t, s, b) c, err := s.Next() if err != nil { t.Error(err) } if c.Size() != StreamChunkSize { t.Error(c.Size()) } if !c.EqualTo(ref[:StreamChunkSize]) { t.Error("incorrect data") } c.Destroy() c, err = s.Flush() if err != nil { t.Error(err) } if c.Size() != size-StreamChunkSize { t.Error("unexpected length:", c.Size()) } if !c.EqualTo(ref[StreamChunkSize:]) { t.Error("incorrect data") } c.Destroy() } func TestStreamReadWrite(t *testing.T) { // Create new stream object. s := NewStream() // Initialise some data to store. b := make([]byte, 1024) ScrambleBytes(b) ref := make([]byte, len(b)) copy(ref, b) // Write the data to the stream. write(t, s, b) // Read the data back. read(t, s, ref, nil) // Check for end of data error read(t, s, nil, io.EOF) // Write more than the pagesize to the stream b = make([]byte, os.Getpagesize()*4+16) ScrambleBytes(b) copy(b[os.Getpagesize()*4:], []byte("yellow submarine")) ref = make([]byte, len(b)) copy(ref, b) write(t, s, b) // Read back four pages for i := 0; i < 4; i++ { read(t, s, ref[i*os.Getpagesize():(i+1)*os.Getpagesize()], nil) } // Read back the remaining data read(t, s, []byte("yellow submarine"), nil) // Should be no data left read(t, s, nil, io.EOF) // Test reading less data than is in the chunk data := make([]byte, 16) ScrambleBytes(data) ref = make([]byte, len(data)) copy(ref, data) write(t, s, data) write(t, s, data) // have two enclaves in the stream, 32 bytes total read(t, s, ref[:4], nil) read(t, s, ref[4:8], nil) read(t, s, ref[8:], nil) read(t, s, make([]byte, 16), nil) read(t, s, nil, io.EOF) // Test reading after purging the session ScrambleBytes(data) write(t, s, data) Purge() read(t, s, nil, core.ErrDecryptionFailed) } func TestStreamingSanity(t *testing.T) { s := NewStream() // write 2 pages + 1024 bytes to the stream size := 2*os.Getpagesize() + 1024 b := make([]byte, size) ScrambleBytes(b) ref := make([]byte, len(b)) copy(ref, b) write(t, s, b) // read it back exactly c, err := NewBufferFromReader(s, size) if err != nil { t.Error(err) } if c.Size() != size { t.Error("not enough data read back") } if !c.EqualTo(ref) { t.Error("data mismatch") } c.Destroy() // should be no data left read(t, s, nil, io.EOF) // write the data back to the stream copy(b, ref) write(t, s, b) // read it all back c, err = NewBufferFromEntireReader(s) if err != nil { t.Error(err) } if c.Size() != size { t.Error("not enough data read back") } if !c.EqualTo(ref) { t.Error("data mismatch") } c.Destroy() // should be no data left read(t, s, nil, io.EOF) // write a page + 1024 bytes size = os.Getpagesize() + 1024 b = make([]byte, size) b[size-1] = 'x' write(t, s, b) // read it back until the delimiter c, err = NewBufferFromReaderUntil(s, 'x') if err != nil { t.Error(err) } if c.Size() != size-1 { t.Error("not enough data read back:", c.Size(), "want", size-1) } if !c.EqualTo(make([]byte, size-1)) { t.Error("data mismatch") } c.Destroy() // should be no data left read(t, s, nil, io.EOF) } func TestStreamSize(t *testing.T) { s := NewStream() if s.Size() != 0 { t.Error("size is", s.Size()) } size := 1024 * 32 b := make([]byte, size) write(t, s, b) if s.Size() != size { t.Error("size should be", size, "instead is", s.Size()) } } func BenchmarkStreamWrite(b *testing.B) { b.ReportAllocs() b.SetBytes(int64(StreamChunkSize)) s := NewStream() buf := make([]byte, StreamChunkSize) for i := 0; i < b.N; i++ { s.Write(buf) } runtime.KeepAlive(s) } func BenchmarkStreamRead(b *testing.B) { s := NewStream() buf := make([]byte, StreamChunkSize) for i := 0; i < b.N; i++ { s.Write(buf) } b.ReportAllocs() b.SetBytes(int64(StreamChunkSize)) b.ResetTimer() for i := 0; i < b.N; i++ { s.Read(buf) } runtime.KeepAlive(s) }