mirror of
https://github.com/xor-gate/go-socks5-ssh-proxy
synced 2026-03-23 06:16:35 +01:00
Use github.com/awnumar/memguard to protect de-obfuscated embedded ssh private key and write logging to file when VMK is set
This commit is contained in:
78
vendor/github.com/awnumar/memguard/.cirrus.yml
generated
vendored
Normal file
78
vendor/github.com/awnumar/memguard/.cirrus.yml
generated
vendored
Normal file
@ -0,0 +1,78 @@
|
||||
linux_task:
|
||||
container:
|
||||
image: golang:latest
|
||||
env:
|
||||
GO111MODULE: on
|
||||
GOPATH: /tmp/go
|
||||
CIRRUS_WORKING_DIR: /tmp/go/src/github.com/${CIRRUS_REPO_FULL_NAME}
|
||||
build_script:
|
||||
- go version
|
||||
- go get ./...
|
||||
- go build -race -v ./...
|
||||
test_script:
|
||||
- go test -race -v ./...
|
||||
bench_script:
|
||||
- go test -run=XXX -bench=. ./...
|
||||
|
||||
osx_task:
|
||||
macos_instance:
|
||||
image: ghcr.io/cirruslabs/macos-ventura-base:latest
|
||||
env:
|
||||
GO111MODULE: on
|
||||
GOPATH: /tmp/go
|
||||
PATH: ${GOPATH}/bin:${PATH}
|
||||
CIRRUS_WORKING_DIR: /tmp/go/src/github.com/${CIRRUS_REPO_FULL_NAME}
|
||||
install_script:
|
||||
- brew install go
|
||||
build_script:
|
||||
- go version
|
||||
- go get ./...
|
||||
- go build -race -v ./...
|
||||
test_script:
|
||||
- go test -race -v ./...
|
||||
bench_script:
|
||||
- go test -run=XXX -bench=. ./...
|
||||
|
||||
windows_task:
|
||||
windows_container:
|
||||
image: cirrusci/windowsservercore:2019
|
||||
env:
|
||||
GO111MODULE: on
|
||||
GOPATH: C:\golang
|
||||
PATH: ${GOPATH}\bin;C:\Program Files\Go\bin;C:\Users\ContainerAdministrator\go\bin;${PATH}
|
||||
CIRRUS_WORKING_DIR: C:\golang\src\github.com\${CIRRUS_REPO_FULL_NAME}
|
||||
install_script:
|
||||
- choco install -y golang
|
||||
- choco install -y mingw # This installs MinGW which includes gcc
|
||||
- refreshenv
|
||||
- gcc --version
|
||||
build_script:
|
||||
- go version
|
||||
- go get ./...
|
||||
- env CGO_ENABLED=1 go build -race -v ./...
|
||||
test_script:
|
||||
- echo $PATH
|
||||
- refreshenv
|
||||
- echo $PATH
|
||||
- env CGO_ENABLED=1 go test -race -v ./...
|
||||
bench_script:
|
||||
- go test -run=XXX -bench=. ./...
|
||||
|
||||
freebsd_task:
|
||||
freebsd_instance:
|
||||
image: freebsd-14-0-release-amd64-ufs
|
||||
env:
|
||||
GO111MODULE: on
|
||||
GOPATH: /tmp/go
|
||||
PATH: ${GOPATH}/bin:${PATH}
|
||||
CIRRUS_WORKING_DIR: /tmp/go/src/github.com/${CIRRUS_REPO_FULL_NAME}
|
||||
install_script:
|
||||
- pkg install -y go git
|
||||
build_script:
|
||||
- go version
|
||||
- go get ./...
|
||||
- go build -race -v ./...
|
||||
test_script:
|
||||
- go test -race -v ./...
|
||||
bench_script:
|
||||
- go test -run=XXX -bench=. ./...
|
||||
12
vendor/github.com/awnumar/memguard/AUTHORS
generated
vendored
Normal file
12
vendor/github.com/awnumar/memguard/AUTHORS
generated
vendored
Normal file
@ -0,0 +1,12 @@
|
||||
# Entries should be added alphabetically in the form:
|
||||
# Name or Organization <email address>
|
||||
|
||||
Andrew LeFevre <jalefevre@liberty.edu>
|
||||
Awn Umar <awn@spacetime.dev>
|
||||
Carlo Alberto Ferraris <cafxx@strayorange.com>
|
||||
dotcppfile <dotcppfile@gmail.com>
|
||||
Fedor Korotkov <fedor@cirruslabs.org>
|
||||
Jam Adams <wodadehencou@gmail.com>
|
||||
Joseph Richey <joerichey@google.com>
|
||||
Neven Sajko <nsajko@gmail.com>
|
||||
Paul Zeinlinger <paul.zeinlinger@gmail.com>
|
||||
201
vendor/github.com/awnumar/memguard/LICENSE
generated
vendored
Normal file
201
vendor/github.com/awnumar/memguard/LICENSE
generated
vendored
Normal file
@ -0,0 +1,201 @@
|
||||
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.
|
||||
46
vendor/github.com/awnumar/memguard/README.md
generated
vendored
Normal file
46
vendor/github.com/awnumar/memguard/README.md
generated
vendored
Normal file
@ -0,0 +1,46 @@
|
||||
<p align="center">
|
||||
<img src="https://cdn.rawgit.com/awnumar/memguard/master/logo.svg" height="140" />
|
||||
<h3 align="center">MemGuard</h3>
|
||||
<p align="center">Software enclave for storage of sensitive information in memory.</p>
|
||||
<p align="center">
|
||||
<a href="https://cirrus-ci.com/github/awnumar/memguard"><img src="https://api.cirrus-ci.com/github/awnumar/memguard.svg"></a>
|
||||
<a href="https://pkg.go.dev/github.com/awnumar/memguard?tab=doc"><img src="https://godoc.org/github.com/awnumar/memguard?status.svg"></a>
|
||||
</p>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
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.
|
||||
697
vendor/github.com/awnumar/memguard/buffer.go
generated
vendored
Normal file
697
vendor/github.com/awnumar/memguard/buffer.go
generated
vendored
Normal file
@ -0,0 +1,697 @@
|
||||
package memguard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"unsafe"
|
||||
|
||||
"github.com/awnumar/memguard/core"
|
||||
)
|
||||
|
||||
/*
|
||||
LockedBuffer is a structure that holds raw sensitive data.
|
||||
|
||||
The number of LockedBuffers that you are able to create is limited by how much memory your system's kernel allows each process to mlock/VirtualLock. Therefore you should call Destroy on LockedBuffers that you no longer need or defer a Destroy call after creating a new LockedBuffer.
|
||||
*/
|
||||
type LockedBuffer struct {
|
||||
*core.Buffer
|
||||
}
|
||||
|
||||
// Constructs a LockedBuffer object from a core.Buffer while also setting up the finalizer for it.
|
||||
func newBuffer(buf *core.Buffer) *LockedBuffer {
|
||||
return &LockedBuffer{buf}
|
||||
}
|
||||
|
||||
// Constructs a quasi-destroyed LockedBuffer with size zero.
|
||||
func newNullBuffer() *LockedBuffer {
|
||||
return &LockedBuffer{new(core.Buffer)}
|
||||
}
|
||||
|
||||
/*
|
||||
NewBuffer creates a mutable data container of the specified size.
|
||||
*/
|
||||
func NewBuffer(size int) *LockedBuffer {
|
||||
// Construct a Buffer of the specified size.
|
||||
buf, err := core.NewBuffer(size)
|
||||
if err != nil {
|
||||
return newNullBuffer()
|
||||
}
|
||||
|
||||
// Construct and return the wrapped container object.
|
||||
return newBuffer(buf)
|
||||
}
|
||||
|
||||
/*
|
||||
NewBufferFromBytes constructs an immutable buffer from a byte slice. The source buffer is wiped after the value has been copied over to the created container.
|
||||
*/
|
||||
func NewBufferFromBytes(src []byte) *LockedBuffer {
|
||||
// Construct a buffer of the correct size.
|
||||
b := NewBuffer(len(src))
|
||||
if b.Size() == 0 {
|
||||
return b
|
||||
}
|
||||
|
||||
// Move the data over.
|
||||
b.Move(src)
|
||||
|
||||
// Make the buffer immutable.
|
||||
b.Freeze()
|
||||
|
||||
// Return the created Buffer object.
|
||||
return b
|
||||
}
|
||||
|
||||
/*
|
||||
NewBufferFromReader reads some number of bytes from an io.Reader into an immutable LockedBuffer.
|
||||
|
||||
An error is returned precisely when the number of bytes read is less than the requested amount. Any data read is returned in either case.
|
||||
*/
|
||||
func NewBufferFromReader(r io.Reader, size int) (*LockedBuffer, error) {
|
||||
// Construct a buffer of the provided size.
|
||||
b := NewBuffer(size)
|
||||
if b.Size() == 0 {
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// Attempt to fill it with data from the Reader.
|
||||
if n, err := io.ReadFull(r, b.Bytes()); err != nil {
|
||||
if n == 0 {
|
||||
// nothing was read
|
||||
b.Destroy()
|
||||
return newNullBuffer(), err
|
||||
}
|
||||
|
||||
// partial read
|
||||
d := NewBuffer(n)
|
||||
d.Copy(b.Bytes()[:n])
|
||||
d.Freeze()
|
||||
b.Destroy()
|
||||
return d, err
|
||||
}
|
||||
|
||||
// success
|
||||
b.Freeze()
|
||||
return b, nil
|
||||
}
|
||||
|
||||
/*
|
||||
NewBufferFromReaderUntil constructs an immutable buffer containing data sourced from an io.Reader object.
|
||||
|
||||
If an error is encountered before the delimiter value, the error will be returned along with the data read up until that point.
|
||||
*/
|
||||
func NewBufferFromReaderUntil(r io.Reader, delim byte) (*LockedBuffer, error) {
|
||||
// Construct a buffer with a data page that fills an entire memory page.
|
||||
b := NewBuffer(os.Getpagesize())
|
||||
|
||||
// Loop over the buffer a byte at a time.
|
||||
for i := 0; ; i++ {
|
||||
// If we have filled this buffer...
|
||||
if i == b.Size() {
|
||||
// Construct a new buffer that is a page size larger.
|
||||
c := NewBuffer(b.Size() + os.Getpagesize())
|
||||
|
||||
// Copy the data over.
|
||||
c.Copy(b.Bytes())
|
||||
|
||||
// Destroy the old one and reassign its variable.
|
||||
b.Destroy()
|
||||
b = c
|
||||
}
|
||||
|
||||
// Attempt to read a single byte.
|
||||
n, err := r.Read(b.Bytes()[i : i+1])
|
||||
if n != 1 { // if we did not read a byte
|
||||
if err == nil { // and there was no error
|
||||
i-- // try again
|
||||
continue
|
||||
}
|
||||
// if instead there was an error, we're done early
|
||||
if i == 0 { // no data read
|
||||
b.Destroy()
|
||||
return newNullBuffer(), err
|
||||
}
|
||||
d := NewBuffer(i)
|
||||
d.Copy(b.Bytes()[:i])
|
||||
d.Freeze()
|
||||
b.Destroy()
|
||||
return d, err
|
||||
}
|
||||
// we managed to read a byte, check if it was the delimiter
|
||||
// note that errors are ignored in this case where we got data
|
||||
if b.Bytes()[i] == delim {
|
||||
if i == 0 {
|
||||
// if first byte was delimiter, there's no data to return
|
||||
b.Destroy()
|
||||
return newNullBuffer(), nil
|
||||
}
|
||||
d := NewBuffer(i)
|
||||
d.Copy(b.Bytes()[:i])
|
||||
d.Freeze()
|
||||
b.Destroy()
|
||||
return d, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
NewBufferFromEntireReader reads from an io.Reader into an immutable buffer. It will continue reading until EOF.
|
||||
|
||||
A nil error is returned precisely when we managed to read all the way until EOF. Any data read is returned in either case.
|
||||
*/
|
||||
func NewBufferFromEntireReader(r io.Reader) (*LockedBuffer, error) {
|
||||
// Create a buffer with a data region of one page size.
|
||||
b := NewBuffer(os.Getpagesize())
|
||||
|
||||
for read := 0; ; {
|
||||
// Attempt to read some data from the reader.
|
||||
n, err := r.Read(b.Bytes()[read:])
|
||||
|
||||
// Nothing read but no error, try again.
|
||||
if n == 0 && err == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// 1) so either have data and no error
|
||||
// 2) or have error and no data
|
||||
// 3) or both have data and have error
|
||||
|
||||
// Increment the read count by the number of bytes that we just read.
|
||||
read += n
|
||||
|
||||
if err != nil {
|
||||
// Suppress EOF error
|
||||
if err == io.EOF {
|
||||
err = nil
|
||||
}
|
||||
// We're done, return the data.
|
||||
if read == 0 {
|
||||
// No data read.
|
||||
b.Destroy()
|
||||
return newNullBuffer(), err
|
||||
}
|
||||
d := NewBuffer(read)
|
||||
d.Copy(b.Bytes()[:read])
|
||||
d.Freeze()
|
||||
b.Destroy()
|
||||
return d, err
|
||||
}
|
||||
|
||||
// If we've filled this buffer, grow it by another page size.
|
||||
if len(b.Bytes()[read:]) == 0 {
|
||||
d := NewBuffer(b.Size() + os.Getpagesize())
|
||||
d.Copy(b.Bytes())
|
||||
b.Destroy()
|
||||
b = d
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
NewBufferRandom constructs an immutable buffer filled with cryptographically-secure random bytes.
|
||||
*/
|
||||
func NewBufferRandom(size int) *LockedBuffer {
|
||||
// Construct a buffer of the specified size.
|
||||
b := NewBuffer(size)
|
||||
if b.Size() == 0 {
|
||||
return b
|
||||
}
|
||||
|
||||
// Fill the buffer with random bytes.
|
||||
b.Scramble()
|
||||
|
||||
// Make the buffer immutable.
|
||||
b.Freeze()
|
||||
|
||||
// Return the created Buffer object.
|
||||
return b
|
||||
}
|
||||
|
||||
// Freeze makes a LockedBuffer's memory immutable. The call can be reversed with Melt.
|
||||
func (b *LockedBuffer) Freeze() {
|
||||
b.Buffer.Freeze()
|
||||
}
|
||||
|
||||
// Melt makes a LockedBuffer's memory mutable. The call can be reversed with Freeze.
|
||||
func (b *LockedBuffer) Melt() {
|
||||
b.Buffer.Melt()
|
||||
}
|
||||
|
||||
/*
|
||||
Seal takes a LockedBuffer object and returns its contents encrypted inside a sealed Enclave object. The LockedBuffer is subsequently destroyed and its contents wiped.
|
||||
|
||||
If Seal is called on a destroyed buffer, a nil enclave is returned.
|
||||
*/
|
||||
func (b *LockedBuffer) Seal() *Enclave {
|
||||
e, err := core.Seal(b.Buffer)
|
||||
if err != nil {
|
||||
if err == core.ErrBufferExpired {
|
||||
return nil
|
||||
}
|
||||
core.Panic(err)
|
||||
}
|
||||
return &Enclave{e}
|
||||
}
|
||||
|
||||
/*
|
||||
Copy performs a time-constant copy into a LockedBuffer. Move is preferred if the source is not also a LockedBuffer or if the source is no longer needed.
|
||||
*/
|
||||
func (b *LockedBuffer) Copy(src []byte) {
|
||||
b.CopyAt(0, src)
|
||||
}
|
||||
|
||||
/*
|
||||
CopyAt performs a time-constant copy into a LockedBuffer at an offset. Move is preferred if the source is not also a LockedBuffer or if the source is no longer needed.
|
||||
*/
|
||||
func (b *LockedBuffer) CopyAt(offset int, src []byte) {
|
||||
if !b.IsAlive() {
|
||||
return
|
||||
}
|
||||
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
|
||||
core.Copy(b.Bytes()[offset:], src)
|
||||
}
|
||||
|
||||
/*
|
||||
Move performs a time-constant move into a LockedBuffer. The source is wiped after the bytes are copied.
|
||||
*/
|
||||
func (b *LockedBuffer) Move(src []byte) {
|
||||
b.MoveAt(0, src)
|
||||
}
|
||||
|
||||
/*
|
||||
MoveAt performs a time-constant move into a LockedBuffer at an offset. The source is wiped after the bytes are copied.
|
||||
*/
|
||||
func (b *LockedBuffer) MoveAt(offset int, src []byte) {
|
||||
if !b.IsAlive() {
|
||||
return
|
||||
}
|
||||
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
|
||||
core.Move(b.Bytes()[offset:], src)
|
||||
}
|
||||
|
||||
/*
|
||||
Scramble attempts to overwrite the data with cryptographically-secure random bytes.
|
||||
*/
|
||||
func (b *LockedBuffer) Scramble() {
|
||||
if !b.IsAlive() {
|
||||
return
|
||||
}
|
||||
|
||||
b.Buffer.Scramble()
|
||||
}
|
||||
|
||||
/*
|
||||
Wipe attempts to overwrite the data with zeros.
|
||||
*/
|
||||
func (b *LockedBuffer) Wipe() {
|
||||
if !b.IsAlive() {
|
||||
return
|
||||
}
|
||||
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
|
||||
core.Wipe(b.Bytes())
|
||||
}
|
||||
|
||||
/*
|
||||
Size gives you the length of a given LockedBuffer's data segment. A destroyed LockedBuffer will have a size of zero.
|
||||
*/
|
||||
func (b *LockedBuffer) Size() int {
|
||||
return len(b.Bytes())
|
||||
}
|
||||
|
||||
/*
|
||||
Destroy wipes and frees the underlying memory of a LockedBuffer. The LockedBuffer will not be accessible or usable after this calls is made.
|
||||
*/
|
||||
func (b *LockedBuffer) Destroy() {
|
||||
b.Buffer.Destroy()
|
||||
}
|
||||
|
||||
/*
|
||||
IsAlive returns a boolean value indicating if a LockedBuffer is alive, i.e. that it has not been destroyed.
|
||||
*/
|
||||
func (b *LockedBuffer) IsAlive() bool {
|
||||
return b.Buffer.Alive()
|
||||
}
|
||||
|
||||
/*
|
||||
IsMutable returns a boolean value indicating if a LockedBuffer is mutable.
|
||||
*/
|
||||
func (b *LockedBuffer) IsMutable() bool {
|
||||
return b.Buffer.Mutable()
|
||||
}
|
||||
|
||||
/*
|
||||
EqualTo performs a time-constant comparison on the contents of a LockedBuffer with a given buffer. A destroyed LockedBuffer will always return false.
|
||||
*/
|
||||
func (b *LockedBuffer) EqualTo(buf []byte) bool {
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
|
||||
return core.Equal(b.Bytes(), buf)
|
||||
}
|
||||
|
||||
/*
|
||||
Functions for representing the memory region as various data types.
|
||||
*/
|
||||
|
||||
/*
|
||||
Bytes returns a byte slice referencing the protected region of memory.
|
||||
*/
|
||||
func (b *LockedBuffer) Bytes() []byte {
|
||||
return b.Buffer.Data()
|
||||
}
|
||||
|
||||
/*
|
||||
Reader returns a Reader object referencing the protected region of memory.
|
||||
*/
|
||||
func (b *LockedBuffer) Reader() *bytes.Reader {
|
||||
return bytes.NewReader(b.Bytes())
|
||||
}
|
||||
|
||||
/*
|
||||
String returns a string representation of the protected region of memory.
|
||||
*/
|
||||
func (b *LockedBuffer) String() string {
|
||||
slice := b.Bytes()
|
||||
return *(*string)(unsafe.Pointer(&slice))
|
||||
}
|
||||
|
||||
/*
|
||||
Uint16 returns a slice pointing to the protected region of memory with the data represented as a sequence of unsigned 16 bit integers. Its length will be half that of the byte slice, excluding any remaining part that doesn't form a complete uint16 value.
|
||||
|
||||
If called on a destroyed LockedBuffer, a nil slice will be returned.
|
||||
*/
|
||||
func (b *LockedBuffer) Uint16() []uint16 {
|
||||
|
||||
// Check if still alive.
|
||||
if !b.Buffer.Alive() {
|
||||
return nil
|
||||
}
|
||||
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
|
||||
// Compute size of new slice representation.
|
||||
size := b.Size() / 2
|
||||
if size < 1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Construct the new slice representation.
|
||||
var sl = struct {
|
||||
addr uintptr
|
||||
len int
|
||||
cap int
|
||||
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
|
||||
|
||||
// Cast the representation to the correct type and return it.
|
||||
return *(*[]uint16)(unsafe.Pointer(&sl))
|
||||
}
|
||||
|
||||
/*
|
||||
Uint32 returns a slice pointing to the protected region of memory with the data represented as a sequence of unsigned 32 bit integers. Its length will be one quarter that of the byte slice, excluding any remaining part that doesn't form a complete uint32 value.
|
||||
|
||||
If called on a destroyed LockedBuffer, a nil slice will be returned.
|
||||
*/
|
||||
func (b *LockedBuffer) Uint32() []uint32 {
|
||||
|
||||
// Check if still alive.
|
||||
if !b.Buffer.Alive() {
|
||||
return nil
|
||||
}
|
||||
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
|
||||
// Compute size of new slice representation.
|
||||
size := b.Size() / 4
|
||||
if size < 1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Construct the new slice representation.
|
||||
var sl = struct {
|
||||
addr uintptr
|
||||
len int
|
||||
cap int
|
||||
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
|
||||
|
||||
// Cast the representation to the correct type and return it.
|
||||
return *(*[]uint32)(unsafe.Pointer(&sl))
|
||||
}
|
||||
|
||||
/*
|
||||
Uint64 returns a slice pointing to the protected region of memory with the data represented as a sequence of unsigned 64 bit integers. Its length will be one eighth that of the byte slice, excluding any remaining part that doesn't form a complete uint64 value.
|
||||
|
||||
If called on a destroyed LockedBuffer, a nil slice will be returned.
|
||||
*/
|
||||
func (b *LockedBuffer) Uint64() []uint64 {
|
||||
|
||||
// Check if still alive.
|
||||
if !b.Buffer.Alive() {
|
||||
return nil
|
||||
}
|
||||
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
|
||||
// Compute size of new slice representation.
|
||||
size := b.Size() / 8
|
||||
if size < 1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Construct the new slice representation.
|
||||
var sl = struct {
|
||||
addr uintptr
|
||||
len int
|
||||
cap int
|
||||
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
|
||||
|
||||
// Cast the representation to the correct type and return it.
|
||||
return *(*[]uint64)(unsafe.Pointer(&sl))
|
||||
}
|
||||
|
||||
/*
|
||||
Int8 returns a slice pointing to the protected region of memory with the data represented as a sequence of signed 8 bit integers. If called on a destroyed LockedBuffer, a nil slice will be returned.
|
||||
*/
|
||||
func (b *LockedBuffer) Int8() []int8 {
|
||||
|
||||
// Check if still alive.
|
||||
if !b.Buffer.Alive() {
|
||||
return nil
|
||||
}
|
||||
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
|
||||
// Construct the new slice representation.
|
||||
var sl = struct {
|
||||
addr uintptr
|
||||
len int
|
||||
cap int
|
||||
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), b.Size(), b.Size()}
|
||||
|
||||
// Cast the representation to the correct type and return it.
|
||||
return *(*[]int8)(unsafe.Pointer(&sl))
|
||||
}
|
||||
|
||||
/*
|
||||
Int16 returns a slice pointing to the protected region of memory with the data represented as a sequence of signed 16 bit integers. Its length will be half that of the byte slice, excluding any remaining part that doesn't form a complete int16 value.
|
||||
|
||||
If called on a destroyed LockedBuffer, a nil slice will be returned.
|
||||
*/
|
||||
func (b *LockedBuffer) Int16() []int16 {
|
||||
|
||||
// Check if still alive.
|
||||
if !b.Buffer.Alive() {
|
||||
return nil
|
||||
}
|
||||
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
|
||||
// Compute size of new slice representation.
|
||||
size := b.Size() / 2
|
||||
if size < 1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Construct the new slice representation.
|
||||
var sl = struct {
|
||||
addr uintptr
|
||||
len int
|
||||
cap int
|
||||
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
|
||||
|
||||
// Cast the representation to the correct type and return it.
|
||||
return *(*[]int16)(unsafe.Pointer(&sl))
|
||||
}
|
||||
|
||||
/*
|
||||
Int32 returns a slice pointing to the protected region of memory with the data represented as a sequence of signed 32 bit integers. Its length will be one quarter that of the byte slice, excluding any remaining part that doesn't form a complete int32 value.
|
||||
|
||||
If called on a destroyed LockedBuffer, a nil slice will be returned.
|
||||
*/
|
||||
func (b *LockedBuffer) Int32() []int32 {
|
||||
|
||||
// Check if still alive.
|
||||
if !b.Buffer.Alive() {
|
||||
return nil
|
||||
}
|
||||
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
|
||||
// Compute size of new slice representation.
|
||||
size := b.Size() / 4
|
||||
if size < 1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Construct the new slice representation.
|
||||
var sl = struct {
|
||||
addr uintptr
|
||||
len int
|
||||
cap int
|
||||
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
|
||||
|
||||
// Cast the representation to the correct type and return it.
|
||||
return *(*[]int32)(unsafe.Pointer(&sl))
|
||||
}
|
||||
|
||||
/*
|
||||
Int64 returns a slice pointing to the protected region of memory with the data represented as a sequence of signed 64 bit integers. Its length will be one eighth that of the byte slice, excluding any remaining part that doesn't form a complete int64 value.
|
||||
|
||||
If called on a destroyed LockedBuffer, a nil slice will be returned.
|
||||
*/
|
||||
func (b *LockedBuffer) Int64() []int64 {
|
||||
|
||||
// Check if still alive.
|
||||
if !b.Buffer.Alive() {
|
||||
return nil
|
||||
}
|
||||
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
|
||||
// Compute size of new slice representation.
|
||||
size := b.Size() / 8
|
||||
if size < 1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Construct the new slice representation.
|
||||
var sl = struct {
|
||||
addr uintptr
|
||||
len int
|
||||
cap int
|
||||
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
|
||||
|
||||
// Cast the representation to the correct type and return it.
|
||||
return *(*[]int64)(unsafe.Pointer(&sl))
|
||||
}
|
||||
|
||||
/*
|
||||
ByteArray8 returns a pointer to some 8 byte array. Care must be taken not to dereference the pointer and instead pass it around as-is.
|
||||
|
||||
The length of the buffer must be at least 8 bytes in size and the LockedBuffer should not be destroyed. In either of these cases a nil value is returned.
|
||||
*/
|
||||
func (b *LockedBuffer) ByteArray8() *[8]byte {
|
||||
|
||||
// Check if still alive.
|
||||
if !b.Buffer.Alive() {
|
||||
return nil
|
||||
}
|
||||
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
|
||||
// Check if the length is large enough.
|
||||
if len(b.Bytes()) < 8 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Cast the representation to the correct type.
|
||||
return (*[8]byte)(unsafe.Pointer(&b.Bytes()[0]))
|
||||
}
|
||||
|
||||
/*
|
||||
ByteArray16 returns a pointer to some 16 byte array. Care must be taken not to dereference the pointer and instead pass it around as-is.
|
||||
|
||||
The length of the buffer must be at least 16 bytes in size and the LockedBuffer should not be destroyed. In either of these cases a nil value is returned.
|
||||
*/
|
||||
func (b *LockedBuffer) ByteArray16() *[16]byte {
|
||||
|
||||
// Check if still alive.
|
||||
if !b.Buffer.Alive() {
|
||||
return nil
|
||||
}
|
||||
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
|
||||
// Check if the length is large enough.
|
||||
if len(b.Bytes()) < 16 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Cast the representation to the correct type.
|
||||
return (*[16]byte)(unsafe.Pointer(&b.Bytes()[0]))
|
||||
}
|
||||
|
||||
/*
|
||||
ByteArray32 returns a pointer to some 32 byte array. Care must be taken not to dereference the pointer and instead pass it around as-is.
|
||||
|
||||
The length of the buffer must be at least 32 bytes in size and the LockedBuffer should not be destroyed. In either of these cases a nil value is returned.
|
||||
*/
|
||||
func (b *LockedBuffer) ByteArray32() *[32]byte {
|
||||
|
||||
// Check if still alive.
|
||||
if !b.Buffer.Alive() {
|
||||
return nil
|
||||
}
|
||||
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
|
||||
// Check if the length is large enough.
|
||||
if len(b.Bytes()) < 32 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Cast the representation to the correct type.
|
||||
return (*[32]byte)(unsafe.Pointer(&b.Bytes()[0]))
|
||||
}
|
||||
|
||||
/*
|
||||
ByteArray64 returns a pointer to some 64 byte array. Care must be taken not to dereference the pointer and instead pass it around as-is.
|
||||
|
||||
The length of the buffer must be at least 64 bytes in size and the LockedBuffer should not be destroyed. In either of these cases a nil value is returned.
|
||||
*/
|
||||
func (b *LockedBuffer) ByteArray64() *[64]byte {
|
||||
|
||||
// Check if still alive.
|
||||
if !b.Buffer.Alive() {
|
||||
return nil
|
||||
}
|
||||
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
|
||||
// Check if the length is large enough.
|
||||
if len(b.Bytes()) < 64 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Cast the representation to the correct type.
|
||||
return (*[64]byte)(unsafe.Pointer(&b.Bytes()[0]))
|
||||
}
|
||||
23
vendor/github.com/awnumar/memguard/core/auxiliary.go
generated
vendored
Normal file
23
vendor/github.com/awnumar/memguard/core/auxiliary.go
generated
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
// Ascertain and store the system memory page size.
|
||||
pageSize = os.Getpagesize()
|
||||
)
|
||||
|
||||
// Round a length to a multiple of the system page size.
|
||||
func roundToPageSize(length int) int {
|
||||
return (length + (pageSize - 1)) & (^(pageSize - 1))
|
||||
}
|
||||
|
||||
// Convert a pointer and length to a byte slice that describes that memory.
|
||||
func getBytes(ptr *byte, len int) []byte {
|
||||
var sl = reflect.SliceHeader{Data: uintptr(unsafe.Pointer(ptr)), Len: len, Cap: len}
|
||||
return *(*[]byte)(unsafe.Pointer(&sl))
|
||||
}
|
||||
317
vendor/github.com/awnumar/memguard/core/buffer.go
generated
vendored
Normal file
317
vendor/github.com/awnumar/memguard/core/buffer.go
generated
vendored
Normal file
@ -0,0 +1,317 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
|
||||
"github.com/awnumar/memcall"
|
||||
)
|
||||
|
||||
var (
|
||||
buffers = new(bufferList)
|
||||
)
|
||||
|
||||
// ErrNullBuffer is returned when attempting to construct a buffer of size less than one.
|
||||
var ErrNullBuffer = errors.New("<memguard::core::ErrNullBuffer> buffer size must be greater than zero")
|
||||
|
||||
// ErrBufferExpired is returned when attempting to perform an operation on or with a buffer that has been destroyed.
|
||||
var ErrBufferExpired = errors.New("<memguard::core::ErrBufferExpired> buffer has been purged from memory and can no longer be used")
|
||||
|
||||
/*
|
||||
Buffer is a structure that holds raw sensitive data.
|
||||
|
||||
The number of Buffers that can exist at one time is limited by how much memory your system's kernel allows each process to mlock/VirtualLock. Therefore you should call DestroyBuffer on Buffers that you no longer need, ideally defering a Destroy call after creating a new one.
|
||||
*/
|
||||
type Buffer struct {
|
||||
sync.RWMutex // Local mutex lock // TODO: this does not protect 'data' field
|
||||
|
||||
alive bool // Signals that destruction has not come
|
||||
mutable bool // Mutability state of underlying memory
|
||||
|
||||
data []byte // Portion of memory holding the data
|
||||
memory []byte // Entire allocated memory region
|
||||
|
||||
preguard []byte // Guard page addressed before the data
|
||||
inner []byte // Inner region between the guard pages
|
||||
postguard []byte // Guard page addressed after the data
|
||||
|
||||
canary []byte // Value written behind data to detect spillage
|
||||
}
|
||||
|
||||
/*
|
||||
NewBuffer is a raw constructor for the Buffer object.
|
||||
*/
|
||||
func NewBuffer(size int) (*Buffer, error) {
|
||||
var err error
|
||||
|
||||
if size < 1 {
|
||||
return nil, ErrNullBuffer
|
||||
}
|
||||
|
||||
b := new(Buffer)
|
||||
|
||||
// Allocate the total needed memory
|
||||
innerLen := roundToPageSize(size)
|
||||
b.memory, err = memcall.Alloc((2 * pageSize) + innerLen)
|
||||
if err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
|
||||
// Construct slice reference for data buffer.
|
||||
b.data = getBytes(&b.memory[pageSize+innerLen-size], size)
|
||||
|
||||
// Construct slice references for page sectors.
|
||||
b.preguard = getBytes(&b.memory[0], pageSize)
|
||||
b.inner = getBytes(&b.memory[pageSize], innerLen)
|
||||
b.postguard = getBytes(&b.memory[pageSize+innerLen], pageSize)
|
||||
|
||||
// Construct slice reference for canary portion of inner page.
|
||||
b.canary = getBytes(&b.memory[pageSize], len(b.inner)-len(b.data))
|
||||
|
||||
// Lock the pages that will hold sensitive data.
|
||||
if err := memcall.Lock(b.inner); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
|
||||
// Initialise the canary value and reference regions.
|
||||
if err := Scramble(b.canary); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
Copy(b.preguard, b.canary)
|
||||
Copy(b.postguard, b.canary)
|
||||
|
||||
// Make the guard pages inaccessible.
|
||||
if err := memcall.Protect(b.preguard, memcall.NoAccess()); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
if err := memcall.Protect(b.postguard, memcall.NoAccess()); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
|
||||
// Set remaining properties
|
||||
b.alive = true
|
||||
b.mutable = true
|
||||
|
||||
// Append the container to list of active buffers.
|
||||
buffers.add(b)
|
||||
|
||||
// Return the created Buffer to the caller.
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// Data returns a byte slice representing the memory region containing the data.
|
||||
func (b *Buffer) Data() []byte {
|
||||
return b.data
|
||||
}
|
||||
|
||||
// Inner returns a byte slice representing the entire inner memory pages. This should NOT be used unless you have a specific need.
|
||||
func (b *Buffer) Inner() []byte {
|
||||
return b.inner
|
||||
}
|
||||
|
||||
// Freeze makes the underlying memory of a given buffer immutable. This will do nothing if the Buffer has been destroyed.
|
||||
func (b *Buffer) Freeze() {
|
||||
if err := b.freeze(); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Buffer) freeze() error {
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
|
||||
if !b.alive {
|
||||
return nil
|
||||
}
|
||||
|
||||
if b.mutable {
|
||||
if err := memcall.Protect(b.inner, memcall.ReadOnly()); err != nil {
|
||||
return err
|
||||
}
|
||||
b.mutable = false
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Melt makes the underlying memory of a given buffer mutable. This will do nothing if the Buffer has been destroyed.
|
||||
func (b *Buffer) Melt() {
|
||||
if err := b.melt(); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Buffer) melt() error {
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
|
||||
if !b.alive {
|
||||
return nil
|
||||
}
|
||||
|
||||
if !b.mutable {
|
||||
if err := memcall.Protect(b.inner, memcall.ReadWrite()); err != nil {
|
||||
return err
|
||||
}
|
||||
b.mutable = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Scramble attempts to overwrite the data with cryptographically-secure random bytes.
|
||||
func (b *Buffer) Scramble() {
|
||||
if err := b.scramble(); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Buffer) scramble() error {
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
return Scramble(b.Data())
|
||||
}
|
||||
|
||||
/*
|
||||
Destroy performs some security checks, securely wipes the contents of, and then releases a Buffer's memory back to the OS. If a security check fails, the process will attempt to wipe all it can before safely panicking.
|
||||
|
||||
If the Buffer has already been destroyed, the function does nothing and returns nil.
|
||||
*/
|
||||
func (b *Buffer) Destroy() {
|
||||
if err := b.destroy(); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
// Remove this one from global slice.
|
||||
buffers.remove(b)
|
||||
}
|
||||
|
||||
func (b *Buffer) destroy() error {
|
||||
if b == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Attain a mutex lock on this Buffer.
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
|
||||
// Return if it's already destroyed.
|
||||
if !b.alive {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Make all of the memory readable and writable.
|
||||
if err := memcall.Protect(b.memory, memcall.ReadWrite()); err != nil {
|
||||
return err
|
||||
}
|
||||
b.mutable = true
|
||||
|
||||
// Wipe data field.
|
||||
Wipe(b.data)
|
||||
|
||||
// Verify the canary
|
||||
if !Equal(b.preguard, b.postguard) || !Equal(b.preguard[:len(b.canary)], b.canary) {
|
||||
return errors.New("<memguard::core::buffer> canary verification failed; buffer overflow detected")
|
||||
}
|
||||
|
||||
// Wipe the memory.
|
||||
Wipe(b.memory)
|
||||
|
||||
// Unlock pages locked into memory.
|
||||
if err := memcall.Unlock(b.inner); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Free all related memory.
|
||||
if err := memcall.Free(b.memory); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Reset the fields.
|
||||
b.alive = false
|
||||
b.mutable = false
|
||||
b.data = nil
|
||||
b.memory = nil
|
||||
b.preguard = nil
|
||||
b.inner = nil
|
||||
b.postguard = nil
|
||||
b.canary = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// Alive returns true if the buffer has not been destroyed.
|
||||
func (b *Buffer) Alive() bool {
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
return b.alive
|
||||
}
|
||||
|
||||
// Mutable returns true if the buffer is mutable.
|
||||
func (b *Buffer) Mutable() bool {
|
||||
b.RLock()
|
||||
defer b.RUnlock()
|
||||
return b.mutable
|
||||
}
|
||||
|
||||
// BufferList stores a list of buffers in a thread-safe manner.
|
||||
type bufferList struct {
|
||||
sync.RWMutex
|
||||
list []*Buffer
|
||||
}
|
||||
|
||||
// Add appends a given Buffer to the list.
|
||||
func (l *bufferList) add(b ...*Buffer) {
|
||||
l.Lock()
|
||||
defer l.Unlock()
|
||||
|
||||
l.list = append(l.list, b...)
|
||||
}
|
||||
|
||||
// Copy returns an instantaneous snapshot of the list.
|
||||
func (l *bufferList) copy() []*Buffer {
|
||||
l.Lock()
|
||||
defer l.Unlock()
|
||||
|
||||
list := make([]*Buffer, len(l.list))
|
||||
copy(list, l.list)
|
||||
|
||||
return list
|
||||
}
|
||||
|
||||
// Remove removes a given Buffer from the list.
|
||||
func (l *bufferList) remove(b *Buffer) {
|
||||
l.Lock()
|
||||
defer l.Unlock()
|
||||
|
||||
for i, v := range l.list {
|
||||
if v == b {
|
||||
l.list = append(l.list[:i], l.list[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Exists checks if a given buffer is in the list.
|
||||
func (l *bufferList) exists(b *Buffer) bool {
|
||||
l.RLock()
|
||||
defer l.RUnlock()
|
||||
|
||||
for _, v := range l.list {
|
||||
if b == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Flush clears the list and returns its previous contents.
|
||||
func (l *bufferList) flush() []*Buffer {
|
||||
l.Lock()
|
||||
defer l.Unlock()
|
||||
|
||||
list := make([]*Buffer, len(l.list))
|
||||
copy(list, l.list)
|
||||
|
||||
l.list = nil
|
||||
|
||||
return list
|
||||
}
|
||||
182
vendor/github.com/awnumar/memguard/core/coffer.go
generated
vendored
Normal file
182
vendor/github.com/awnumar/memguard/core/coffer.go
generated
vendored
Normal file
@ -0,0 +1,182 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Interval of time between each verify & re-key cycle.
|
||||
const interval = 500 * time.Millisecond
|
||||
|
||||
// ErrCofferExpired is returned when a function attempts to perform an operation using a secure key container that has been wiped and destroyed.
|
||||
var ErrCofferExpired = errors.New("<memguard::core::ErrCofferExpired> attempted usage of destroyed key object")
|
||||
|
||||
/*
|
||||
Coffer is a specialized container for securing highly-sensitive, 32 byte values.
|
||||
*/
|
||||
type Coffer struct {
|
||||
sync.Mutex
|
||||
|
||||
left *Buffer
|
||||
right *Buffer
|
||||
|
||||
rand *Buffer
|
||||
}
|
||||
|
||||
// NewCoffer is a raw constructor for the *Coffer object.
|
||||
func NewCoffer() *Coffer {
|
||||
s := new(Coffer)
|
||||
s.left, _ = NewBuffer(32)
|
||||
s.right, _ = NewBuffer(32)
|
||||
s.rand, _ = NewBuffer(32)
|
||||
|
||||
s.Init()
|
||||
|
||||
go func(s *Coffer) {
|
||||
ticker := time.NewTicker(interval)
|
||||
|
||||
for range ticker.C {
|
||||
if err := s.Rekey(); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}(s)
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// Init is used to reset the value stored inside a Coffer to a new random 32 byte value, overwriting the old.
|
||||
func (s *Coffer) Init() error {
|
||||
if s.Destroyed() {
|
||||
return ErrCofferExpired
|
||||
}
|
||||
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
if err := Scramble(s.left.Data()); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := Scramble(s.right.Data()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// left = left XOR hash(right)
|
||||
hr := Hash(s.right.Data())
|
||||
for i := range hr {
|
||||
s.left.Data()[i] ^= hr[i]
|
||||
}
|
||||
Wipe(hr)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/*
|
||||
View returns a snapshot of the contents of a Coffer inside a Buffer. As usual the Buffer should be destroyed as soon as possible after use by calling the Destroy method.
|
||||
*/
|
||||
func (s *Coffer) View() (*Buffer, error) {
|
||||
if s.Destroyed() {
|
||||
return nil, ErrCofferExpired
|
||||
}
|
||||
|
||||
b, _ := NewBuffer(32)
|
||||
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
// data = hash(right) XOR left
|
||||
h := Hash(s.right.Data())
|
||||
|
||||
for i := range b.Data() {
|
||||
b.Data()[i] = h[i] ^ s.left.Data()[i]
|
||||
}
|
||||
Wipe(h)
|
||||
|
||||
return b, nil
|
||||
}
|
||||
|
||||
/*
|
||||
Rekey is used to re-key a Coffer. Ideally this should be done at short, regular intervals.
|
||||
*/
|
||||
func (s *Coffer) Rekey() error {
|
||||
if s.Destroyed() {
|
||||
return ErrCofferExpired
|
||||
}
|
||||
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
if err := Scramble(s.rand.Data()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Hash the current right partition for later.
|
||||
hashRightCurrent := Hash(s.right.Data())
|
||||
|
||||
// new_right = current_right XOR buf32
|
||||
for i := range s.right.Data() {
|
||||
s.right.Data()[i] ^= s.rand.Data()[i]
|
||||
}
|
||||
|
||||
// new_left = current_left XOR hash(current_right) XOR hash(new_right)
|
||||
hashRightNew := Hash(s.right.Data())
|
||||
for i := range s.left.Data() {
|
||||
s.left.Data()[i] ^= hashRightCurrent[i] ^ hashRightNew[i]
|
||||
}
|
||||
Wipe(hashRightNew)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/*
|
||||
Destroy wipes and cleans up all memory related to a Coffer object. Once this method has been called, the Coffer can no longer be used and a new one should be created instead.
|
||||
*/
|
||||
func (s *Coffer) Destroy() error {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
err1 := s.left.destroy()
|
||||
if err1 == nil {
|
||||
buffers.remove(s.left)
|
||||
}
|
||||
err2 := s.right.destroy()
|
||||
if err2 == nil {
|
||||
buffers.remove(s.right)
|
||||
}
|
||||
err3 := s.rand.destroy()
|
||||
if err3 == nil {
|
||||
buffers.remove(s.rand)
|
||||
}
|
||||
|
||||
errS := ""
|
||||
if err1 != nil {
|
||||
errS = errS + err1.Error() + "\n"
|
||||
}
|
||||
if err2 != nil {
|
||||
errS = errS + err2.Error() + "\n"
|
||||
}
|
||||
if err3 != nil {
|
||||
errS = errS + err3.Error() + "\n"
|
||||
}
|
||||
if errS == "" {
|
||||
return nil
|
||||
}
|
||||
return errors.New(errS)
|
||||
}
|
||||
|
||||
// Destroyed returns a boolean value indicating if a Coffer has been destroyed.
|
||||
func (s *Coffer) Destroyed() bool {
|
||||
if s == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
if s.left == nil || s.right == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
return s.left.data == nil || s.right.data == nil
|
||||
}
|
||||
131
vendor/github.com/awnumar/memguard/core/crypto.go
generated
vendored
Normal file
131
vendor/github.com/awnumar/memguard/core/crypto.go
generated
vendored
Normal file
@ -0,0 +1,131 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"errors"
|
||||
"runtime"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/crypto/blake2b"
|
||||
"golang.org/x/crypto/nacl/secretbox"
|
||||
)
|
||||
|
||||
// Overhead is the size by which the ciphertext exceeds the plaintext.
|
||||
const Overhead int = secretbox.Overhead + 24 // auth + nonce
|
||||
|
||||
// ErrInvalidKeyLength is returned when attempting to encrypt or decrypt with a key that is not exactly 32 bytes in size.
|
||||
var ErrInvalidKeyLength = errors.New("<memguard::core::ErrInvalidKeyLength> key must be exactly 32 bytes")
|
||||
|
||||
// ErrBufferTooSmall is returned when the decryption function, Open, is given an output buffer that is too small to hold the plaintext. In practice the plaintext will be Overhead bytes smaller than the ciphertext returned by the encryption function, Seal.
|
||||
var ErrBufferTooSmall = errors.New("<memguard::core::ErrBufferTooSmall> the given buffer is too small to hold the plaintext")
|
||||
|
||||
// ErrDecryptionFailed is returned when the attempted decryption fails. This can occur if the given key is incorrect or if the ciphertext is invalid.
|
||||
var ErrDecryptionFailed = errors.New("<memguard::core::ErrDecryptionFailed> decryption failed: key is wrong or ciphertext is corrupt")
|
||||
|
||||
// Encrypt takes a plaintext message and a 32 byte key and returns an authenticated ciphertext.
|
||||
func Encrypt(plaintext, key []byte) ([]byte, error) {
|
||||
// Check the length of the key is correct.
|
||||
if len(key) != 32 {
|
||||
return nil, ErrInvalidKeyLength
|
||||
}
|
||||
|
||||
// Get a reference to the key's underlying array without making a copy.
|
||||
k := (*[32]byte)(unsafe.Pointer(&key[0]))
|
||||
|
||||
// Allocate space for and generate a nonce value.
|
||||
var nonce [24]byte
|
||||
if err := Scramble(nonce[:]); err != nil {
|
||||
Panic(err)
|
||||
}
|
||||
|
||||
// Encrypt m and return the result.
|
||||
return secretbox.Seal(nonce[:], plaintext, &nonce, k), nil
|
||||
}
|
||||
|
||||
/*
|
||||
Decrypt decrypts a given ciphertext with a given 32 byte key and writes the result to the start of a given buffer.
|
||||
|
||||
The buffer must be large enough to contain the decrypted data. This is in practice Overhead bytes less than the length of the ciphertext returned by the Seal function above. This value is the size of the nonce plus the size of the Poly1305 authenticator.
|
||||
|
||||
The size of the decrypted data is returned.
|
||||
*/
|
||||
func Decrypt(ciphertext, key []byte, output []byte) (int, error) {
|
||||
// Check the length of the key is correct.
|
||||
if len(key) != 32 {
|
||||
return 0, ErrInvalidKeyLength
|
||||
}
|
||||
|
||||
// Check the capacity of the given output buffer.
|
||||
if cap(output) < (len(ciphertext) - Overhead) {
|
||||
return 0, ErrBufferTooSmall
|
||||
}
|
||||
|
||||
// Get a reference to the key's underlying array without making a copy.
|
||||
k := (*[32]byte)(unsafe.Pointer(&key[0]))
|
||||
|
||||
// Retrieve and store the nonce value.
|
||||
var nonce [24]byte
|
||||
Copy(nonce[:], ciphertext[:24])
|
||||
|
||||
// Decrypt and return the result.
|
||||
m, ok := secretbox.Open(nil, ciphertext[24:], &nonce, k)
|
||||
if ok { // Decryption successful.
|
||||
Move(output[:cap(output)], m) // Move plaintext to given output buffer.
|
||||
return len(m), nil // Return length of decrypted plaintext.
|
||||
}
|
||||
|
||||
// Decryption unsuccessful. Either the key was wrong or the authentication failed.
|
||||
return 0, ErrDecryptionFailed
|
||||
}
|
||||
|
||||
// Hash implements a cryptographic hash function using Blake2b.
|
||||
func Hash(b []byte) []byte {
|
||||
h := blake2b.Sum256(b)
|
||||
return h[:]
|
||||
}
|
||||
|
||||
// Scramble fills a given buffer with cryptographically-secure random bytes.
|
||||
func Scramble(buf []byte) error {
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// See Wipe
|
||||
runtime.KeepAlive(buf)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Wipe takes a buffer and wipes it with zeroes.
|
||||
func Wipe(buf []byte) {
|
||||
for i := range buf {
|
||||
buf[i] = 0
|
||||
}
|
||||
|
||||
// This should keep buf's backing array live and thus prevent dead store
|
||||
// elimination, according to discussion at
|
||||
// https://github.com/golang/go/issues/33325 .
|
||||
runtime.KeepAlive(buf)
|
||||
}
|
||||
|
||||
// Copy is identical to Go's builtin copy function except the copying is done in constant time. This is to mitigate against side-channel attacks.
|
||||
func Copy(dst, src []byte) {
|
||||
if len(dst) > len(src) {
|
||||
subtle.ConstantTimeCopy(1, dst[:len(src)], src)
|
||||
} else if len(dst) < len(src) {
|
||||
subtle.ConstantTimeCopy(1, dst, src[:len(dst)])
|
||||
} else {
|
||||
subtle.ConstantTimeCopy(1, dst, src)
|
||||
}
|
||||
}
|
||||
|
||||
// Move is identical to Copy except it wipes the source buffer after the copy operation is executed.
|
||||
func Move(dst, src []byte) {
|
||||
Copy(dst, src)
|
||||
Wipe(src)
|
||||
}
|
||||
|
||||
// Equal does a constant-time comparison of two byte slices. This is to mitigate against side-channel attacks.
|
||||
func Equal(x, y []byte) bool {
|
||||
return subtle.ConstantTimeCompare(x, y) == 1
|
||||
}
|
||||
138
vendor/github.com/awnumar/memguard/core/enclave.go
generated
vendored
Normal file
138
vendor/github.com/awnumar/memguard/core/enclave.go
generated
vendored
Normal file
@ -0,0 +1,138 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
key = &Coffer{}
|
||||
keyMtx = sync.Mutex{}
|
||||
)
|
||||
|
||||
func getOrCreateKey() *Coffer {
|
||||
keyMtx.Lock()
|
||||
defer keyMtx.Unlock()
|
||||
|
||||
if key.Destroyed() {
|
||||
key = NewCoffer()
|
||||
}
|
||||
|
||||
return key
|
||||
}
|
||||
|
||||
func getKey() *Coffer {
|
||||
keyMtx.Lock()
|
||||
defer keyMtx.Unlock()
|
||||
|
||||
return key
|
||||
}
|
||||
|
||||
// ErrNullEnclave is returned when attempting to construct an enclave of size less than one.
|
||||
var ErrNullEnclave = errors.New("<memguard::core::ErrNullEnclave> enclave size must be greater than zero")
|
||||
|
||||
/*
|
||||
Enclave is a sealed and encrypted container for sensitive data.
|
||||
*/
|
||||
type Enclave struct {
|
||||
ciphertext []byte
|
||||
}
|
||||
|
||||
/*
|
||||
NewEnclave is a raw constructor for the Enclave object. The given buffer is wiped after the enclave is created.
|
||||
*/
|
||||
func NewEnclave(buf []byte) (*Enclave, error) {
|
||||
// Return an error if length < 1.
|
||||
if len(buf) < 1 {
|
||||
return nil, ErrNullEnclave
|
||||
}
|
||||
|
||||
// Create a new Enclave.
|
||||
e := new(Enclave)
|
||||
|
||||
// Get a view of the key.
|
||||
k, err := getOrCreateKey().View()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Encrypt the plaintext.
|
||||
e.ciphertext, err = Encrypt(buf, k.Data())
|
||||
if err != nil {
|
||||
Panic(err) // key is not 32 bytes long
|
||||
}
|
||||
|
||||
// Destroy our copy of the key.
|
||||
k.Destroy()
|
||||
|
||||
// Wipe the given buffer.
|
||||
Wipe(buf)
|
||||
|
||||
return e, nil
|
||||
}
|
||||
|
||||
/*
|
||||
Seal consumes a given Buffer object and returns its data secured and encrypted inside an Enclave. The given Buffer is destroyed after the Enclave is created.
|
||||
*/
|
||||
func Seal(b *Buffer) (*Enclave, error) {
|
||||
// Check if the Buffer has been destroyed.
|
||||
if !b.Alive() {
|
||||
return nil, ErrBufferExpired
|
||||
}
|
||||
|
||||
b.Melt() // Make the buffer mutable so that we can wipe it.
|
||||
|
||||
// Construct the Enclave from the Buffer's data.
|
||||
e, err := func() (*Enclave, error) {
|
||||
b.RLock() // Attain a read lock.
|
||||
defer b.RUnlock()
|
||||
return NewEnclave(b.Data())
|
||||
}()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Destroy the Buffer object.
|
||||
b.Destroy()
|
||||
|
||||
// Return the newly created Enclave.
|
||||
return e, nil
|
||||
}
|
||||
|
||||
/*
|
||||
Open decrypts an Enclave and puts the contents into a Buffer object. The given Enclave is left untouched and may be reused.
|
||||
|
||||
The Buffer object should be destroyed after the contents are no longer needed.
|
||||
*/
|
||||
func Open(e *Enclave) (*Buffer, error) {
|
||||
// Allocate a secure Buffer to hold the decrypted data.
|
||||
b, err := NewBuffer(len(e.ciphertext) - Overhead)
|
||||
if err != nil {
|
||||
Panic("<memguard:core> ciphertext has invalid length") // ciphertext has invalid length
|
||||
}
|
||||
|
||||
// Grab a view of the key.
|
||||
k, err := getOrCreateKey().View()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Decrypt the enclave into the buffer we created.
|
||||
_, err = Decrypt(e.ciphertext, k.Data(), b.Data())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Destroy our copy of the key.
|
||||
k.Destroy()
|
||||
|
||||
// Return the contents of the Enclave inside a Buffer.
|
||||
return b, nil
|
||||
}
|
||||
|
||||
/*
|
||||
EnclaveSize returns the number of bytes of plaintext data stored inside an Enclave.
|
||||
*/
|
||||
func EnclaveSize(e *Enclave) int {
|
||||
return len(e.ciphertext) - Overhead
|
||||
}
|
||||
87
vendor/github.com/awnumar/memguard/core/exit.go
generated
vendored
Normal file
87
vendor/github.com/awnumar/memguard/core/exit.go
generated
vendored
Normal file
@ -0,0 +1,87 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/awnumar/memcall"
|
||||
)
|
||||
|
||||
/*
|
||||
Purge wipes all sensitive data and keys before reinitialising the session with a fresh encryption key and secure values. Subsequent library operations will use these fresh values and the old data is assumed to be practically unrecoverable.
|
||||
|
||||
The creation of new Enclave objects should wait for this function to return since subsequent Enclave objects will use the newly created key.
|
||||
|
||||
This function should be called before the program terminates, or else the provided Exit or Panic functions should be used to terminate.
|
||||
*/
|
||||
func Purge() {
|
||||
var opErr error
|
||||
|
||||
func() {
|
||||
// Halt the re-key cycle and prevent new enclaves or keys being created.
|
||||
keyMtx.Lock()
|
||||
defer keyMtx.Unlock()
|
||||
if !key.Destroyed() {
|
||||
key.Lock()
|
||||
defer key.Unlock()
|
||||
}
|
||||
|
||||
// Get a snapshot of existing Buffers.
|
||||
snapshot := buffers.flush()
|
||||
|
||||
// Destroy them, performing the usual sanity checks.
|
||||
for _, b := range snapshot {
|
||||
if err := b.destroy(); err != nil {
|
||||
if opErr == nil {
|
||||
opErr = err
|
||||
} else {
|
||||
opErr = fmt.Errorf("%s; %s", opErr.Error(), err.Error())
|
||||
}
|
||||
// buffer destroy failed; wipe instead
|
||||
b.Lock()
|
||||
defer b.Unlock()
|
||||
if !b.mutable {
|
||||
if err := memcall.Protect(b.inner, memcall.ReadWrite()); err != nil {
|
||||
// couldn't change it to mutable; we can't wipe it! (could this happen?)
|
||||
// not sure what we can do at this point, just warn and move on
|
||||
fmt.Fprintf(os.Stderr, "!WARNING: failed to wipe immutable data at address %p", &b.data)
|
||||
continue // wipe in subprocess?
|
||||
}
|
||||
}
|
||||
Wipe(b.data)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// If we encountered an error, panic.
|
||||
if opErr != nil {
|
||||
panic(opErr)
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Exit terminates the process with a specified exit code but securely wipes and cleans up sensitive data before doing so.
|
||||
*/
|
||||
func Exit(c int) {
|
||||
// Wipe the encryption key used to encrypt data inside Enclaves.
|
||||
getKey().Destroy()
|
||||
|
||||
// Get a snapshot of existing Buffers.
|
||||
snapshot := buffers.copy() // copy ensures the buffers stay in the list until they are destroyed.
|
||||
|
||||
// Destroy them, performing the usual sanity checks.
|
||||
for _, b := range snapshot {
|
||||
b.Destroy()
|
||||
}
|
||||
|
||||
// Exit with the specified exit code.
|
||||
os.Exit(c)
|
||||
}
|
||||
|
||||
/*
|
||||
Panic is identical to the builtin panic except it purges the session before calling panic.
|
||||
*/
|
||||
func Panic(v interface{}) {
|
||||
Purge() // creates a new key so it is safe to recover from this panic
|
||||
panic(v)
|
||||
}
|
||||
9
vendor/github.com/awnumar/memguard/core/init.go
generated
vendored
Normal file
9
vendor/github.com/awnumar/memguard/core/init.go
generated
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"github.com/awnumar/memcall"
|
||||
)
|
||||
|
||||
func init() {
|
||||
memcall.DisableCoreDumps()
|
||||
}
|
||||
90
vendor/github.com/awnumar/memguard/docs.go
generated
vendored
Normal file
90
vendor/github.com/awnumar/memguard/docs.go
generated
vendored
Normal file
@ -0,0 +1,90 @@
|
||||
/*
|
||||
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
|
||||
59
vendor/github.com/awnumar/memguard/enclave.go
generated
vendored
Normal file
59
vendor/github.com/awnumar/memguard/enclave.go
generated
vendored
Normal file
@ -0,0 +1,59 @@
|
||||
package memguard
|
||||
|
||||
import (
|
||||
"github.com/awnumar/memguard/core"
|
||||
)
|
||||
|
||||
/*
|
||||
Enclave is a sealed and encrypted container for sensitive data.
|
||||
*/
|
||||
type Enclave struct {
|
||||
*core.Enclave
|
||||
}
|
||||
|
||||
/*
|
||||
NewEnclave seals up some data into an encrypted enclave object. The buffer is wiped after the data is copied. If the length of the buffer is zero, the function will return nil.
|
||||
|
||||
A LockedBuffer may alternatively be converted into an Enclave object using its Seal method. This will also have the effect of destroying the LockedBuffer.
|
||||
*/
|
||||
func NewEnclave(src []byte) *Enclave {
|
||||
e, err := core.NewEnclave(src)
|
||||
if err != nil {
|
||||
if err == core.ErrNullEnclave {
|
||||
return nil
|
||||
}
|
||||
core.Panic(err)
|
||||
}
|
||||
return &Enclave{e}
|
||||
}
|
||||
|
||||
/*
|
||||
NewEnclaveRandom generates and seals arbitrary amounts of cryptographically-secure random bytes into an encrypted enclave object. If size is not strictly positive the function will return nil.
|
||||
*/
|
||||
func NewEnclaveRandom(size int) *Enclave {
|
||||
// todo: stream data into enclave
|
||||
b := NewBufferRandom(size)
|
||||
return b.Seal()
|
||||
}
|
||||
|
||||
/*
|
||||
Open decrypts an Enclave object and places its contents into an immutable LockedBuffer. An error will be returned if decryption failed.
|
||||
*/
|
||||
func (e *Enclave) Open() (*LockedBuffer, error) {
|
||||
b, err := core.Open(e.Enclave)
|
||||
if err != nil {
|
||||
if err != core.ErrDecryptionFailed {
|
||||
core.Panic(err)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
b.Freeze()
|
||||
return newBuffer(b), nil
|
||||
}
|
||||
|
||||
/*
|
||||
Size returns the number of bytes of data stored within an Enclave.
|
||||
*/
|
||||
func (e *Enclave) Size() int {
|
||||
return core.EnclaveSize(e.Enclave)
|
||||
}
|
||||
2
vendor/github.com/awnumar/memguard/logo.svg
generated
vendored
Normal file
2
vendor/github.com/awnumar/memguard/logo.svg
generated
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 68 100" enable-background="new 0 0 68 100" xml:space="preserve"><path d="M60.5,41.338V26.5C60.5,11.888,48.612,0,34,0S7.5,11.888,7.5,26.5v14.838L0,42v55l34,3l34-3V42L60.5,41.338z M15.5,40.633
|
||||
V26.5C15.5,16.299,23.799,8,34,8s18.5,8.299,18.5,18.5v14.133L34,39L15.5,40.633z"></path></svg>
|
||||
|
After Width: | Height: | Size: 548 B |
44
vendor/github.com/awnumar/memguard/memguard.go
generated
vendored
Normal file
44
vendor/github.com/awnumar/memguard/memguard.go
generated
vendored
Normal file
@ -0,0 +1,44 @@
|
||||
package 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)
|
||||
}
|
||||
63
vendor/github.com/awnumar/memguard/signals.go
generated
vendored
Normal file
63
vendor/github.com/awnumar/memguard/signals.go
generated
vendored
Normal file
@ -0,0 +1,63 @@
|
||||
package 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)
|
||||
}
|
||||
155
vendor/github.com/awnumar/memguard/stream.go
generated
vendored
Normal file
155
vendor/github.com/awnumar/memguard/stream.go
generated
vendored
Normal file
@ -0,0 +1,155 @@
|
||||
package 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)
|
||||
}
|
||||
Reference in New Issue
Block a user