Initial commit
This commit is contained in:
commit
648d16d1cc
88 changed files with 11355 additions and 0 deletions
.gitignore.golangci.yml.travis.ymlAUTHORSCODE_OF_CONDUCT.mdGopkg.lockGopkg.tomlLICENSEREADME.mdSPEC.mdtools_test.gotruststore.go
cmd
buildcfg-envelope.gocfg-signet.gocfg-tools.gocmd-close.gocmd-configure.gocmd-generate.gocmd-manage.gocmd-open.gocmd-tools.gocmd-verify.gocmd-version.godoc.goformat.gomain.gopassword.gopassword_test.goutils.go
core-wire.gocore-wire_test.gocore.gocore_test.godefaults.godoc.goenvelope.goerrors.gohashtools
helper.goletter-file.goletter-wire.goletter.goletter_test.golhash
password.gopassword_test.gorandom.gorequirements.gorequirements_test.gosession-wire.gosession.gosignet.gosupply
testtools.gotools
all
ecdh
errors.gogostdlib
aes-ctr.goaes-gcm.gochacha20-poly1305.goed25519.gohkdf.gohmac.gopbkdf2.gopoly1305.gorsa-keys.gorsa-oaep.gorsa-pss.gosalsa20.go
interfaces.gotool.gotoollogic.gotools.gotruststores
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
cpu.out
|
||||
tinker.test
|
||||
vendor
|
11
.golangci.yml
Normal file
11
.golangci.yml
Normal file
|
@ -0,0 +1,11 @@
|
|||
linters:
|
||||
enable-all: true
|
||||
disable:
|
||||
- lll
|
||||
- gochecknoinits
|
||||
- gochecknoglobals
|
||||
- funlen
|
||||
- whitespace
|
||||
- wsl
|
||||
- godox
|
||||
|
23
.travis.yml
Normal file
23
.travis.yml
Normal file
|
@ -0,0 +1,23 @@
|
|||
language: go
|
||||
|
||||
go:
|
||||
- 1.x
|
||||
|
||||
os:
|
||||
- linux
|
||||
- windows
|
||||
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
- develop
|
||||
- /^feature\/travis\/.+$/ # feature/travis/*
|
||||
- /^fix\/travis\/.+$/ # fix/travis/*
|
||||
|
||||
install:
|
||||
- go get -d -u github.com/golang/dep
|
||||
- go install github.com/golang/dep/cmd/dep
|
||||
- dep ensure
|
||||
- ./test install
|
||||
|
||||
script: ./test --scripted
|
1
AUTHORS
Normal file
1
AUTHORS
Normal file
|
@ -0,0 +1 @@
|
|||
All files in this repository (unless otherwise noted) are authored, owned and copyrighted by Safing ICS Technologies GmbH (Austria).
|
76
CODE_OF_CONDUCT.md
Normal file
76
CODE_OF_CONDUCT.md
Normal file
|
@ -0,0 +1,76 @@
|
|||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
||||
level of experience, education, socio-economic status, nationality, personal
|
||||
appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at coc@safing.io. All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see
|
||||
https://www.contributor-covenant.org/faq
|
170
Gopkg.lock
generated
Normal file
170
Gopkg.lock
generated
Normal file
|
@ -0,0 +1,170 @@
|
|||
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
|
||||
|
||||
|
||||
[[projects]]
|
||||
digest = "1:6e5a3c39b076935a83346f9e51e11ae3e791524f6fc92c18975d3c5399872fd7"
|
||||
name = "github.com/AlecAivazis/survey"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "e4af3b345125b0903edb492a33a99a23e9eb3487"
|
||||
version = "v1.8.7"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:d38cc62bf81b2247597596ee088042c400c40307e5a6bbeb9df4190c83e19a00"
|
||||
name = "github.com/aead/ecdh"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "85c03e91d99ae3280de8341f9434bf4c733ddafb"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:870d441fe217b8e689d7949fef6e43efbc787e50f200cb1e70dbca9204a1d6be"
|
||||
name = "github.com/inconshreveable/mousetrap"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75"
|
||||
version = "v1.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:400e113a367b511b9b09ca642ee11d9885485a93838526d697033af334a2fdde"
|
||||
name = "github.com/kballard/go-shellquote"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "95032a82bc518f77982ea72343cc1ade730072f0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:4a29eeb25603debe8f2098a9902c4d3851034cf70d33be428826e86e8c30a1b0"
|
||||
name = "github.com/mattn/go-colorable"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "98ec13f34aabf44cc914c65a1cfb7b9bc815aef1"
|
||||
version = "v0.1.4"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:29895093e370d9da5fd1c9ab12a5855ccb568f28766e0c3ff159c4b0f09aa127"
|
||||
name = "github.com/mattn/go-isatty"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "31745d66dd679ac0ac4f8d3ecff168fce6170c6a"
|
||||
version = "v0.0.11"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:2b32af4d2a529083275afc192d1067d8126b578c7a9613b26600e4df9c735155"
|
||||
name = "github.com/mgutz/ansi"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "9520e82c474b0a04dd04f8a40959027271bab992"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:3b7bb4dccaa604125b8392b33d69a4a477efb928644d534e3d4063d4b6892693"
|
||||
name = "github.com/safing/portbase"
|
||||
packages = [
|
||||
"container",
|
||||
"formats/dsd",
|
||||
"formats/varint",
|
||||
"info",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "a120990396939bbe3480f752d190c476b1d56c3a"
|
||||
version = "v0.4.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:274f67cb6fed9588ea2521ecdac05a6d62a8c51c074c1fccc6a49a40ba80e925"
|
||||
name = "github.com/satori/go.uuid"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "f58768cc1a7a7e77a3bd49e98cdd21419399b6a3"
|
||||
version = "v1.2.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:e096613fb7cf34743d49af87d197663cfccd61876e2219853005a57baedfa562"
|
||||
name = "github.com/spf13/cobra"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "f2b07da1e2c38d5f12845a4f607e2e1018cbb1f5"
|
||||
version = "v0.0.5"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:524b71991fc7d9246cc7dc2d9e0886ccb97648091c63e30eef619e6862c955dd"
|
||||
name = "github.com/spf13/pflag"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "2e9d26c8c37aae03e3f9d4e90b7116f5accb7cab"
|
||||
version = "v1.0.5"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:93d6687fc19da8a35c7352d72117a6acd2072dfb7e9bfd65646227bf2a913b2a"
|
||||
name = "github.com/tevino/abool"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "9b9efcf221b50905aab9bbabd3daed56dc10f339"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:23e3d5f66ff9fd60dd264fbf26e71cab6b4a3bd2ef993a1645432d5c4c3b50fc"
|
||||
name = "golang.org/x/crypto"
|
||||
packages = [
|
||||
"blake2b",
|
||||
"blake2s",
|
||||
"chacha20",
|
||||
"chacha20poly1305",
|
||||
"curve25519",
|
||||
"hkdf",
|
||||
"internal/subtle",
|
||||
"pbkdf2",
|
||||
"poly1305",
|
||||
"salsa20",
|
||||
"salsa20/salsa",
|
||||
"sha3",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "e1110fd1c708ef015366ea01799a23c459593c47"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:2a7bb603cdfc77afb007e411395d21947ac9e8f9cc220ca0f6883027402bbdc3"
|
||||
name = "golang.org/x/sys"
|
||||
packages = [
|
||||
"cpu",
|
||||
"unix",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "4c7a9d0fe056d9d1de37e1409ca8a5c17accb46a"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:a8136ab6079cc7a9de8d8665e6757b506bf2bb4c88014a4dc1e35eaaa449dfc0"
|
||||
name = "gopkg.in/AlecAivazis/survey.v1"
|
||||
packages = [
|
||||
"core",
|
||||
"terminal",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "e4af3b345125b0903edb492a33a99a23e9eb3487"
|
||||
version = "v1.8.7"
|
||||
|
||||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
input-imports = [
|
||||
"github.com/AlecAivazis/survey",
|
||||
"github.com/aead/ecdh",
|
||||
"github.com/safing/portbase/container",
|
||||
"github.com/safing/portbase/formats/dsd",
|
||||
"github.com/safing/portbase/info",
|
||||
"github.com/satori/go.uuid",
|
||||
"github.com/spf13/cobra",
|
||||
"github.com/tevino/abool",
|
||||
"golang.org/x/crypto/blake2b",
|
||||
"golang.org/x/crypto/blake2s",
|
||||
"golang.org/x/crypto/chacha20poly1305",
|
||||
"golang.org/x/crypto/hkdf",
|
||||
"golang.org/x/crypto/pbkdf2",
|
||||
"golang.org/x/crypto/poly1305",
|
||||
"golang.org/x/crypto/salsa20",
|
||||
"golang.org/x/crypto/sha3",
|
||||
]
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
29
Gopkg.toml
Normal file
29
Gopkg.toml
Normal file
|
@ -0,0 +1,29 @@
|
|||
# Gopkg.toml example
|
||||
#
|
||||
# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html
|
||||
# for detailed Gopkg.toml documentation.
|
||||
#
|
||||
# required = ["github.com/user/thing/cmd/thing"]
|
||||
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
|
||||
#
|
||||
# [[constraint]]
|
||||
# name = "github.com/user/project"
|
||||
# version = "1.0.0"
|
||||
#
|
||||
# [[constraint]]
|
||||
# name = "github.com/user/project2"
|
||||
# branch = "dev"
|
||||
# source = "github.com/myfork/project2"
|
||||
#
|
||||
# [[override]]
|
||||
# name = "github.com/x/y"
|
||||
# version = "2.4.0"
|
||||
#
|
||||
# [prune]
|
||||
# non-go = false
|
||||
# go-tests = true
|
||||
# unused-packages = true
|
||||
|
||||
[prune]
|
||||
go-tests = true
|
||||
unused-packages = true
|
674
LICENSE
Normal file
674
LICENSE
Normal file
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
105
README.md
Normal file
105
README.md
Normal file
|
@ -0,0 +1,105 @@
|
|||
# Jess
|
||||
|
||||
Jess is a cryptographic library and cli tool that focuses on usability and freedom.
|
||||
|
||||
DISCLAIMER: This is still work in progress. Breaking changes might still occur. Do _not_ use in production yet! Use at your own risk.
|
||||
|
||||
### Usage & Intro
|
||||
|
||||
Jess uses the theme of envelopes and letters in order to make everything a bit more comprehensible. Here is a list of terms that will prove helpful:
|
||||
- __Signet__ private or secret key
|
||||
- __Recipient__ public key
|
||||
- __Envelope__ encryption configuration
|
||||
- __Letter__ encrypted data with associated configuration
|
||||
- __Trust Store__ a storage of everything you trust, your own keys and configurations, and your friends' public keys.
|
||||
|
||||
Jess makes heavy use of `trust stores`, which in its basic form is just a directory, where you can store your keys and configuration. You can either set a default through an environment variable, or set it manually every time. This makes it easy to compartmentalize your trust zones.
|
||||
|
||||
Here is how you can setup a trust store and generate some keys:
|
||||
|
||||
export JESS_TSDIR=/tmp/truststore-test
|
||||
jess generate --name Alice --scheme Ed25519
|
||||
jess generate --name Alice --scheme ECDH-X25519
|
||||
jess generate --name Bob --scheme Ed25519
|
||||
jess generate --name Bob --scheme ECDH-X25519
|
||||
jess generate --name BackupPassword --scheme pw
|
||||
# look at result
|
||||
jess manage
|
||||
|
||||
Now let's configure an envelope to get started with encrypting - set up an envelope to have Alice send Bob a file. Use the preset `Encrypt for someone`.
|
||||
|
||||
jess configure toBob
|
||||
# look at result
|
||||
jess manage
|
||||
|
||||
If now want to encrypt a file for Bob, you take a piece of data, put it in the envelope, and you have a letter!
|
||||
|
||||
echo "Hello, Bob!" > forbob.txt
|
||||
jess close forbob.txt with toBob
|
||||
|
||||
And because we also have Bob's secret key, we can also go ahead and decrypt the file again.
|
||||
|
||||
jess open forbob.txt.letter -o -
|
||||
|
||||
Normally, of course, you would have a friend send you their `recipient` file (public key) and you would add it to your trust store.
|
||||
|
||||
Jess does not have a PKI or some sort of web of trust. You have to exchange public keys by yourself.
|
||||
|
||||
Jess is also capable of securing a network connection, but this currently only works with the library, not the CLI.
|
||||
|
||||
### Architecture
|
||||
|
||||
Before we dive into technical details, here are some more/updated terms:
|
||||
- __Tool/Scheme__ a cryptographic primitive/scheme
|
||||
- Identified via their Name/ID (used interchangeably)
|
||||
- __Signet/Recipient__ the
|
||||
- Identified by their ID (usually a UUID)
|
||||
- __Envelope__ hold configuration, but also requirements
|
||||
- Identified by the name given to them
|
||||
|
||||
Every algorithm/piece that can be used to _build_ a complete encryption operation is called a Tool. Tools have different capabilites and might cover more than just one primitive - eg. AES-GCM covers _Confidentiality_ and _Integrity_.
|
||||
|
||||
Tinker can either operate in _single-op_ (eg. file encryption) or _communication_ (eg. securing network traffic) mode.
|
||||
|
||||
Basically, every operation needs:
|
||||
- _SenderAuthentication_ and _ReceiverAuthentication_:
|
||||
- `PassDerivation`: derive a key from given password
|
||||
- provides _SenderAuthentication_, _ReceiverAuthentication_
|
||||
- `KeyExchange`: supply trusted public key of peer _comm mode only_
|
||||
- provides _ReceiverAuthentication_
|
||||
- `KeyEncapsulation`: encrypt the key with trusted public key of peer
|
||||
- provides _ReceiverAuthentication_
|
||||
- `Signing`: sign the whole message
|
||||
- provides _SenderAuthentication_
|
||||
- _KeyDerivation_: guarantees clean key material, also more material than given may be needed.
|
||||
- _Confidentiality_:
|
||||
- `Cipher`: encrypt the data
|
||||
- `IntegratedCipher`: also provides _Integrity_
|
||||
- _Integrity_:
|
||||
- `MAC`: check data integrity
|
||||
- `IntegratedCipher`: also provides _Confidentiality_
|
||||
|
||||
Some of these properties may also be used multiple times. For example, you could choose to encrypt your data with multiple ciphers or use multiple MACs for data integrity checks.
|
||||
|
||||
Should any of these properties _not_ be required, the user has to intentionally remove requirements.
|
||||
|
||||
### Specification
|
||||
|
||||
There is some more detail in `SPEC.md`.
|
||||
|
||||
### Testing
|
||||
|
||||
There is a special variable to enable very comprehensive testing:
|
||||
|
||||
```
|
||||
go test -timeout 10m github.com/safing/jess -v -count=1 -cover -ldflags "-X github.com/safing/jess.RunComprehensiveTests=true"
|
||||
```
|
||||
|
||||
There is some randomness to this, so you can use this command for predictable output in order to debug a problem:
|
||||
|
||||
```
|
||||
go test -timeout 10m github.com/safing/jess -v -count=1 -cover -ldflags "-X github.com/safing/jess.RunComprehensiveTests=true -X github.com/safing/jess.RunTestsInDebugStyle=true"
|
||||
|
||||
# if you only want the comprehensive test itself:
|
||||
go test -timeout 10m github.com/safing/jess -run ^TestCoreAllCombinations$ -v -count=1 -cover -ldflags "-X github.com/safing/jess.RunComprehensiveTests=true -X github.com/safing/jess.RunTestsInDebugStyle=true"
|
||||
```
|
110
SPEC.md
Normal file
110
SPEC.md
Normal file
File diff suppressed because one or more lines are too long
52
cmd/build
Executable file
52
cmd/build
Executable file
|
@ -0,0 +1,52 @@
|
|||
#!/bin/bash
|
||||
|
||||
# get build data
|
||||
if [[ "$BUILD_COMMIT" == "" ]]; then
|
||||
BUILD_COMMIT=$(git describe --all --long --abbrev=99 --dirty 2>/dev/null)
|
||||
fi
|
||||
if [[ "$BUILD_USER" == "" ]]; then
|
||||
BUILD_USER=$(id -un)
|
||||
fi
|
||||
if [[ "$BUILD_HOST" == "" ]]; then
|
||||
BUILD_HOST=$(hostname -f)
|
||||
fi
|
||||
if [[ "$BUILD_DATE" == "" ]]; then
|
||||
BUILD_DATE=$(date +%d.%m.%Y)
|
||||
fi
|
||||
if [[ "$BUILD_SOURCE" == "" ]]; then
|
||||
BUILD_SOURCE=$(git remote -v | grep origin | cut -f2 | cut -d" " -f1 | head -n 1)
|
||||
fi
|
||||
if [[ "$BUILD_SOURCE" == "" ]]; then
|
||||
BUILD_SOURCE=$(git remote -v | cut -f2 | cut -d" " -f1 | head -n 1)
|
||||
fi
|
||||
BUILD_BUILDOPTIONS=$(echo $* | sed "s/ /§/g")
|
||||
|
||||
# check
|
||||
if [[ "$BUILD_COMMIT" == "" ]]; then
|
||||
echo "could not automatically determine BUILD_COMMIT, please supply manually as environment variable."
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$BUILD_USER" == "" ]]; then
|
||||
echo "could not automatically determine BUILD_USER, please supply manually as environment variable."
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$BUILD_HOST" == "" ]]; then
|
||||
echo "could not automatically determine BUILD_HOST, please supply manually as environment variable."
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$BUILD_DATE" == "" ]]; then
|
||||
echo "could not automatically determine BUILD_DATE, please supply manually as environment variable."
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$BUILD_SOURCE" == "" ]]; then
|
||||
echo "could not automatically determine BUILD_SOURCE, please supply manually as environment variable."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Please notice, that this build script includes metadata into the build."
|
||||
echo "This information is useful for debugging and license compliance."
|
||||
echo "Run the compiled binary with the -version flag to see the information included."
|
||||
|
||||
# build
|
||||
BUILD_PATH="github.com/safing/portbase/info"
|
||||
go build -ldflags "-X ${BUILD_PATH}.commit=${BUILD_COMMIT} -X ${BUILD_PATH}.buildOptions=${BUILD_BUILDOPTIONS} -X ${BUILD_PATH}.buildUser=${BUILD_USER} -X ${BUILD_PATH}.buildHost=${BUILD_HOST} -X ${BUILD_PATH}.buildDate=${BUILD_DATE} -X ${BUILD_PATH}.buildSource=${BUILD_SOURCE}" $@
|
196
cmd/cfg-envelope.go
Normal file
196
cmd/cfg-envelope.go
Normal file
|
@ -0,0 +1,196 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/AlecAivazis/survey"
|
||||
"github.com/safing/jess"
|
||||
)
|
||||
|
||||
func newEnvelope(name string) (*jess.Envelope, error) {
|
||||
// check name
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return nil, errors.New("missing envelope name")
|
||||
}
|
||||
|
||||
// start init process
|
||||
envelope := jess.NewUnconfiguredEnvelope()
|
||||
envelope.Name = name
|
||||
|
||||
// preset menu
|
||||
var preset string
|
||||
prompt := &survey.Select{
|
||||
Message: "Select preset:",
|
||||
Options: []string{
|
||||
"Encrypt with password",
|
||||
"Encrypt with keyfile",
|
||||
"Encrypt for someone",
|
||||
"Sign a file",
|
||||
"Custom from scratch",
|
||||
},
|
||||
}
|
||||
err := survey.AskOne(prompt, &preset, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch preset {
|
||||
case "Encrypt with password":
|
||||
envelope.Tools = jess.RecommendedStoragePassword
|
||||
err = selectSignets(envelope, "pw")
|
||||
|
||||
case "Encrypt with keyfile":
|
||||
envelope.Tools = jess.RecommendedStorageKey
|
||||
err = selectSignets(envelope, "key")
|
||||
|
||||
case "Encrypt for someone":
|
||||
envelope.Tools = jess.RecommendedStorageKey
|
||||
err = selectSignets(envelope, "recipient")
|
||||
if err == nil {
|
||||
err = selectSignets(envelope, "sender")
|
||||
}
|
||||
|
||||
case "Sign a file":
|
||||
envelope.NoConfidentiality().NoIntegrity().NoRecipientAuth()
|
||||
err = selectSignets(envelope, "sender")
|
||||
|
||||
case "Custom from scratch":
|
||||
// do nothing
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return envelope, nil
|
||||
}
|
||||
|
||||
func editEnvelope(envelope *jess.Envelope) error {
|
||||
for {
|
||||
// main menu
|
||||
|
||||
// print envelope status
|
||||
session, err := envelope.Correspondence(trustStore)
|
||||
if err != nil {
|
||||
fmt.Printf("Envelope status: %s\n", err)
|
||||
} else {
|
||||
fmt.Println("Envelope status: valid.")
|
||||
envelope.MinimumSecurityLevel = session.SecurityLevel
|
||||
}
|
||||
|
||||
// sub menu
|
||||
var submenu string
|
||||
prompt := &survey.Select{
|
||||
Message: "Select to edit",
|
||||
Options: formatColumns([][]string{
|
||||
{"Done", "save and return"},
|
||||
{" "},
|
||||
{"Requirements", formatRequirements(envelope)},
|
||||
{"Tools", strings.Join(envelope.Tools, ", ")},
|
||||
{"Secrets", formatSignetNames(envelope.Secrets)},
|
||||
{"Recipients", formatSignetNames(envelope.Recipients)},
|
||||
{"Senders", formatSignetNames(envelope.Senders)},
|
||||
{" "},
|
||||
{"Abort", "discard changes and return"},
|
||||
{"Delete", "delete and return"},
|
||||
}),
|
||||
PageSize: 10,
|
||||
}
|
||||
err = survey.AskOne(prompt, &submenu, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch {
|
||||
case strings.HasPrefix(submenu, "Done"):
|
||||
// save
|
||||
return trustStore.StoreEnvelope(envelope)
|
||||
case strings.HasPrefix(submenu, "Abort"):
|
||||
return nil
|
||||
case strings.HasPrefix(submenu, "Delete"):
|
||||
return trustStore.DeleteEnvelope(envelope.Name)
|
||||
case strings.HasPrefix(submenu, "Requirements"):
|
||||
err = editEnvelopeRequirements(envelope)
|
||||
case strings.HasPrefix(submenu, "Tools"):
|
||||
err = editEnvelopeTools(envelope)
|
||||
case strings.HasPrefix(submenu, "Secrets"):
|
||||
err = selectSignets(envelope, "pw/key")
|
||||
case strings.HasPrefix(submenu, "Recipients"):
|
||||
err = selectSignets(envelope, "recipient")
|
||||
case strings.HasPrefix(submenu, "Senders"):
|
||||
err = selectSignets(envelope, "sender")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func editEnvelopeRequirements(envelope *jess.Envelope) error {
|
||||
// TODO: improve
|
||||
|
||||
// get reqs
|
||||
requirements := envelope.Requirements()
|
||||
if requirements == nil {
|
||||
return errors.New("envelope requirements uninitialized")
|
||||
}
|
||||
|
||||
// build defaults
|
||||
var defaults []string
|
||||
if requirements.Has(jess.Confidentiality) {
|
||||
defaults = append(defaults, "Confidentiality")
|
||||
}
|
||||
if requirements.Has(jess.Integrity) {
|
||||
defaults = append(defaults, "Integrity")
|
||||
}
|
||||
if requirements.Has(jess.RecipientAuthentication) {
|
||||
defaults = append(defaults, "Recipient Authentication")
|
||||
}
|
||||
if requirements.Has(jess.SenderAuthentication) {
|
||||
defaults = append(defaults, "Sender Authentication")
|
||||
}
|
||||
|
||||
// prompt
|
||||
var selected []string
|
||||
prompt := &survey.MultiSelect{
|
||||
Message: "Select requirements:",
|
||||
Options: []string{
|
||||
"Confidentiality",
|
||||
"Integrity",
|
||||
"Recipient Authentication",
|
||||
"Sender Authentication",
|
||||
},
|
||||
Default: defaults,
|
||||
}
|
||||
err := survey.AskOne(prompt, &selected, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// parse
|
||||
requirements.Remove(jess.Confidentiality)
|
||||
requirements.Remove(jess.Integrity)
|
||||
requirements.Remove(jess.RecipientAuthentication)
|
||||
requirements.Remove(jess.SenderAuthentication)
|
||||
for _, req := range selected {
|
||||
switch req {
|
||||
case "Confidentiality":
|
||||
requirements.Add(jess.Confidentiality)
|
||||
case "Integrity":
|
||||
requirements.Add(jess.Integrity)
|
||||
case "Recipient Authentication":
|
||||
requirements.Add(jess.RecipientAuthentication)
|
||||
case "Sender Authentication":
|
||||
requirements.Add(jess.SenderAuthentication)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func editEnvelopeTools(envelope *jess.Envelope) (err error) {
|
||||
envelope.Tools, err = pickTools(envelope.Tools, "Select tools:")
|
||||
return err
|
||||
}
|
360
cmd/cfg-signet.go
Normal file
360
cmd/cfg-signet.go
Normal file
|
@ -0,0 +1,360 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/AlecAivazis/survey"
|
||||
"github.com/safing/jess"
|
||||
"github.com/safing/jess/tools"
|
||||
)
|
||||
|
||||
//nolint:gocognit
|
||||
func newSignet(name, scheme string) (*jess.Signet, error) {
|
||||
// get name
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
enterName := &survey.Input{
|
||||
Message: "Enter name of signet:",
|
||||
}
|
||||
err := survey.AskOne(enterName, &name, survey.MinLength(1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// get scheme
|
||||
scheme = strings.TrimSpace(scheme)
|
||||
if scheme == "" {
|
||||
// build selection list
|
||||
schemeSelection := [][]string{
|
||||
{jess.SignetSchemePassword, "Password"},
|
||||
{jess.SignetSchemeKey, "Key", "dynamic b/s (set manually via --symkeysize)"},
|
||||
}
|
||||
for _, tool := range tools.AsList() {
|
||||
// check if tool support Signets
|
||||
switch tool.Info.Purpose {
|
||||
case tools.PurposeKeyExchange,
|
||||
tools.PurposeKeyEncapsulation,
|
||||
tools.PurposeSigning:
|
||||
schemeSelection = append(schemeSelection, []string{
|
||||
tool.Info.Name,
|
||||
tool.Info.FormatPurpose(),
|
||||
formatToolSecurityLevel(tool),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// select scheme
|
||||
selectScheme := &survey.Select{
|
||||
Message: "Select Tool/Scheme:",
|
||||
Options: formatColumns(schemeSelection),
|
||||
}
|
||||
err := survey.AskOne(selectScheme, &scheme, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
scheme = strings.Fields(scheme)[0]
|
||||
}
|
||||
|
||||
// generate key
|
||||
var signet *jess.Signet
|
||||
|
||||
switch scheme {
|
||||
case jess.SignetSchemePassword:
|
||||
signet = &jess.Signet{
|
||||
Version: 1,
|
||||
Scheme: jess.SignetSchemePassword,
|
||||
}
|
||||
|
||||
case jess.SignetSchemeKey:
|
||||
signet = &jess.Signet{
|
||||
Version: 1,
|
||||
Scheme: jess.SignetSchemeKey,
|
||||
}
|
||||
if defaultSymmetricKeySize == 0 {
|
||||
return nil, errors.New("missing key size, please supply with --symkeysize")
|
||||
}
|
||||
newKey, err := jess.RandomBytes(defaultSymmetricKeySize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
signet.Key = newKey
|
||||
|
||||
default:
|
||||
// get tool
|
||||
tool, err := tools.Get(scheme)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// create base
|
||||
signet = jess.NewSignetBase(tool)
|
||||
|
||||
// check if tool needs security level or manual key size
|
||||
if tool.Info.HasOption(tools.OptionNeedsSecurityLevel) && minimumSecurityLevel <= 0 {
|
||||
return nil, errors.New("missing security level, please supply with --seclevel")
|
||||
}
|
||||
if tool.Info.HasOption(tools.OptionNeedsDefaultKeySize) && defaultSymmetricKeySize <= 0 {
|
||||
return nil, errors.New("missing key size, please supply with --symkeysize")
|
||||
}
|
||||
|
||||
// generate
|
||||
err = signet.GenerateKey()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = signet.StoreKey()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
err := signet.AssignUUID()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
signet.Info = &jess.SignetInfo{
|
||||
Name: name,
|
||||
Created: time.Now(),
|
||||
}
|
||||
|
||||
// write signet
|
||||
err = trustStore.StoreSignet(signet)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// export as recipient
|
||||
switch scheme {
|
||||
case jess.SignetSchemePassword, jess.SignetSchemeKey:
|
||||
// is secret, no recipient
|
||||
default:
|
||||
rcpt, err := signet.AsRecipient()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = rcpt.StoreKey()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = trustStore.StoreSignet(rcpt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return signet, nil
|
||||
}
|
||||
|
||||
func selectSignets(envelope *jess.Envelope, scope string) error {
|
||||
// collect all signet schemes that fit the scope
|
||||
var schemes []string
|
||||
var promptMsg string
|
||||
var currentSignets []*jess.Signet
|
||||
filter := jess.FilterSignetOnly
|
||||
switch scope {
|
||||
case jess.SignetSchemePassword:
|
||||
schemes = []string{jess.SignetSchemePassword}
|
||||
promptMsg = "Select password references: (selection is AND, not OR!)"
|
||||
case jess.SignetSchemeKey:
|
||||
schemes = []string{jess.SignetSchemeKey}
|
||||
promptMsg = "Select keys: (selection is AND, not OR!)"
|
||||
case "pw/key":
|
||||
schemes = []string{jess.SignetSchemePassword, jess.SignetSchemeKey}
|
||||
promptMsg = "Select keys and password references: (selection is AND, not OR!)"
|
||||
currentSignets = envelope.Secrets
|
||||
case "recipient": //nolint:goconst
|
||||
promptMsg = "Select recipients: (selection is AND, not OR!)"
|
||||
for _, tool := range tools.AsList() {
|
||||
switch tool.Info.Purpose {
|
||||
case tools.PurposeKeyExchange,
|
||||
tools.PurposeKeyEncapsulation:
|
||||
schemes = append(schemes, tool.Info.Name)
|
||||
}
|
||||
}
|
||||
filter = jess.FilterRecipientOnly
|
||||
currentSignets = envelope.Recipients
|
||||
case "sender":
|
||||
promptMsg = "Select senders: (selection is AND, not OR!)"
|
||||
for _, tool := range tools.AsList() {
|
||||
if tool.Info.Purpose == tools.PurposeSigning {
|
||||
schemes = append(schemes, tool.Info.Name)
|
||||
}
|
||||
}
|
||||
currentSignets = envelope.Senders
|
||||
default:
|
||||
return errors.New("unknown signet selection scope")
|
||||
}
|
||||
|
||||
// collect all signet for the scope's schemes
|
||||
signetCandidates, err := trustStore.SelectSignets(filter, schemes...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(signetCandidates) == 0 {
|
||||
return errors.New("no signets available, please create some first using the generate command")
|
||||
}
|
||||
|
||||
// select signets
|
||||
selectedSignets, err := pickSignet(signetCandidates, promptMsg, "", true, currentSignets)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// add schemes to envelope
|
||||
checkSchemaLoop:
|
||||
for _, signet := range selectedSignets {
|
||||
switch signet.Scheme {
|
||||
case jess.SignetSchemePassword, jess.SignetSchemeKey:
|
||||
default:
|
||||
for _, toolID := range envelope.Tools {
|
||||
scheme := toolID
|
||||
if strings.Contains(scheme, "(") {
|
||||
scheme = strings.Split(scheme, "(")[0]
|
||||
}
|
||||
if scheme == signet.Scheme {
|
||||
continue checkSchemaLoop
|
||||
}
|
||||
}
|
||||
|
||||
// schema not found in envelope toolset
|
||||
tool, err := signet.Tool()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tool.Info.HasOption(tools.OptionNeedsManagedHasher) ||
|
||||
tool.Info.HasOption(tools.OptionNeedsDedicatedHasher) {
|
||||
// add hash tool
|
||||
hashToolName, err := pickHashTool(fmt.Sprintf("Select hash tool for %s:", tool.Info.Name), tool.Info.SecurityLevel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
envelope.Tools = append(envelope.Tools, fmt.Sprintf("%s(%s)", tool.Info.Name, hashToolName))
|
||||
} else {
|
||||
envelope.Tools = append(envelope.Tools, signet.Scheme)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// make stubs
|
||||
selectedSignetStubs := make([]*jess.Signet, 0, len(selectedSignets))
|
||||
for _, signet := range selectedSignets {
|
||||
selectedSignetStubs = append(selectedSignetStubs, &jess.Signet{
|
||||
ID: signet.ID,
|
||||
})
|
||||
}
|
||||
|
||||
// add signets to envelope
|
||||
switch scope {
|
||||
case "pw", "key", "pw/key":
|
||||
envelope.Secrets = selectedSignetStubs
|
||||
case "recipient":
|
||||
envelope.Recipients = selectedSignetStubs
|
||||
case "sender":
|
||||
envelope.Senders = selectedSignetStubs
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func pickSignet(signetOptions []*jess.Signet, promptMsg, doneMsg string, multi bool, multiPreselected []*jess.Signet) ([]*jess.Signet, error) {
|
||||
// compile list
|
||||
signetSelection := make([][]string, 0, len(signetOptions)+1)
|
||||
var preSelected int
|
||||
if !multi && doneMsg != "" {
|
||||
signetSelection = append(signetSelection, []string{doneMsg})
|
||||
}
|
||||
if multi {
|
||||
for _, signet := range multiPreselected {
|
||||
signetSelection = append(signetSelection, []string{
|
||||
formatSignetName(signet),
|
||||
formatSignetType(signet),
|
||||
formatSignetScheme(signet),
|
||||
formatSignetPurpose(signet),
|
||||
formatSignetSecurityLevel(signet),
|
||||
signet.ID,
|
||||
})
|
||||
preSelected++
|
||||
}
|
||||
}
|
||||
signetOptionLoop:
|
||||
for _, signet := range signetOptions {
|
||||
// do not add pre-selected signets
|
||||
if multi {
|
||||
for _, preSelectedSignet := range multiPreselected {
|
||||
if signet.ID == preSelectedSignet.ID &&
|
||||
signet.Public == preSelectedSignet.Public {
|
||||
continue signetOptionLoop
|
||||
}
|
||||
}
|
||||
}
|
||||
signetSelection = append(signetSelection, []string{
|
||||
formatSignetName(signet),
|
||||
formatSignetType(signet),
|
||||
formatSignetScheme(signet),
|
||||
formatSignetPurpose(signet),
|
||||
formatSignetSecurityLevel(signet),
|
||||
signet.ID,
|
||||
})
|
||||
}
|
||||
|
||||
// select signet/s
|
||||
var selectedEntries []string
|
||||
if multi {
|
||||
formattedColumns := formatColumns(signetSelection)
|
||||
selectSignets := &survey.MultiSelect{
|
||||
Message: promptMsg,
|
||||
Options: formattedColumns,
|
||||
Default: formattedColumns[:preSelected],
|
||||
PageSize: 15,
|
||||
}
|
||||
err := survey.AskOne(selectSignets, &selectedEntries, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
var selectedEnty string
|
||||
selectSignet := &survey.Select{
|
||||
Message: promptMsg,
|
||||
Options: formatColumns(signetSelection),
|
||||
PageSize: 15,
|
||||
}
|
||||
err := survey.AskOne(selectSignet, &selectedEnty, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// check for done msg
|
||||
if strings.HasPrefix(selectedEnty, doneMsg+" ") {
|
||||
return nil, nil
|
||||
}
|
||||
selectedEntries = []string{selectedEnty}
|
||||
}
|
||||
|
||||
// get selected signet/s
|
||||
var selectedSignets []*jess.Signet
|
||||
selectedEntriesLoop:
|
||||
for _, entry := range selectedEntries {
|
||||
fields := strings.Fields(entry)
|
||||
id := fields[len(fields)-1] // last entry
|
||||
if multi {
|
||||
for _, signet := range multiPreselected {
|
||||
if id == signet.ID {
|
||||
selectedSignets = append(selectedSignets, signet)
|
||||
continue selectedEntriesLoop
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, signet := range signetOptions {
|
||||
if id == signet.ID {
|
||||
selectedSignets = append(selectedSignets, signet)
|
||||
continue selectedEntriesLoop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return selectedSignets, nil
|
||||
}
|
136
cmd/cfg-tools.go
Normal file
136
cmd/cfg-tools.go
Normal file
|
@ -0,0 +1,136 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/safing/jess/hashtools"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
|
||||
"github.com/AlecAivazis/survey"
|
||||
)
|
||||
|
||||
func pickTools(toolNames []string, promptMsg string) ([]string, error) {
|
||||
var toolSelection [][]string //nolint:prealloc
|
||||
preSelectedTools := make([]string, 0, len(toolNames))
|
||||
var preSelected int
|
||||
|
||||
// place already configured tools at top
|
||||
for _, toolName := range toolNames {
|
||||
toolID := toolName
|
||||
if strings.Contains(toolID, "(") {
|
||||
toolID = strings.Split(toolID, "(")[0]
|
||||
}
|
||||
|
||||
tool, err := tools.Get(toolID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
toolSelection = append(toolSelection, []string{
|
||||
toolName,
|
||||
tool.Info.FormatPurpose(),
|
||||
formatToolSecurityLevel(tool),
|
||||
tool.Info.Author,
|
||||
tool.Info.Comment,
|
||||
})
|
||||
preSelectedTools = append(preSelectedTools, tool.Info.Name)
|
||||
|
||||
preSelected++
|
||||
}
|
||||
|
||||
// add all other tools
|
||||
for _, tool := range tools.AsList() {
|
||||
if stringInSlice(tool.Info.Name, preSelectedTools) {
|
||||
continue
|
||||
}
|
||||
|
||||
toolSelection = append(toolSelection, []string{
|
||||
tool.Info.Name,
|
||||
tool.Info.FormatPurpose(),
|
||||
formatToolSecurityLevel(tool),
|
||||
tool.Info.Author,
|
||||
tool.Info.Comment,
|
||||
})
|
||||
}
|
||||
|
||||
// select
|
||||
var selectedEntries []string
|
||||
formattedColumns := formatColumns(toolSelection)
|
||||
selectTools := &survey.MultiSelect{
|
||||
Message: promptMsg,
|
||||
Options: formattedColumns,
|
||||
Default: formattedColumns[:preSelected],
|
||||
PageSize: 15,
|
||||
}
|
||||
err := survey.AskOne(selectTools, &selectedEntries, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// check selection
|
||||
newTools := make([]string, 0, len(selectedEntries))
|
||||
for _, entry := range selectedEntries {
|
||||
toolName := strings.Fields(entry)[0]
|
||||
if strings.Contains(toolName, "(") {
|
||||
newTools = append(newTools, toolName)
|
||||
continue
|
||||
}
|
||||
|
||||
// get tool
|
||||
tool, err := tools.Get(toolName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// check if tool needs hasher
|
||||
if tool.Info.HasOption(tools.OptionNeedsDedicatedHasher) ||
|
||||
tool.Info.HasOption(tools.OptionNeedsManagedHasher) {
|
||||
// add hash tool
|
||||
hashToolName, err := pickHashTool(fmt.Sprintf("Select hash tool for %s:", toolName), tool.Info.SecurityLevel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
newTools = append(newTools, fmt.Sprintf("%s(%s)", toolName, hashToolName))
|
||||
} else {
|
||||
newTools = append(newTools, toolName)
|
||||
}
|
||||
}
|
||||
|
||||
return newTools, nil
|
||||
}
|
||||
|
||||
func pickHashTool(prompt string, minSecurityLevel int) (string, error) {
|
||||
var hashToolSelection [][]string
|
||||
for _, hashTool := range hashtools.AsList() {
|
||||
if hashTool.SecurityLevel >= minSecurityLevel {
|
||||
hashToolSelection = append(hashToolSelection, []string{
|
||||
hashTool.Name,
|
||||
fmt.Sprintf("%d b/s", hashTool.SecurityLevel),
|
||||
hashTool.Author,
|
||||
hashTool.Comment,
|
||||
})
|
||||
}
|
||||
}
|
||||
var selectedEnty string
|
||||
selectHashTool := &survey.Select{
|
||||
Message: prompt,
|
||||
Options: formatColumns(hashToolSelection),
|
||||
PageSize: 15,
|
||||
}
|
||||
err := survey.AskOne(selectHashTool, &selectedEnty, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.Fields(selectedEnty)[0], nil
|
||||
}
|
||||
|
||||
func stringInSlice(s string, a []string) bool {
|
||||
for _, entry := range a {
|
||||
if entry == s {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
130
cmd/cmd-close.go
Normal file
130
cmd/cmd-close.go
Normal file
|
@ -0,0 +1,130 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(closeCmd)
|
||||
closeCmd.Flags().StringVarP(&closeFlagOutput, "output", "o", "", "specify output file")
|
||||
}
|
||||
|
||||
var (
|
||||
closeFlagOutput string
|
||||
closeCmdHelp = "usage: jess close <file> with <envelope name>"
|
||||
|
||||
closeCmd = &cobra.Command{
|
||||
Use: "close",
|
||||
Short: "encrypt file",
|
||||
PreRunE: requireTrustStore,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
registerPasswordCallbacks()
|
||||
|
||||
// check args
|
||||
if len(args) != 3 || args[1] != "with" {
|
||||
return errors.New(closeCmdHelp)
|
||||
}
|
||||
|
||||
// get envelope
|
||||
envelope, err := trustStore.GetEnvelope(args[2])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// create session (check envelope)
|
||||
session, err := envelope.Correspondence(trustStore)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// check filenames
|
||||
filename := args[0]
|
||||
outputFilename := closeFlagOutput
|
||||
if outputFilename == "" {
|
||||
if strings.HasSuffix(filename, ".letter") {
|
||||
return errors.New("cannot automatically derive output filename, please specify with --output")
|
||||
}
|
||||
outputFilename = filename + ".letter"
|
||||
}
|
||||
// check input file
|
||||
if filename != "-" {
|
||||
fileInfo, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if fileInfo.Size() > warnFileSize {
|
||||
confirmed, err := confirm("Input file is really big (%s) and jess needs to load it fully to memory, continue?", true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !confirmed {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
// check output file
|
||||
if outputFilename != "-" {
|
||||
_, err = os.Stat(outputFilename)
|
||||
if err == nil {
|
||||
confirmed, err := confirm("Output file already exists, overwrite?", true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !confirmed {
|
||||
return nil
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return fmt.Errorf("failed to access output file: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// load file
|
||||
var data []byte
|
||||
if filename == "-" {
|
||||
data, err = ioutil.ReadAll(os.Stdin)
|
||||
} else {
|
||||
data, err = ioutil.ReadFile(filename)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// encrypt
|
||||
letter, err := session.Close(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// to file format
|
||||
c, err := letter.ToFileFormat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// open file for writing
|
||||
var file *os.File
|
||||
if outputFilename == "-" {
|
||||
file = os.Stdout
|
||||
} else {
|
||||
file, err = os.OpenFile(outputFilename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// write
|
||||
err = c.WriteAllTo(file)
|
||||
if err != nil {
|
||||
file.Close()
|
||||
return err
|
||||
}
|
||||
return file.Close()
|
||||
},
|
||||
}
|
||||
)
|
53
cmd/cmd-configure.go
Normal file
53
cmd/cmd-configure.go
Normal file
|
@ -0,0 +1,53 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/safing/jess/truststores"
|
||||
|
||||
"github.com/safing/jess"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(configureCmd)
|
||||
}
|
||||
|
||||
var (
|
||||
configureCmd = &cobra.Command{
|
||||
Use: "configure",
|
||||
Short: "configure (and create) envelope",
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
PreRunE: requireTrustStore,
|
||||
RunE: func(cmd *cobra.Command, args []string) (err error) {
|
||||
// check envelope name existence
|
||||
if len(args) == 0 {
|
||||
return errors.New("please specify an envelope name")
|
||||
}
|
||||
envelopeName := args[0]
|
||||
|
||||
// check envelope name
|
||||
if !truststores.NamePlaysNiceWithFS(envelopeName) {
|
||||
return errors.New("please only use alphanumeric characters and `- ._+@` for best compatibility with various systems")
|
||||
}
|
||||
|
||||
// get envelope from trust store
|
||||
envelope, err := trustStore.GetEnvelope(envelopeName)
|
||||
if err != nil && err != jess.ErrEnvelopeNotFound {
|
||||
return err
|
||||
}
|
||||
|
||||
// create
|
||||
if envelope == nil {
|
||||
envelope, err = newEnvelope(envelopeName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// edit (and save)
|
||||
return editEnvelope(envelope)
|
||||
},
|
||||
}
|
||||
)
|
27
cmd/cmd-generate.go
Normal file
27
cmd/cmd-generate.go
Normal file
|
@ -0,0 +1,27 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(generateCmd)
|
||||
generateCmd.Flags().StringVarP(&generateFlagName, "name", "l", "", "specify signet name/label")
|
||||
generateCmd.Flags().StringVarP(&generateFlagScheme, "scheme", "t", "", "specify signet scheme/tool")
|
||||
}
|
||||
|
||||
var (
|
||||
generateFlagName string
|
||||
generateFlagScheme string
|
||||
|
||||
generateCmd = &cobra.Command{
|
||||
Use: "generate",
|
||||
Short: "generate a new signet",
|
||||
Args: cobra.NoArgs,
|
||||
PreRunE: requireTrustStore,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
_, err := newSignet(generateFlagName, generateFlagScheme)
|
||||
return err
|
||||
},
|
||||
}
|
||||
)
|
151
cmd/cmd-manage.go
Normal file
151
cmd/cmd-manage.go
Normal file
|
@ -0,0 +1,151 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/AlecAivazis/survey"
|
||||
"github.com/safing/jess"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const (
|
||||
failPlaceholder = "[fail]"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(manageCmd)
|
||||
}
|
||||
|
||||
var manageCmd = &cobra.Command{
|
||||
Use: "manage",
|
||||
Short: "manage a trust store",
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
PreRunE: requireTrustStore,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
// select action
|
||||
var selectedAction string
|
||||
selectAction := &survey.Select{
|
||||
Message: "Manage:",
|
||||
Options: []string{
|
||||
"Envelopes",
|
||||
"Signets",
|
||||
},
|
||||
PageSize: 15,
|
||||
}
|
||||
err := survey.AskOne(selectAction, &selectedAction, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch selectedAction {
|
||||
case "Envelopes":
|
||||
return manageEnvelopes()
|
||||
case "Signets":
|
||||
return manageSignets()
|
||||
default:
|
||||
fmt.Println("internal error")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func manageSignets() error {
|
||||
for {
|
||||
// get signets
|
||||
all, err := trustStore.SelectSignets(jess.FilterAny)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// select signet
|
||||
signets, err := pickSignet(all, "Select to manage:", "Done", false, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch len(signets) {
|
||||
case 0:
|
||||
return nil // selected done msg
|
||||
case 1:
|
||||
// valid
|
||||
default:
|
||||
return errors.New("internal error: failed to select signet")
|
||||
}
|
||||
selectedSignet := signets[0]
|
||||
|
||||
// select action
|
||||
var selectedAction string
|
||||
selectAction := &survey.Select{
|
||||
Message: "Select action:",
|
||||
Options: []string{
|
||||
"Delete",
|
||||
"Back to list",
|
||||
},
|
||||
PageSize: 15,
|
||||
}
|
||||
err = survey.AskOne(selectAction, &selectedAction, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch selectedAction {
|
||||
case "Delete":
|
||||
err = trustStore.DeleteSignet(selectedSignet.ID, selectedSignet.Public)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
case "Back to list":
|
||||
continue
|
||||
default:
|
||||
fmt.Println("internal error")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func manageEnvelopes() error {
|
||||
for {
|
||||
// get envelopes
|
||||
all, err := trustStore.AllEnvelopes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
selection := [][]string{
|
||||
{"Done"},
|
||||
}
|
||||
for _, envelope := range all {
|
||||
selection = append(selection, []string{
|
||||
envelope.Name,
|
||||
envelope.Requirements().ShortString(),
|
||||
formatEnvelopeSignets(envelope),
|
||||
})
|
||||
}
|
||||
|
||||
var selectedEnvelopeEntry string
|
||||
selectEnvelope := &survey.Select{
|
||||
Message: "Select to manage:",
|
||||
Options: formatColumns(selection),
|
||||
PageSize: 15,
|
||||
}
|
||||
err = survey.AskOne(selectEnvelope, &selectedEnvelopeEntry, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if strings.HasPrefix(selectedEnvelopeEntry, "Done") {
|
||||
return nil
|
||||
}
|
||||
|
||||
selectedEnvelopeName := strings.Fields(selectedEnvelopeEntry)[0]
|
||||
for _, envelope := range all {
|
||||
if envelope.Name == selectedEnvelopeName {
|
||||
err := editEnvelope(envelope)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
126
cmd/cmd-open.go
Normal file
126
cmd/cmd-open.go
Normal file
|
@ -0,0 +1,126 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/safing/portbase/container"
|
||||
|
||||
"github.com/safing/jess"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(openCmd)
|
||||
openCmd.Flags().StringVarP(&openFlagOutput, "output", "o", "", "specify output file")
|
||||
}
|
||||
|
||||
var (
|
||||
openFlagOutput string
|
||||
openCmdHelp = "usage: jess open <file>"
|
||||
|
||||
openCmd = &cobra.Command{
|
||||
Use: "open",
|
||||
Short: "decrypt a file",
|
||||
RunE: func(cmd *cobra.Command, args []string) (err error) {
|
||||
registerPasswordCallbacks()
|
||||
|
||||
// check args
|
||||
if len(args) != 1 {
|
||||
return errors.New(openCmdHelp)
|
||||
}
|
||||
|
||||
// check filenames
|
||||
filename := args[0]
|
||||
outputFilename := openFlagOutput
|
||||
if outputFilename == "" {
|
||||
if !strings.HasSuffix(filename, ".letter") || len(outputFilename) < 8 {
|
||||
return errors.New("cannot automatically derive output filename, please specify with --output")
|
||||
}
|
||||
outputFilename = strings.TrimSuffix(filename, ".letter")
|
||||
}
|
||||
// check input file
|
||||
if filename != "-" {
|
||||
fileInfo, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if fileInfo.Size() > warnFileSize {
|
||||
confirmed, err := confirm("Input file is really big (%s) and jess needs to load it fully to memory, continue?", true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !confirmed {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
// check output file
|
||||
if outputFilename != "-" {
|
||||
_, err = os.Stat(outputFilename)
|
||||
if err == nil {
|
||||
confirmed, err := confirm("Output file already exists, overwrite?", true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !confirmed {
|
||||
return nil
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return fmt.Errorf("failed to access output file: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// load file
|
||||
var data []byte
|
||||
if filename == "-" {
|
||||
data, err = ioutil.ReadAll(os.Stdin)
|
||||
} else {
|
||||
data, err = ioutil.ReadFile(filename)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// parse file
|
||||
letter, err := jess.LetterFromFileFormat(container.New(data))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// decrypt (and verify)
|
||||
plainText, err := letter.Open(requirements, trustStore)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// open file for writing
|
||||
var file *os.File
|
||||
if outputFilename == "-" {
|
||||
file = os.Stdout
|
||||
} else {
|
||||
file, err = os.OpenFile(outputFilename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// write
|
||||
n, err := file.Write(plainText)
|
||||
if err != nil {
|
||||
file.Close()
|
||||
return err
|
||||
}
|
||||
if n < len(plainText) {
|
||||
file.Close()
|
||||
return io.ErrShortWrite
|
||||
}
|
||||
return file.Close()
|
||||
},
|
||||
}
|
||||
)
|
53
cmd/cmd-tools.go
Normal file
53
cmd/cmd-tools.go
Normal file
|
@ -0,0 +1,53 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/safing/jess/hashtools"
|
||||
"github.com/safing/jess/tools"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(toolsCmd)
|
||||
}
|
||||
|
||||
var toolsCmd = &cobra.Command{
|
||||
Use: "tools",
|
||||
Short: "list all available tools",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Tools\n\n")
|
||||
toolTable := [][]string{
|
||||
{"Name/ID", "Purpose", "Security Level", "Author", "Comment"},
|
||||
}
|
||||
for _, tool := range tools.AsList() {
|
||||
toolTable = append(toolTable, []string{
|
||||
tool.Info.Name,
|
||||
tool.Info.FormatPurpose(),
|
||||
formatToolSecurityLevel(tool),
|
||||
tool.Info.Author,
|
||||
tool.Info.Comment,
|
||||
})
|
||||
}
|
||||
for _, line := range formatColumns(toolTable) {
|
||||
fmt.Println(line)
|
||||
}
|
||||
|
||||
fmt.Printf("\nHashTools\n\n")
|
||||
hashToolTable := [][]string{
|
||||
{"Name/ID", "Security Level", "Author", "Comment"},
|
||||
}
|
||||
for _, hashTool := range hashtools.AsList() {
|
||||
hashToolTable = append(hashToolTable, []string{
|
||||
hashTool.Name,
|
||||
fmt.Sprintf("%d b/s", hashTool.SecurityLevel),
|
||||
hashTool.Author,
|
||||
hashTool.Comment,
|
||||
})
|
||||
}
|
||||
for _, line := range formatColumns(hashToolTable) {
|
||||
fmt.Println(line)
|
||||
}
|
||||
},
|
||||
}
|
87
cmd/cmd-verify.go
Normal file
87
cmd/cmd-verify.go
Normal file
|
@ -0,0 +1,87 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"github.com/safing/portbase/container"
|
||||
|
||||
"github.com/safing/jess"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(verifyCmd)
|
||||
}
|
||||
|
||||
var (
|
||||
verifyCmdHelp = "usage: jess verify <file>"
|
||||
|
||||
verifyCmd = &cobra.Command{
|
||||
Use: "verify",
|
||||
Short: "verify a file",
|
||||
RunE: func(cmd *cobra.Command, args []string) (err error) {
|
||||
// check args
|
||||
if len(args) != 1 {
|
||||
return errors.New(verifyCmdHelp)
|
||||
}
|
||||
|
||||
// check filenames
|
||||
filename := args[0]
|
||||
// check input file
|
||||
if filename != "-" {
|
||||
fileInfo, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if fileInfo.Size() > warnFileSize {
|
||||
confirmed, err := confirm("Input file is really big (%s) and jess needs to load it fully to memory, continue?", true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !confirmed {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// load file
|
||||
var data []byte
|
||||
if filename == "-" {
|
||||
data, err = ioutil.ReadAll(os.Stdin)
|
||||
} else {
|
||||
data, err = ioutil.ReadFile(filename)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// parse file
|
||||
letter, err := jess.LetterFromFileFormat(container.New(data))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// adjust requirements
|
||||
if requirements == nil {
|
||||
requirements = jess.NewRequirements().
|
||||
Remove(jess.Confidentiality).
|
||||
Remove(jess.Integrity).
|
||||
Remove(jess.RecipientAuthentication)
|
||||
}
|
||||
|
||||
// verify
|
||||
err = letter.Verify(requirements, trustStore)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// success
|
||||
fmt.Println("ok")
|
||||
return nil
|
||||
},
|
||||
}
|
||||
)
|
21
cmd/cmd-version.go
Normal file
21
cmd/cmd-version.go
Normal file
|
@ -0,0 +1,21 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/safing/portbase/info"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(versionCmd)
|
||||
}
|
||||
|
||||
var versionCmd = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "print version information",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println(info.FullVersion())
|
||||
},
|
||||
}
|
33
cmd/doc.go
Normal file
33
cmd/doc.go
Normal file
|
@ -0,0 +1,33 @@
|
|||
/*
|
||||
CLI:
|
||||
|
||||
jess create <envelope file>
|
||||
|
||||
jess close <file> with <envelope file>
|
||||
encrypt a file, write to file with the same name, but with a .letter suffix
|
||||
-o <file> ... write output to <file>
|
||||
|
||||
jess open <file>
|
||||
decrypt a file, write to file with the same name, but without the .letter suffix
|
||||
-o <file> ... write output to <file>
|
||||
|
||||
jess sign <file> with <envelope>
|
||||
same as close, but will put the signature in a separate file called <file>.seal
|
||||
|
||||
jess verify <file>
|
||||
verifies the signature(s), but does not decrypt
|
||||
|
||||
jess show <file>
|
||||
shows all available information about said file. File can be
|
||||
- envelope
|
||||
- letter
|
||||
- seal (signature-only letter)
|
||||
|
||||
global arguments
|
||||
--tsdir /path/to/truststore
|
||||
--seclevel <uint>
|
||||
--symkeysize <uint>
|
||||
--quiet only output errors and warnings
|
||||
|
||||
*/
|
||||
package main
|
147
cmd/format.go
Normal file
147
cmd/format.go
Normal file
|
@ -0,0 +1,147 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
|
||||
"github.com/safing/jess"
|
||||
"github.com/safing/jess/tools"
|
||||
)
|
||||
|
||||
func formatColumns(table [][]string) []string {
|
||||
buf := bytes.NewBuffer(nil)
|
||||
|
||||
// format table with tab writer
|
||||
tabWriter := tabwriter.NewWriter(buf, 8, 4, 3, ' ', 0)
|
||||
for i := 0; i < len(table); i++ {
|
||||
if i > 0 {
|
||||
// linebreak
|
||||
fmt.Fprint(tabWriter, "\n")
|
||||
}
|
||||
fmt.Fprint(tabWriter, strings.Join(table[i], "\t"))
|
||||
}
|
||||
tabWriter.Flush()
|
||||
|
||||
// parse to []string
|
||||
var lines []string
|
||||
scanner := bufio.NewScanner(buf)
|
||||
for scanner.Scan() {
|
||||
lines = append(lines, scanner.Text())
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return lines
|
||||
}
|
||||
|
||||
func formatToolSecurityLevel(tool *tools.Tool) string {
|
||||
if tool.Info.HasOption(tools.OptionNeedsSecurityLevel) {
|
||||
return "dynamic b/s (set manually via --seclevel)"
|
||||
}
|
||||
if tool.Info.SecurityLevel == 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%d b/s", tool.Info.SecurityLevel)
|
||||
}
|
||||
|
||||
func formatSignetName(signet *jess.Signet) string {
|
||||
switch {
|
||||
case signet.Info != nil && signet.Info.Name != "":
|
||||
return signet.Info.Name
|
||||
case signet.ID != "":
|
||||
return signet.ID
|
||||
default:
|
||||
return "[unknown]"
|
||||
}
|
||||
}
|
||||
|
||||
func formatSignetType(signet *jess.Signet) string {
|
||||
switch {
|
||||
case signet.Scheme == jess.SignetSchemeKey:
|
||||
return "key"
|
||||
case signet.Scheme == jess.SignetSchemePassword:
|
||||
return "password"
|
||||
case signet.Public:
|
||||
return "recipient"
|
||||
default:
|
||||
return "signet"
|
||||
}
|
||||
}
|
||||
|
||||
func formatSignetScheme(signet *jess.Signet) string {
|
||||
switch signet.Scheme {
|
||||
case jess.SignetSchemeKey, jess.SignetSchemePassword:
|
||||
return ""
|
||||
default:
|
||||
return signet.Scheme
|
||||
}
|
||||
}
|
||||
|
||||
func formatSignetPurpose(signet *jess.Signet) string {
|
||||
switch signet.Scheme {
|
||||
case jess.SignetSchemeKey, jess.SignetSchemePassword:
|
||||
return ""
|
||||
}
|
||||
|
||||
tool, err := signet.Tool()
|
||||
if err != nil {
|
||||
return "[unknown]"
|
||||
}
|
||||
return tool.Info.FormatPurpose()
|
||||
}
|
||||
|
||||
func formatSignetSecurityLevel(signet *jess.Signet) string {
|
||||
switch signet.Scheme {
|
||||
case jess.SignetSchemeKey, jess.SignetSchemePassword:
|
||||
return ""
|
||||
}
|
||||
|
||||
tool, err := signet.Tool()
|
||||
if err != nil {
|
||||
return failPlaceholder
|
||||
}
|
||||
|
||||
securityLevel, err := tool.StaticLogic.SecurityLevel(signet)
|
||||
if err != nil {
|
||||
if err == tools.ErrProtected {
|
||||
return "[protected]"
|
||||
}
|
||||
return failPlaceholder
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%d b/s", securityLevel)
|
||||
}
|
||||
|
||||
func formatRequirements(envelope *jess.Envelope) string {
|
||||
attrs := envelope.Requirements()
|
||||
if attrs == nil || attrs.Empty() {
|
||||
return "none (unsafe)"
|
||||
}
|
||||
return attrs.String()
|
||||
}
|
||||
|
||||
func formatSignetNames(signets []*jess.Signet) string {
|
||||
names := make([]string, 0, len(signets))
|
||||
for _, signet := range signets {
|
||||
names = append(names, formatSignetName(signet))
|
||||
}
|
||||
return strings.Join(names, ", ")
|
||||
}
|
||||
|
||||
func formatEnvelopeSignets(envelope *jess.Envelope) string {
|
||||
var sections []string
|
||||
if len(envelope.Secrets) > 0 {
|
||||
sections = append(sections, fmt.Sprintf("Secrets: %s", formatSignetNames(envelope.Secrets)))
|
||||
}
|
||||
if len(envelope.Recipients) > 0 {
|
||||
sections = append(sections, fmt.Sprintf("To: %s", formatSignetNames(envelope.Recipients)))
|
||||
}
|
||||
if len(envelope.Senders) > 0 {
|
||||
sections = append(sections, fmt.Sprintf("From: %s", formatSignetNames(envelope.Senders)))
|
||||
}
|
||||
return strings.Join(sections, ", ")
|
||||
}
|
105
cmd/main.go
Normal file
105
cmd/main.go
Normal file
|
@ -0,0 +1,105 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/safing/jess/truststores"
|
||||
|
||||
"github.com/safing/jess"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/safing/portbase/info"
|
||||
// import all tools
|
||||
_ "github.com/safing/jess/tools/all"
|
||||
)
|
||||
|
||||
const (
|
||||
warnFileSize = 12000000 // 120MB
|
||||
)
|
||||
|
||||
var (
|
||||
rootCmd = &cobra.Command{
|
||||
Use: "jess",
|
||||
PersistentPreRunE: initGlobalFlags,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return cmd.Help()
|
||||
},
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
trustStoreDir string
|
||||
noSpec string
|
||||
minimumSecurityLevel = 0
|
||||
defaultSymmetricKeySize = 0
|
||||
|
||||
trustStore truststores.ExtendedTrustStore
|
||||
requirements = jess.NewRequirements()
|
||||
)
|
||||
|
||||
func main() {
|
||||
info.Set("jess", "v0.0.1", "GPLv3", true)
|
||||
|
||||
err := info.CheckVersion()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
rootCmd.PersistentFlags().StringVarP(&trustStoreDir, "tsdir", "d", "",
|
||||
"specify a truststore directory (default loaded from JESS_TSDIR env variable)",
|
||||
)
|
||||
rootCmd.PersistentFlags().StringVarP(&noSpec, "no", "n", "",
|
||||
"remove requirements using the abbreviations C, I, R, S",
|
||||
)
|
||||
|
||||
rootCmd.PersistentFlags().IntVarP(&minimumSecurityLevel, "seclevel", "s", 0, "specify a minimum security level")
|
||||
rootCmd.PersistentFlags().IntVarP(&defaultSymmetricKeySize, "symkeysize", "k", 0, "specify a default symmetric key size (only applies in certain conditions, use when prompted)")
|
||||
|
||||
err = rootCmd.Execute()
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
func initGlobalFlags(cmd *cobra.Command, args []string) (err error) {
|
||||
// trust store
|
||||
if trustStoreDir == "" {
|
||||
trustStoreDir, _ = os.LookupEnv("JESS_TSDIR")
|
||||
}
|
||||
if trustStoreDir != "" {
|
||||
var err error
|
||||
trustStore, err = truststores.NewDirTrustStore(trustStoreDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// requirements
|
||||
if noSpec != "" {
|
||||
requirements, err = jess.ParseRequirementsFromNoSpec(noSpec)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// security level and default key size
|
||||
if minimumSecurityLevel > 0 {
|
||||
jess.SetMinimumSecurityLevel(minimumSecurityLevel)
|
||||
}
|
||||
if defaultSymmetricKeySize > 0 {
|
||||
jess.SetDefaultKeySize(defaultSymmetricKeySize)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func requireTrustStore(cmd *cobra.Command, args []string) error {
|
||||
if trustStore == nil {
|
||||
return errors.New("please specify/configure a trust store")
|
||||
}
|
||||
return nil
|
||||
}
|
153
cmd/password.go
Normal file
153
cmd/password.go
Normal file
|
@ -0,0 +1,153 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/sha1" //nolint:gosec // required for HIBP API
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/safing/jess"
|
||||
|
||||
"github.com/AlecAivazis/survey"
|
||||
)
|
||||
|
||||
func registerPasswordCallbacks() {
|
||||
jess.SetPasswordCallbacks(createPasswordInterface, getPasswordInterface)
|
||||
}
|
||||
|
||||
func getPasswordInterface(signet *jess.Signet) error {
|
||||
pw, err := getPassword(formatSignetName(signet))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
signet.Key = []byte(pw)
|
||||
return nil
|
||||
}
|
||||
|
||||
func createPasswordInterface(signet *jess.Signet, minSecurityLevel int) error {
|
||||
pw, err := createPassword(formatSignetName(signet), minSecurityLevel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
signet.Key = []byte(pw)
|
||||
return nil
|
||||
}
|
||||
|
||||
func getPassword(reference string) (string, error) {
|
||||
// enter new pw
|
||||
var pw string
|
||||
prompt := &survey.Password{
|
||||
Message: makePrompt("Please enter password", reference),
|
||||
}
|
||||
err := survey.AskOne(prompt, &pw, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return pw, nil
|
||||
}
|
||||
|
||||
func createPassword(reference string, minSecurityLevel int) (string, error) {
|
||||
// enter new pw
|
||||
var pw1 string
|
||||
prompt := &survey.Password{
|
||||
Message: makePrompt("Please enter password", reference),
|
||||
}
|
||||
err := survey.AskOne(prompt, &pw1, func(val interface{}) error {
|
||||
pwVal, ok := val.(string)
|
||||
if !ok {
|
||||
return errors.New("input error")
|
||||
}
|
||||
// TODO: adapt interations based on tool
|
||||
pwSecLevel := jess.CalculatePasswordSecurityLevel(pwVal, 20000)
|
||||
if pwSecLevel < minSecurityLevel {
|
||||
return fmt.Errorf("please enter a stronger password, you only reached %d bits of security, while the envelope has a minimum of %d", pwSecLevel, minSecurityLevel)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// confirm
|
||||
var pw2 string
|
||||
prompt = &survey.Password{
|
||||
Message: makePrompt("Please confirm password", reference),
|
||||
}
|
||||
err = survey.AskOne(prompt, &pw2, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// check match
|
||||
if pw1 != pw2 {
|
||||
return "", errors.New("the entered passwords mismatch")
|
||||
}
|
||||
|
||||
// check password?
|
||||
check, err := confirm("Do you want to check if the password has been compromised in the past?", false)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if check {
|
||||
err := checkForWeakPassword(pw1)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
return pw1, nil
|
||||
}
|
||||
|
||||
func checkForWeakPassword(pw string) error {
|
||||
// check HIBP
|
||||
// docs: https://haveibeenpwned.com/API/v2#SearchingPwnedPasswordsByRange
|
||||
|
||||
// hash and split
|
||||
sum := sha1.Sum([]byte(pw)) //nolint:gosec // required for HIBP API
|
||||
hexSum := hex.EncodeToString(sum[:])
|
||||
prefix := strings.ToUpper(hexSum[:5])
|
||||
suffix := strings.ToUpper(hexSum[5:])
|
||||
|
||||
// request hash list
|
||||
resp, err := http.Get(fmt.Sprintf("https://api.pwnedpasswords.com/range/%s", prefix))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to contact HIBP service: %s", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// check if password is in hash list
|
||||
bodyReader := bufio.NewReader(resp.Body)
|
||||
scanner := bufio.NewScanner(bodyReader)
|
||||
cnt := 0
|
||||
for scanner.Scan() {
|
||||
if strings.HasPrefix(scanner.Text(), suffix) {
|
||||
log.Printf("%+v", scanner.Text())
|
||||
fields := strings.Split(scanner.Text(), ":")
|
||||
log.Printf("%+v", fields)
|
||||
if len(fields) >= 2 {
|
||||
//nolint:golint,stylecheck // is user error message
|
||||
return fmt.Errorf("password detected in HIBP database - it has been leaked %s times!", fields[1])
|
||||
}
|
||||
//nolint:golint,stylecheck // is user error message
|
||||
return errors.New("password detected in HIBP database - it has been leaked!")
|
||||
}
|
||||
cnt++
|
||||
}
|
||||
// fmt.Printf("checked %d leaked passwords\n", cnt)
|
||||
if err := scanner.Err(); err != nil {
|
||||
return fmt.Errorf("failed to read HIBP response: %s", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func makePrompt(prompt, reference string) string {
|
||||
if reference != "" {
|
||||
return fmt.Sprintf(`%s "%s":`, prompt, reference)
|
||||
}
|
||||
return fmt.Sprintf("%s:", prompt)
|
||||
}
|
23
cmd/password_test.go
Normal file
23
cmd/password_test.go
Normal file
|
@ -0,0 +1,23 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
//nolint:unused,deadcode // tested manually
|
||||
func testCfWP(t *testing.T, password string, expectedError string) {
|
||||
var errMsg string
|
||||
err := checkForWeakPassword(password)
|
||||
if err != nil {
|
||||
errMsg = err.Error()
|
||||
}
|
||||
if errMsg != expectedError {
|
||||
t.Errorf(`expected error "%s", got: "%s"`, expectedError, errMsg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckForWeakPassword(t *testing.T) {
|
||||
// TODO: only run these manually, es they actually require the live HIBP API.
|
||||
// testCfWP(t, "asdfasdfasdf", "")
|
||||
// testCfWP(t, "mfJLiQH9O9V9zXYrkNeYvGLvE14HcPyW7/sWWGfBX2nBU7c", "")
|
||||
}
|
18
cmd/utils.go
Normal file
18
cmd/utils.go
Normal file
|
@ -0,0 +1,18 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/AlecAivazis/survey"
|
||||
)
|
||||
|
||||
func confirm(promptMsg string, suggest bool) (bool, error) {
|
||||
confirmed := suggest
|
||||
prompt := &survey.Confirm{
|
||||
Message: promptMsg,
|
||||
Default: suggest,
|
||||
}
|
||||
err := survey.AskOne(prompt, &confirmed, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return confirmed, nil
|
||||
}
|
466
core-wire.go
Normal file
466
core-wire.go
Normal file
|
@ -0,0 +1,466 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// msgNo uint64
|
||||
// lastReKeyAtMsgNo uint64
|
||||
//
|
||||
// sendKeyCarryover []byte
|
||||
// recvKeyCarryover []byte
|
||||
//
|
||||
// handshakeState uint8
|
||||
// eKXSignetPairs [][2]*Signet
|
||||
// eKESignets []*Signet
|
||||
// newKey []byte
|
||||
|
||||
func (w *WireSession) sendHandshakeAndInitKDF(letter *Letter) error {
|
||||
var err error
|
||||
var keyMaterial [][]byte
|
||||
var burn bool
|
||||
|
||||
// process handshake
|
||||
switch w.handshakeState {
|
||||
case wireStateInit: // client
|
||||
keyMaterial, err = w.session.setupClosingKeyMaterial(letter)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to setup initial sending handshake key material: %s", err)
|
||||
}
|
||||
fallthrough
|
||||
|
||||
case wireStateIdle: // client and server
|
||||
if w.msgNo == 0 || (!w.server && w.reKeyNeeded()) {
|
||||
err = w.generateLocalKeyExchangeSignets(letter)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to generate local key exchange signets for initiating handshake: %s", err)
|
||||
}
|
||||
|
||||
err = w.generateLocalKeyEncapsulationSignets(letter)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to generate local key encapsulation signets for initiating handshake: %s", err)
|
||||
}
|
||||
|
||||
w.handshakeState = wireStateAwaitKey
|
||||
}
|
||||
|
||||
case wireStateSendKey: // server
|
||||
|
||||
err = w.generateLocalKeyExchangeSignets(letter)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to generate local key exchange signets for completing handshake: %s", err)
|
||||
}
|
||||
|
||||
// debugging:
|
||||
/*
|
||||
fmt.Println("key states:")
|
||||
for _, kxPair := range w.eKXSignets {
|
||||
fmt.Printf("kxPair: %+v\n", kxPair)
|
||||
fmt.Printf("signet: %+v\n", kxPair.signet)
|
||||
fmt.Printf("peer: %+v\n", kxPair.peer)
|
||||
}
|
||||
for _, kePair := range w.eKESignets {
|
||||
fmt.Printf("kePair: %+v\n", kePair)
|
||||
}
|
||||
*/
|
||||
|
||||
keyMaterial, err = w.makeSharedKeys(keyMaterial)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create shared keys for completing handshake: %s", err)
|
||||
}
|
||||
|
||||
err = w.generateLocalKeyEncapsulationSignets(letter)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to generate local key encapsulation signets for completing handshake: %s", err)
|
||||
}
|
||||
|
||||
keyMaterial, err = w.makeAndEncapsulateNewKeys(letter, keyMaterial)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encapsulate keys for completing handshake: %s", err)
|
||||
}
|
||||
|
||||
w.newKeyMaterial = copyKeyMaterial(keyMaterial)
|
||||
w.handshakeState = wireStatsAwaitApply
|
||||
|
||||
case wireStateSendApply: // client
|
||||
keyMaterial = append(keyMaterial, w.newKeyMaterial...)
|
||||
letter.ApplyKeys = true
|
||||
burn = true
|
||||
}
|
||||
|
||||
// add carryover key
|
||||
if w.msgNo == 0 {
|
||||
if w.session.DefaultSymmetricKeySize == 0 {
|
||||
return fmt.Errorf("missing default key size")
|
||||
}
|
||||
w.sendKeyCarryover = make([]byte, w.session.DefaultSymmetricKeySize)
|
||||
} else {
|
||||
keyMaterial = append(keyMaterial, w.sendKeyCarryover)
|
||||
}
|
||||
|
||||
// init KDF
|
||||
err = w.session.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to init %s kdf: %s", w.session.kdf.Info().Name, err)
|
||||
}
|
||||
|
||||
// derive new carryover key
|
||||
err = w.session.kdf.DeriveKeyWriteTo(w.sendKeyCarryover)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to iterate session key with %s: %s", w.session.kdf.Info().Name, err)
|
||||
}
|
||||
if w.msgNo == 0 {
|
||||
// copy initial sendkey to recvkey
|
||||
w.recvKeyCarryover = make([]byte, len(w.sendKeyCarryover))
|
||||
copy(w.recvKeyCarryover, w.sendKeyCarryover)
|
||||
}
|
||||
|
||||
// increase msg counter
|
||||
w.msgNo++
|
||||
|
||||
// burn and return
|
||||
if burn {
|
||||
return w.burnEphemeralKeys()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//nolint:gocognit
|
||||
func (w *WireSession) recvHandshakeAndInitKDF(letter *Letter) error {
|
||||
var err error
|
||||
var keyMaterial [][]byte
|
||||
var burn bool
|
||||
|
||||
// process handshake
|
||||
switch w.handshakeState {
|
||||
case wireStateInit: // server
|
||||
keyMaterial, err = w.session.setupOpeningKeyMaterial(letter)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to setup initial receiving handshake key material: %s", err)
|
||||
}
|
||||
fallthrough
|
||||
|
||||
case wireStateIdle: // server
|
||||
if len(letter.Keys) > 0 {
|
||||
// apply keys to pairs
|
||||
|
||||
// check if there are the right amount of keys
|
||||
if len(w.session.keyEncapsulators) == 0 {
|
||||
// TODO:
|
||||
// initial wire handshake is special:
|
||||
// key encapsulators send two seals in the initial handshake messages
|
||||
// one of them is added to the recipients
|
||||
// the other is a new ephermal key
|
||||
if len(letter.Keys) != len(w.eKXSignets)+len(w.eKESignets) {
|
||||
return errors.New("failed to setup initial receiving handshake: incorrect amount of keys in letter")
|
||||
}
|
||||
}
|
||||
|
||||
// assign keys to kx/ke pairs
|
||||
keyIndex := 0
|
||||
for _, kxPair := range w.eKXSignets {
|
||||
kxPair.peer = &Signet{
|
||||
Version: letter.Version,
|
||||
Key: letter.Keys[keyIndex].Value,
|
||||
Public: true,
|
||||
tool: kxPair.tool.Definition(),
|
||||
}
|
||||
keyIndex++
|
||||
}
|
||||
for _, kePair := range w.eKESignets {
|
||||
// skip keys with ID
|
||||
for letter.Keys[keyIndex].ID != "" {
|
||||
keyIndex++
|
||||
}
|
||||
kePair.signet = &Signet{
|
||||
Version: letter.Version,
|
||||
Key: letter.Keys[keyIndex].Value,
|
||||
Public: true,
|
||||
tool: kePair.tool.Definition(),
|
||||
}
|
||||
keyIndex++
|
||||
}
|
||||
|
||||
w.handshakeState = wireStateSendKey
|
||||
}
|
||||
|
||||
case wireStateAwaitKey: // client
|
||||
if len(letter.Keys) > 0 {
|
||||
// apply keys to pairs
|
||||
|
||||
// check if there are the right amount of keys
|
||||
if len(letter.Keys) != len(w.eKXSignets)+len(w.eKESignets) {
|
||||
return errors.New("incorrect amount of keys in letter")
|
||||
}
|
||||
|
||||
// assign keys to kx/ke pairs
|
||||
keyIndex := 0
|
||||
for _, kxPair := range w.eKXSignets {
|
||||
kxPair.peer = &Signet{
|
||||
Version: letter.Version,
|
||||
Key: letter.Keys[keyIndex].Value,
|
||||
Public: true,
|
||||
tool: kxPair.tool.Definition(),
|
||||
}
|
||||
keyIndex++
|
||||
}
|
||||
for _, kePair := range w.eKESignets {
|
||||
kePair.seal = letter.Keys[keyIndex]
|
||||
keyIndex++
|
||||
}
|
||||
|
||||
// make shared keys
|
||||
keyMaterial, err = w.makeSharedKeys(keyMaterial)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// unwrap keys
|
||||
keyMaterial, err = w.unwrapKeys(keyMaterial)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.newKeyMaterial = copyKeyMaterial(keyMaterial)
|
||||
w.handshakeState = wireStateSendApply
|
||||
}
|
||||
|
||||
case wireStatsAwaitApply: // server
|
||||
if letter.ApplyKeys {
|
||||
keyMaterial = append(keyMaterial, w.newKeyMaterial...)
|
||||
burn = true
|
||||
}
|
||||
}
|
||||
|
||||
// add carryover key
|
||||
if w.msgNo == 0 {
|
||||
if w.session.DefaultSymmetricKeySize == 0 {
|
||||
return fmt.Errorf("missing default key size")
|
||||
}
|
||||
w.recvKeyCarryover = make([]byte, w.session.DefaultSymmetricKeySize)
|
||||
} else {
|
||||
keyMaterial = append(keyMaterial, w.recvKeyCarryover)
|
||||
}
|
||||
|
||||
// init KDF
|
||||
err = w.session.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to init %s kdf: %s", w.session.kdf.Info().Name, err)
|
||||
}
|
||||
|
||||
// derive new carryover key
|
||||
err = w.session.kdf.DeriveKeyWriteTo(w.recvKeyCarryover)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to iterate session key with %s: %s", w.session.kdf.Info().Name, err)
|
||||
}
|
||||
if w.msgNo == 0 {
|
||||
// copy initial recvkey to sendkey
|
||||
w.sendKeyCarryover = make([]byte, len(w.recvKeyCarryover))
|
||||
copy(w.sendKeyCarryover, w.recvKeyCarryover)
|
||||
}
|
||||
|
||||
// increase msg counter
|
||||
w.msgNo++
|
||||
|
||||
// burn and return
|
||||
if burn {
|
||||
return w.burnEphemeralKeys()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *WireSession) generateLocalKeyExchangeSignets(letter *Letter) (err error) {
|
||||
for _, kxp := range w.eKXSignets {
|
||||
if kxp.signet == nil {
|
||||
// generate signet
|
||||
kxp.signet = NewSignetBase(kxp.tool.Definition())
|
||||
err := kxp.signet.GenerateKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// store signet
|
||||
err = kxp.signet.StoreKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// add to letter
|
||||
rcpt, err := kxp.signet.AsRecipient() // convert to public signet
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = rcpt.StoreKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
letter.Keys = append(letter.Keys, &Seal{
|
||||
Value: rcpt.Key,
|
||||
})
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *WireSession) makeSharedKeys(keyMaterial [][]byte) ([][]byte, error) {
|
||||
for _, kxp := range w.eKXSignets {
|
||||
// check signet
|
||||
if kxp.signet == nil {
|
||||
return nil, fmt.Errorf("missing key exchange signet for %s", kxp.tool.Info().Name)
|
||||
}
|
||||
// check peer signet
|
||||
if kxp.peer == nil {
|
||||
return nil, fmt.Errorf("missing key exchange recipient/peer for %s", kxp.tool.Info().Name)
|
||||
}
|
||||
|
||||
// load peer key
|
||||
err := kxp.peer.LoadKey()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// make shared key
|
||||
sharedKey, err := kxp.tool.MakeSharedKey(kxp.signet, kxp.peer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// append key to material
|
||||
keyMaterial = append(keyMaterial, sharedKey)
|
||||
}
|
||||
return keyMaterial, nil
|
||||
}
|
||||
|
||||
func (w *WireSession) generateLocalKeyEncapsulationSignets(letter *Letter) (err error) {
|
||||
for _, kep := range w.eKESignets {
|
||||
if kep.signet == nil {
|
||||
// generate signet
|
||||
kep.signet = NewSignetBase(kep.tool.Definition())
|
||||
err := kep.signet.GenerateKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// store signet
|
||||
err = kep.signet.StoreKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// add to letter
|
||||
rcpt, err := kep.signet.AsRecipient() // convert to public signet
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = rcpt.StoreKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
letter.Keys = append(letter.Keys, &Seal{
|
||||
Value: rcpt.Key,
|
||||
})
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *WireSession) makeAndEncapsulateNewKeys(letter *Letter, keyMaterial [][]byte) ([][]byte, error) {
|
||||
for _, kep := range w.eKESignets {
|
||||
// check signet
|
||||
if kep.signet == nil {
|
||||
return nil, fmt.Errorf("missing key encapsulation signet for %s", kep.tool.Info().Name)
|
||||
}
|
||||
|
||||
// load signet key
|
||||
err := kep.signet.LoadKey()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// generate new key
|
||||
newKey, err := RandomBytes(w.session.DefaultSymmetricKeySize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// encapsulate it
|
||||
encapsulatedKey, err := kep.tool.EncapsulateKey(newKey, kep.signet)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// add key to material and letter
|
||||
keyMaterial = append(keyMaterial, newKey)
|
||||
letter.Keys = append(letter.Keys, &Seal{Value: encapsulatedKey})
|
||||
}
|
||||
return keyMaterial, nil
|
||||
}
|
||||
|
||||
func (w *WireSession) unwrapKeys(keyMaterial [][]byte) ([][]byte, error) {
|
||||
for _, kep := range w.eKESignets {
|
||||
// check signet
|
||||
if kep.signet == nil {
|
||||
return nil, fmt.Errorf("missing key encapsulation signet for %s", kep.tool.Info().Name)
|
||||
}
|
||||
// check seal
|
||||
if kep.seal == nil {
|
||||
return nil, fmt.Errorf("missing key encapsulation seal for %s", kep.tool.Info().Name)
|
||||
}
|
||||
|
||||
// unwrap key
|
||||
unwrappedKey, err := kep.tool.UnwrapKey(kep.seal.Value, kep.signet)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// add key to material
|
||||
keyMaterial = append(keyMaterial, unwrappedKey)
|
||||
}
|
||||
return keyMaterial, nil
|
||||
}
|
||||
|
||||
// burnEphemeralKeys burns all the ephemeral key material in the session.
|
||||
func (w *WireSession) burnEphemeralKeys() error {
|
||||
var lastErr error
|
||||
|
||||
// burn key exchange signets
|
||||
for _, entry := range w.eKXSignets {
|
||||
if entry.signet != nil {
|
||||
lastErr = entry.signet.Burn()
|
||||
}
|
||||
entry.signet = nil
|
||||
if entry.peer != nil {
|
||||
lastErr = entry.peer.Burn()
|
||||
}
|
||||
entry.peer = nil
|
||||
}
|
||||
|
||||
// burn key encapsulation signets
|
||||
for _, entry := range w.eKESignets {
|
||||
if entry.signet != nil {
|
||||
lastErr = entry.signet.Burn()
|
||||
}
|
||||
entry.signet = nil
|
||||
if entry.seal != nil {
|
||||
Burn(entry.seal.Value)
|
||||
}
|
||||
entry.seal = nil
|
||||
}
|
||||
|
||||
// burn new key material
|
||||
for _, part := range w.newKeyMaterial {
|
||||
Burn(part)
|
||||
}
|
||||
w.newKeyMaterial = nil
|
||||
|
||||
return lastErr
|
||||
}
|
||||
|
||||
func copyKeyMaterial(keyMaterial [][]byte) [][]byte {
|
||||
new := make([][]byte, len(keyMaterial))
|
||||
for index, part := range keyMaterial {
|
||||
newPart := make([]byte, len(part))
|
||||
copy(newPart, part)
|
||||
new[index] = newPart
|
||||
}
|
||||
return new
|
||||
}
|
241
core-wire_test.go
Normal file
241
core-wire_test.go
Normal file
|
@ -0,0 +1,241 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/safing/portbase/container"
|
||||
)
|
||||
|
||||
func TestWire(t *testing.T) {
|
||||
wireReKeyAfterMsgs = 100
|
||||
|
||||
testWireCorrespondence(t, RecommendedNetwork, testData1)
|
||||
testWireCorrespondence(t, RecommendedNetwork, testData2)
|
||||
|
||||
testWireCorrespondence(t, []string{"ECDH-P224", "HKDF(SHA2-256)", "CHACHA20-POLY1305"}, testData1)
|
||||
testWireCorrespondence(t, []string{"ECDH-P256", "HKDF(SHA2-256)", "CHACHA20-POLY1305"}, testData1)
|
||||
testWireCorrespondence(t, []string{"ECDH-P384", "HKDF(SHA2-256)", "CHACHA20-POLY1305"}, testData1)
|
||||
testWireCorrespondence(t, []string{"ECDH-P521", "HKDF(SHA2-256)", "CHACHA20-POLY1305"}, testData1)
|
||||
testWireCorrespondence(t, []string{"RSA-OAEP(SHA2-256)", "HKDF(SHA2-256)", "CHACHA20-POLY1305"}, testData1)
|
||||
}
|
||||
|
||||
func testWireCorrespondence(t *testing.T, toolIDs []string, testData string) {
|
||||
wtr := &wireTestRange{t: t}
|
||||
wtr.init(toolIDs, testData)
|
||||
fmt.Printf("\n\nsimulating %v\n", toolIDs)
|
||||
fmt.Println("two dots are one packet send+recv:")
|
||||
|
||||
fmt.Println("\nclient ->")
|
||||
wtr.clientSend()
|
||||
|
||||
fmt.Println("\n-> server")
|
||||
wtr.serverRecv()
|
||||
|
||||
wtr.clientSend()
|
||||
wtr.serverRecv()
|
||||
|
||||
fmt.Println("\n<- server")
|
||||
wtr.serverSend()
|
||||
|
||||
fmt.Println("\nclient <-")
|
||||
wtr.clientRecv()
|
||||
|
||||
for i := 0; i < 100; i++ {
|
||||
// up
|
||||
wtr.clientSend()
|
||||
wtr.serverRecv()
|
||||
wtr.clientSend()
|
||||
wtr.serverRecv()
|
||||
// down
|
||||
wtr.serverSend()
|
||||
wtr.clientRecv()
|
||||
wtr.serverSend()
|
||||
wtr.clientRecv()
|
||||
}
|
||||
|
||||
for i := 0; i < 100; i++ {
|
||||
// up
|
||||
wtr.clientSend()
|
||||
wtr.serverRecv()
|
||||
|
||||
// down
|
||||
wtr.serverSend()
|
||||
wtr.clientRecv()
|
||||
wtr.serverSend()
|
||||
wtr.clientRecv()
|
||||
wtr.serverSend()
|
||||
wtr.clientRecv()
|
||||
}
|
||||
|
||||
wtr.endTime = time.Now()
|
||||
overhead := ((float64(wtr.bytesOnWire) / float64(wtr.bytesTransferred)) - 1) * 100
|
||||
duration := wtr.endTime.Sub(wtr.startTime)
|
||||
t.Logf(
|
||||
"%v tested: msgsize=%d, rekey every %d msgs, %d msgs, %d bytes, +%f%% overhead, %s, %s per msg, %f Mbit/s",
|
||||
wtr.toolIDs,
|
||||
len(testData),
|
||||
wireReKeyAfterMsgs,
|
||||
wtr.msgsTransferred,
|
||||
wtr.bytesTransferred,
|
||||
overhead,
|
||||
duration,
|
||||
time.Duration(duration.Nanoseconds()/int64(wtr.msgsTransferred)),
|
||||
float64(wtr.bytesTransferred*8/1000000)/duration.Seconds(),
|
||||
)
|
||||
}
|
||||
|
||||
// TODO
|
||||
// func benchmarkWireCorrespondence(t *testing.T, toolIDs []string) {
|
||||
// }
|
||||
|
||||
type wireTestRange struct {
|
||||
t *testing.T
|
||||
toolIDs []string
|
||||
testData string
|
||||
|
||||
client *Session
|
||||
server *Session
|
||||
|
||||
clientToServer chan *container.Container
|
||||
serverToClient chan *container.Container
|
||||
|
||||
msgsTransferred int
|
||||
bytesTransferred int
|
||||
bytesOnWire int
|
||||
startTime time.Time
|
||||
endTime time.Time
|
||||
}
|
||||
|
||||
func (wtr *wireTestRange) init(toolIDs []string, testData string) (detectedInvalid bool) {
|
||||
wtr.toolIDs = toolIDs
|
||||
|
||||
e, err := setupEnvelopeAndTrustStore(wtr.t, wtr.toolIDs)
|
||||
if err != nil {
|
||||
wtr.t.Fatalf("%v failed to setup envelope: %s", wtr.toolIDs, err)
|
||||
return false
|
||||
}
|
||||
if e == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
wtr.client, err = e.WireCorrespondence(testTrustStore)
|
||||
if err != nil {
|
||||
wtr.t.Fatalf("%v failed to init client session: %s", wtr.toolIDs, err)
|
||||
}
|
||||
|
||||
// setup and reset
|
||||
wtr.testData = testData
|
||||
wtr.server = nil
|
||||
wtr.clientToServer = make(chan *container.Container, 1000)
|
||||
wtr.serverToClient = make(chan *container.Container, 1000)
|
||||
wtr.msgsTransferred = 0
|
||||
wtr.bytesTransferred = 0
|
||||
wtr.bytesOnWire = 0
|
||||
wtr.startTime = time.Now()
|
||||
wtr.endTime = time.Time{}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (wtr *wireTestRange) clientSend() {
|
||||
letter, err := wtr.client.Close([]byte(wtr.testData))
|
||||
if err != nil {
|
||||
wtr.t.Fatalf("%v failed to close: %s", wtr.toolIDs, err)
|
||||
}
|
||||
|
||||
wireData, err := letter.ToWire()
|
||||
if err != nil {
|
||||
wtr.t.Fatalf("%v failed to serialize to wire: %s", wtr.toolIDs, err)
|
||||
}
|
||||
|
||||
select {
|
||||
case wtr.clientToServer <- wireData:
|
||||
default:
|
||||
wtr.t.Fatalf("%v could not send to server", wtr.toolIDs)
|
||||
}
|
||||
|
||||
fmt.Print(".")
|
||||
}
|
||||
|
||||
func (wtr *wireTestRange) serverRecv() {
|
||||
select {
|
||||
case wireData := <-wtr.clientToServer:
|
||||
wtr.msgsTransferred++
|
||||
wtr.bytesOnWire += wireData.Length()
|
||||
|
||||
letter, err := LetterFromWire(wireData)
|
||||
if err != nil {
|
||||
wtr.t.Fatalf("%v failed to parse initial wired letter: %s", wtr.toolIDs, err)
|
||||
}
|
||||
|
||||
if wtr.server == nil {
|
||||
wtr.server, err = letter.WireCorrespondence(testTrustStore)
|
||||
if err != nil {
|
||||
wtr.t.Fatalf("%v failed to init server session: %s", wtr.toolIDs, err)
|
||||
}
|
||||
}
|
||||
|
||||
origData, err := wtr.server.Open(letter)
|
||||
if err != nil {
|
||||
wtr.t.Fatalf("%v failed to open: %s", wtr.toolIDs, err)
|
||||
}
|
||||
wtr.bytesTransferred += len(origData)
|
||||
|
||||
if string(origData) != wtr.testData {
|
||||
wtr.t.Fatalf("%v testdata mismatch", wtr.toolIDs)
|
||||
}
|
||||
default:
|
||||
wtr.t.Fatalf("%v could not recv from client", wtr.toolIDs)
|
||||
}
|
||||
|
||||
fmt.Print(".")
|
||||
}
|
||||
|
||||
func (wtr *wireTestRange) serverSend() {
|
||||
letter, err := wtr.server.Close([]byte(wtr.testData))
|
||||
if err != nil {
|
||||
wtr.t.Fatalf("%v failed to close: %s", wtr.toolIDs, err)
|
||||
}
|
||||
|
||||
wireData, err := letter.ToWire()
|
||||
if err != nil {
|
||||
wtr.t.Fatalf("%v failed to serialize to wire: %s", wtr.toolIDs, err)
|
||||
}
|
||||
|
||||
select {
|
||||
case wtr.serverToClient <- wireData:
|
||||
default:
|
||||
wtr.t.Fatalf("%v could not send to client", wtr.toolIDs)
|
||||
}
|
||||
|
||||
fmt.Print(".")
|
||||
}
|
||||
|
||||
func (wtr *wireTestRange) clientRecv() {
|
||||
select {
|
||||
case wireData := <-wtr.serverToClient:
|
||||
wtr.msgsTransferred++
|
||||
wtr.bytesOnWire += wireData.Length()
|
||||
|
||||
letter, err := LetterFromWire(wireData)
|
||||
if err != nil {
|
||||
wtr.t.Fatalf("%v failed to parse initial wired letter: %s", wtr.toolIDs, err)
|
||||
}
|
||||
|
||||
origData, err := wtr.client.Open(letter)
|
||||
if err != nil {
|
||||
wtr.t.Fatalf("%v failed to open: %s", wtr.toolIDs, err)
|
||||
}
|
||||
wtr.bytesTransferred += len(origData)
|
||||
|
||||
if string(origData) != wtr.testData {
|
||||
wtr.t.Fatalf("%v testdata mismatch", wtr.toolIDs)
|
||||
}
|
||||
default:
|
||||
wtr.t.Fatalf("%v could not recv from server", wtr.toolIDs)
|
||||
}
|
||||
|
||||
fmt.Print(".")
|
||||
}
|
663
core.go
Normal file
663
core.go
Normal file
|
@ -0,0 +1,663 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/safing/portbase/container"
|
||||
)
|
||||
|
||||
// Close encrypts (and possibly signs) the given data and returns a Letter. Storyline: Close takes an envelope, inserts the message and closes it, resulting in a letter.
|
||||
func (s *Session) Close(data []byte) (*Letter, error) { //nolint:gocognit
|
||||
var err error
|
||||
var associatedData []byte
|
||||
letter := &Letter{}
|
||||
|
||||
if s.wire == nil || s.wire.msgNo == 0 {
|
||||
letter.Version = 1
|
||||
letter.Tools = s.envelope.Tools
|
||||
}
|
||||
|
||||
/////////////////
|
||||
// key management
|
||||
/////////////////
|
||||
|
||||
// create nonce
|
||||
nonce, err := RandomBytes(s.NonceSize())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get nonce: %s", err)
|
||||
}
|
||||
letter.Nonce = nonce
|
||||
|
||||
if s.kdf != nil {
|
||||
// if we require a key
|
||||
|
||||
// key establishment
|
||||
if s.wire != nil {
|
||||
err = s.wire.sendHandshakeAndInitKDF(letter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
keyMaterial, err := s.setupClosingKeyMaterial(letter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// init KDF
|
||||
err = s.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to init %s kdf: %s", s.kdf.Info().Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
/////////////
|
||||
// encryption
|
||||
/////////////
|
||||
|
||||
// setup tools
|
||||
err = s.setup()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer s.reset() //nolint:errcheck // TODO: handle error? Currently there should be none.
|
||||
|
||||
// Ciphers
|
||||
for _, tool := range s.ciphers {
|
||||
data, err = tool.Encrypt(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to encrypt with %s: %s", tool.Info().Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
// build associated data
|
||||
if len(s.integratedCiphers) > 0 || len(s.macs) > 0 {
|
||||
associatedData = letter.compileAssociatedData()
|
||||
}
|
||||
|
||||
// Integrated Ciphers / AEAD
|
||||
for _, tool := range s.integratedCiphers {
|
||||
data, err = tool.AuthenticatedEncrypt(data, associatedData)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to auth-encrypt with %s: %s", tool.Info().Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(s.macs) > 0 {
|
||||
// run managed mac hashers
|
||||
if s.managedMACHashers != nil {
|
||||
err = s.feedManagedHashers(s.managedMACHashers, data, associatedData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer s.resetManagedHashers(s.managedMACHashers)
|
||||
}
|
||||
|
||||
// run MAC tools
|
||||
allMacs := container.New()
|
||||
for _, tool := range s.macs {
|
||||
mac, err := tool.MAC(data, associatedData)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to calculate MAC with %s: %s", tool.Info().Name, err)
|
||||
}
|
||||
allMacs.Append(mac)
|
||||
}
|
||||
letter.Mac = allMacs.CompileData()
|
||||
}
|
||||
|
||||
} else if len(s.ciphers) > 0 || len(s.integratedCiphers) > 0 || len(s.macs) > 0 {
|
||||
// check if there is really nothing to do with a key
|
||||
return nil, errors.New("missing a kdf tool")
|
||||
}
|
||||
|
||||
// data processing is complete
|
||||
letter.Data = data
|
||||
|
||||
// Signature
|
||||
if len(s.signers) > 0 {
|
||||
associatedSigningData := letter.compileAssociatedSigningData(associatedData)
|
||||
|
||||
// run managed signing hashers
|
||||
if s.managedSigningHashers != nil {
|
||||
err = s.feedManagedHashers(s.managedSigningHashers, data, associatedSigningData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer s.resetManagedHashers(s.managedSigningHashers)
|
||||
}
|
||||
|
||||
// run signers
|
||||
for _, tool := range s.signers {
|
||||
//nolint:scopelint // function is executed immediately within loop
|
||||
err = s.envelope.LoopSenders(tool.Info().Name, func(signet *Signet) error {
|
||||
|
||||
sig, err := tool.Sign(data, associatedSigningData, signet)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to sign with %s: %s", tool.Info().Name, err)
|
||||
}
|
||||
|
||||
letter.Signatures = append(letter.Signatures, &Seal{
|
||||
Scheme: tool.Info().Name,
|
||||
ID: signet.ID,
|
||||
Value: sig,
|
||||
})
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return letter, nil
|
||||
}
|
||||
|
||||
// Open decrypts (and possibly verifies) the given letter and returns the original data. Storyline: Open takes a letter, checks any seals, opens it and returns the message.
|
||||
func (s *Session) Open(letter *Letter) ([]byte, error) { //nolint:gocognit,gocyclo
|
||||
|
||||
// debugging:
|
||||
/*
|
||||
fmt.Printf("opening: %+v\n", letter)
|
||||
for _, seal := range letter.Keys {
|
||||
fmt.Printf("key: %+v\n", seal)
|
||||
}
|
||||
*/
|
||||
|
||||
var err error
|
||||
if s.wire == nil && letter.Version != 1 {
|
||||
return nil, fmt.Errorf("unsupported letter version: %d", letter.Version)
|
||||
}
|
||||
|
||||
/////////
|
||||
// verify
|
||||
/////////
|
||||
|
||||
// TODO: signature verification is run before tool setup. Currently, this is ok, but might change in the future. This might break additional signing algorithms that actually need setup.
|
||||
|
||||
data := letter.Data
|
||||
|
||||
// build associated data
|
||||
var associatedData []byte
|
||||
if len(s.integratedCiphers) > 0 || len(s.macs) > 0 {
|
||||
associatedData = letter.compileAssociatedData()
|
||||
}
|
||||
|
||||
// Signature
|
||||
if len(s.signers) > 0 {
|
||||
associatedSigningData := letter.compileAssociatedSigningData(associatedData)
|
||||
|
||||
// run managed signing hashers
|
||||
if s.managedSigningHashers != nil {
|
||||
err = s.feedManagedHashers(s.managedSigningHashers, data, associatedSigningData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer s.resetManagedHashers(s.managedSigningHashers)
|
||||
}
|
||||
|
||||
// run signers
|
||||
if len(s.envelope.Senders) != len(letter.Signatures) {
|
||||
return nil, errors.New("mismatch regarding available signatures and senders")
|
||||
}
|
||||
sigIndex := 0
|
||||
|
||||
for _, tool := range s.signers {
|
||||
//nolint:scopelint // function is executed immediately within loop
|
||||
err = s.envelope.LoopSenders(tool.Info().Name, func(signet *Signet) error {
|
||||
|
||||
err := tool.Verify(data, associatedSigningData, letter.Signatures[sigIndex].Value, signet)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to verify signature (%s) with ID %s: %s", tool.Info().Name, letter.Signatures[sigIndex].ID, err)
|
||||
}
|
||||
|
||||
sigIndex++
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// end early if we are only verifying sigs
|
||||
if s.kdf == nil {
|
||||
// check if there is really nothing to do with a key
|
||||
if len(s.ciphers) > 0 || len(s.integratedCiphers) > 0 || len(s.macs) > 0 {
|
||||
return nil, errors.New("missing a kdf tool")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
/////////////////
|
||||
// key management
|
||||
/////////////////
|
||||
|
||||
// key establishment
|
||||
if s.wire != nil {
|
||||
err = s.wire.recvHandshakeAndInitKDF(letter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
keyMaterial, err := s.setupOpeningKeyMaterial(letter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// init KDF
|
||||
err = s.kdf.InitKeyDerivation(letter.Nonce, keyMaterial...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to init %s kdf: %s", s.kdf.Info().Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
/////////////
|
||||
// decryption
|
||||
/////////////
|
||||
|
||||
// setup tools
|
||||
err = s.setup()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer s.reset() //nolint:errcheck // TODO: handle error? Currently there should be none.
|
||||
|
||||
// MAC
|
||||
if len(s.macs) > 0 {
|
||||
// run managed mac hashers
|
||||
if s.managedMACHashers != nil {
|
||||
err = s.feedManagedHashers(s.managedMACHashers, data, associatedData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer s.resetManagedHashers(s.managedMACHashers)
|
||||
}
|
||||
|
||||
// run MAC tools
|
||||
allMacs := container.New()
|
||||
for _, tool := range s.macs {
|
||||
mac, err := tool.MAC(data, associatedData)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to calculate MAC with %s: %s", tool.Info().Name, err)
|
||||
}
|
||||
allMacs.Append(mac)
|
||||
}
|
||||
if subtle.ConstantTimeCompare(letter.Mac, allMacs.CompileData()) != 1 {
|
||||
return nil, fmt.Errorf("%w: MAC verification failed", ErrIntegrityViolation)
|
||||
}
|
||||
}
|
||||
|
||||
// Integrated Ciphers / AEAD (in reversed order)
|
||||
for i := len(s.integratedCiphers) - 1; i >= 0; i-- {
|
||||
data, err = s.integratedCiphers[i].AuthenticatedDecrypt(data, associatedData)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: [%s] %s", ErrIntegrityViolation, s.integratedCiphers[i].Info().Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Ciphers (in reversed order)
|
||||
for i := len(s.ciphers) - 1; i >= 0; i-- {
|
||||
data, err = s.ciphers[i].Decrypt(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: decryption failed: [%s] %s", ErrIntegrityViolation, s.ciphers[i].Info().Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// Verify verifies signatures of the given letter.
|
||||
func (s *Session) Verify(letter *Letter) error {
|
||||
var err error
|
||||
if s.wire == nil && letter.Version != 1 {
|
||||
return fmt.Errorf("unsupported letter version: %d", letter.Version)
|
||||
}
|
||||
|
||||
/////////
|
||||
// verify
|
||||
/////////
|
||||
|
||||
if len(s.signers) == 0 {
|
||||
return errors.New("letter is not signed")
|
||||
}
|
||||
|
||||
data := letter.Data
|
||||
associatedSigningData := letter.compileAssociatedSigningData(nil)
|
||||
|
||||
// run managed signing hashers
|
||||
if s.managedSigningHashers != nil {
|
||||
err = s.feedManagedHashers(s.managedSigningHashers, data, associatedSigningData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer s.resetManagedHashers(s.managedSigningHashers)
|
||||
}
|
||||
|
||||
// run signers
|
||||
if len(s.envelope.Senders) != len(letter.Signatures) {
|
||||
return errors.New("mismatch regarding available signatures and senders")
|
||||
}
|
||||
sigIndex := 0
|
||||
|
||||
for _, tool := range s.signers {
|
||||
//nolint:scopelint // function is executed immediately within loop
|
||||
err = s.envelope.LoopSenders(tool.Info().Name, func(signet *Signet) error {
|
||||
|
||||
err := tool.Verify(data, associatedSigningData, letter.Signatures[sigIndex].Value, signet)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to verify signature (%s) with ID %s: %s", tool.Info().Name, letter.Signatures[sigIndex].ID, err)
|
||||
}
|
||||
|
||||
sigIndex++
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Session) setupClosingKeyMaterial(letter *Letter) ([][]byte, error) {
|
||||
signetsUsed := 0
|
||||
var keyMaterial [][]byte
|
||||
|
||||
// add raw keys
|
||||
_ = s.envelope.LoopSecrets(SignetSchemeKey, func(signet *Signet) error {
|
||||
letter.Keys = append(letter.Keys, &Seal{
|
||||
Scheme: SignetSchemeKey,
|
||||
ID: signet.ID,
|
||||
})
|
||||
|
||||
keyMaterial = append(keyMaterial, signet.Key)
|
||||
signetsUsed++
|
||||
return nil
|
||||
})
|
||||
|
||||
// add passwords
|
||||
err := s.envelope.LoopSecrets(SignetSchemePassword, func(signet *Signet) error {
|
||||
if len(signet.Key) == 0 {
|
||||
return fmt.Errorf("signet [%s] is missing it's password", signet.ID)
|
||||
}
|
||||
pwKey, err := s.passDerivator.DeriveKeyFromPassword(signet.Key, letter.Nonce)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get derive key from password with %s: %s", s.passDerivator.Info().Name, err)
|
||||
}
|
||||
letter.Keys = append(letter.Keys, &Seal{
|
||||
Scheme: SignetSchemePassword,
|
||||
ID: signet.ID,
|
||||
})
|
||||
|
||||
keyMaterial = append(keyMaterial, pwKey)
|
||||
signetsUsed++
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// add key exchange
|
||||
for _, tool := range s.keyExchangers {
|
||||
//nolint:scopelint // function is executed immediately within loop
|
||||
err = s.envelope.LoopRecipients(tool.Info().Name, func(recipient *Signet) error {
|
||||
// generate new sender exchange signet
|
||||
senderSignet := NewSignetBase(tool.Definition())
|
||||
err := senderSignet.GenerateKey()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to generate new sender signet for %s: %s", tool.Info().Name, err)
|
||||
}
|
||||
|
||||
// create exchange and add to letter
|
||||
exchKey, err := tool.MakeSharedKey(senderSignet, recipient)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to make managed key with %s: %s", tool.Info().Name, err)
|
||||
}
|
||||
|
||||
// add to letter
|
||||
senderRcpt, err := senderSignet.AsRecipient() // convert to public signet
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get public sender signet for %s: %s", tool.Info().Name, err)
|
||||
}
|
||||
err = senderRcpt.StoreKey()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to serialize sender public key for %s: %s", tool.Info().Name, err)
|
||||
}
|
||||
letter.Keys = append(letter.Keys, &Seal{
|
||||
ID: recipient.ID,
|
||||
Value: senderRcpt.Key,
|
||||
})
|
||||
|
||||
// save sender signet to state (or burn)
|
||||
if s.wire == nil {
|
||||
_ = senderSignet.Burn()
|
||||
} else {
|
||||
s.wire.eKXSignets = append(s.wire.eKXSignets, &kxPair{
|
||||
tool: tool,
|
||||
signet: senderSignet,
|
||||
})
|
||||
}
|
||||
|
||||
// add key
|
||||
keyMaterial = append(keyMaterial, exchKey)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// add key encapsulation
|
||||
for _, tool := range s.keyEncapsulators {
|
||||
//nolint:scopelint // function is executed immediately within loop
|
||||
err = s.envelope.LoopRecipients(tool.Info().Name, func(recipient *Signet) error {
|
||||
// save to state
|
||||
if s.wire != nil {
|
||||
s.wire.eKESignets = append(s.wire.eKESignets, &kePair{
|
||||
tool: tool,
|
||||
})
|
||||
}
|
||||
|
||||
// generate new key
|
||||
newKey, err := RandomBytes(tool.Helper().DefaultSymmetricKeySize())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to generate new key for %s: %s", tool.Info().Name, err)
|
||||
}
|
||||
|
||||
// encapsulate key
|
||||
wrappedKey, err := tool.EncapsulateKey(newKey, recipient)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encapsulate key with %s: %s", tool.Info().Name, err)
|
||||
}
|
||||
|
||||
// add to letter
|
||||
letter.Keys = append(letter.Keys, &Seal{
|
||||
ID: recipient.ID,
|
||||
Value: wrappedKey,
|
||||
})
|
||||
|
||||
// add key
|
||||
keyMaterial = append(keyMaterial, newKey)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return keyMaterial, nil
|
||||
}
|
||||
|
||||
func (s *Session) setupOpeningKeyMaterial(letter *Letter) ([][]byte, error) {
|
||||
// Hint: Signets are loaded from the seals in the letter, so the order will always match.
|
||||
|
||||
var keyMaterial [][]byte
|
||||
sealIndex := 0
|
||||
|
||||
// sanity check
|
||||
if s.wire == nil {
|
||||
// TODO:
|
||||
// initial wire handshake is special:
|
||||
// key encapsulators send two seals in the initial handshake messages
|
||||
// one of them is added to the recipients
|
||||
// the other is a new ephermal key
|
||||
if len(s.envelope.Secrets)+
|
||||
len(s.envelope.Senders)+
|
||||
len(s.envelope.Recipients) < len(letter.Keys) {
|
||||
return nil, fmt.Errorf("missing Keys in letter")
|
||||
}
|
||||
}
|
||||
|
||||
// add raw keys
|
||||
_ = s.envelope.LoopSecrets(SignetSchemeKey, func(signet *Signet) error {
|
||||
keyMaterial = append(keyMaterial, signet.Key)
|
||||
sealIndex++ // basically just skip, because key has to be loaded from the Signet anyway
|
||||
return nil
|
||||
})
|
||||
|
||||
// add passwords
|
||||
err := s.envelope.LoopSecrets(SignetSchemePassword, func(signet *Signet) error {
|
||||
if len(signet.Key) == 0 {
|
||||
return fmt.Errorf("signet [%s] is missing it's password", signet.ID)
|
||||
}
|
||||
pwKey, err := s.passDerivator.DeriveKeyFromPassword(signet.Key, letter.Nonce)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get derive key from password with %s: %s", s.passDerivator.Info().Name, err)
|
||||
}
|
||||
|
||||
keyMaterial = append(keyMaterial, pwKey)
|
||||
sealIndex++ // basically just skip, because password has to be loaded from the Signet anyway
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// add key exchange
|
||||
for _, tool := range s.keyExchangers {
|
||||
//nolint:scopelint // function is executed immediately within loop
|
||||
err = s.envelope.LoopRecipients(tool.Info().Name, func(signet *Signet) error {
|
||||
// get senderRcpt
|
||||
peerSignet := &Signet{
|
||||
Version: letter.Version,
|
||||
tool: tool.Definition(),
|
||||
Key: letter.Keys[sealIndex].Value,
|
||||
Public: true,
|
||||
}
|
||||
sealIndex++
|
||||
// load key
|
||||
err := peerSignet.LoadKey()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load ephermal signet for key exchange: %s", err)
|
||||
}
|
||||
// save to state
|
||||
if s.wire != nil {
|
||||
s.wire.eKXSignets = append(s.wire.eKXSignets, &kxPair{
|
||||
tool: tool,
|
||||
peer: peerSignet,
|
||||
})
|
||||
}
|
||||
|
||||
// make shared key
|
||||
exchKey, err := tool.MakeSharedKey(signet, peerSignet)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to make shared key with %s: %s", tool.Info().Name, err)
|
||||
}
|
||||
|
||||
// add key
|
||||
keyMaterial = append(keyMaterial, exchKey)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// add key encapsulation
|
||||
for _, tool := range s.keyEncapsulators {
|
||||
//nolint:scopelint // function is executed immediately within loop
|
||||
err = s.envelope.LoopRecipients(tool.Info().Name, func(signet *Signet) error {
|
||||
// save to state
|
||||
if s.wire != nil {
|
||||
s.wire.eKESignets = append(s.wire.eKESignets, &kePair{
|
||||
tool: tool,
|
||||
})
|
||||
}
|
||||
|
||||
unwrappedKey, err := tool.UnwrapKey(letter.Keys[sealIndex].Value, signet)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sealIndex++
|
||||
|
||||
// add key
|
||||
keyMaterial = append(keyMaterial, unwrappedKey)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return keyMaterial, nil
|
||||
}
|
||||
|
||||
// setup runs the setup function on all tools.
|
||||
func (s *Session) setup() error {
|
||||
for _, tool := range s.toolsWithState {
|
||||
err := tool.Setup()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to run tool %s setup: %s", tool.Info().Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// reset runs the reset function on all tools and managed hashers.
|
||||
func (s *Session) reset() error {
|
||||
// reset all tools
|
||||
for _, tool := range s.toolsWithState {
|
||||
err := tool.Reset()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to run tool %s reset: %s", tool.Info().Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Session) feedManagedHashers(managedHashers map[string]*managedHasher, data, associatedData []byte) error {
|
||||
for _, mngdHasher := range managedHashers {
|
||||
n, err := mngdHasher.hash.Write(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write data to managed hasher %s: %s", mngdHasher.tool.Name, err)
|
||||
}
|
||||
if n != len(data) {
|
||||
return fmt.Errorf("failed to fully write data to managed hasher %s", mngdHasher.tool.Name)
|
||||
}
|
||||
|
||||
n, err = mngdHasher.hash.Write(associatedData)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write associated data to managed hasher %s: %s", mngdHasher.tool.Name, err)
|
||||
}
|
||||
if n != len(associatedData) {
|
||||
return fmt.Errorf("failed to fully write associated data to managed hasher %s", mngdHasher.tool.Name)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Session) resetManagedHashers(managedHashers map[string]*managedHasher) {
|
||||
for _, mngdHasher := range managedHashers {
|
||||
mngdHasher.hash.Reset()
|
||||
}
|
||||
}
|
583
core_test.go
Normal file
583
core_test.go
Normal file
|
@ -0,0 +1,583 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
)
|
||||
|
||||
const (
|
||||
testData1 = "The quick brown fox jumps over the lazy dog. "
|
||||
testData2 = `Tempora aut rerum ut esse illo. Aut quo qui rem consequuntur quia suscipit nihil labore. Quisquam et corrupti exercitationem nesciunt. Ut nisi voluptas natus.
|
||||
Nihil ipsum maxime necessitatibus distinctio velit. Debitis perferendis suscipit ut. Aut illum blanditiis ut voluptates qui.
|
||||
Consequatur cupiditate itaque qui quam. Sed qui velit et aperiam voluptatum reprehenderit aut voluptas. Eaque facere sit exercitationem dolore quos eum. Consectetur est voluptas nemo dolor rerum quae. Nisi sed velit quasi alias assumenda.
|
||||
Commodi eos asperiores fugiat molestiae ea eos eligendi. Explicabo illo quisquam et ut incidunt libero vel eius. Libero accusamus corporis cum rem. Voluptas molestias corporis veritatis sapiente nihil voluptatibus. Delectus sit qui iste ut vero. Occaecati reiciendis ex sed consequuntur dolor et.
|
||||
Qui voluptates quod omnis rerum. Soluta dolore quia eius quo similique accusamus. Quisquam fugiat sed voluptatibus eos earum sed. Numquam quia at commodi aut esse ducimus enim.
|
||||
Enim nihil architecto architecto. Reprehenderit at assumenda labore. Et ut sed ut inventore tenetur autem. Iusto et neque ab dolores eum. Praesentium amet sint ut voluptate impedit sit.
|
||||
A accusantium ullam voluptatibus. Adipisci architecto minus dolore tenetur eos. Id illum quo neque laborum numquam laborum animi libero.
|
||||
Debitis voluptatem non aut ex. Et et quis qui aut aut fugit accusantium. Est dolor quia accusantium culpa.
|
||||
Facere iste dolor a qui. Earum aut facilis maxime repudiandae magnam. Laborum illum distinctio quo libero corrupti maxime. Eum nam officiis culpa nobis.
|
||||
Et repellat qui ut quaerat error explicabo. Distinctio repudiandae sit dolores nam at. Suscipit aliquam alias ullam id.`
|
||||
|
||||
testPassword1 = "Jt0gYfUh0mMsWH1jYhOI2SXQ8rKMmu38pkBgDa6p8YlOlae" //nolint:gosec
|
||||
testPassword2 = "6+cYgtpM6CYjApRvc+ayx4t4zXJ9PSr80ykp3jmwagATaw4" //nolint:gosec
|
||||
|
||||
testHasher = "SHA2-256"
|
||||
)
|
||||
|
||||
var (
|
||||
testKey1 []byte
|
||||
testKey2 []byte
|
||||
|
||||
testTrustStore = NewMemTrustStore()
|
||||
|
||||
RunComprehensiveTests string
|
||||
runComprehensiveTestsActive bool
|
||||
|
||||
RunTestsInDebugStyle string
|
||||
runTestsInDebugStyleActive bool
|
||||
|
||||
debugStyleMaxErrors = 10
|
||||
debugStyleErrorCnt int
|
||||
)
|
||||
|
||||
func tErrorf(t *testing.T, msg string, args ...interface{}) {
|
||||
t.Errorf(msg, args...)
|
||||
if runTestsInDebugStyleActive {
|
||||
debugStyleErrorCnt++
|
||||
if debugStyleErrorCnt >= debugStyleMaxErrors {
|
||||
t.Skipf("reached %d errors, ending early", debugStyleErrorCnt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
// init test key
|
||||
var err error
|
||||
testKey1, err = RandomBytes(defaultSymmetricKeySize)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
testKey2, err = RandomBytes(defaultSymmetricKeySize)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// init trust store
|
||||
err = testTrustStore.StoreSignet(&Signet{
|
||||
Version: 1,
|
||||
ID: "test-key-1",
|
||||
Scheme: SignetSchemeKey,
|
||||
Key: testKey1,
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = testTrustStore.StoreSignet(&Signet{
|
||||
Version: 1,
|
||||
ID: "test-key-2",
|
||||
Scheme: SignetSchemeKey,
|
||||
Key: testKey2,
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
err = testTrustStore.StoreSignet(&Signet{
|
||||
Version: 1,
|
||||
ID: "test-pw-1",
|
||||
Scheme: SignetSchemePassword,
|
||||
Key: []byte(testPassword1),
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = testTrustStore.StoreSignet(&Signet{
|
||||
Version: 1,
|
||||
ID: "test-pw-2",
|
||||
Scheme: SignetSchemePassword,
|
||||
Key: []byte(testPassword2),
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// lower defaults for better test speed
|
||||
defaultSymmetricKeySize = 16
|
||||
defaultSecurityLevel = 128
|
||||
|
||||
// init special test config
|
||||
if RunComprehensiveTests == "true" { //nolint:goconst
|
||||
runComprehensiveTestsActive = true
|
||||
}
|
||||
if RunTestsInDebugStyle == "true" { //nolint:goconst
|
||||
runTestsInDebugStyleActive = true
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoreBasic(t *testing.T) {
|
||||
// toolsets to test
|
||||
toolsets := [][]string{
|
||||
RecommendedStorageKey,
|
||||
RecommendedStoragePassword,
|
||||
{"HKDF(SHA2-256)", "CHACHA20-POLY1305"},
|
||||
{"PBKDF2-SHA2-256", "HKDF(SHA2-256)", "CHACHA20-POLY1305"},
|
||||
}
|
||||
|
||||
for _, toolIDs := range toolsets {
|
||||
testStorage(t, toolIDs)
|
||||
}
|
||||
}
|
||||
|
||||
//nolint:gocognit
|
||||
func TestCoreAllCombinations(t *testing.T) {
|
||||
// This shall test all tools in all combinations and every tool should be tested when placed before and after every other tool.
|
||||
|
||||
// skip in short tests
|
||||
if testing.Short() {
|
||||
return
|
||||
}
|
||||
|
||||
// add all tools
|
||||
var all []string
|
||||
if runTestsInDebugStyleActive {
|
||||
for _, tool := range tools.AsList() {
|
||||
all = append(all, tool.Info.Name)
|
||||
}
|
||||
} else {
|
||||
for _, tool := range tools.AsMap() {
|
||||
all = append(all, tool.Info.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// add hashers to tools that need them
|
||||
for i := 0; i < len(all); i++ {
|
||||
// get tool
|
||||
tool, err := tools.Get(all[i])
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get tool %s: %s", all[i], err)
|
||||
return
|
||||
}
|
||||
|
||||
// add hasher if needed
|
||||
if tool.Info.HasOption(tools.OptionNeedsManagedHasher) ||
|
||||
tool.Info.HasOption(tools.OptionNeedsDedicatedHasher) {
|
||||
all[i] = fmt.Sprintf("%s(%s)", all[i], testHasher)
|
||||
}
|
||||
}
|
||||
|
||||
// compute all combinations
|
||||
combinations := generateCombinations(all)
|
||||
combinationsTested := 0
|
||||
combinationsDetectedInvalid := 0
|
||||
|
||||
if runComprehensiveTestsActive {
|
||||
fmt.Println("running comprehensive tests, printing one dot per 1000 combinations tested.")
|
||||
}
|
||||
|
||||
for _, testTools := range combinations {
|
||||
// >4 tools && !comprehensive: don't test
|
||||
if !runComprehensiveTestsActive && len(testTools) > 4 {
|
||||
continue
|
||||
}
|
||||
|
||||
if len(testTools) == 4 &&
|
||||
runComprehensiveTestsActive {
|
||||
// ==4 tools && comprehensive: rotate
|
||||
|
||||
// if we want to test before/after differences, we need to use at least 4 tools, because if we have 2 key exchanges, they need at least an aead cipher and key derivation tool in order to work.
|
||||
|
||||
// rotate to test before/after differences
|
||||
for i := 0; i < len(testTools); i++ {
|
||||
detectedInvalid := testStorage(t, testTools)
|
||||
combinationsTested++
|
||||
if detectedInvalid {
|
||||
combinationsDetectedInvalid++
|
||||
}
|
||||
if runComprehensiveTestsActive && combinationsTested%1000 == 0 {
|
||||
fmt.Print(".")
|
||||
}
|
||||
|
||||
// rotate
|
||||
testTools = append(testTools, testTools[0])[1:]
|
||||
}
|
||||
} else {
|
||||
// test this order only
|
||||
detectedInvalid := testStorage(t, testTools)
|
||||
combinationsTested++
|
||||
if detectedInvalid {
|
||||
combinationsDetectedInvalid++
|
||||
}
|
||||
if runComprehensiveTestsActive && combinationsTested%1000 == 0 {
|
||||
fmt.Print(".")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if runComprehensiveTestsActive {
|
||||
fmt.Println("\n\nfinished.")
|
||||
}
|
||||
|
||||
t.Logf("tested %d tool combinations", combinationsTested)
|
||||
t.Logf("of these, %d were successfully detected as invalid", combinationsDetectedInvalid)
|
||||
}
|
||||
|
||||
func testStorage(t *testing.T, toolIDs []string) (detectedInvalid bool) {
|
||||
// t.Logf("testing storage with %v", toolIDs)
|
||||
|
||||
e, err := setupEnvelopeAndTrustStore(t, toolIDs)
|
||||
if err != nil {
|
||||
tErrorf(t, "%v failed: %s", toolIDs, err)
|
||||
return false
|
||||
}
|
||||
if e == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
// test 1: close
|
||||
|
||||
s, err := e.Correspondence(testTrustStore)
|
||||
if err != nil {
|
||||
tErrorf(t, "%v failed to init session (1): %s", toolIDs, err)
|
||||
return false
|
||||
}
|
||||
|
||||
letter, err := s.Close([]byte(testData1))
|
||||
if err != nil {
|
||||
tErrorf(t, "%v failed to close (1): %s", toolIDs, err)
|
||||
return false
|
||||
}
|
||||
|
||||
msg, err := letter.ToJSON()
|
||||
if err != nil {
|
||||
tErrorf(t, "%v failed to json encode (1): %s", toolIDs, err)
|
||||
return false
|
||||
}
|
||||
|
||||
// test 2: open from session
|
||||
|
||||
letter2, err := LetterFromJSON(msg)
|
||||
if err != nil {
|
||||
tErrorf(t, "%v failed to json decode (2): %s", toolIDs, err)
|
||||
return false
|
||||
}
|
||||
|
||||
origData2, err := s.Open(letter2)
|
||||
if err != nil {
|
||||
tErrorf(t, "%v failed to open (2): %s", toolIDs, err)
|
||||
return false
|
||||
}
|
||||
if string(origData2) != testData1 {
|
||||
tErrorf(t, "%v original data mismatch (2): %s", toolIDs, string(origData2))
|
||||
return false
|
||||
}
|
||||
|
||||
if len(letter2.Signatures) > 0 {
|
||||
err = s.Verify(letter2)
|
||||
if err != nil {
|
||||
tErrorf(t, "%v failed to verify (2): %s", toolIDs, err)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// extended tests
|
||||
// only run for toolsets greater than 3 if we comprehensive testing is on
|
||||
// for these tests, it is enough if every tool is tested once
|
||||
if len(toolIDs) > 3 && RunComprehensiveTests != "true" {
|
||||
return false
|
||||
}
|
||||
|
||||
// test 2.1: open again to check if reset after opening works
|
||||
|
||||
letter21, err := LetterFromJSON(msg)
|
||||
if err != nil {
|
||||
tErrorf(t, "%v failed to json decode (2.1): %s", toolIDs, err)
|
||||
return false
|
||||
}
|
||||
|
||||
origData21, err := s.Open(letter21)
|
||||
if err != nil {
|
||||
tErrorf(t, "%v failed to open (2.1): %s", toolIDs, err)
|
||||
return false
|
||||
}
|
||||
if string(origData21) != testData1 {
|
||||
tErrorf(t, "%v original data mismatch (2.1): %s", toolIDs, string(origData21))
|
||||
return false
|
||||
}
|
||||
|
||||
// test 2.2: close and open again to check if reset after closing works
|
||||
|
||||
letter22, err := s.Close([]byte(testData1))
|
||||
if err != nil {
|
||||
tErrorf(t, "%v failed to close (2.2): %s", toolIDs, err)
|
||||
return false
|
||||
}
|
||||
|
||||
origData22, err := s.Open(letter22)
|
||||
if err != nil {
|
||||
tErrorf(t, "%v failed to open (2.2): %s", toolIDs, err)
|
||||
return false
|
||||
}
|
||||
if string(origData22) != testData1 {
|
||||
tErrorf(t, "%v original data mismatch (2.2): %s", toolIDs, string(origData22))
|
||||
return false
|
||||
}
|
||||
|
||||
// test 3: open from letter
|
||||
|
||||
// FIXME - other improvements broke these tests, pausing them
|
||||
/*
|
||||
letter3, err := LetterFromJSON(msg)
|
||||
if err != nil {
|
||||
tErrorf(t, "%v failed to json decode (3): %s", toolIDs, err)
|
||||
return false
|
||||
}
|
||||
|
||||
origData3, err := letter3.Open(nil, testTrustStore)
|
||||
if err != nil {
|
||||
tErrorf(t, "%v failed to open (3): %s", toolIDs, err)
|
||||
return false
|
||||
}
|
||||
if string(origData3) != testData1 {
|
||||
tErrorf(t, "%v original data mismatch (3): %s", toolIDs, string(origData3))
|
||||
return false
|
||||
}
|
||||
*/
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
//nolint:gocognit,gocyclo
|
||||
func setupEnvelopeAndTrustStore(t *testing.T, toolIDs []string) (*Envelope, error) {
|
||||
|
||||
// create envelope baseline
|
||||
e := &Envelope{
|
||||
Tools: toolIDs,
|
||||
requirements: newEmptyRequirements(),
|
||||
}
|
||||
|
||||
// check vars
|
||||
keyDerPresent := false
|
||||
passDerPresent := false
|
||||
asyncKeyEstablishmentPresent := false
|
||||
|
||||
// process tools and setup envelope
|
||||
for _, toolID := range e.Tools {
|
||||
|
||||
// remove hasher argument for now
|
||||
if strings.Contains(toolID, "(") {
|
||||
toolID = strings.Split(toolID, "(")[0]
|
||||
}
|
||||
|
||||
// get tool
|
||||
tool, err := tools.Get(toolID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// generate needed signets
|
||||
switch tool.Info.Purpose {
|
||||
case tools.PurposePassDerivation:
|
||||
pw, err := getOrMakeSignet(t, nil, false, "test-pw-1")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.Secrets = append(e.Secrets, pw)
|
||||
|
||||
// add a second one!
|
||||
if len(toolIDs) <= 2 {
|
||||
pw1, err := getOrMakeSignet(t, nil, false, "test-pw-2")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.Secrets = append(e.Secrets, pw1)
|
||||
}
|
||||
|
||||
case tools.PurposeKeyExchange, tools.PurposeKeyEncapsulation:
|
||||
asyncKeyEstablishmentPresent = true
|
||||
|
||||
recipient, err := getOrMakeSignet(t, tool.StaticLogic, true, fmt.Sprintf("test-%s", tool.Info.Name))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.Recipients = append(e.Recipients, recipient)
|
||||
|
||||
case tools.PurposeSigning:
|
||||
sender, err := getOrMakeSignet(t, tool.StaticLogic, false, fmt.Sprintf("test-%s", tool.Info.Name))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.Senders = append(e.Senders, sender)
|
||||
}
|
||||
|
||||
// add required requirements
|
||||
switch tool.Info.Purpose {
|
||||
case tools.PurposeKeyDerivation:
|
||||
keyDerPresent = true
|
||||
case tools.PurposePassDerivation:
|
||||
passDerPresent = true
|
||||
// add passderivation requirements later, as it is a bit special
|
||||
case tools.PurposeKeyExchange:
|
||||
e.requirements.Add(RecipientAuthentication)
|
||||
case tools.PurposeKeyEncapsulation:
|
||||
e.requirements.Add(RecipientAuthentication)
|
||||
case tools.PurposeSigning:
|
||||
e.requirements.Add(SenderAuthentication)
|
||||
case tools.PurposeIntegratedCipher:
|
||||
e.requirements.Add(Confidentiality)
|
||||
e.requirements.Add(Integrity)
|
||||
case tools.PurposeCipher:
|
||||
e.requirements.Add(Confidentiality)
|
||||
case tools.PurposeMAC:
|
||||
e.requirements.Add(Integrity)
|
||||
}
|
||||
}
|
||||
|
||||
// if invalid: test if toolset is recognized as invalid
|
||||
|
||||
// no requirements -> only "meta" tools (kdf, pass derivation)
|
||||
if e.requirements.Empty() {
|
||||
return nil, testInvalidToolset(e, "there are only meta tools in toolset")
|
||||
}
|
||||
|
||||
// recipient auth, but no confidentiality? nope.
|
||||
if e.requirements.Has(RecipientAuthentication) &&
|
||||
!e.requirements.Has(Confidentiality) {
|
||||
return nil, testInvalidToolset(e, "authenticating the recipient without using confidentiality does not make sense")
|
||||
}
|
||||
|
||||
// check if we are missing key derivation - this is only ok if we are merely signing
|
||||
if !keyDerPresent &&
|
||||
(len(e.requirements.all) != 1 ||
|
||||
!e.requirements.Has(SenderAuthentication)) {
|
||||
return nil, testInvalidToolset(e, "omitting a key derivation tool is only allowed when merely signing")
|
||||
}
|
||||
|
||||
// check if we have key derivation, but not need it
|
||||
if keyDerPresent &&
|
||||
(!e.requirements.Has(Confidentiality) &&
|
||||
!e.requirements.Has(Integrity)) {
|
||||
return nil, testInvalidToolset(e, "a key derivation tool was specified, albeit none is needed")
|
||||
}
|
||||
|
||||
// add passderivation here, as to easier handle the other cases
|
||||
if passDerPresent {
|
||||
e.requirements.Add(SenderAuthentication)
|
||||
e.requirements.Add(RecipientAuthentication)
|
||||
|
||||
// need Confidentiality for this to make sense
|
||||
if !e.requirements.Has(Confidentiality) {
|
||||
return nil, testInvalidToolset(e, "using a password without confidentiality does not make sense")
|
||||
}
|
||||
}
|
||||
|
||||
if e.requirements.Has(Confidentiality) &&
|
||||
!e.requirements.Has(Integrity) {
|
||||
return nil, testInvalidToolset(e, "having confidentiality without integrity does not make sense")
|
||||
}
|
||||
|
||||
// add static key if needed
|
||||
if !asyncKeyEstablishmentPresent && !passDerPresent && keyDerPresent {
|
||||
key, err := getOrMakeSignet(t, nil, false, "test-key-1")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.Secrets = append(e.Secrets, key)
|
||||
|
||||
// add a second one!
|
||||
if len(toolIDs) <= 2 {
|
||||
key2, err := getOrMakeSignet(t, nil, false, "test-key-2")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.Secrets = append(e.Secrets, key2)
|
||||
}
|
||||
}
|
||||
|
||||
return e, nil
|
||||
}
|
||||
|
||||
func testInvalidToolset(e *Envelope, whyInvalid string) error {
|
||||
if e.Check(testTrustStore) == nil {
|
||||
return fmt.Errorf("passed check although %s", whyInvalid)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getOrMakeSignet(t *testing.T, tool tools.ToolLogic, recipient bool, signetID string) (*Signet, error) {
|
||||
|
||||
// check if signet already exists
|
||||
signet, err := testTrustStore.GetSignet(signetID, recipient)
|
||||
if err == nil {
|
||||
return signet, nil
|
||||
}
|
||||
|
||||
// handle special cases
|
||||
if tool == nil {
|
||||
return nil, errors.New("bad parameters")
|
||||
}
|
||||
|
||||
// create new signet
|
||||
new := NewSignetBase(tool.Definition())
|
||||
new.ID = signetID
|
||||
// generate signet and log time taken
|
||||
start := time.Now()
|
||||
err = tool.GenerateKey(new)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.Logf("generated %s signet %s in %s", new.Scheme, new.ID, time.Since(start))
|
||||
|
||||
// store signet
|
||||
err = testTrustStore.StoreSignet(new)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// store recipient
|
||||
newRcpt, err := new.AsRecipient()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = testTrustStore.StoreSignet(newRcpt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// return
|
||||
if recipient {
|
||||
return newRcpt, nil
|
||||
}
|
||||
return new, nil
|
||||
}
|
||||
|
||||
// generateCombinations returns all possible combinations of the given []string slice.
|
||||
// Forked from https://github.com/mxschmitt/golang-combinations/blob/a887187146560effd2677e987b069262f356297f/combinations.go
|
||||
// Copyright (c) 2018 Max Schmitt
|
||||
// MIT License
|
||||
func generateCombinations(set []string) (subsets [][]string) {
|
||||
length := uint(len(set))
|
||||
|
||||
// Go through all possible combinations of objects
|
||||
// from 1 (only first object in subset) to 2^length (all objects in subset)
|
||||
for subsetBits := 1; subsetBits < (1 << length); subsetBits++ {
|
||||
var subset []string
|
||||
|
||||
for object := uint(0); object < length; object++ {
|
||||
// checks if object is contained in subset
|
||||
// by checking if bit 'object' is set in subsetBits
|
||||
if (subsetBits>>object)&1 == 1 {
|
||||
// add object to subset
|
||||
subset = append(subset, set[object])
|
||||
}
|
||||
}
|
||||
// add subset to subsets
|
||||
subsets = append(subsets, subset)
|
||||
}
|
||||
return subsets
|
||||
}
|
34
defaults.go
Normal file
34
defaults.go
Normal file
|
@ -0,0 +1,34 @@
|
|||
package jess
|
||||
|
||||
var (
|
||||
// must be var in order decrease for testing for better speed
|
||||
|
||||
defaultSecurityLevel = 256
|
||||
minimumSecurityLevel = 0
|
||||
|
||||
defaultSymmetricKeySize = 32
|
||||
minimumSymmetricKeySize = 0
|
||||
)
|
||||
|
||||
// Currently recommended toolsets
|
||||
var (
|
||||
RecommendedNetwork = []string{"ECDH-X25519", "HKDF(SHA2-256)", "CHACHA20-POLY1305"}
|
||||
RecommendedStoragePassword = []string{"PBKDF2-SHA2-256", "HKDF(SHA2-256)", "CHACHA20-POLY1305"}
|
||||
RecommendedStorageKey = []string{"HKDF(SHA2-256)", "CHACHA20-POLY1305"}
|
||||
|
||||
RecommendedStorageRecipient = []string{"ECDH-X25519", "HKDF(SHA2-256)", "CHACHA20-POLY1305"}
|
||||
|
||||
RecommendedSigning = []string{"Ed25519(SHA2-256)"}
|
||||
)
|
||||
|
||||
// SetMinimumSecurityLevel sets a global minimum security level. Jess will refuse any operations that violate this security level.
|
||||
func SetMinimumSecurityLevel(securityLevel int) {
|
||||
defaultSecurityLevel = securityLevel
|
||||
minimumSecurityLevel = securityLevel
|
||||
}
|
||||
|
||||
// SetDefaultKeySize sets a global default key size to be used as a fallback value. This will be only used if the default key size could not be derived from already present information.
|
||||
func SetDefaultKeySize(sizeInBytes int) {
|
||||
defaultSymmetricKeySize = sizeInBytes
|
||||
minimumSymmetricKeySize = sizeInBytes
|
||||
}
|
96
doc.go
Normal file
96
doc.go
Normal file
|
@ -0,0 +1,96 @@
|
|||
/*
|
||||
jess is a lovely cat that protects your data.
|
||||
|
||||
Jess uses four types of objects:
|
||||
- Envelopes (encryption configuration)
|
||||
- Letters (encrypted data)
|
||||
- Stamp (private or secret key)
|
||||
- Signet (certificate / public key)
|
||||
- Seal (separate signature)
|
||||
|
||||
Usage:
|
||||
|
||||
message := "I love milk"
|
||||
|
||||
// configure
|
||||
envelope, err := jess.NewEnvelope().SupplyPassword("paw").Check()
|
||||
|
||||
// encrypt
|
||||
letter := jess.Close(envelope, message)
|
||||
encrypted := letter.AsString()
|
||||
fmt.Println(encrypted)
|
||||
|
||||
// decrypt
|
||||
letter = jess.LetterFromString(encrypted)
|
||||
message = jess.Open(envelope, letter)
|
||||
fmt.Println(message)
|
||||
|
||||
CLI: coming soon
|
||||
|
||||
jess new <envelope>
|
||||
// create new configuration
|
||||
|
||||
jess close <file> with <envelope>
|
||||
// encrypt data in a letter
|
||||
|
||||
jess open <file>
|
||||
// decrypt and verify letter
|
||||
|
||||
jess show <file>
|
||||
// show information about object
|
||||
|
||||
jess sign <file> with <envelope>
|
||||
// special close case, where only a signature is created and put in a separate `.seal` file
|
||||
|
||||
Internals:
|
||||
|
||||
Envelope.Correspondence() *Session
|
||||
|
||||
|
||||
|
||||
Key Establishment
|
||||
|
||||
|
||||
Exchange:
|
||||
|
||||
c=IDLE s=IDLE
|
||||
|
||||
c -> new ephemeral public key -> s
|
||||
... detected by len(keys) > 0
|
||||
c=AWAIT_KEY, s=SEND_KEY
|
||||
|
||||
s: make new ephemeral key, apply new shared secret immediately
|
||||
s -> new ephemeral public key -> c
|
||||
... detected by len(keys) > 0
|
||||
c: apply new shared secret immediately for s->c
|
||||
c=SEND_APPLY, s=AWAIT_APPLY
|
||||
|
||||
c: apply new shared secret to c->s
|
||||
c -> apply -> s
|
||||
... detected by APPLY flag
|
||||
s: apply to c->s
|
||||
c=IDLE, S=IDLE
|
||||
|
||||
Encapsulation:
|
||||
|
||||
c=IDLE s=IDLE
|
||||
|
||||
c -> new ephemeral public key -> s
|
||||
... detected by len(keys) > 0
|
||||
c=AWAIT_KEY, s=SEND_KEY
|
||||
|
||||
s: make key, apply immediately and encapsulate
|
||||
s -> encapsulated key -> c
|
||||
... detected by len(keys) > 0
|
||||
c: apply encapsulated key immediately for s->c
|
||||
c=SEND_APPLY, s=AWAIT_APPLY
|
||||
|
||||
c: apply encapsulated secret for c->s
|
||||
c -> apply -> s
|
||||
... detected by APPLY flag
|
||||
s: apply to c->s
|
||||
c=IDLE, S=IDLE
|
||||
|
||||
*/
|
||||
|
||||
package jess
|
319
envelope.go
Normal file
319
envelope.go
Normal file
|
@ -0,0 +1,319 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Envelope holds configuration for jess to put data into a letter.
|
||||
type Envelope struct { //nolint:maligned // TODO
|
||||
Version uint8
|
||||
Name string
|
||||
Tools []string
|
||||
|
||||
// Secret keys and passwords
|
||||
Secrets []*Signet
|
||||
|
||||
// Sender related signets
|
||||
// When closing: private keys for signatures
|
||||
// When opening: public keys for signatures
|
||||
Senders []*Signet
|
||||
|
||||
// Recipient related signets
|
||||
// When closing: public keys for key exchange or key encapsulation
|
||||
// When opening: private keys for key exchange or key encapsulation
|
||||
Recipients []*Signet
|
||||
|
||||
// For users, envelopes describe how a letter is closed.
|
||||
// Therefore Secrets and Senders always refer to private keys and Recipients to public keys in that context.
|
||||
// These distictions are important in order for the user to easily and confidently distinguish what is going to happen. Think of it as "human security".
|
||||
|
||||
MinimumSecurityLevel int
|
||||
No string
|
||||
requirements *Requirements
|
||||
|
||||
// flag to signify if envelope is used for opening
|
||||
opening bool
|
||||
}
|
||||
|
||||
// NewUnconfiguredEnvelope returns an unconfigured, but slightly initialized envelope.
|
||||
func NewUnconfiguredEnvelope() *Envelope {
|
||||
e := &Envelope{
|
||||
Version: 1,
|
||||
requirements: NewRequirements(),
|
||||
}
|
||||
e.SerializeRequirements()
|
||||
return e
|
||||
}
|
||||
|
||||
// Correspondence returns a new session configured with the envelope.
|
||||
func (e *Envelope) Correspondence(trustStore TrustStore) (*Session, error) {
|
||||
return e.initCorrespondence(trustStore, false)
|
||||
}
|
||||
|
||||
func (e *Envelope) initCorrespondence(trustStore TrustStore, verifying bool) (*Session, error) {
|
||||
err := e.LoadRequirements()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if verifying {
|
||||
// prep sender signets only
|
||||
err = e.prepSignets(e.Senders, e.opening, trustStore)
|
||||
} else {
|
||||
// prep all signets
|
||||
err = e.PrepareSignets(trustStore)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return newSession(e)
|
||||
}
|
||||
|
||||
// WireCorrespondence returns a new wire session (live communication) configured with the envelope.
|
||||
func (e *Envelope) WireCorrespondence(trustStore TrustStore) (*Session, error) {
|
||||
s, err := e.Correspondence(trustStore)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = s.initWireSession()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Check returns whether the envelope is valid and can be used as is.
|
||||
func (e *Envelope) Check(trustStore TrustStore) error {
|
||||
_, err := e.Correspondence(trustStore)
|
||||
return err
|
||||
}
|
||||
|
||||
// NoRecipientAuth removes the requirement to authenticate the recipient.
|
||||
func (e *Envelope) NoRecipientAuth() *Envelope {
|
||||
if e.requirements == nil {
|
||||
e.requirements = NewRequirements()
|
||||
}
|
||||
|
||||
e.requirements.Remove(RecipientAuthentication)
|
||||
return e
|
||||
}
|
||||
|
||||
// NoSenderAuth removes the requirement to authenticate the sender.
|
||||
func (e *Envelope) NoSenderAuth() *Envelope {
|
||||
if e.requirements == nil {
|
||||
e.requirements = NewRequirements()
|
||||
}
|
||||
|
||||
e.requirements.Remove(SenderAuthentication)
|
||||
e.SerializeRequirements()
|
||||
return e
|
||||
}
|
||||
|
||||
// NoConfidentiality removes the requirement to provide confidentiality.
|
||||
func (e *Envelope) NoConfidentiality() *Envelope {
|
||||
if e.requirements == nil {
|
||||
e.requirements = NewRequirements()
|
||||
}
|
||||
|
||||
e.requirements.Remove(Confidentiality)
|
||||
e.SerializeRequirements()
|
||||
return e
|
||||
}
|
||||
|
||||
// NoIntegrity removes the requirement to provide integrity.
|
||||
func (e *Envelope) NoIntegrity() *Envelope {
|
||||
if e.requirements == nil {
|
||||
e.requirements = NewRequirements()
|
||||
}
|
||||
|
||||
e.requirements.Remove(Integrity)
|
||||
e.SerializeRequirements()
|
||||
return e
|
||||
}
|
||||
|
||||
// Unsafe removes all requirements.
|
||||
func (e *Envelope) Unsafe() *Envelope {
|
||||
e.requirements = &Requirements{}
|
||||
e.SerializeRequirements()
|
||||
return e
|
||||
}
|
||||
|
||||
// Requirements returns the required requirements.
|
||||
func (e *Envelope) Requirements() *Requirements {
|
||||
return e.requirements
|
||||
}
|
||||
|
||||
// SetRequirements sets new requirements.
|
||||
func (e *Envelope) SetRequirements(requirements *Requirements) {
|
||||
e.requirements = requirements
|
||||
}
|
||||
|
||||
// LoadRequirements loads the required requirements from the struct's exposed negated "No" specification.
|
||||
func (e *Envelope) LoadRequirements() error {
|
||||
if e.requirements == nil {
|
||||
attrs, err := ParseRequirementsFromNoSpec(e.No)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
e.requirements = attrs
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SerializeRequirements saves the requirement requirements in the struct's exposed negated "No" specification.
|
||||
func (e *Envelope) SerializeRequirements() {
|
||||
e.No = e.requirements.SerializeToNoSpec()
|
||||
}
|
||||
|
||||
// LoopSecrets loops over all secrets of the given scheme.
|
||||
func (e *Envelope) LoopSecrets(scheme string, fn func(*Signet) error) error {
|
||||
for _, signet := range e.Secrets {
|
||||
if len(scheme) == 0 || signet.Scheme == scheme {
|
||||
err := fn(signet)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoopSenders loops over all sender signets of the given scheme.
|
||||
func (e *Envelope) LoopSenders(scheme string, fn func(*Signet) error) error {
|
||||
for _, signet := range e.Senders {
|
||||
if len(scheme) == 0 || signet.Scheme == scheme {
|
||||
err := fn(signet)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoopRecipients loops over all recipient signets of the given scheme.
|
||||
func (e *Envelope) LoopRecipients(scheme string, fn func(*Signet) error) error {
|
||||
for _, signet := range e.Recipients {
|
||||
if len(scheme) == 0 || signet.Scheme == scheme {
|
||||
err := fn(signet)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// PrepareSignets checks that all signets of the envelope are ready to use. It will fetch referenced signets and load the keys.
|
||||
func (e *Envelope) PrepareSignets(storage TrustStore) error {
|
||||
err := e.prepSignets(e.Secrets, e.opening, storage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = e.prepSignets(e.Senders, e.opening, storage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return e.prepSignets(e.Recipients, !e.opening, storage)
|
||||
}
|
||||
|
||||
// prepSignets checks that all signets of the envelope are ready to use.
|
||||
func (e *Envelope) prepSignets(signets []*Signet, recipients bool, storage TrustStore) error {
|
||||
for i, signet := range signets {
|
||||
// load from storage
|
||||
if len(signet.Key) == 0 {
|
||||
if signet.Scheme == SignetSchemePassword {
|
||||
err := fillPassword(signet, !recipients, storage, e.MinimumSecurityLevel)
|
||||
if err != nil {
|
||||
return fmt.Errorf(`failed to get password for "%s": %s`, signet.ID, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// signet is referrer
|
||||
if len(signet.ID) == 0 {
|
||||
return errors.New("signets must have a scheme+key or an ID")
|
||||
}
|
||||
|
||||
// check if we have a storage
|
||||
if storage == nil {
|
||||
return fmt.Errorf(`failed to get signet with ID "%s": no truststore provided`, signet.ID)
|
||||
}
|
||||
|
||||
// get signet from trust store
|
||||
new, err := storage.GetSignet(signet.ID, recipients)
|
||||
if err != nil {
|
||||
return fmt.Errorf(`failed to get signet with ID "%s" from truststore: %s`, signet.ID, err)
|
||||
}
|
||||
|
||||
// check for scheme mismatch
|
||||
if signet.Scheme != "" && signet.Scheme != new.Scheme {
|
||||
return fmt.Errorf(`failed to apply signet with ID "%s" from truststore: was expected to be of type %s, but is %s`, signet.ID, signet.Scheme, new.Scheme)
|
||||
}
|
||||
|
||||
// apply signet back into envelope
|
||||
signet = new
|
||||
signets[i] = new
|
||||
}
|
||||
|
||||
// unwrap protection
|
||||
if signet.Protection != nil {
|
||||
return errors.New("protected signets are not yet supported")
|
||||
}
|
||||
|
||||
// load signet
|
||||
switch signet.Scheme {
|
||||
case SignetSchemeKey, SignetSchemePassword:
|
||||
// no loading needed
|
||||
default:
|
||||
err := signet.LoadKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func fillPassword(signet *Signet, createPassword bool, storage TrustStore, minSecurityLevel int) (err error) {
|
||||
if createPassword {
|
||||
if createPasswordCallback == nil {
|
||||
return nil // ignore
|
||||
}
|
||||
} else if getPasswordCallback == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// find reference
|
||||
if signet.Info == nil || signet.Info.Name == "" {
|
||||
// check trust store for name
|
||||
if len(signet.ID) > 0 && storage != nil {
|
||||
// get signet from trust store
|
||||
new, err := storage.GetSignet(signet.ID, false)
|
||||
if err == nil && new.Info != nil {
|
||||
if signet.Info == nil {
|
||||
signet.Info = new.Info
|
||||
} else {
|
||||
signet.Info.Name = new.Info.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if createPassword {
|
||||
return createPasswordCallback(signet, minSecurityLevel)
|
||||
}
|
||||
return getPasswordCallback(signet)
|
||||
}
|
15
errors.go
Normal file
15
errors.go
Normal file
|
@ -0,0 +1,15 @@
|
|||
package jess
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
// ErrIntegrityViolation is returned when the integrity was found the be violated.
|
||||
ErrIntegrityViolation = errors.New("integrity violation")
|
||||
// ErrConfidentialityViolation is returned when the confidentiality was found the be violated.
|
||||
ErrConfidentialityViolation = errors.New("confidentiality violation")
|
||||
// ErrAuthenticityViolation is returned when the authenticity was found the be violated.
|
||||
ErrAuthenticityViolation = errors.New("authenticity violation")
|
||||
|
||||
// ErrInsufficientRandom is returned if the configured RNG cannot deliver enough data.
|
||||
ErrInsufficientRandom = errors.New("not enough random data available from source")
|
||||
)
|
46
hashtools/blake2.go
Normal file
46
hashtools/blake2.go
Normal file
|
@ -0,0 +1,46 @@
|
|||
package hashtools
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
|
||||
// register BLAKE2 in Go's internal registry
|
||||
_ "golang.org/x/crypto/blake2b"
|
||||
_ "golang.org/x/crypto/blake2s"
|
||||
)
|
||||
|
||||
func init() {
|
||||
blake2bBase := &HashTool{
|
||||
Comment: "RFC 7693, successor of SHA3 finalist, optimized for 64 bit software",
|
||||
Author: "Jean-Philippe Aumasson et al., 2013",
|
||||
}
|
||||
|
||||
Register(blake2bBase.With(&HashTool{
|
||||
Name: "BLAKE2s-256",
|
||||
Hash: crypto.BLAKE2s_256,
|
||||
DigestSize: crypto.BLAKE2s_256.Size(),
|
||||
BlockSize: crypto.BLAKE2s_256.New().BlockSize(),
|
||||
SecurityLevel: 128,
|
||||
Comment: "RFC 7693, successor of SHA3 finalist, optimized for 8-32 bit software",
|
||||
}))
|
||||
Register(blake2bBase.With(&HashTool{
|
||||
Name: "BLAKE2b-256",
|
||||
Hash: crypto.BLAKE2b_256,
|
||||
DigestSize: crypto.BLAKE2b_256.Size(),
|
||||
BlockSize: crypto.BLAKE2b_256.New().BlockSize(),
|
||||
SecurityLevel: 128,
|
||||
}))
|
||||
Register(blake2bBase.With(&HashTool{
|
||||
Name: "BLAKE2b-384",
|
||||
Hash: crypto.BLAKE2b_384,
|
||||
DigestSize: crypto.BLAKE2b_384.Size(),
|
||||
BlockSize: crypto.BLAKE2b_384.New().BlockSize(),
|
||||
SecurityLevel: 192,
|
||||
}))
|
||||
Register(blake2bBase.With(&HashTool{
|
||||
Name: "BLAKE2b-512",
|
||||
Hash: crypto.BLAKE2b_512,
|
||||
DigestSize: crypto.BLAKE2b_512.Size(),
|
||||
BlockSize: crypto.BLAKE2b_512.New().BlockSize(),
|
||||
SecurityLevel: 256,
|
||||
}))
|
||||
}
|
51
hashtools/hashtool.go
Normal file
51
hashtools/hashtool.go
Normal file
|
@ -0,0 +1,51 @@
|
|||
package hashtools
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"hash"
|
||||
)
|
||||
|
||||
// HashTool holds generic information about a hash tool.
|
||||
type HashTool struct {
|
||||
Name string
|
||||
Hash crypto.Hash
|
||||
|
||||
DigestSize int // in bytes
|
||||
BlockSize int // in bytes
|
||||
SecurityLevel int // approx. attack complexity as 2^n
|
||||
|
||||
Comment string
|
||||
Author string
|
||||
}
|
||||
|
||||
// New returns a new hash.Hash instance of the hash tool.
|
||||
func (ht *HashTool) New() hash.Hash {
|
||||
return ht.Hash.New()
|
||||
}
|
||||
|
||||
// With uses the original HashTool as a template for a new HashTool and returns the new HashTool.
|
||||
func (ht *HashTool) With(changes *HashTool) *HashTool {
|
||||
if changes.Name == "" {
|
||||
changes.Name = ht.Name
|
||||
}
|
||||
if changes.Hash == 0 {
|
||||
changes.Hash = ht.Hash
|
||||
}
|
||||
if changes.DigestSize == 0 {
|
||||
changes.DigestSize = ht.DigestSize
|
||||
}
|
||||
if changes.BlockSize == 0 {
|
||||
changes.BlockSize = ht.BlockSize
|
||||
}
|
||||
if changes.SecurityLevel == 0 {
|
||||
changes.SecurityLevel = ht.SecurityLevel
|
||||
}
|
||||
if changes.Comment == "" {
|
||||
changes.Comment = ht.Comment
|
||||
}
|
||||
if changes.Author == "" {
|
||||
changes.Author = ht.Author
|
||||
}
|
||||
|
||||
return changes
|
||||
}
|
97
hashtools/sha.go
Normal file
97
hashtools/sha.go
Normal file
|
@ -0,0 +1,97 @@
|
|||
package hashtools
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
|
||||
// register SHA2 in Go's internal registry
|
||||
_ "crypto/sha256"
|
||||
_ "crypto/sha512"
|
||||
|
||||
// register SHA3 in Go's internal registry
|
||||
_ "golang.org/x/crypto/sha3"
|
||||
)
|
||||
|
||||
func init() {
|
||||
// SHA2
|
||||
sha2Base := &HashTool{
|
||||
Comment: "FIPS 180-4",
|
||||
Author: "NSA, 2001",
|
||||
}
|
||||
Register(sha2Base.With(&HashTool{
|
||||
Name: "SHA2-224",
|
||||
Hash: crypto.SHA224,
|
||||
DigestSize: crypto.SHA224.Size(),
|
||||
BlockSize: crypto.SHA224.New().BlockSize(),
|
||||
SecurityLevel: 112,
|
||||
Author: "NSA, 2004",
|
||||
}))
|
||||
Register(sha2Base.With(&HashTool{
|
||||
Name: "SHA2-256",
|
||||
Hash: crypto.SHA256,
|
||||
DigestSize: crypto.SHA256.Size(),
|
||||
BlockSize: crypto.SHA256.New().BlockSize(),
|
||||
SecurityLevel: 128,
|
||||
}))
|
||||
Register(sha2Base.With(&HashTool{
|
||||
Name: "SHA2-384",
|
||||
Hash: crypto.SHA384,
|
||||
DigestSize: crypto.SHA384.Size(),
|
||||
BlockSize: crypto.SHA384.New().BlockSize(),
|
||||
SecurityLevel: 192,
|
||||
}))
|
||||
Register(sha2Base.With(&HashTool{
|
||||
Name: "SHA2-512",
|
||||
Hash: crypto.SHA512,
|
||||
DigestSize: crypto.SHA512.Size(),
|
||||
BlockSize: crypto.SHA512.New().BlockSize(),
|
||||
SecurityLevel: 256,
|
||||
}))
|
||||
Register(sha2Base.With(&HashTool{
|
||||
Name: "SHA2-512-224",
|
||||
Hash: crypto.SHA512_224,
|
||||
DigestSize: crypto.SHA512_224.Size(),
|
||||
BlockSize: crypto.SHA512_224.New().BlockSize(),
|
||||
SecurityLevel: 112,
|
||||
}))
|
||||
Register(sha2Base.With(&HashTool{
|
||||
Name: "SHA2-512-256",
|
||||
Hash: crypto.SHA512_256,
|
||||
DigestSize: crypto.SHA512_256.Size(),
|
||||
BlockSize: crypto.SHA512_256.New().BlockSize(),
|
||||
SecurityLevel: 128,
|
||||
}))
|
||||
|
||||
// SHA3
|
||||
sha3Base := &HashTool{
|
||||
Comment: "aka Keccak, FIPS-202, optimized for hardware",
|
||||
Author: "Guido Bertoni et al., 2015",
|
||||
}
|
||||
Register(sha3Base.With(&HashTool{
|
||||
Name: "SHA3-224",
|
||||
Hash: crypto.SHA3_224,
|
||||
DigestSize: crypto.SHA3_224.Size(),
|
||||
BlockSize: crypto.SHA3_224.New().BlockSize(),
|
||||
SecurityLevel: 112,
|
||||
}))
|
||||
Register(sha3Base.With(&HashTool{
|
||||
Name: "SHA3-256",
|
||||
Hash: crypto.SHA3_256,
|
||||
DigestSize: crypto.SHA3_256.Size(),
|
||||
BlockSize: crypto.SHA3_256.New().BlockSize(),
|
||||
SecurityLevel: 128,
|
||||
}))
|
||||
Register(sha3Base.With(&HashTool{
|
||||
Name: "SHA3-384",
|
||||
Hash: crypto.SHA3_384,
|
||||
DigestSize: crypto.SHA3_384.Size(),
|
||||
BlockSize: crypto.SHA3_384.New().BlockSize(),
|
||||
SecurityLevel: 192,
|
||||
}))
|
||||
Register(sha3Base.With(&HashTool{
|
||||
Name: "SHA3-512",
|
||||
Hash: crypto.SHA3_512,
|
||||
DigestSize: crypto.SHA3_512.Size(),
|
||||
BlockSize: crypto.SHA3_512.New().BlockSize(),
|
||||
SecurityLevel: 256,
|
||||
}))
|
||||
}
|
63
hashtools/tools.go
Normal file
63
hashtools/tools.go
Normal file
|
@ -0,0 +1,63 @@
|
|||
package hashtools
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"sort"
|
||||
)
|
||||
|
||||
var (
|
||||
hashToolMap = make(map[string]*HashTool)
|
||||
hashToolList = sortableHashToolList{}
|
||||
|
||||
// ErrNotFound is returned when a hash tool cannot be found.
|
||||
ErrNotFound = errors.New("does not exist")
|
||||
)
|
||||
|
||||
// Register registers a new HashTool. This function may only be called in init() functions.
|
||||
func Register(hashTool *HashTool) {
|
||||
hashToolMap[hashTool.Name] = hashTool
|
||||
hashToolList = append(hashToolList, hashTool)
|
||||
sort.Sort(hashToolList)
|
||||
}
|
||||
|
||||
// Get returns the HashTool with the given name.
|
||||
func Get(name string) (*HashTool, error) {
|
||||
hashTool, ok := hashToolMap[name]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("tool %s %w", name, ErrNotFound)
|
||||
}
|
||||
return hashTool, nil
|
||||
}
|
||||
|
||||
// New returns a new hash.Hash with the given Name
|
||||
func New(name string) (hash.Hash, error) {
|
||||
hashTool, err := Get(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return hashTool.New(), nil
|
||||
}
|
||||
|
||||
// AsMap returns all HashTools in a map. The returned map must not be modified.
|
||||
func AsMap() map[string]*HashTool {
|
||||
return hashToolMap
|
||||
}
|
||||
|
||||
// AsList returns all HashTools in a slice. The returned slice must not be modified.
|
||||
func AsList() []*HashTool {
|
||||
return hashToolList
|
||||
}
|
||||
|
||||
type sortableHashToolList []*HashTool
|
||||
|
||||
// Len implements sort.Interface.
|
||||
func (l sortableHashToolList) Len() int { return len(l) }
|
||||
|
||||
// Swap implements sort.Interface.
|
||||
func (l sortableHashToolList) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
|
||||
|
||||
// Less implements sort.Interface.
|
||||
func (l sortableHashToolList) Less(i, j int) bool { return l[i].Name < l[j].Name }
|
33
hashtools/tools_test.go
Normal file
33
hashtools/tools_test.go
Normal file
|
@ -0,0 +1,33 @@
|
|||
package hashtools
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAll(t *testing.T) {
|
||||
|
||||
testData := []byte("The quick brown fox jumps over the lazy dog. ")
|
||||
|
||||
all := AsList()
|
||||
for _, hashTool := range all {
|
||||
|
||||
// take detour in getting hash.Hash for testing
|
||||
hash, err := New(hashTool.Name)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get HashTool %s", hashTool.Name)
|
||||
}
|
||||
|
||||
if hash.BlockSize() != hashTool.BlockSize {
|
||||
t.Errorf("hashTool %s is broken or reports invalid block size. Expected %d, got %d.", hashTool.Name, hashTool.BlockSize, hash.BlockSize())
|
||||
}
|
||||
|
||||
_, err = hash.Write(testData)
|
||||
if err != nil {
|
||||
t.Errorf("hashTool %s failed to write: %s", hashTool.Name, err)
|
||||
}
|
||||
|
||||
sum := hash.Sum(nil)
|
||||
if len(sum) != hashTool.DigestSize {
|
||||
t.Errorf("hashTool %s is broken or reports invalid digest size. Expected %d, got %d.", hashTool.Name, hashTool.DigestSize, len(sum))
|
||||
}
|
||||
|
||||
}
|
||||
}
|
109
helper.go
Normal file
109
helper.go
Normal file
|
@ -0,0 +1,109 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
)
|
||||
|
||||
var (
|
||||
errNoSession = errors.New("helper is used outside of session")
|
||||
errNoKDF = errors.New("session has no key derivation tool")
|
||||
)
|
||||
|
||||
// Helper provides a basic interface for tools to access session properties and functionality.
|
||||
type Helper struct {
|
||||
session *Session
|
||||
info *tools.ToolInfo
|
||||
}
|
||||
|
||||
// NewSessionKey returns a new session key in tool's specified length.
|
||||
func (h *Helper) NewSessionKey() ([]byte, error) {
|
||||
if h.session == nil {
|
||||
return nil, errNoSession
|
||||
}
|
||||
if h.session.kdf == nil {
|
||||
return nil, errNoKDF
|
||||
}
|
||||
|
||||
if h.info.KeySize > 0 {
|
||||
return h.session.kdf.DeriveKey(h.info.KeySize)
|
||||
}
|
||||
return h.session.kdf.DeriveKey(h.session.DefaultSymmetricKeySize)
|
||||
}
|
||||
|
||||
// FillNewSessionKey fills the given []byte slice with a new session key (or nonce).
|
||||
func (h *Helper) FillNewSessionKey(key []byte) error {
|
||||
if h.session == nil {
|
||||
return errNoSession
|
||||
}
|
||||
if h.session.kdf == nil {
|
||||
return errNoKDF
|
||||
}
|
||||
|
||||
return h.session.kdf.DeriveKeyWriteTo(key)
|
||||
}
|
||||
|
||||
// NewSessionNonce returns a new session nonce in tool's specified length.
|
||||
func (h *Helper) NewSessionNonce() ([]byte, error) {
|
||||
if h.session == nil {
|
||||
return nil, errNoSession
|
||||
}
|
||||
if h.session.kdf == nil {
|
||||
return nil, errNoKDF
|
||||
}
|
||||
|
||||
if h.info.NonceSize > 0 {
|
||||
return h.session.kdf.DeriveKey(h.info.NonceSize)
|
||||
}
|
||||
return h.session.kdf.DeriveKey(h.session.DefaultSymmetricKeySize)
|
||||
}
|
||||
|
||||
// Random returns the io.Reader for reading randomness.
|
||||
func (h *Helper) Random() io.Reader {
|
||||
return Random()
|
||||
}
|
||||
|
||||
// RandomBytes returns the specified amount of random bytes in a []byte slice.
|
||||
func (h *Helper) RandomBytes(n int) ([]byte, error) {
|
||||
return RandomBytes(n)
|
||||
}
|
||||
|
||||
// Burn gets rid of the given []byte slice(s).
|
||||
func (h *Helper) Burn(data ...[]byte) {
|
||||
Burn(data...)
|
||||
}
|
||||
|
||||
// DefaultSymmetricKeySize returns the default key size for this session.
|
||||
func (h *Helper) DefaultSymmetricKeySize() int {
|
||||
if h.session != nil && h.session.DefaultSymmetricKeySize > 0 {
|
||||
return h.session.DefaultSymmetricKeySize
|
||||
}
|
||||
return defaultSymmetricKeySize
|
||||
}
|
||||
|
||||
// SecurityLevel returns the effective (ie. lowest) security level for this session.
|
||||
func (h *Helper) SecurityLevel() int {
|
||||
if h.session != nil && h.session.SecurityLevel > 0 {
|
||||
return h.session.SecurityLevel
|
||||
}
|
||||
return defaultSecurityLevel
|
||||
}
|
||||
|
||||
// MaxSecurityLevel returns the (highest) security level for this session.
|
||||
func (h *Helper) MaxSecurityLevel() int {
|
||||
if h.session != nil && h.session.maxSecurityLevel > 0 {
|
||||
return h.session.maxSecurityLevel
|
||||
}
|
||||
return defaultSecurityLevel
|
||||
}
|
||||
|
||||
// Burn gets rid of the given []byte slice(s).
|
||||
func Burn(data ...[]byte) {
|
||||
for _, slice := range data {
|
||||
for i := 0; i < len(slice); i++ {
|
||||
slice[i] = 0xFF
|
||||
}
|
||||
}
|
||||
}
|
85
letter-file.go
Normal file
85
letter-file.go
Normal file
|
@ -0,0 +1,85 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/safing/portbase/formats/dsd"
|
||||
|
||||
"github.com/safing/portbase/container"
|
||||
)
|
||||
|
||||
/*
|
||||
### File Format Version 1
|
||||
|
||||
- File Format Version: varint
|
||||
- Header: Letter without Data as byte block
|
||||
- Data: byte block
|
||||
*/
|
||||
|
||||
var (
|
||||
// ErrIncompatibleFileFormatVersion is returned when an incompatible wire format is encountered.
|
||||
ErrIncompatibleFileFormatVersion = errors.New("incompatible file format version")
|
||||
)
|
||||
|
||||
// ToFileFormat serializes the letter for storing it as a file.
|
||||
func (letter *Letter) ToFileFormat() (*container.Container, error) {
|
||||
c := container.New()
|
||||
|
||||
// File Format Version: varint
|
||||
c.AppendNumber(1)
|
||||
|
||||
// split header and data
|
||||
letterData := letter.Data
|
||||
letter.Data = nil
|
||||
|
||||
// Header: Letter without Data as byte block
|
||||
headerData, err := dsd.DumpIndent(letter, dsd.JSON, "\t")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// add newline for better raw viewability
|
||||
headerData = append(headerData, byte('\n'))
|
||||
// add header
|
||||
c.AppendAsBlock(headerData)
|
||||
|
||||
// Data: byte block
|
||||
c.AppendAsBlock(letterData)
|
||||
|
||||
// put back together
|
||||
letter.Data = letterData
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// LetterFromFileFormat parses a letter stored as a file.
|
||||
func LetterFromFileFormat(c *container.Container) (*Letter, error) {
|
||||
letter := &Letter{}
|
||||
|
||||
// File Format Version: varint
|
||||
fileFormatVersion, err := c.GetNextN8()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if fileFormatVersion != 1 {
|
||||
return nil, ErrIncompatibleFileFormatVersion
|
||||
}
|
||||
|
||||
// Header: Letter without Data as byte block
|
||||
data, err := c.GetNextBlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = dsd.Load(data, letter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Data: byte block
|
||||
letterData, err := c.GetNextBlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
letter.Data = letterData
|
||||
|
||||
return letter, nil
|
||||
}
|
200
letter-wire.go
Normal file
200
letter-wire.go
Normal file
|
@ -0,0 +1,200 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/safing/portbase/container"
|
||||
)
|
||||
|
||||
/*
|
||||
### Wire Format Version 1
|
||||
|
||||
- Wire Format Version: varint
|
||||
- Flags: varint
|
||||
- 1: Setup Msg (includes Version and Tools)
|
||||
- 2: Sending Keys
|
||||
- 4: Apply Keys
|
||||
- Version: varint (if Setup Msg)
|
||||
- Tools: (if Setup Msg)
|
||||
- Amount: varint
|
||||
- Names: byte blocks
|
||||
- Keys:
|
||||
- Amount: varint
|
||||
- IDs/Values: byte blocks
|
||||
- Nonce: byte block
|
||||
- Data: byte block
|
||||
- MAC: byte block
|
||||
*/
|
||||
|
||||
var (
|
||||
// ErrIncompatibleWireFormatVersion is returned when an incompatible wire format is encountered.
|
||||
ErrIncompatibleWireFormatVersion = errors.New("incompatible wire format version")
|
||||
)
|
||||
|
||||
// ToWire serializes to letter for sending it over a network connection.
|
||||
func (letter *Letter) ToWire() (*container.Container, error) {
|
||||
c := container.New()
|
||||
|
||||
// Wire Format Version: varint
|
||||
c.AppendNumber(1)
|
||||
|
||||
// Flags: varint
|
||||
// - 1: Setup Msg (includes Version and Tools)
|
||||
// - 2: Sending Keys
|
||||
// - 4: Apply Keys
|
||||
var flags uint64
|
||||
if letter.Version > 0 {
|
||||
flags |= 1
|
||||
}
|
||||
if len(letter.Keys) > 0 {
|
||||
flags |= 2
|
||||
}
|
||||
if letter.ApplyKeys {
|
||||
flags |= 4
|
||||
}
|
||||
c.AppendNumber(flags)
|
||||
|
||||
if letter.Version > 0 {
|
||||
// Version: varint (if Setup Msg)
|
||||
c.AppendNumber(uint64(letter.Version))
|
||||
|
||||
// Tools: (if Setup Msg)
|
||||
// - Amount: varint
|
||||
// - Names: byte blocks
|
||||
c.AppendInt(len(letter.Tools))
|
||||
for _, toolName := range letter.Tools {
|
||||
c.AppendAsBlock([]byte(toolName))
|
||||
}
|
||||
}
|
||||
|
||||
if len(letter.Keys) > 0 {
|
||||
// Keys:
|
||||
// - Amount: varint
|
||||
// - IDs/Values: byte blocks
|
||||
c.AppendInt(len(letter.Keys))
|
||||
for _, seal := range letter.Keys {
|
||||
c.AppendAsBlock([]byte(seal.ID))
|
||||
c.AppendAsBlock(seal.Value)
|
||||
}
|
||||
}
|
||||
|
||||
// Nonce: byte block
|
||||
c.AppendAsBlock(letter.Nonce)
|
||||
|
||||
// Data: byte block
|
||||
c.AppendAsBlock(letter.Data)
|
||||
|
||||
// MAC: byte block
|
||||
c.AppendAsBlock(letter.Mac)
|
||||
|
||||
// debugging:
|
||||
// fmt.Printf("%+v\n", c.CompileData())
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// LetterFromWire parses a letter sent over a network connection.
|
||||
func LetterFromWire(c *container.Container) (*Letter, error) {
|
||||
letter := &Letter{}
|
||||
|
||||
// Wire Format Version: varint
|
||||
wireFormatVersion, err := c.GetNextN8()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if wireFormatVersion != 1 {
|
||||
return nil, ErrIncompatibleWireFormatVersion
|
||||
}
|
||||
|
||||
// Flags: varint
|
||||
// - 1: Setup Msg (includes Version and Tools)
|
||||
// - 2: Sending Keys
|
||||
// - 4: Apply Keys
|
||||
var (
|
||||
setupMsg bool
|
||||
sendingKeys bool
|
||||
)
|
||||
flags, err := c.GetNextN64()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if flags&1 > 0 {
|
||||
setupMsg = true
|
||||
}
|
||||
if flags&2 > 0 {
|
||||
sendingKeys = true
|
||||
}
|
||||
if flags&4 > 0 {
|
||||
letter.ApplyKeys = true
|
||||
}
|
||||
|
||||
if setupMsg {
|
||||
// Version: varint (if Setup Msg)
|
||||
n, err := c.GetNextN8()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
letter.Version = n
|
||||
|
||||
// Tools: (if Setup Msg)
|
||||
// - Amount: varint
|
||||
// - Names: byte blocks
|
||||
n, err = c.GetNextN8()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
letter.Tools = make([]string, n)
|
||||
for i := 0; i < len(letter.Tools); i++ {
|
||||
toolName, err := c.GetNextBlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
letter.Tools[i] = string(toolName)
|
||||
}
|
||||
}
|
||||
|
||||
if sendingKeys {
|
||||
// Keys:
|
||||
// - Amount: varint
|
||||
// - IDs/Values: byte blocks
|
||||
n, err := c.GetNextN8()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
letter.Keys = make([]*Seal, n)
|
||||
for i := 0; i < len(letter.Keys); i++ {
|
||||
signetID, err := c.GetNextBlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sealValue, err := c.GetNextBlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
letter.Keys[i] = &Seal{
|
||||
ID: string(signetID),
|
||||
Value: sealValue,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Nonce: byte block
|
||||
letter.Nonce, err = c.GetNextBlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Data: byte block
|
||||
letter.Data, err = c.GetNextBlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// MAC: byte block
|
||||
letter.Mac, err = c.GetNextBlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return letter, nil
|
||||
}
|
257
letter.go
Normal file
257
letter.go
Normal file
|
@ -0,0 +1,257 @@
|
|||
// Container versions
|
||||
//
|
||||
// 1: for network, simple
|
||||
// 2: for storage
|
||||
// 3: for network, concealed (TBD)
|
||||
|
||||
package jess
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/safing/portbase/container"
|
||||
|
||||
"github.com/safing/portbase/formats/dsd"
|
||||
)
|
||||
|
||||
// Letter is the data format for encrypted data at rest or in transit.
|
||||
type Letter struct { //nolint:maligned // TODO
|
||||
Version uint8 // signed, MAC'd (may not exist when wired)
|
||||
Tools []string // signed, MAC'd (may not exist when wired)
|
||||
|
||||
Nonce []byte // signed, MAC'd
|
||||
Keys []*Seal `json:",omitempty"` // signed, MAC'd
|
||||
|
||||
Data []byte `json:",omitempty"` // signed, MAC'd
|
||||
Mac []byte `json:",omitempty"` // signed
|
||||
Signatures []*Seal `json:",omitempty"`
|
||||
|
||||
// Flags for wire protocol
|
||||
ApplyKeys bool `json:",omitempty"` // MAC'd
|
||||
}
|
||||
|
||||
// Seal holds a key, key exchange or signature within a letter.
|
||||
type Seal struct {
|
||||
Scheme string `json:",omitempty"`
|
||||
|
||||
// Key Establishment: Signet ID of recipient's signet
|
||||
// Signature: Signet ID of signer's signet
|
||||
ID string `json:",omitempty"`
|
||||
|
||||
// Key Establishment: Public key or wrapped key
|
||||
// Signature: Signature value
|
||||
Value []byte `json:",omitempty"`
|
||||
}
|
||||
|
||||
// Envelope returns an envelope built from the letter, configured for opening it.
|
||||
func (letter *Letter) Envelope() (*Envelope, error) {
|
||||
if letter.Version == 0 {
|
||||
return nil, fmt.Errorf("letter does not specify version")
|
||||
}
|
||||
if len(letter.Tools) == 0 {
|
||||
return nil, fmt.Errorf("letter does not specify any tools")
|
||||
}
|
||||
|
||||
e := &Envelope{
|
||||
Version: letter.Version,
|
||||
Tools: letter.Tools,
|
||||
requirements: newEmptyRequirements(),
|
||||
}
|
||||
|
||||
for _, seal := range letter.Keys {
|
||||
// handshake messages have ephermal encapsulation keys in first message
|
||||
if len(seal.ID) > 0 {
|
||||
if seal.Scheme == SignetSchemeKey || seal.Scheme == SignetSchemePassword {
|
||||
e.Secrets = append(e.Secrets, &Signet{
|
||||
Version: letter.Version,
|
||||
ID: seal.ID,
|
||||
Scheme: seal.Scheme,
|
||||
})
|
||||
} else {
|
||||
e.Recipients = append(e.Recipients, &Signet{
|
||||
Version: letter.Version,
|
||||
ID: seal.ID,
|
||||
Scheme: seal.Scheme,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, seal := range letter.Signatures {
|
||||
e.Senders = append(e.Senders, &Signet{
|
||||
Version: letter.Version,
|
||||
ID: seal.ID,
|
||||
Scheme: seal.Scheme,
|
||||
})
|
||||
}
|
||||
|
||||
e.opening = true
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// Open creates a session and opens the letter in one step.
|
||||
func (letter *Letter) Open(requirements *Requirements, trustStore TrustStore) ([]byte, error) {
|
||||
e, err := letter.Envelope()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if requirements != nil {
|
||||
e.requirements = requirements
|
||||
}
|
||||
|
||||
s, err := e.Correspondence(trustStore)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s.Open(letter)
|
||||
}
|
||||
|
||||
// Verify creates a session and verifies the letter in one step.
|
||||
func (letter *Letter) Verify(requirements *Requirements, trustStore TrustStore) error {
|
||||
e, err := letter.Envelope()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if requirements != nil {
|
||||
e.requirements = requirements
|
||||
}
|
||||
|
||||
s, err := e.initCorrespondence(trustStore, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.Verify(letter)
|
||||
}
|
||||
|
||||
// WireCorrespondence creates a wire session (communication over a network connection) from a letter.
|
||||
func (letter *Letter) WireCorrespondence(trustStore TrustStore) (*Session, error) {
|
||||
e, err := letter.Envelope()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return e.WireCorrespondence(trustStore)
|
||||
}
|
||||
|
||||
// ToJSON serializes the letter to json.
|
||||
func (letter *Letter) ToJSON() ([]byte, error) {
|
||||
return json.Marshal(letter)
|
||||
}
|
||||
|
||||
// LetterFromJSON loads a json-serialized letter
|
||||
func LetterFromJSON(data []byte) (*Letter, error) {
|
||||
letter := &Letter{}
|
||||
|
||||
err := json.Unmarshal(data, letter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return letter, nil
|
||||
}
|
||||
|
||||
// ToDSD serializes the letter to the given dsd format.
|
||||
func (letter *Letter) ToDSD(dsdFormat uint8) ([]byte, error) {
|
||||
data, err := dsd.Dump(letter, dsdFormat)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// LetterFromDSD loads a dsd-serialized letter.
|
||||
func LetterFromDSD(data []byte) (*Letter, error) {
|
||||
letter := &Letter{}
|
||||
|
||||
_, err := dsd.Load(data, letter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return letter, nil
|
||||
}
|
||||
|
||||
const (
|
||||
// Field IDs for signing
|
||||
// These IDs MUST NOT CHANGE
|
||||
|
||||
fieldIDLetterVersion uint64 = 1 // signed, MAC'd (may not exist when wired)
|
||||
fieldIDLetterTools uint64 = 2 // signed, MAC'd (may not exist when wired)
|
||||
fieldIDLetterNonce uint64 = 3 // signed, MAC'd
|
||||
fieldIDLetterKeys uint64 = 4 // signed, MAC'd
|
||||
fieldIDLetterMac uint64 = 5 // signed
|
||||
|
||||
fieldIDSealScheme uint64 = 16 // signed, MAC'd
|
||||
fieldIDSealID uint64 = 17 // signed, MAC'd
|
||||
fieldIDSealValue uint64 = 18 // signed, MAC'd
|
||||
)
|
||||
|
||||
func (letter *Letter) compileAssociatedData() []byte {
|
||||
// every field is transformed and prepended with a static ID
|
||||
// this makes it easy to stay backward compatible without hassling around with versioning when fields are added
|
||||
|
||||
c := container.New()
|
||||
|
||||
if letter.Version > 0 {
|
||||
c.AppendNumber(fieldIDLetterVersion) // append field ID
|
||||
c.AppendNumber(uint64(letter.Version))
|
||||
}
|
||||
if len(letter.Tools) > 0 {
|
||||
c.AppendNumber(fieldIDLetterTools) // append field ID
|
||||
c.AppendInt(len(letter.Tools)) // append number of tools
|
||||
for _, toolID := range letter.Tools {
|
||||
c.AppendAsBlock([]byte(toolID)) // append field content with length
|
||||
}
|
||||
}
|
||||
if len(letter.Nonce) > 0 {
|
||||
c.AppendNumber(fieldIDLetterNonce) // append field ID
|
||||
c.AppendAsBlock(letter.Nonce) // append field content with length
|
||||
}
|
||||
if len(letter.Keys) > 0 {
|
||||
c.AppendNumber(fieldIDLetterKeys) // append field ID
|
||||
c.AppendInt(len(letter.Keys)) // append number of keys
|
||||
for i, seal := range letter.Keys {
|
||||
c.AppendInt(i) // append index
|
||||
seal.compileAssociatedData(c) // append field content with length
|
||||
}
|
||||
}
|
||||
|
||||
return c.CompileData()
|
||||
}
|
||||
|
||||
func (letter *Letter) compileAssociatedSigningData(associatedData []byte) []byte {
|
||||
// compile basic associated data if not yet done
|
||||
if len(associatedData) == 0 {
|
||||
associatedData = letter.compileAssociatedData()
|
||||
}
|
||||
|
||||
// return if there is no Mac
|
||||
if len(letter.Mac) == 0 {
|
||||
return associatedData
|
||||
}
|
||||
|
||||
// add Mac to associated data and return
|
||||
c := container.New(associatedData)
|
||||
c.AppendNumber(fieldIDLetterMac) // append field ID
|
||||
c.AppendAsBlock(letter.Mac) // append field content with length
|
||||
|
||||
return c.CompileData()
|
||||
}
|
||||
|
||||
func (seal *Seal) compileAssociatedData(c *container.Container) {
|
||||
if seal.Scheme != "" {
|
||||
c.AppendNumber(fieldIDSealScheme) // append field ID
|
||||
c.AppendAsBlock([]byte(seal.Scheme)) // append field content with length
|
||||
}
|
||||
if seal.ID != "" {
|
||||
c.AppendNumber(fieldIDSealID) // append field ID
|
||||
c.AppendAsBlock([]byte(seal.ID)) // append field content with length
|
||||
}
|
||||
if len(seal.Value) > 0 {
|
||||
c.AppendNumber(fieldIDSealValue) // append field ID
|
||||
c.AppendAsBlock(seal.Value) // append field content with length
|
||||
}
|
||||
}
|
114
letter_test.go
Normal file
114
letter_test.go
Normal file
|
@ -0,0 +1,114 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSerialization(t *testing.T) {
|
||||
subject := &Letter{
|
||||
Version: 1,
|
||||
Tools: RecommendedNetwork,
|
||||
Keys: []*Seal{
|
||||
{ID: "a"},
|
||||
{ID: "b"},
|
||||
{ID: "c"},
|
||||
},
|
||||
Nonce: []byte{1, 2, 3},
|
||||
Data: []byte{4, 5, 6},
|
||||
Mac: []byte{7, 8, 9},
|
||||
ApplyKeys: true,
|
||||
}
|
||||
testSerialize(t, subject, true)
|
||||
|
||||
subject.Version = 0
|
||||
subject.Tools = nil
|
||||
testSerialize(t, subject, true)
|
||||
|
||||
subject.ApplyKeys = false
|
||||
testSerialize(t, subject, true)
|
||||
|
||||
subject.Keys = nil
|
||||
testSerialize(t, subject, true)
|
||||
}
|
||||
|
||||
func testSerialize(t *testing.T, letter *Letter, wireFormat bool) { //nolint:unparam
|
||||
// File Format
|
||||
|
||||
fileData, err := letter.ToFileFormat()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
letter2, err := LetterFromFileFormat(fileData)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
err = letter.CheckEqual(letter2)
|
||||
if err != nil {
|
||||
t.Errorf("letters (file format) do not match: %s\n%+v\n%+v\n", err, jsonFormat(letter), jsonFormat(letter2))
|
||||
return
|
||||
}
|
||||
|
||||
// Wire Format
|
||||
|
||||
if !wireFormat {
|
||||
return
|
||||
}
|
||||
|
||||
wire, err := letter.ToWire()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
letter3, err := LetterFromWire(wire)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
err = letter.CheckEqual(letter3)
|
||||
if err != nil {
|
||||
t.Errorf("letters (wire format) do not match: %s\n%+v\n%+v\n", err, jsonFormat(letter), jsonFormat(letter3))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (letter *Letter) CheckEqual(other *Letter) error {
|
||||
letterValue := reflect.ValueOf(*letter)
|
||||
otherValue := reflect.ValueOf(*other)
|
||||
|
||||
numElements := letterValue.NumField()
|
||||
for i := 0; i < numElements; i++ {
|
||||
ok := false
|
||||
|
||||
name := letterValue.Type().Field(i).Name
|
||||
switch name {
|
||||
case "Data": // TODO: this required special handling in the past, leave it here for now.
|
||||
ok = bytes.Equal(letter.Data, other.Data)
|
||||
default:
|
||||
ok = reflect.DeepEqual(letterValue.Field(i).Interface(), otherValue.Field(i).Interface())
|
||||
}
|
||||
|
||||
if !ok {
|
||||
return fmt.Errorf("field %s mismatches", name)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func jsonFormat(v interface{}) string {
|
||||
formatted, err := json.MarshalIndent(v, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Sprintf("<JSON format error: %s>", err)
|
||||
}
|
||||
return string(formatted)
|
||||
}
|
82
lhash/algs.go
Normal file
82
lhash/algs.go
Normal file
|
@ -0,0 +1,82 @@
|
|||
package lhash
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"hash"
|
||||
|
||||
// register SHA2 in Go's internal registry
|
||||
_ "crypto/sha256"
|
||||
_ "crypto/sha512"
|
||||
|
||||
// register SHA3 in Go's internal registry
|
||||
_ "golang.org/x/crypto/sha3"
|
||||
|
||||
// register BLAKE2 in Go's internal registry
|
||||
_ "golang.org/x/crypto/blake2b"
|
||||
_ "golang.org/x/crypto/blake2s"
|
||||
)
|
||||
|
||||
// Algorithm is an identifier for a hash function.
|
||||
type Algorithm uint
|
||||
|
||||
//nolint:golint,stylecheck // names are really the best this way
|
||||
const (
|
||||
SHA2_224 Algorithm = 8
|
||||
SHA2_256 Algorithm = 9
|
||||
SHA2_384 Algorithm = 10
|
||||
SHA2_512 Algorithm = 11
|
||||
SHA2_512_224 Algorithm = 12
|
||||
SHA2_512_256 Algorithm = 13
|
||||
|
||||
SHA3_224 Algorithm = 16
|
||||
SHA3_256 Algorithm = 17
|
||||
SHA3_384 Algorithm = 18
|
||||
SHA3_512 Algorithm = 19
|
||||
|
||||
BLAKE2s_256 Algorithm = 24
|
||||
BLAKE2b_256 Algorithm = 25
|
||||
BLAKE2b_384 Algorithm = 26
|
||||
BLAKE2b_512 Algorithm = 27
|
||||
)
|
||||
|
||||
func (a Algorithm) new() hash.Hash {
|
||||
switch a {
|
||||
|
||||
// SHA2
|
||||
case SHA2_224:
|
||||
return crypto.SHA224.New()
|
||||
case SHA2_256:
|
||||
return crypto.SHA256.New()
|
||||
case SHA2_384:
|
||||
return crypto.SHA384.New()
|
||||
case SHA2_512:
|
||||
return crypto.SHA512.New()
|
||||
case SHA2_512_224:
|
||||
return crypto.SHA512_224.New()
|
||||
case SHA2_512_256:
|
||||
return crypto.SHA512_256.New()
|
||||
|
||||
// SHA3
|
||||
case SHA3_224:
|
||||
return crypto.SHA3_224.New()
|
||||
case SHA3_256:
|
||||
return crypto.SHA3_256.New()
|
||||
case SHA3_384:
|
||||
return crypto.SHA3_384.New()
|
||||
case SHA3_512:
|
||||
return crypto.SHA3_512.New()
|
||||
|
||||
// BLAKE2
|
||||
case BLAKE2s_256:
|
||||
return crypto.BLAKE2s_256.New()
|
||||
case BLAKE2b_256:
|
||||
return crypto.BLAKE2b_256.New()
|
||||
case BLAKE2b_384:
|
||||
return crypto.BLAKE2b_384.New()
|
||||
case BLAKE2b_512:
|
||||
return crypto.BLAKE2b_512.New()
|
||||
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
89
lhash/labeledhash.go
Normal file
89
lhash/labeledhash.go
Normal file
|
@ -0,0 +1,89 @@
|
|||
package lhash
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/safing/portbase/container"
|
||||
)
|
||||
|
||||
// LabeledHash represents a typed hash value.
|
||||
type LabeledHash struct {
|
||||
alg Algorithm
|
||||
digest []byte
|
||||
}
|
||||
|
||||
// Digest creates a new labeled hash and digests the given data.
|
||||
func Digest(alg Algorithm, data []byte) *LabeledHash {
|
||||
hasher := alg.new()
|
||||
_, _ = hasher.Write(data) // never returns an error
|
||||
defer hasher.Reset() // internal state may leak data if kept in memory
|
||||
|
||||
return &LabeledHash{
|
||||
alg: alg,
|
||||
digest: hasher.Sum(nil),
|
||||
}
|
||||
}
|
||||
|
||||
// Load loads a labeled hash from the given []byte slice.
|
||||
func Load(labeledHash []byte) (*LabeledHash, error) {
|
||||
c := container.New(labeledHash)
|
||||
|
||||
algID, err := c.GetNextN64()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse algorithm ID: %s", err)
|
||||
}
|
||||
|
||||
digest, err := c.GetNextBlock()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse digest: %s", err)
|
||||
}
|
||||
|
||||
if c.Length() > 0 {
|
||||
return nil, errors.New("integrity error: data left over after parsing")
|
||||
}
|
||||
|
||||
alg := Algorithm(uint(algID))
|
||||
if alg.new() == nil {
|
||||
return nil, errors.New("compatibility error: invalid or unsupported algorithm")
|
||||
}
|
||||
|
||||
return &LabeledHash{
|
||||
alg: alg,
|
||||
digest: digest,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// LoadFromString loads a labeled hash from the given string.
|
||||
func LoadFromString(labeledHash string) (*LabeledHash, error) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(labeledHash)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode: %s", err)
|
||||
}
|
||||
|
||||
return Load(raw)
|
||||
}
|
||||
|
||||
// Bytes return the []byte representation of the labeled hash.
|
||||
func (lh *LabeledHash) Bytes() []byte {
|
||||
c := container.New()
|
||||
c.AppendNumber(uint64(lh.alg))
|
||||
c.AppendAsBlock(lh.digest)
|
||||
return c.CompileData()
|
||||
}
|
||||
|
||||
// String returns the string representation of the labeled hash (base64 raw url encoding).
|
||||
func (lh *LabeledHash) String() string {
|
||||
return base64.RawURLEncoding.EncodeToString(lh.Bytes())
|
||||
}
|
||||
|
||||
// Matches returns true if the digest of the given data matches the hash.
|
||||
func (lh *LabeledHash) Matches(data []byte) bool {
|
||||
hasher := lh.alg.new()
|
||||
_, _ = hasher.Write(data) // never returns an error
|
||||
defer hasher.Reset() // internal state may leak data if kept in memory
|
||||
|
||||
return subtle.ConstantTimeCompare(lh.digest, hasher.Sum(nil)) == 1
|
||||
}
|
86
lhash/labeledhash_test.go
Normal file
86
lhash/labeledhash_test.go
Normal file
|
@ -0,0 +1,86 @@
|
|||
package lhash
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var (
|
||||
testEmpty = []byte("")
|
||||
testFox = []byte("The quick brown fox jumps over the lazy dog.")
|
||||
)
|
||||
|
||||
func testAlgorithm(t *testing.T, alg Algorithm, emptyHex, foxHex string) {
|
||||
|
||||
// setup
|
||||
emptyBytes, err := hex.DecodeString(emptyHex)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
foxBytes, err := hex.DecodeString(foxHex)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// check against reference hashes
|
||||
|
||||
// test empty
|
||||
lh := Digest(alg, testEmpty)
|
||||
if !bytes.Equal(lh.Bytes()[2:], emptyBytes) {
|
||||
t.Errorf("alg %d: test empty: digest mismatch, expected %+v, got %+v", alg, emptyBytes, lh.Bytes()[2:])
|
||||
}
|
||||
|
||||
// test fox
|
||||
lh = Digest(alg, testFox)
|
||||
if !bytes.Equal(lh.Bytes()[2:], foxBytes) {
|
||||
t.Errorf("alg %d: test fox: digest mismatch, expected %+v, got %+v", alg, foxBytes, lh.Bytes()[2:])
|
||||
}
|
||||
|
||||
// test matching
|
||||
if !lh.Matches(testFox) {
|
||||
t.Errorf("alg %d: failed to match reference", alg)
|
||||
}
|
||||
if lh.Matches([]byte("nope")) {
|
||||
t.Errorf("alg %d: failed to non-match garbage", alg)
|
||||
}
|
||||
|
||||
// serialize
|
||||
lhs := Digest(alg, testFox).String()
|
||||
// load
|
||||
loaded, err := LoadFromString(lhs)
|
||||
if err != nil {
|
||||
t.Errorf("alg %d: failed to load from string: %s", alg, err)
|
||||
return
|
||||
}
|
||||
|
||||
// test matching with serialized/loaded labeled hash
|
||||
if !loaded.Matches(testFox) {
|
||||
t.Errorf("alg %d: failed to match reference", alg)
|
||||
}
|
||||
if loaded.Matches([]byte("nope")) {
|
||||
t.Errorf("alg %d: failed to non-match garbage", alg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHash(t *testing.T) {
|
||||
testAlgorithm(t, SHA2_256,
|
||||
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c",
|
||||
)
|
||||
|
||||
testAlgorithm(t, SHA2_512,
|
||||
"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e",
|
||||
"91ea1245f20d46ae9a037a989f54f1f790f0a47607eeb8a14d12890cea77a1bbc6c7ed9cf205e67b7f2b8fd4c7dfd3a7a8617e45f3c463d481c7e586c39ac1ed",
|
||||
)
|
||||
|
||||
testAlgorithm(t, SHA3_512,
|
||||
"a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26",
|
||||
"18f4f4bd419603f95538837003d9d254c26c23765565162247483f65c50303597bc9ce4d289f21d1c2f1f458828e33dc442100331b35e7eb031b5d38ba6460f8",
|
||||
)
|
||||
|
||||
testAlgorithm(t, BLAKE2b_512,
|
||||
"786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce",
|
||||
"87af9dc4afe5651b7aa89124b905fd214bf17c79af58610db86a0fb1e0194622a4e9d8e395b352223a8183b0d421c0994b98286cbf8c68a495902e0fe6e2bda2",
|
||||
)
|
||||
}
|
104
password.go
Normal file
104
password.go
Normal file
|
@ -0,0 +1,104 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
// ASCII printable characters (character codes 32-127)
|
||||
passwordCharSets = []string{
|
||||
"abcdefghijklmnopqrstuvwxyz",
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
|
||||
"0123456789",
|
||||
"- .,_", // more common special characters, especially with passwords using words
|
||||
"!\"#$%&'()*+/:;<=>?@[\\]^`{|}~",
|
||||
}
|
||||
|
||||
// extended ASCII codes (character code 128-255)
|
||||
// assume pool size of 32 (a quarter), as not all of them are common / easily accessible on every keyboard
|
||||
passwordExtraPoolSize = 32
|
||||
|
||||
createPasswordCallback func(signet *Signet, minSecurityLevel int) error
|
||||
getPasswordCallback func(signet *Signet) error
|
||||
)
|
||||
|
||||
// SetPasswordCallbacks sets callbacks that are used to let the user enter passwords.
|
||||
func SetPasswordCallbacks(
|
||||
createPassword func(signet *Signet, minSecurityLevel int) error,
|
||||
getPassword func(signet *Signet) error,
|
||||
) {
|
||||
if createPasswordCallback == nil {
|
||||
createPasswordCallback = createPassword
|
||||
}
|
||||
if getPasswordCallback == nil {
|
||||
getPasswordCallback = getPassword
|
||||
}
|
||||
}
|
||||
|
||||
// CalculatePasswordSecurityLevel calculates the security level of the given password and iterations of the pbkdf algorithm.
|
||||
func CalculatePasswordSecurityLevel(password string, iterations int) int {
|
||||
|
||||
// TODO: this calculation is pretty conservative and errs on the safe side
|
||||
// maybe soften this up a litte, but couldn't find any scientific foundation for that
|
||||
|
||||
charactersFound := 0
|
||||
distinctCharactersFound := 0
|
||||
characterPoolSize := 0
|
||||
|
||||
// loop all character sets
|
||||
for _, charSet := range passwordCharSets {
|
||||
foundInCharSet := false
|
||||
|
||||
// loop through every character in the character set
|
||||
for _, char := range charSet {
|
||||
// count occurrences in password
|
||||
cnt := countRuneInString(password, char)
|
||||
// disqualify if a single character is 1/4 of the password
|
||||
if cnt*4 >= len(password) {
|
||||
return -1
|
||||
}
|
||||
// we found something!
|
||||
if cnt > 0 {
|
||||
charactersFound += cnt
|
||||
distinctCharactersFound++
|
||||
foundInCharSet = true
|
||||
}
|
||||
}
|
||||
|
||||
// if we found anything in this char set, add the it's length to the total pool
|
||||
if foundInCharSet {
|
||||
characterPoolSize += len(charSet)
|
||||
}
|
||||
}
|
||||
|
||||
// disqualify if characters are repeated 4 or more times, on average
|
||||
if distinctCharactersFound*4 <= len(password) {
|
||||
return -1
|
||||
}
|
||||
|
||||
// check if there are some extra characters
|
||||
if charactersFound < len(password) {
|
||||
// add the extra pool size
|
||||
characterPoolSize += passwordExtraPoolSize
|
||||
}
|
||||
|
||||
possibleCombinationsWithPoolSize := math.Pow(float64(characterPoolSize), float64(len(password)))
|
||||
entropy := math.Log2(possibleCombinationsWithPoolSize)
|
||||
avgNumberOfGuesses := math.Pow(2, entropy-1)
|
||||
avgGuessingOperations := avgNumberOfGuesses * float64(iterations)
|
||||
securityLevel := math.Log2(avgGuessingOperations)
|
||||
|
||||
return int(securityLevel) // always round down
|
||||
}
|
||||
|
||||
func countRuneInString(s string, r rune) (n int) {
|
||||
for {
|
||||
i := strings.IndexRune(s, r)
|
||||
if i < 0 {
|
||||
return
|
||||
}
|
||||
n++
|
||||
s = s[i+1:]
|
||||
}
|
||||
}
|
74
password_test.go
Normal file
74
password_test.go
Normal file
|
@ -0,0 +1,74 @@
|
|||
package jess
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCalculatePasswordSecurityLevel(t *testing.T) {
|
||||
// basic weak
|
||||
testPWSL(t, "asdf", -1)
|
||||
testPWSL(t, "asdfasdf", -1)
|
||||
testPWSL(t, "asdfasdxxxx", -1)
|
||||
testPWSL(t, "asdfasdfasdf", -1)
|
||||
testPWSL(t, "asdfasdfasdf", -1)
|
||||
testPWSL(t, "WgEKCp8c8{bPrG{Zo(Ms97pxaaaaaaaa", -1)
|
||||
testPWSL(t, "aaaaaaaaAAAAAAAA00000000********", -1)
|
||||
|
||||
// chars only
|
||||
testPWSL(t, "AVWHBwmF", 58)
|
||||
testPWSL(t, "AVWHBwmFGt", 70)
|
||||
testPWSL(t, "AVWHBwmFGtLM", 81)
|
||||
testPWSL(t, "AVWHBwmFGtLMGh", 93)
|
||||
testPWSL(t, "AVWHBwmFGtLMGhYf", 104)
|
||||
testPWSL(t, "AVWHBwmFGtLMGhYfPkcyawfmZXRTQdxs", 195)
|
||||
|
||||
// with number
|
||||
testPWSL(t, "AVWHBwm1", 60)
|
||||
testPWSL(t, "AVWHBwmFG1", 72)
|
||||
testPWSL(t, "AVWHBwmFGtL1", 84)
|
||||
testPWSL(t, "AVWHBwmFGtLMG1", 96)
|
||||
testPWSL(t, "AVWHBwmFGtLMGhY1", 108)
|
||||
testPWSL(t, "AVWHBwmFGtLMGhYfPkcyawfmZXRTQdx1", 203)
|
||||
|
||||
// with number and special
|
||||
testPWSL(t, "AVWHBw1_", 61)
|
||||
testPWSL(t, "AVWHBwmF1_", 73)
|
||||
testPWSL(t, "AVWHBwmFGt1_", 86)
|
||||
testPWSL(t, "AVWHBwmFGtLM1_", 98)
|
||||
testPWSL(t, "AVWHBwmFGtLMGh1_", 110)
|
||||
testPWSL(t, "AVWHBwmFGtLMGhYfPkcyawfmZXRTQd1_", 207)
|
||||
|
||||
// with number and more special
|
||||
testPWSL(t, "AVWHBw1*", 65)
|
||||
testPWSL(t, "AVWHBwmF1*", 78)
|
||||
testPWSL(t, "AVWHBwmFGt1*", 91)
|
||||
testPWSL(t, "AVWHBwmFGtLM1*", 104)
|
||||
testPWSL(t, "AVWHBwmFGtLMGh1*", 117)
|
||||
testPWSL(t, "AVWHBwmFGtLMGhYfPkcyawfmZXRTQd1*", 221)
|
||||
|
||||
// created, strong
|
||||
|
||||
// "Schneier scheme"
|
||||
// source: https://www.schneier.com/blog/archives/2014/03/choosing_secure_1.html
|
||||
testPWSL(t, "WIw7,mstmsritt...", 116)
|
||||
testPWSL(t, "Wow...doestcst", 94)
|
||||
testPWSL(t, "Ltime@go-inag~faaa!", 135)
|
||||
testPWSL(t, "uTVM,TPw55:utvm,tpwstillsecure", 210)
|
||||
|
||||
// generated, strong
|
||||
testPWSL(t, "YebGPQuuoxQwyeJMvEWACTLexUUxVBFdHYqqUybBUNfBttCvWQxDdDCdYfgMPCQp", 378)
|
||||
testPWSL(t, "dpPyXmXpbECn6LWuQDJaitTTJguGfRTqNUxWfoHnBKDHvRhjR2WiQ7iDcuRJNnEd", 394)
|
||||
testPWSL(t, "WgEKCp8c8{bPrG{Zo(Ms97pKt3EsR9ycz4R=kMjPp^Uafqxsd2ZTFtkfvnoueKJz", 428)
|
||||
testPWSL(t, "galena-fighter-festival", 127)
|
||||
testPWSL(t, "impotent-drug-dropout-damage", 152)
|
||||
testPWSL(t, "artless-newswire-rill-belgium-marplot", 196)
|
||||
testPWSL(t, "forbade-momenta-spook-sure-devilish-wobbly", 221)
|
||||
}
|
||||
|
||||
func testPWSL(t *testing.T, password string, expectedSecurityLevel int) {
|
||||
securityLevel := CalculatePasswordSecurityLevel(password, 20000)
|
||||
|
||||
if securityLevel < expectedSecurityLevel {
|
||||
t.Errorf("password %s (%di): %d - expected at least %d", password, 20000, securityLevel, expectedSecurityLevel)
|
||||
} else {
|
||||
t.Logf("password %s (%di): %d", password, 20000, securityLevel)
|
||||
}
|
||||
}
|
44
random.go
Normal file
44
random.go
Normal file
|
@ -0,0 +1,44 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"io"
|
||||
|
||||
"github.com/tevino/abool"
|
||||
)
|
||||
|
||||
var (
|
||||
customRandReader io.Reader
|
||||
customRandReaderFlag = abool.NewBool(false)
|
||||
)
|
||||
|
||||
// Random returns the io.Reader for reading randomness. By default, it uses crypto/rand.Reader.
|
||||
func Random() io.Reader {
|
||||
if customRandReaderFlag.IsSet() {
|
||||
return customRandReader
|
||||
}
|
||||
return rand.Reader
|
||||
}
|
||||
|
||||
// RandomBytes returns the specified amount of random bytes in a []byte slice. By default, it uses crypto/rand.Reader.
|
||||
func RandomBytes(n int) ([]byte, error) {
|
||||
rBytes := make([]byte, n)
|
||||
|
||||
bytesRead, err := Random().Read(rBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if bytesRead != n {
|
||||
return nil, ErrInsufficientRandom
|
||||
}
|
||||
|
||||
return rBytes, nil
|
||||
}
|
||||
|
||||
// SetCustomRNG sets a custom RNG to be used with jess.
|
||||
func SetCustomRNG(randReader io.Reader) {
|
||||
if !customRandReaderFlag.IsSet() {
|
||||
customRandReader = randReader
|
||||
customRandReaderFlag.Set()
|
||||
}
|
||||
}
|
161
requirements.go
Normal file
161
requirements.go
Normal file
|
@ -0,0 +1,161 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Security requirements of a letter
|
||||
const (
|
||||
Confidentiality uint8 = iota
|
||||
Integrity
|
||||
RecipientAuthentication
|
||||
SenderAuthentication
|
||||
)
|
||||
|
||||
// Requirements describe security properties.
|
||||
type Requirements struct {
|
||||
all []uint8
|
||||
}
|
||||
|
||||
// newEmptyRequirements returns an empty requirements instance.
|
||||
func newEmptyRequirements() *Requirements {
|
||||
return &Requirements{}
|
||||
}
|
||||
|
||||
// NewRequirements returns an attribute instance with all requirements.
|
||||
func NewRequirements() *Requirements {
|
||||
return &Requirements{
|
||||
all: []uint8{
|
||||
Confidentiality,
|
||||
Integrity,
|
||||
RecipientAuthentication,
|
||||
SenderAuthentication,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Empty returns whether the requirements are empty.
|
||||
func (requirements *Requirements) Empty() bool {
|
||||
return len(requirements.all) == 0
|
||||
}
|
||||
|
||||
// Has returns whether the requirements contain the given attribute.
|
||||
func (requirements *Requirements) Has(attribute uint8) bool {
|
||||
for _, attr := range requirements.all {
|
||||
if attr == attribute {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Add adds an attribute.
|
||||
func (requirements *Requirements) Add(attribute uint8) *Requirements {
|
||||
if !requirements.Has(attribute) {
|
||||
requirements.all = append(requirements.all, attribute)
|
||||
}
|
||||
return requirements
|
||||
}
|
||||
|
||||
// Remove removes an attribute.
|
||||
func (requirements *Requirements) Remove(attribute uint8) *Requirements {
|
||||
for i, attr := range requirements.all {
|
||||
if attr == attribute {
|
||||
requirements.all = append(requirements.all[:i], requirements.all[i+1:]...)
|
||||
return requirements
|
||||
}
|
||||
}
|
||||
return requirements
|
||||
}
|
||||
|
||||
// CheckComplianceTo checks if the requirements are compliant to the given required requirements.
|
||||
func (requirements *Requirements) CheckComplianceTo(requirement *Requirements) error {
|
||||
var missing *Requirements
|
||||
for _, attr := range requirement.all {
|
||||
if !requirements.Has(attr) {
|
||||
if missing == nil {
|
||||
missing = newEmptyRequirements()
|
||||
}
|
||||
missing.Add(attr)
|
||||
}
|
||||
}
|
||||
if missing != nil {
|
||||
return fmt.Errorf("missing tools with security requirements: %s", missing.String())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// String returns a string representation of the requirements.
|
||||
func (requirements *Requirements) String() string {
|
||||
var names []string
|
||||
for _, attr := range requirements.all {
|
||||
switch attr {
|
||||
case Confidentiality:
|
||||
names = append(names, "Confidentiality")
|
||||
case Integrity:
|
||||
names = append(names, "Integrity")
|
||||
case RecipientAuthentication:
|
||||
names = append(names, "RecipientAuthentication")
|
||||
case SenderAuthentication:
|
||||
names = append(names, "SenderAuthentication")
|
||||
}
|
||||
}
|
||||
return strings.Join(names, ", ")
|
||||
}
|
||||
|
||||
// ShortString returns a short string representation of the requirements.
|
||||
func (requirements *Requirements) ShortString() string {
|
||||
var s string
|
||||
if requirements.Has(Confidentiality) {
|
||||
s += "C"
|
||||
}
|
||||
if requirements.Has(Integrity) {
|
||||
s += "I"
|
||||
}
|
||||
if requirements.Has(RecipientAuthentication) {
|
||||
s += "R"
|
||||
}
|
||||
if requirements.Has(SenderAuthentication) {
|
||||
s += "S"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// SerializeToNoSpec returns the requirements as a negated "No" string.
|
||||
func (requirements *Requirements) SerializeToNoSpec() string {
|
||||
var s string
|
||||
if !requirements.Has(Confidentiality) {
|
||||
s += "C"
|
||||
}
|
||||
if !requirements.Has(Integrity) {
|
||||
s += "I"
|
||||
}
|
||||
if !requirements.Has(RecipientAuthentication) {
|
||||
s += "R"
|
||||
}
|
||||
if !requirements.Has(SenderAuthentication) {
|
||||
s += "S"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// ParseRequirementsFromNoSpec parses the requirements from a negated "No" string.
|
||||
func ParseRequirementsFromNoSpec(no string) (*Requirements, error) {
|
||||
requirements := NewRequirements()
|
||||
for _, id := range no {
|
||||
switch id {
|
||||
case 'C':
|
||||
requirements.Remove(Confidentiality)
|
||||
case 'I':
|
||||
requirements.Remove(Integrity)
|
||||
case 'R':
|
||||
requirements.Remove(RecipientAuthentication)
|
||||
case 'S':
|
||||
requirements.Remove(SenderAuthentication)
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown attribute identifier: %c", id)
|
||||
}
|
||||
}
|
||||
return requirements, nil
|
||||
}
|
40
requirements_test.go
Normal file
40
requirements_test.go
Normal file
|
@ -0,0 +1,40 @@
|
|||
package jess
|
||||
|
||||
import "testing"
|
||||
|
||||
func checkNoSpec(t *testing.T, a *Requirements, expectedNoSpec string) {
|
||||
noSpec := a.SerializeToNoSpec()
|
||||
if noSpec != expectedNoSpec {
|
||||
t.Errorf(`unexpected no spec "%s", expected "%s"`, noSpec, expectedNoSpec)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequirements(t *testing.T) {
|
||||
|
||||
a := NewRequirements()
|
||||
checkNoSpec(t, a, "")
|
||||
|
||||
a.Remove(SenderAuthentication)
|
||||
checkNoSpec(t, a, "S")
|
||||
|
||||
a.Remove(RecipientAuthentication)
|
||||
checkNoSpec(t, a, "RS")
|
||||
|
||||
a.Remove(Integrity)
|
||||
checkNoSpec(t, a, "IRS")
|
||||
|
||||
a.Remove(Confidentiality)
|
||||
checkNoSpec(t, a, "CIRS")
|
||||
|
||||
a.Add(SenderAuthentication)
|
||||
checkNoSpec(t, a, "CIR")
|
||||
|
||||
a.Add(RecipientAuthentication)
|
||||
checkNoSpec(t, a, "CI")
|
||||
|
||||
a.Add(Integrity)
|
||||
checkNoSpec(t, a, "C")
|
||||
|
||||
a.Add(Confidentiality)
|
||||
checkNoSpec(t, a, "")
|
||||
}
|
99
session-wire.go
Normal file
99
session-wire.go
Normal file
|
@ -0,0 +1,99 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
)
|
||||
|
||||
const (
|
||||
wireStateInit uint8 = iota
|
||||
wireStateIdle
|
||||
wireStateSendKey
|
||||
wireStateAwaitKey
|
||||
wireStateSendApply
|
||||
wireStatsAwaitApply
|
||||
)
|
||||
|
||||
var (
|
||||
wireReKeyAfterMsgs uint64 = 100000 // re-exchange keys every 100000 messages
|
||||
|
||||
requiredWireSessionRequirements = NewRequirements().Remove(SenderAuthentication)
|
||||
)
|
||||
|
||||
// WireSession holds session information specific to communication over a network connection.
|
||||
type WireSession struct { //nolint:maligned // TODO
|
||||
session *Session
|
||||
|
||||
server bool
|
||||
msgNo uint64
|
||||
lastReKeyAtMsgNo uint64
|
||||
|
||||
sendKeyCarryover []byte
|
||||
recvKeyCarryover []byte
|
||||
|
||||
// key mgmt state
|
||||
eKXSignets []*kxPair
|
||||
eKESignets []*kePair
|
||||
handshakeState uint8
|
||||
newKeyMaterial [][]byte
|
||||
}
|
||||
|
||||
// kxPair is key exchange pair
|
||||
type kxPair struct {
|
||||
tool tools.ToolLogic
|
||||
signet *Signet
|
||||
peer *Signet
|
||||
}
|
||||
|
||||
// kePair is key encapsulation "pair"
|
||||
type kePair struct {
|
||||
tool tools.ToolLogic
|
||||
signet *Signet
|
||||
seal *Seal
|
||||
}
|
||||
|
||||
// initWireSession is called after newSession() to make a wire session from a regular one.
|
||||
func (s *Session) initWireSession() error {
|
||||
// check required requirements
|
||||
err := s.toolRequirements.CheckComplianceTo(requiredWireSessionRequirements)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// check for currently unsupported features
|
||||
for _, tool := range s.all {
|
||||
switch tool.Info().Purpose {
|
||||
case tools.PurposePassDerivation,
|
||||
tools.PurposeSigning:
|
||||
return fmt.Errorf("wire sessions currently do not support %s", tool.Info().Name)
|
||||
}
|
||||
}
|
||||
|
||||
// check for static pre shared keys
|
||||
err = s.envelope.LoopSecrets(SignetSchemeKey, func(signet *Signet) error {
|
||||
return errors.New("wire sessions currently do not support pre-shared keys")
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s.wire = &WireSession{
|
||||
session: s,
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Server marks a wire session as being in the role of the server, rather than the client.
|
||||
func (s *Session) Server() {
|
||||
if s.wire != nil {
|
||||
s.wire.server = true
|
||||
}
|
||||
}
|
||||
|
||||
// reKeyNeeded returns whether rekeying is needed.
|
||||
func (w *WireSession) reKeyNeeded() bool {
|
||||
return w.msgNo-w.lastReKeyAtMsgNo > wireReKeyAfterMsgs
|
||||
}
|
511
session.go
Normal file
511
session.go
Normal file
|
@ -0,0 +1,511 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"strings"
|
||||
|
||||
"github.com/safing/jess/hashtools"
|
||||
"github.com/safing/jess/tools"
|
||||
)
|
||||
|
||||
// Session holds session information for operations using the envelope it was initialized with.
|
||||
type Session struct {
|
||||
envelope *Envelope
|
||||
|
||||
DefaultSymmetricKeySize int
|
||||
SecurityLevel int
|
||||
maxSecurityLevel int
|
||||
toolRequirements *Requirements
|
||||
|
||||
// session over the wire
|
||||
wire *WireSession
|
||||
|
||||
// instances
|
||||
|
||||
all []tools.ToolLogic
|
||||
toolsWithState []tools.ToolLogic
|
||||
|
||||
kdf tools.ToolLogic
|
||||
|
||||
passDerivator tools.ToolLogic
|
||||
keyExchangers []tools.ToolLogic
|
||||
keyEncapsulators []tools.ToolLogic
|
||||
|
||||
integratedCiphers []tools.ToolLogic
|
||||
ciphers []tools.ToolLogic
|
||||
|
||||
managedMACHashers map[string]*managedHasher
|
||||
macs []tools.ToolLogic
|
||||
|
||||
managedSigningHashers map[string]*managedHasher
|
||||
signers []tools.ToolLogic
|
||||
}
|
||||
|
||||
type managedHasher struct {
|
||||
tool *hashtools.HashTool
|
||||
hash hash.Hash
|
||||
}
|
||||
|
||||
// Sum returns the hash sum of the managed hasher
|
||||
func (sh *managedHasher) Sum() ([]byte, error) {
|
||||
if sh == nil || sh.hash == nil {
|
||||
return nil, errors.New("managed hasher is broken")
|
||||
}
|
||||
return sh.hash.Sum(nil), nil
|
||||
}
|
||||
|
||||
func newSession(e *Envelope) (*Session, error) { //nolint:gocognit,gocyclo
|
||||
if len(e.Tools) == 0 {
|
||||
return nil, errors.New("envelope is missing tools")
|
||||
}
|
||||
|
||||
s := &Session{
|
||||
envelope: e,
|
||||
toolRequirements: newEmptyRequirements(),
|
||||
}
|
||||
|
||||
var (
|
||||
keySourceAvailable bool = false
|
||||
totalSignetsSeen int
|
||||
requireSecurityLevel bool = false
|
||||
requireDefaultKeySize bool = false
|
||||
)
|
||||
|
||||
// tool init loop: start
|
||||
for i, toolID := range s.envelope.Tools {
|
||||
|
||||
///////////////////////////////////////
|
||||
// tool init loop: check for duplicates
|
||||
///////////////////////////////////////
|
||||
|
||||
for j, dupeToolID := range s.envelope.Tools {
|
||||
if i != j && toolID == dupeToolID {
|
||||
return nil, fmt.Errorf("cannot use tool %s twice, each tool may be only specified once", toolID)
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////
|
||||
// tool init loop: parse, prep and get
|
||||
//////////////////////////////////////
|
||||
|
||||
var (
|
||||
hashTool *hashtools.HashTool
|
||||
hashSumFn func() ([]byte, error)
|
||||
)
|
||||
|
||||
// parse ID for args
|
||||
var arg string
|
||||
if strings.Contains(toolID, "(") {
|
||||
splitted := strings.Split(toolID, "(")
|
||||
toolID = splitted[0]
|
||||
arg = strings.Trim(splitted[1], "()")
|
||||
}
|
||||
|
||||
// get tool
|
||||
tool, err := tools.Get(toolID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the specified tool %s could not be found", toolID)
|
||||
}
|
||||
|
||||
// create logic instance and add to logic and state lists
|
||||
logic := tool.Factory()
|
||||
s.all = append(s.all, logic)
|
||||
if tool.Info.HasOption(tools.OptionHasState) {
|
||||
s.toolsWithState = append(s.toolsWithState, logic)
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////
|
||||
// tool init loop: assign tools to queues and add requirements
|
||||
////////////////////////////////////////////////////////////
|
||||
|
||||
switch tool.Info.Purpose {
|
||||
case tools.PurposeKeyDerivation:
|
||||
if s.kdf != nil {
|
||||
return nil, fmt.Errorf("cannot use %s, you may only specify one key derivation tool and %s was already specified", tool.Info.Name, s.kdf.Info().Name)
|
||||
}
|
||||
s.kdf = logic
|
||||
|
||||
case tools.PurposePassDerivation:
|
||||
if s.passDerivator != nil {
|
||||
return nil, fmt.Errorf("cannot use %s, you may only specify one password derivation tool and %s was already specified", tool.Info.Name, s.passDerivator.Info().Name)
|
||||
}
|
||||
s.passDerivator = logic
|
||||
s.toolRequirements.Add(SenderAuthentication)
|
||||
s.toolRequirements.Add(RecipientAuthentication)
|
||||
|
||||
case tools.PurposeKeyExchange:
|
||||
s.keyExchangers = append(s.keyExchangers, logic)
|
||||
s.toolRequirements.Add(RecipientAuthentication)
|
||||
|
||||
case tools.PurposeKeyEncapsulation:
|
||||
s.keyEncapsulators = append(s.keyEncapsulators, logic)
|
||||
s.toolRequirements.Add(RecipientAuthentication)
|
||||
|
||||
case tools.PurposeSigning:
|
||||
s.signers = append(s.signers, logic)
|
||||
s.toolRequirements.Add(SenderAuthentication)
|
||||
|
||||
case tools.PurposeIntegratedCipher:
|
||||
s.integratedCiphers = append(s.integratedCiphers, logic)
|
||||
s.toolRequirements.Add(Confidentiality)
|
||||
s.toolRequirements.Add(Integrity)
|
||||
|
||||
case tools.PurposeCipher:
|
||||
s.ciphers = append(s.ciphers, logic)
|
||||
s.toolRequirements.Add(Confidentiality)
|
||||
|
||||
case tools.PurposeMAC:
|
||||
s.macs = append(s.macs, logic)
|
||||
s.toolRequirements.Add(Integrity)
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////
|
||||
// tool init loop: process options, get hashers
|
||||
///////////////////////////////////////////////
|
||||
|
||||
for _, option := range tool.Info.Options {
|
||||
switch option {
|
||||
|
||||
case tools.OptionStreaming:
|
||||
// TODO: Implementation pending.
|
||||
|
||||
case tools.OptionNeedsManagedHasher:
|
||||
// get managed hasher list
|
||||
var managedHashers map[string]*managedHasher
|
||||
switch tool.Info.Purpose {
|
||||
case tools.PurposeMAC:
|
||||
if s.managedMACHashers == nil {
|
||||
s.managedMACHashers = make(map[string]*managedHasher)
|
||||
}
|
||||
managedHashers = s.managedMACHashers
|
||||
case tools.PurposeSigning:
|
||||
if s.managedSigningHashers == nil {
|
||||
s.managedSigningHashers = make(map[string]*managedHasher)
|
||||
}
|
||||
managedHashers = s.managedSigningHashers
|
||||
default:
|
||||
return nil, fmt.Errorf("only MAC and Signing tools may use managed hashers")
|
||||
}
|
||||
|
||||
// get or assign a new managed hasher
|
||||
mngdHasher, ok := managedHashers[arg]
|
||||
if !ok {
|
||||
// get hashtool
|
||||
ht, err := hashtools.Get(arg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the specified hashtool for %s(%s) could not be found", toolID, arg)
|
||||
}
|
||||
|
||||
// save to managed hashers
|
||||
mngdHasher = &managedHasher{
|
||||
tool: ht,
|
||||
hash: ht.New(),
|
||||
}
|
||||
managedHashers[arg] = mngdHasher
|
||||
}
|
||||
|
||||
hashTool = mngdHasher.tool
|
||||
hashSumFn = mngdHasher.Sum
|
||||
|
||||
case tools.OptionNeedsDedicatedHasher:
|
||||
hashTool, err = hashtools.Get(arg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the specified hashtool for %s(%s) could not be found", toolID, arg)
|
||||
}
|
||||
|
||||
case tools.OptionNeedsSecurityLevel:
|
||||
requireSecurityLevel = true
|
||||
|
||||
case tools.OptionNeedsDefaultKeySize:
|
||||
requireDefaultKeySize = true
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////
|
||||
// tool init loop: initialize tool
|
||||
//////////////////////////////////
|
||||
|
||||
// init tool
|
||||
logic.Init(
|
||||
tool,
|
||||
&Helper{
|
||||
session: s,
|
||||
info: tool.Info,
|
||||
},
|
||||
hashTool,
|
||||
hashSumFn,
|
||||
)
|
||||
|
||||
/////////////////////////////////////////////////
|
||||
// tool init loop: calc and check security levels
|
||||
/////////////////////////////////////////////////
|
||||
|
||||
err = s.calcAndCheckSecurityLevel(logic, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////
|
||||
// tool init loop: calculate default key size
|
||||
/////////////////////////////////////////////
|
||||
|
||||
// find biggest key size for default
|
||||
if tool.Info.KeySize > s.DefaultSymmetricKeySize {
|
||||
s.DefaultSymmetricKeySize = tool.Info.KeySize
|
||||
}
|
||||
|
||||
} // tool init loop: end
|
||||
|
||||
//////////////////////////////////////////////////////////
|
||||
// calc and check signet security levels, default key size
|
||||
//////////////////////////////////////////////////////////
|
||||
|
||||
for _, tool := range s.all {
|
||||
|
||||
var err error
|
||||
var seen int
|
||||
|
||||
// calc and check signet security levels
|
||||
switch tool.Info().Purpose {
|
||||
case tools.PurposePassDerivation:
|
||||
//nolint:scopelint // function is executed immediately within loop
|
||||
err = e.LoopSecrets(SignetSchemePassword, func(signet *Signet) error {
|
||||
seen++
|
||||
return s.calcAndCheckSecurityLevel(tool, signet)
|
||||
})
|
||||
keySourceAvailable = true
|
||||
|
||||
case tools.PurposeKeyExchange,
|
||||
tools.PurposeKeyEncapsulation:
|
||||
//nolint:scopelint // function is executed immediately within loop
|
||||
err = e.LoopRecipients(tool.Info().Name, func(signet *Signet) error {
|
||||
seen++
|
||||
return s.calcAndCheckSecurityLevel(tool, signet)
|
||||
})
|
||||
keySourceAvailable = true
|
||||
|
||||
case tools.PurposeSigning:
|
||||
//nolint:scopelint // function is executed immediately within loop
|
||||
err = e.LoopSenders(tool.Info().Name, func(signet *Signet) error {
|
||||
seen++
|
||||
return s.calcAndCheckSecurityLevel(tool, signet)
|
||||
})
|
||||
keySourceAvailable = true
|
||||
|
||||
default:
|
||||
continue
|
||||
}
|
||||
|
||||
// check error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// check if anything is here
|
||||
if seen == 0 {
|
||||
return nil, fmt.Errorf("tool %s requires at least one signet", tool.Info().Name)
|
||||
}
|
||||
totalSignetsSeen += seen
|
||||
}
|
||||
|
||||
// key signets
|
||||
err := e.LoopSecrets(SignetSchemeKey, func(signet *Signet) error {
|
||||
totalSignetsSeen++
|
||||
keySourceAvailable = true
|
||||
// FIXME
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
/////////////////////////////////////////////////////////
|
||||
// check security level and default key size requirements
|
||||
/////////////////////////////////////////////////////////
|
||||
|
||||
// apply manual security level
|
||||
if minimumSecurityLevel > 0 && minimumSecurityLevel > s.SecurityLevel {
|
||||
s.SecurityLevel = minimumSecurityLevel
|
||||
}
|
||||
// apply manual key size
|
||||
if minimumSymmetricKeySize > 0 && minimumSymmetricKeySize > s.DefaultSymmetricKeySize {
|
||||
s.DefaultSymmetricKeySize = minimumSymmetricKeySize
|
||||
}
|
||||
|
||||
// check security level requirement
|
||||
if requireSecurityLevel && s.SecurityLevel == 0 {
|
||||
return nil, fmt.Errorf("this toolset requires the security level to be set manually")
|
||||
}
|
||||
// check default key size requirement
|
||||
if requireDefaultKeySize && s.DefaultSymmetricKeySize == 0 {
|
||||
return nil, fmt.Errorf("this toolset requires the default key size to be set manually")
|
||||
}
|
||||
|
||||
///////////////
|
||||
// final checks
|
||||
///////////////
|
||||
|
||||
// check requirements requirements
|
||||
if s.toolRequirements.Empty() {
|
||||
return nil, errors.New("envelope excludes all security requirements, no meaningful operation possible")
|
||||
}
|
||||
err = s.toolRequirements.CheckComplianceTo(s.envelope.requirements)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// check if we have recipient auth without confidentiality
|
||||
if s.toolRequirements.Has(RecipientAuthentication) &&
|
||||
!s.toolRequirements.Has(Confidentiality) {
|
||||
return nil, errors.New("having recipient authentication without confidentiality does not make sense")
|
||||
}
|
||||
|
||||
// check if we have confidentiality without integrity
|
||||
if s.toolRequirements.Has(Confidentiality) &&
|
||||
!s.toolRequirements.Has(Integrity) {
|
||||
return nil, errors.New("having confidentiality without integrity does not make sense")
|
||||
}
|
||||
|
||||
// check if we are missing a kdf, but need one
|
||||
if s.kdf == nil && len(s.signers) != len(s.envelope.Tools) {
|
||||
return nil, errors.New("missing a key derivation tool")
|
||||
}
|
||||
|
||||
// check if have a kdf, even if we don't need one
|
||||
if len(s.integratedCiphers) == 0 &&
|
||||
len(s.ciphers) == 0 &&
|
||||
len(s.macs) == 0 &&
|
||||
s.kdf != nil {
|
||||
return nil, errors.New("key derivation tool specified, but not needed")
|
||||
}
|
||||
|
||||
// check if we have a key source
|
||||
if !keySourceAvailable &&
|
||||
(s.toolRequirements.Has(Integrity) || s.toolRequirements.Has(Confidentiality)) {
|
||||
return nil, errors.New("missing key source, please add a tool that provides a key or add a key signet directly")
|
||||
}
|
||||
|
||||
// check if there are unused signets
|
||||
if len(s.envelope.Secrets)+
|
||||
len(s.envelope.Senders)+
|
||||
len(s.envelope.Recipients) > totalSignetsSeen {
|
||||
return nil, fmt.Errorf("detected signet or recipient in envelope that is not used by any tool")
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
//nolint:gocognit
|
||||
func (s *Session) calcAndCheckSecurityLevel(logic tools.ToolLogic, signet *Signet) error {
|
||||
// get signet scheme
|
||||
signetScheme := ""
|
||||
if signet != nil {
|
||||
signetScheme = signet.Scheme
|
||||
}
|
||||
|
||||
var err error
|
||||
var calculatedSecurityLevel int
|
||||
|
||||
switch {
|
||||
case signetScheme == SignetSchemeKey:
|
||||
calculatedSecurityLevel = len(signet.Key) * 8
|
||||
case signetScheme == SignetSchemePassword && signet != nil:
|
||||
// only check if present
|
||||
// existence check is done when opening/closing
|
||||
if len(signet.Key) > 0 {
|
||||
switch logic.Info().Name {
|
||||
case "PBKDF2-SHA2-256":
|
||||
// TODO: integrate this into the tool interface
|
||||
calculatedSecurityLevel = CalculatePasswordSecurityLevel(string(signet.Key), 20000)
|
||||
default:
|
||||
calculatedSecurityLevel = CalculatePasswordSecurityLevel(string(signet.Key), 1)
|
||||
}
|
||||
if calculatedSecurityLevel < 0 {
|
||||
return fmt.Errorf(`supplied password signet "%s" is exceptionally weak and should not be used`, signet.ID)
|
||||
}
|
||||
}
|
||||
default:
|
||||
// get tool security level
|
||||
if signet == nil {
|
||||
// nil interface hackery for inherited SecurityLevel() functions
|
||||
calculatedSecurityLevel, err = logic.SecurityLevel(nil)
|
||||
} else {
|
||||
calculatedSecurityLevel, err = logic.SecurityLevel(signet)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if calculatedSecurityLevel == 0 {
|
||||
// not applicable
|
||||
return nil
|
||||
}
|
||||
if calculatedSecurityLevel < 0 {
|
||||
// broken!
|
||||
if signet != nil {
|
||||
return fmt.Errorf(`supplied %s signet "%s" is considered broken and should not be used anymore`, signet.Scheme, signet.ID)
|
||||
}
|
||||
return fmt.Errorf(`tool %s is considered broken and should not be used anymore`, logic.Info().Name)
|
||||
}
|
||||
|
||||
if signet != nil {
|
||||
|
||||
// signet based security level checks
|
||||
switch {
|
||||
case minimumSecurityLevel > 0:
|
||||
// check against minimumSecurityLevel
|
||||
// minimumSecurityLevel overrides other checks
|
||||
if calculatedSecurityLevel < minimumSecurityLevel {
|
||||
return fmt.Errorf(`supplied %s signet "%s" with a security level of %d is weaker than the desired security level of %d`, signet.Scheme, signet.ID, calculatedSecurityLevel, minimumSecurityLevel)
|
||||
}
|
||||
case s.envelope.MinimumSecurityLevel > 0 && calculatedSecurityLevel < s.envelope.MinimumSecurityLevel:
|
||||
// check against envelope's minimum security level
|
||||
return fmt.Errorf(`supplied %s signet "%s" with a security level of %d is weaker than the envelope's minimum security level of %d`, signet.Scheme, signet.ID, calculatedSecurityLevel, s.envelope.MinimumSecurityLevel)
|
||||
case s.SecurityLevel > 0 && calculatedSecurityLevel < s.SecurityLevel:
|
||||
// check against toolset's security level
|
||||
return fmt.Errorf(`supplied %s signet "%s" with a security level of %d is weaker than the toolset's security level of %d`, signet.Scheme, signet.ID, calculatedSecurityLevel, s.SecurityLevel)
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
// tool based security level checks
|
||||
switch {
|
||||
case minimumSecurityLevel > 0:
|
||||
// check against minimumSecurityLevel
|
||||
// minimumSecurityLevel overrides other checks
|
||||
if calculatedSecurityLevel < minimumSecurityLevel {
|
||||
return fmt.Errorf(`tool %s with a security level of %d is weaker than the desired security level of %d`, logic.Info().Name, calculatedSecurityLevel, minimumSecurityLevel)
|
||||
}
|
||||
case s.envelope.MinimumSecurityLevel > 0 && calculatedSecurityLevel < s.envelope.MinimumSecurityLevel:
|
||||
// check against envelope's minimum security level
|
||||
return fmt.Errorf(`tool %s with a security level of %d is weaker than the envelope's minimum security level of %d`, logic.Info().Name, calculatedSecurityLevel, s.envelope.MinimumSecurityLevel)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// adapt security level of session
|
||||
|
||||
// lower session security level
|
||||
if s.SecurityLevel == 0 || calculatedSecurityLevel < s.SecurityLevel {
|
||||
s.SecurityLevel = calculatedSecurityLevel
|
||||
}
|
||||
// raise session max security level
|
||||
if calculatedSecurityLevel > s.maxSecurityLevel {
|
||||
s.maxSecurityLevel = calculatedSecurityLevel
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// NonceSize returns the nonce size to use for new letters.
|
||||
func (s *Session) NonceSize() int {
|
||||
size := s.maxSecurityLevel / 32
|
||||
if size < 4 {
|
||||
size = 4
|
||||
}
|
||||
|
||||
return size
|
||||
}
|
251
signet.go
Normal file
251
signet.go
Normal file
|
@ -0,0 +1,251 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
|
||||
uuid "github.com/satori/go.uuid"
|
||||
)
|
||||
|
||||
// Special signet types
|
||||
const (
|
||||
SignetSchemePassword = "pw"
|
||||
SignetSchemeKey = "key"
|
||||
)
|
||||
|
||||
// Signet describes a cryptographic key pair. Passwords and Keys may also be wrapped in a Signet for easier integration.
|
||||
type Signet struct { //nolint:maligned // TODO
|
||||
Version uint8
|
||||
ID string
|
||||
Scheme string
|
||||
|
||||
Key []byte
|
||||
Public bool `json:",omitempty"` // key is the public part of a key pair
|
||||
Protection *Envelope `json:",omitempty"` // key is a serialized letter
|
||||
|
||||
// Metadata about Signet
|
||||
Info *SignetInfo `json:",omitempty"`
|
||||
|
||||
// Signature of Version, Scheme, Key, Public, Protected, Info
|
||||
Signature *Letter `json:",omitempty"`
|
||||
|
||||
// cache
|
||||
tool *tools.Tool
|
||||
loadedPublicKey crypto.PublicKey
|
||||
loadedPrivateKey crypto.PrivateKey
|
||||
}
|
||||
|
||||
// SignetInfo holds human readable meta information about a signet.
|
||||
type SignetInfo struct {
|
||||
Name string
|
||||
Owner string
|
||||
Created time.Time
|
||||
Expires time.Time
|
||||
|
||||
Details [][2]string
|
||||
}
|
||||
|
||||
// NewSignetBase creates a new signet base without a key.
|
||||
func NewSignetBase(tool *tools.Tool) *Signet {
|
||||
return &Signet{
|
||||
Version: 1,
|
||||
Scheme: tool.Info.Name,
|
||||
tool: tool,
|
||||
}
|
||||
}
|
||||
|
||||
// GenerateSignet returns a new signet with a freshly generated key.
|
||||
func GenerateSignet(toolID string, securityLevel int) (*Signet, error) {
|
||||
tool, err := tools.Get(toolID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// generate signet
|
||||
signet := NewSignetBase(tool)
|
||||
err = signet.GenerateKey()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return signet, nil
|
||||
}
|
||||
|
||||
// GenerateKey generates a new key. Will not operate if key is already present.
|
||||
func (signet *Signet) GenerateKey() error {
|
||||
// check if there already is a key
|
||||
if len(signet.Key) > 0 ||
|
||||
signet.loadedPrivateKey != nil ||
|
||||
signet.loadedPublicKey != nil {
|
||||
return errors.New("cannot generate key: key already present")
|
||||
}
|
||||
|
||||
// load tool
|
||||
err := signet.loadTool()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// check if tool support Signets
|
||||
switch signet.tool.Info.Purpose {
|
||||
case tools.PurposeKeyExchange,
|
||||
tools.PurposeKeyEncapsulation,
|
||||
tools.PurposeSigning:
|
||||
// uses signets!
|
||||
default:
|
||||
return fmt.Errorf("tool %s does not use signets", signet.tool.Info.Name)
|
||||
}
|
||||
|
||||
// generate key
|
||||
return signet.tool.StaticLogic.GenerateKey(signet)
|
||||
}
|
||||
|
||||
// GetStoredKey returns the stored key and whether it is public.
|
||||
func (signet *Signet) GetStoredKey() (key []byte, public bool) {
|
||||
return signet.Key, signet.Public
|
||||
}
|
||||
|
||||
// SetStoredKey sets a new stored key and whether it is public.
|
||||
func (signet *Signet) SetStoredKey(key []byte, public bool) {
|
||||
signet.Key = key
|
||||
signet.Public = public
|
||||
}
|
||||
|
||||
// PublicKey returns the public key.
|
||||
func (signet *Signet) PublicKey() crypto.PublicKey {
|
||||
return signet.loadedPublicKey
|
||||
}
|
||||
|
||||
// PrivateKey returns the private key or nil, if there is none.
|
||||
func (signet *Signet) PrivateKey() crypto.PrivateKey {
|
||||
return signet.loadedPrivateKey
|
||||
}
|
||||
|
||||
// SetLoadedKeys sets the loaded public and private keys.
|
||||
func (signet *Signet) SetLoadedKeys(pubKey crypto.PublicKey, privKey crypto.PrivateKey) {
|
||||
signet.loadedPublicKey = pubKey
|
||||
signet.loadedPrivateKey = privKey
|
||||
}
|
||||
|
||||
// AsRecipient returns a public version of the Signet.
|
||||
func (signet *Signet) AsRecipient() (*Signet, error) {
|
||||
// load so we can split keys
|
||||
err := signet.LoadKey()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Signet{
|
||||
Version: signet.Version,
|
||||
ID: signet.ID,
|
||||
Scheme: signet.Scheme,
|
||||
Key: nil, // do not copy serialized key
|
||||
Public: true, // mark explicitly as public
|
||||
Protection: nil, // remove protection
|
||||
Info: signet.Info,
|
||||
Signature: nil, // remove signature, as it would be invalid
|
||||
tool: signet.tool,
|
||||
loadedPublicKey: signet.loadedPublicKey,
|
||||
loadedPrivateKey: nil, // remove private key
|
||||
}, nil
|
||||
}
|
||||
|
||||
// LoadKey loads the serialized key pair.
|
||||
func (signet *Signet) LoadKey() error {
|
||||
// check if already loaded
|
||||
if signet.loadedPublicKey != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// check if protected
|
||||
if signet.Protection != nil {
|
||||
return tools.ErrProtected
|
||||
}
|
||||
|
||||
// load tool
|
||||
err := signet.loadTool()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return signet.tool.StaticLogic.LoadKey(signet)
|
||||
}
|
||||
|
||||
// Tool returns the tool of the signet
|
||||
func (signet *Signet) Tool() (*tools.Tool, error) {
|
||||
// load tool
|
||||
err := signet.loadTool()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return signet.tool, nil
|
||||
}
|
||||
|
||||
// loadTool gets and caches the tool for the signet.
|
||||
func (signet *Signet) loadTool() error {
|
||||
if signet.tool != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
tool, err := tools.Get(signet.Scheme)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
signet.tool = tool
|
||||
return nil
|
||||
}
|
||||
|
||||
// StoreKey serializes the loaded key pair.
|
||||
func (signet *Signet) StoreKey() error {
|
||||
// check if already stored
|
||||
if len(signet.Key) != 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// load tool
|
||||
err := signet.loadTool()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return signet.tool.StaticLogic.StoreKey(signet)
|
||||
}
|
||||
|
||||
// Verify verifies the signature of the signet.
|
||||
func (signet *Signet) Verify() error {
|
||||
// FIXME
|
||||
return errors.New("NIY")
|
||||
}
|
||||
|
||||
// Burn destroys all the key material and renders the Signet unusable.
|
||||
func (signet *Signet) Burn() error {
|
||||
// load tool
|
||||
err := signet.loadTool()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return signet.tool.StaticLogic.BurnKey(signet)
|
||||
}
|
||||
|
||||
// AssignUUID generates a (new) UUID for the Signet.
|
||||
func (signet *Signet) AssignUUID() error {
|
||||
// generate UUID v4
|
||||
u := uuid.UUID{}
|
||||
_, err := io.ReadFull(Random(), u[:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
u.SetVersion(uuid.V4)
|
||||
u.SetVariant(uuid.VariantRFC4122)
|
||||
signet.ID = u.String()
|
||||
return nil
|
||||
}
|
210
supply/supply.go
Normal file
210
supply/supply.go
Normal file
|
@ -0,0 +1,210 @@
|
|||
// Package supply provides a cache of signets for pre-generating signets.
|
||||
package supply
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/safing/jess"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
)
|
||||
|
||||
// SignetSupply is cache of signets for pre-generating signets.
|
||||
type SignetSupply struct {
|
||||
lock sync.RWMutex
|
||||
caches map[string]*signetCache
|
||||
|
||||
notifyEmpty chan struct{}
|
||||
notifyFillable chan struct{}
|
||||
cacheSize int
|
||||
}
|
||||
|
||||
type signetCache struct {
|
||||
sync.Mutex
|
||||
tool *tools.Tool
|
||||
|
||||
stock []*jess.Signet
|
||||
stockIterator int
|
||||
stockFillLevel int
|
||||
}
|
||||
|
||||
// NewSignetSupply returns a new empty *SignetSupply. `cacheSize` specifies how many Signets to cache at maximum (min 1).
|
||||
func NewSignetSupply(cacheSize int) *SignetSupply {
|
||||
if cacheSize < 1 {
|
||||
cacheSize = 1
|
||||
}
|
||||
|
||||
return &SignetSupply{
|
||||
caches: make(map[string]*signetCache),
|
||||
notifyEmpty: make(chan struct{}, 1),
|
||||
notifyFillable: make(chan struct{}, 1),
|
||||
cacheSize: cacheSize,
|
||||
}
|
||||
}
|
||||
|
||||
// GetSignet returns a new signet from the supply.
|
||||
func (supply *SignetSupply) GetSignet(scheme string) (*jess.Signet, error) {
|
||||
supply.lock.RLock()
|
||||
cache, ok := supply.caches[scheme]
|
||||
supply.lock.RUnlock()
|
||||
|
||||
// init
|
||||
if !ok {
|
||||
// get tool
|
||||
tool, err := tools.Get(scheme)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// create new cache
|
||||
cache = &signetCache{
|
||||
tool: tool,
|
||||
stock: make([]*jess.Signet, supply.cacheSize),
|
||||
}
|
||||
// save to index
|
||||
supply.lock.Lock()
|
||||
supply.caches[scheme] = cache
|
||||
supply.lock.Unlock()
|
||||
}
|
||||
|
||||
signet := cache.get()
|
||||
|
||||
// returned signet from supply
|
||||
if signet != nil {
|
||||
// notify that supply can be filled again
|
||||
select {
|
||||
case supply.notifyFillable <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
|
||||
return signet, nil
|
||||
}
|
||||
|
||||
// notify that supply is empty
|
||||
select {
|
||||
case supply.notifyEmpty <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
|
||||
// generate ad hoc
|
||||
signet = jess.NewSignetBase(cache.tool)
|
||||
err := signet.GenerateKey()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return signet, nil
|
||||
}
|
||||
|
||||
func (sc *signetCache) get() *jess.Signet {
|
||||
sc.Lock()
|
||||
defer sc.Unlock()
|
||||
|
||||
// get slot
|
||||
signet := sc.stock[sc.stockIterator]
|
||||
if signet == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// reset slot
|
||||
sc.stock[sc.stockIterator] = nil
|
||||
|
||||
// debugging
|
||||
// fmt.Printf("returning %s: iter=%d fill=%d\n", sc.tool.Info.Name, sc.stockIterator, sc.stockFillLevel-1)
|
||||
|
||||
// adjust helpers
|
||||
sc.stockFillLevel--
|
||||
sc.stockIterator = (sc.stockIterator + 1) % len(sc.stock)
|
||||
|
||||
return signet
|
||||
}
|
||||
|
||||
// Fill fills all caches with new Signets in the specified amount (up to the cache size), and returns whether the caches are now full. This function is meant to be called periodically (when there is time) with small values for `amount` until the supply is full.
|
||||
func (supply *SignetSupply) Fill(amount int) (full bool, lastErr error) {
|
||||
supply.lock.RLock()
|
||||
defer supply.lock.RUnlock()
|
||||
|
||||
full = true
|
||||
for _, cache := range supply.caches {
|
||||
cacheIsFull, err := cache.fill(amount)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
}
|
||||
if !cacheIsFull {
|
||||
full = false
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (sc *signetCache) fill(amount int) (full bool, err error) {
|
||||
sc.Lock()
|
||||
defer sc.Unlock()
|
||||
|
||||
var signet *jess.Signet
|
||||
fillUpTo := sc.stockFillLevel + amount
|
||||
|
||||
// check upper bound
|
||||
if fillUpTo > len(sc.stock) {
|
||||
fillUpTo = len(sc.stock)
|
||||
}
|
||||
|
||||
// generate new signets until wanted fill amount is reached
|
||||
for i := (sc.stockIterator + sc.stockFillLevel) % len(sc.stock); // start at first empty index
|
||||
sc.stockFillLevel < fillUpTo; // continue until fill amount is reached
|
||||
i = (i + 1) % len(sc.stock) /* increase i, but wrap to start */ {
|
||||
// get signet from slot
|
||||
signet = sc.stock[i]
|
||||
|
||||
// debugging
|
||||
// fmt.Printf("filling %s: i=%d iter=%d fill=%d upto=%d signet=%+v\n", sc.tool.Info.Name, i, sc.stockIterator, sc.stockFillLevel, fillUpTo, signet)
|
||||
|
||||
if signet != nil {
|
||||
// full
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// generate new
|
||||
signet = jess.NewSignetBase(sc.tool)
|
||||
err := signet.GenerateKey()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// reassign
|
||||
sc.stock[i] = signet
|
||||
sc.stockFillLevel++
|
||||
}
|
||||
|
||||
return sc.stockFillLevel == len(sc.stock), nil
|
||||
}
|
||||
|
||||
// Status holds status information about a signet supply.
|
||||
type Status struct {
|
||||
TotalSize int
|
||||
FillLevel int
|
||||
}
|
||||
|
||||
// Status returns current status information.
|
||||
func (supply *SignetSupply) Status() *Status {
|
||||
supply.lock.RLock()
|
||||
defer supply.lock.RUnlock()
|
||||
|
||||
status := &Status{
|
||||
TotalSize: supply.cacheSize * len(supply.caches),
|
||||
}
|
||||
|
||||
// get current fill level
|
||||
for _, cache := range supply.caches {
|
||||
cache.status(status)
|
||||
}
|
||||
|
||||
return status
|
||||
}
|
||||
|
||||
func (sc *signetCache) status(status *Status) {
|
||||
sc.Lock()
|
||||
defer sc.Unlock()
|
||||
|
||||
status.FillLevel += sc.stockFillLevel
|
||||
}
|
71
supply/supply_test.go
Normal file
71
supply/supply_test.go
Normal file
|
@ -0,0 +1,71 @@
|
|||
package supply
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
_ "github.com/safing/jess/tools/all"
|
||||
)
|
||||
|
||||
func TestSupply(t *testing.T) {
|
||||
|
||||
total := 10
|
||||
supply := NewSignetSupply(total)
|
||||
scheme := "ECDH-X25519"
|
||||
|
||||
// get signet to initialize space
|
||||
_, err := supply.GetSignet(scheme)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// fill one
|
||||
full, err := supply.Fill(1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if full {
|
||||
t.Fatal("not expected to be full")
|
||||
}
|
||||
|
||||
// take two
|
||||
for i := 0; i < 2; i++ {
|
||||
_, err := supply.GetSignet(scheme)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// fill up
|
||||
full, err = supply.Fill(total + 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !full {
|
||||
t.Fatal("expected to be full")
|
||||
}
|
||||
|
||||
// empty all
|
||||
for i := 0; i < total; i++ {
|
||||
_, err := supply.GetSignet(scheme)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// fill and empty with different sizes
|
||||
for i := 0; i < total+3; i++ {
|
||||
// fill i
|
||||
_, err := supply.Fill(i)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// empty total-i
|
||||
for j := 0; j < total+3-i; j++ {
|
||||
_, err := supply.GetSignet(scheme)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
195
test
Executable file
195
test
Executable file
|
@ -0,0 +1,195 @@
|
|||
#!/bin/bash
|
||||
|
||||
warnings=0
|
||||
errors=0
|
||||
scripted=0
|
||||
goUp="\\e[1A"
|
||||
all=0
|
||||
fullTestFlags="-short"
|
||||
install=0
|
||||
|
||||
function help {
|
||||
echo "usage: $0 [command] [options]"
|
||||
echo ""
|
||||
echo "commands:"
|
||||
echo " <none> run baseline tests"
|
||||
echo " all run all tests"
|
||||
echo " install install deps for running baseline tests"
|
||||
echo " install all install deps for running all tests"
|
||||
echo ""
|
||||
echo "options:"
|
||||
echo " --scripted dont jump console lines (still use colors)"
|
||||
echo " [package] run tests only on this package"
|
||||
}
|
||||
|
||||
function run {
|
||||
if [[ $scripted -eq 0 ]]; then
|
||||
echo "[......] $*"
|
||||
fi
|
||||
|
||||
# create tmpfile
|
||||
tmpfile=$(mktemp)
|
||||
# execute
|
||||
$* >$tmpfile 2>&1
|
||||
rc=$?
|
||||
output=$(cat $tmpfile)
|
||||
|
||||
# check return code
|
||||
if [[ $rc -eq 0 ]]; then
|
||||
if [[ $output == *"[no test files]"* ]]; then
|
||||
echo -e "${goUp}[\e[01;33mNOTEST\e[00m] $*"
|
||||
warnings=$((warnings+1))
|
||||
else
|
||||
echo -ne "${goUp}[\e[01;32m OK \e[00m] "
|
||||
if [[ $2 == "test" ]]; then
|
||||
echo -n $*
|
||||
echo -n ": "
|
||||
echo $output | cut -f "3-" -d " "
|
||||
else
|
||||
echo $*
|
||||
fi
|
||||
fi
|
||||
else
|
||||
if [[ $output == *"build constraints exclude all Go files"* ]]; then
|
||||
echo -e "${goUp}[ !=OS ] $*"
|
||||
else
|
||||
echo -e "${goUp}[\e[01;31m FAIL \e[00m] $*"
|
||||
cat $tmpfile
|
||||
errors=$((errors+1))
|
||||
fi
|
||||
fi
|
||||
|
||||
rm -f $tmpfile
|
||||
}
|
||||
|
||||
function checkformat {
|
||||
if [[ $scripted -eq 0 ]]; then
|
||||
echo "[......] gofmt $1"
|
||||
fi
|
||||
|
||||
output=$(gofmt -l $GOPATH/src/$1/*.go)
|
||||
if [[ $output == "" ]]; then
|
||||
echo -e "${goUp}[\e[01;32m OK \e[00m] gofmt $*"
|
||||
else
|
||||
echo -e "${goUp}[\e[01;31m FAIL \e[00m] gofmt $*"
|
||||
echo "The following files do not conform to gofmt:"
|
||||
gofmt -l $GOPATH/src/$1/*.go # keeps format
|
||||
errors=$((errors+1))
|
||||
fi
|
||||
}
|
||||
|
||||
# get and switch to script dir
|
||||
baseDir="$( cd "$(dirname "$0")" && pwd )"
|
||||
cd "$baseDir"
|
||||
|
||||
# args
|
||||
while true; do
|
||||
case "$1" in
|
||||
"-h"|"help"|"--help")
|
||||
help
|
||||
exit 0
|
||||
;;
|
||||
"--scripted")
|
||||
scripted=1
|
||||
goUp=""
|
||||
shift 1
|
||||
;;
|
||||
"install")
|
||||
install=1
|
||||
shift 1
|
||||
;;
|
||||
"all")
|
||||
all=1
|
||||
fullTestFlags=""
|
||||
shift 1
|
||||
;;
|
||||
*)
|
||||
break
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# check if $GOPATH/bin is in $PATH
|
||||
if [[ $PATH != *"$GOPATH/bin"* ]]; then
|
||||
export PATH=$GOPATH/bin:$PATH
|
||||
fi
|
||||
|
||||
# install
|
||||
if [[ $install -eq 1 ]]; then
|
||||
echo "installing dependencies..."
|
||||
echo "$ go get -u golang.org/x/lint/golint"
|
||||
go get -u golang.org/x/lint/golint
|
||||
if [[ $all -eq 1 ]]; then
|
||||
echo "$ go get -u github.com/golangci/golangci-lint/cmd/golangci-lint"
|
||||
go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# check dependencies
|
||||
if [[ $(which go) == "" ]]; then
|
||||
echo "go command not found"
|
||||
exit 1
|
||||
fi
|
||||
if [[ $(which gofmt) == "" ]]; then
|
||||
echo "gofmt command not found"
|
||||
exit 1
|
||||
fi
|
||||
if [[ $(which golint) == "" ]]; then
|
||||
echo "golint command not found"
|
||||
echo "install with: go get -u golang.org/x/lint/golint"
|
||||
echo "or run: ./test install"
|
||||
exit 1
|
||||
fi
|
||||
if [[ $all -eq 1 ]]; then
|
||||
if [[ $(which golangci-lint) == "" ]]; then
|
||||
echo "golangci-lint command not found"
|
||||
echo "install locally with: go get -u github.com/golangci/golangci-lint/cmd/golangci-lint"
|
||||
echo "or run: ./test install all"
|
||||
echo ""
|
||||
echo "hint: install for CI with: curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin vX.Y.Z"
|
||||
echo "don't forget to specify the version you want"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# target selection
|
||||
if [[ "$1" == "" ]]; then
|
||||
# get all packages
|
||||
packages=$(go list ./...)
|
||||
else
|
||||
# single package testing
|
||||
packages=$(go list)/$1
|
||||
if [[ ! -d "$GOPATH/src/$packages" ]]; then
|
||||
echo "go package $packages does not exist"
|
||||
help
|
||||
exit 1
|
||||
fi
|
||||
echo "note: only running tests for package $packages"
|
||||
fi
|
||||
|
||||
# platform info
|
||||
platformInfo=$(go env GOOS GOARCH)
|
||||
echo "running tests for ${platformInfo//$'\n'/ }:"
|
||||
|
||||
# run vet/test on packages
|
||||
for package in $packages; do
|
||||
echo ""
|
||||
echo $package
|
||||
checkformat $package
|
||||
run golint -set_exit_status -min_confidence 1.0 $package
|
||||
run go vet $package
|
||||
if [[ $all -eq 1 ]]; then
|
||||
run golangci-lint run $GOPATH/src/$package
|
||||
fi
|
||||
run go test -cover $fullTestFlags $package
|
||||
done
|
||||
|
||||
echo ""
|
||||
if [[ $errors -gt 0 ]]; then
|
||||
echo "failed with $errors errors and $warnings warnings"
|
||||
exit 1
|
||||
else
|
||||
echo "succeeded with $warnings warnings"
|
||||
exit 0
|
||||
fi
|
24
tools.go
Normal file
24
tools.go
Normal file
|
@ -0,0 +1,24 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"github.com/safing/jess/tools"
|
||||
|
||||
// import all tools
|
||||
_ "github.com/safing/jess/tools/all"
|
||||
)
|
||||
|
||||
func init() {
|
||||
// init static logic
|
||||
for _, tool := range tools.AsList() {
|
||||
tool.StaticLogic = tool.Factory()
|
||||
tool.StaticLogic.Init(
|
||||
tool,
|
||||
&Helper{
|
||||
session: nil,
|
||||
info: tool.Info,
|
||||
},
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
}
|
||||
}
|
7
tools/all/all.go
Normal file
7
tools/all/all.go
Normal file
|
@ -0,0 +1,7 @@
|
|||
package all
|
||||
|
||||
import (
|
||||
// Import all tool subpackages
|
||||
_ "github.com/safing/jess/tools/ecdh"
|
||||
_ "github.com/safing/jess/tools/gostdlib"
|
||||
)
|
173
tools/ecdh/nist.go
Normal file
173
tools/ecdh/nist.go
Normal file
|
@ -0,0 +1,173 @@
|
|||
package ecdh
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/elliptic"
|
||||
"math/big"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
"github.com/safing/portbase/container"
|
||||
|
||||
"github.com/aead/ecdh"
|
||||
)
|
||||
|
||||
var (
|
||||
nistCurveInfo = &tools.ToolInfo{
|
||||
Purpose: tools.PurposeKeyExchange,
|
||||
Comment: "FIPS 186",
|
||||
Author: "NIST, 2009",
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
tools.Register(&tools.Tool{
|
||||
Info: nistCurveInfo.With(&tools.ToolInfo{
|
||||
Name: "ECDH-P224",
|
||||
SecurityLevel: 112,
|
||||
}),
|
||||
Factory: func() tools.ToolLogic { return &NistCurve{curve: ecdh.Generic(elliptic.P224())} },
|
||||
})
|
||||
tools.Register(&tools.Tool{
|
||||
Info: nistCurveInfo.With(&tools.ToolInfo{
|
||||
Name: "ECDH-P256",
|
||||
SecurityLevel: 128,
|
||||
}),
|
||||
Factory: func() tools.ToolLogic { return &NistCurve{curve: ecdh.Generic(elliptic.P256())} },
|
||||
})
|
||||
tools.Register(&tools.Tool{
|
||||
Info: nistCurveInfo.With(&tools.ToolInfo{
|
||||
Name: "ECDH-P384",
|
||||
SecurityLevel: 192,
|
||||
}),
|
||||
Factory: func() tools.ToolLogic { return &NistCurve{curve: ecdh.Generic(elliptic.P384())} },
|
||||
})
|
||||
tools.Register(&tools.Tool{
|
||||
Info: nistCurveInfo.With(&tools.ToolInfo{
|
||||
Name: "ECDH-P521",
|
||||
SecurityLevel: 256,
|
||||
}),
|
||||
Factory: func() tools.ToolLogic { return &NistCurve{curve: ecdh.Generic(elliptic.P521())} },
|
||||
})
|
||||
}
|
||||
|
||||
// NistCurve implements the cryptographic interface for ECDH key exchange with NIST curves.
|
||||
type NistCurve struct {
|
||||
tools.ToolLogicBase
|
||||
curve ecdh.KeyExchange
|
||||
}
|
||||
|
||||
// MakeSharedKey implements the ToolLogic interface.
|
||||
func (ec *NistCurve) MakeSharedKey(local tools.SignetInt, remote tools.SignetInt) ([]byte, error) {
|
||||
return ec.curve.ComputeSecret(local.PrivateKey(), remote.PublicKey()), nil
|
||||
}
|
||||
|
||||
// LoadKey implements the ToolLogic interface.
|
||||
func (ec *NistCurve) LoadKey(signet tools.SignetInt) error {
|
||||
var pubKey crypto.PublicKey
|
||||
var privKey crypto.PrivateKey
|
||||
|
||||
key, public := signet.GetStoredKey()
|
||||
c := container.New(key)
|
||||
|
||||
// check serialization version
|
||||
version, err := c.GetNextN8()
|
||||
if err != nil || version != 1 {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
|
||||
// load public key
|
||||
// extract public key data
|
||||
pointXData, err := c.GetNextBlock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pointYData, err := c.GetNextBlock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// transform public key data
|
||||
point := ecdh.Point{}
|
||||
point.X = new(big.Int).SetBytes(pointXData)
|
||||
point.Y = new(big.Int).SetBytes(pointYData)
|
||||
pubKey = point
|
||||
|
||||
// check public key
|
||||
err = ec.curve.Check(pubKey)
|
||||
if err != nil {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
|
||||
// load private key
|
||||
if !public {
|
||||
privKey = c.CompileData()
|
||||
}
|
||||
|
||||
signet.SetLoadedKeys(pubKey, privKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
// StoreKey implements the ToolLogic interface.
|
||||
func (ec *NistCurve) StoreKey(signet tools.SignetInt) error {
|
||||
pubKey := signet.PublicKey()
|
||||
privKey := signet.PrivateKey()
|
||||
public := privKey == nil
|
||||
|
||||
// create storage with serialization version
|
||||
c := container.New()
|
||||
c.AppendNumber(1)
|
||||
|
||||
// store public key
|
||||
curvePoint := pubKey.(ecdh.Point)
|
||||
c.AppendAsBlock(curvePoint.X.Bytes())
|
||||
c.AppendAsBlock(curvePoint.Y.Bytes())
|
||||
|
||||
// store private key
|
||||
if !public {
|
||||
c.Append(privKey.([]byte))
|
||||
}
|
||||
|
||||
signet.SetStoredKey(c.CompileData(), public)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GenerateKey implements the ToolLogic interface.
|
||||
func (ec *NistCurve) GenerateKey(signet tools.SignetInt) error {
|
||||
// define variable types for API security
|
||||
var pubKey crypto.PublicKey
|
||||
var privKey crypto.PrivateKey
|
||||
var err error
|
||||
|
||||
// generate keys
|
||||
privKey, pubKey, err = ec.curve.GenerateKey(ec.Helper().Random())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
signet.SetLoadedKeys(pubKey, privKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
// BurnKey implements the ToolLogic interface.
|
||||
func (ec *NistCurve) BurnKey(signet tools.SignetInt) error {
|
||||
pubKey := signet.PublicKey()
|
||||
privKey := signet.PrivateKey()
|
||||
|
||||
// burn public key
|
||||
if pubKey != nil {
|
||||
point, ok := pubKey.(*ecdh.Point)
|
||||
if ok {
|
||||
point.X.Set(big.NewInt(0))
|
||||
point.Y.Set(big.NewInt(0))
|
||||
}
|
||||
}
|
||||
|
||||
// burn private key
|
||||
if privKey != nil {
|
||||
data, ok := privKey.([]byte)
|
||||
if ok {
|
||||
ec.Helper().Burn(data)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
140
tools/ecdh/x25519.go
Normal file
140
tools/ecdh/x25519.go
Normal file
|
@ -0,0 +1,140 @@
|
|||
package ecdh
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
"github.com/safing/portbase/container"
|
||||
|
||||
"github.com/aead/ecdh"
|
||||
)
|
||||
|
||||
func init() {
|
||||
tools.Register(&tools.Tool{
|
||||
Info: &tools.ToolInfo{
|
||||
Name: "ECDH-X25519",
|
||||
Purpose: tools.PurposeKeyExchange,
|
||||
SecurityLevel: 128,
|
||||
Comment: "",
|
||||
Author: "Daniel J. Bernstein, 2005",
|
||||
},
|
||||
Factory: func() tools.ToolLogic { return &X25519Curve{} },
|
||||
})
|
||||
}
|
||||
|
||||
// X25519Curve implements the cryptographic interface for the ECDH X25519 key exchange.
|
||||
type X25519Curve struct {
|
||||
tools.ToolLogicBase
|
||||
}
|
||||
|
||||
// MakeSharedKey implements the ToolLogic interface.
|
||||
func (ec *X25519Curve) MakeSharedKey(local tools.SignetInt, remote tools.SignetInt) ([]byte, error) {
|
||||
return ecdh.X25519().ComputeSecret(local.PrivateKey(), remote.PublicKey()), nil
|
||||
}
|
||||
|
||||
// LoadKey implements the ToolLogic interface.
|
||||
func (ec *X25519Curve) LoadKey(signet tools.SignetInt) error {
|
||||
var pubKey crypto.PublicKey
|
||||
var privKey crypto.PrivateKey
|
||||
|
||||
key, public := signet.GetStoredKey()
|
||||
c := container.New(key)
|
||||
|
||||
// check serialization version
|
||||
version, err := c.GetNextN8()
|
||||
if err != nil || version != 1 {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
|
||||
// load public key
|
||||
data, err := c.Get(32)
|
||||
if err != nil {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
var pubKeyData [32]byte
|
||||
copy(pubKeyData[:], data)
|
||||
pubKey = pubKeyData
|
||||
|
||||
// check public key
|
||||
err = ecdh.X25519().Check(pubKey)
|
||||
if err != nil {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
|
||||
// load private key
|
||||
if !public {
|
||||
data, err = c.Get(32)
|
||||
if err != nil {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
var privKeyData [32]byte
|
||||
copy(privKeyData[:], data)
|
||||
privKey = privKeyData
|
||||
}
|
||||
|
||||
signet.SetLoadedKeys(pubKey, privKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
// StoreKey implements the ToolLogic interface.
|
||||
func (ec *X25519Curve) StoreKey(signet tools.SignetInt) error {
|
||||
pubKey := signet.PublicKey()
|
||||
privKey := signet.PrivateKey()
|
||||
public := privKey == nil
|
||||
|
||||
// create storage with serialization version
|
||||
c := container.New()
|
||||
c.AppendNumber(1)
|
||||
|
||||
// store keys
|
||||
pubKeyData := pubKey.([32]byte)
|
||||
c.Append(pubKeyData[:])
|
||||
if !public {
|
||||
privKeyData := privKey.([32]byte)
|
||||
c.Append(privKeyData[:])
|
||||
}
|
||||
|
||||
signet.SetStoredKey(c.CompileData(), public)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GenerateKey implements the ToolLogic interface.
|
||||
func (ec *X25519Curve) GenerateKey(signet tools.SignetInt) error {
|
||||
// define variable types for API security
|
||||
var pubKey crypto.PublicKey
|
||||
var privKey crypto.PrivateKey
|
||||
var err error
|
||||
|
||||
// generate keys
|
||||
privKey, pubKey, err = ecdh.X25519().GenerateKey(ec.Helper().Random())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
signet.SetLoadedKeys(pubKey, privKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
// BurnKey implements the ToolLogic interface.
|
||||
func (ec *X25519Curve) BurnKey(signet tools.SignetInt) error {
|
||||
pubKey := signet.PublicKey()
|
||||
privKey := signet.PrivateKey()
|
||||
|
||||
// burn public key
|
||||
if pubKey != nil {
|
||||
data, ok := pubKey.([32]byte)
|
||||
if ok {
|
||||
ec.Helper().Burn(data[:])
|
||||
}
|
||||
}
|
||||
|
||||
// burn private key
|
||||
if privKey != nil {
|
||||
data, ok := privKey.([32]byte)
|
||||
if ok {
|
||||
ec.Helper().Burn(data[:])
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
17
tools/errors.go
Normal file
17
tools/errors.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package tools
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
// ErrNotFound is returned when a tool cannot be found.
|
||||
ErrNotFound = errors.New("does not exist")
|
||||
|
||||
// ErrInvalidKey is returned when a invalid public or private key was supplied.
|
||||
ErrInvalidKey = errors.New("invalid key")
|
||||
|
||||
// ErrNotImplemented is returned by the dummy functions if they are not overridden correctly.
|
||||
ErrNotImplemented = errors.New("not implemented")
|
||||
|
||||
// ErrProtected is returned if an operation is executed, but the key is still protected.
|
||||
ErrProtected = errors.New("key is protected")
|
||||
)
|
103
tools/gostdlib/aes-ctr.go
Normal file
103
tools/gostdlib/aes-ctr.go
Normal file
|
@ -0,0 +1,103 @@
|
|||
package gostdlib
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
)
|
||||
|
||||
//nolint:dupl
|
||||
func init() {
|
||||
aesCtrInfo := &tools.ToolInfo{
|
||||
Purpose: tools.PurposeCipher,
|
||||
Options: []uint8{tools.OptionHasState},
|
||||
NonceSize: aes.BlockSize,
|
||||
Comment: "aka Rijndael, FIPS 197",
|
||||
Author: "Vincent Rijmen and Joan Daemen, 1998",
|
||||
}
|
||||
aesCtrFactory := func() tools.ToolLogic { return &AesCTR{} }
|
||||
|
||||
tools.Register(&tools.Tool{
|
||||
Info: aesCtrInfo.With(&tools.ToolInfo{
|
||||
Name: "AES128-CTR",
|
||||
KeySize: 16, // 128 bits
|
||||
SecurityLevel: 128,
|
||||
}),
|
||||
Factory: aesCtrFactory,
|
||||
})
|
||||
tools.Register(&tools.Tool{
|
||||
Info: aesCtrInfo.With(&tools.ToolInfo{
|
||||
Name: "AES192-CTR",
|
||||
KeySize: 24, // 192 bits
|
||||
SecurityLevel: 192,
|
||||
}),
|
||||
Factory: aesCtrFactory,
|
||||
})
|
||||
tools.Register(&tools.Tool{
|
||||
Info: aesCtrInfo.With(&tools.ToolInfo{
|
||||
Name: "AES256-CTR",
|
||||
KeySize: 32, // 256 bits
|
||||
SecurityLevel: 256,
|
||||
}),
|
||||
Factory: aesCtrFactory,
|
||||
})
|
||||
}
|
||||
|
||||
// AesCTR implements the cryptographic interface for AES-CTR encryption.
|
||||
type AesCTR struct {
|
||||
tools.ToolLogicBase
|
||||
stream cipher.Stream
|
||||
key, iv []byte
|
||||
}
|
||||
|
||||
// Setup implements the ToolLogic interface.
|
||||
func (aesctr *AesCTR) Setup() (err error) {
|
||||
// get key
|
||||
aesctr.key, err = aesctr.Helper().NewSessionKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// get IV
|
||||
aesctr.iv, err = aesctr.Helper().NewSessionNonce()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// get cipher.Block
|
||||
block, err := aes.NewCipher(aesctr.key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// get cipher.Stream
|
||||
aesctr.stream = cipher.NewCTR(block, aesctr.iv)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Reset implements the ToolLogic interface.
|
||||
func (aesctr *AesCTR) Reset() error {
|
||||
// clean up keys
|
||||
aesctr.Helper().Burn(aesctr.key)
|
||||
aesctr.Helper().Burn(aesctr.iv)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Encrypt implements the ToolLogic interface.
|
||||
func (aesctr *AesCTR) Encrypt(data []byte) ([]byte, error) {
|
||||
// encrypt
|
||||
aesctr.stream.XORKeyStream(data, data)
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// Decrypt implements the ToolLogic interface.
|
||||
func (aesctr *AesCTR) Decrypt(data []byte) ([]byte, error) {
|
||||
// decrypt
|
||||
aesctr.stream.XORKeyStream(data, data)
|
||||
|
||||
return data, nil
|
||||
}
|
109
tools/gostdlib/aes-gcm.go
Normal file
109
tools/gostdlib/aes-gcm.go
Normal file
|
@ -0,0 +1,109 @@
|
|||
package gostdlib
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
)
|
||||
|
||||
//nolint:dupl
|
||||
func init() {
|
||||
aesGcmInfo := &tools.ToolInfo{
|
||||
Purpose: tools.PurposeIntegratedCipher,
|
||||
Options: []uint8{tools.OptionHasState},
|
||||
NonceSize: 12, // standard nonce size for GCM in Golang stdlib
|
||||
Comment: "aka Rijndael, FIPS 197",
|
||||
Author: "Vincent Rijmen and Joan Daemen, 1998",
|
||||
}
|
||||
aesGcmFactory := func() tools.ToolLogic { return &AesGCM{} }
|
||||
|
||||
tools.Register(&tools.Tool{
|
||||
Info: aesGcmInfo.With(&tools.ToolInfo{
|
||||
Name: "AES128-GCM",
|
||||
KeySize: 16, // 128 bits
|
||||
SecurityLevel: 128,
|
||||
}),
|
||||
Factory: aesGcmFactory,
|
||||
})
|
||||
tools.Register(&tools.Tool{
|
||||
Info: aesGcmInfo.With(&tools.ToolInfo{
|
||||
Name: "AES192-GCM",
|
||||
KeySize: 24, // 192 bits
|
||||
SecurityLevel: 192,
|
||||
}),
|
||||
Factory: aesGcmFactory,
|
||||
})
|
||||
tools.Register(&tools.Tool{
|
||||
Info: aesGcmInfo.With(&tools.ToolInfo{
|
||||
Name: "AES256-GCM",
|
||||
KeySize: 32, // 256 bits
|
||||
SecurityLevel: 256,
|
||||
}),
|
||||
Factory: aesGcmFactory,
|
||||
})
|
||||
}
|
||||
|
||||
// AesGCM implements the cryptographic interface for AES-GCM encryption.
|
||||
type AesGCM struct {
|
||||
tools.ToolLogicBase
|
||||
aead cipher.AEAD
|
||||
key, nonce []byte
|
||||
}
|
||||
|
||||
// Setup implements the ToolLogic interface.
|
||||
func (aesgcm *AesGCM) Setup() (err error) {
|
||||
// get key
|
||||
aesgcm.key, err = aesgcm.Helper().NewSessionKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// get nonce
|
||||
aesgcm.nonce, err = aesgcm.Helper().NewSessionNonce()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// get cipher.Block
|
||||
block, err := aes.NewCipher(aesgcm.key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// get aead interface
|
||||
aesgcm.aead, err = cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
aesgcm.aead.NonceSize()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Reset implements the ToolLogic interface.
|
||||
func (aesgcm *AesGCM) Reset() error {
|
||||
// clean up keys
|
||||
aesgcm.Helper().Burn(aesgcm.key)
|
||||
aesgcm.Helper().Burn(aesgcm.nonce)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// AuthenticatedEncrypt implements the ToolLogic interface.
|
||||
func (aesgcm *AesGCM) AuthenticatedEncrypt(data, associatedData []byte) ([]byte, error) {
|
||||
// encrypt and authenticate
|
||||
data = aesgcm.aead.Seal(data[:0], aesgcm.nonce, data, associatedData)
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// AuthenticatedDecrypt implements the ToolLogic interface.
|
||||
func (aesgcm *AesGCM) AuthenticatedDecrypt(data, associatedData []byte) ([]byte, error) {
|
||||
// decrypt and authenticate
|
||||
var err error
|
||||
data, err = aesgcm.aead.Open(data[:0], aesgcm.nonce, data, associatedData)
|
||||
|
||||
return data, err
|
||||
}
|
81
tools/gostdlib/chacha20-poly1305.go
Normal file
81
tools/gostdlib/chacha20-poly1305.go
Normal file
|
@ -0,0 +1,81 @@
|
|||
package gostdlib
|
||||
|
||||
import (
|
||||
"crypto/cipher"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
|
||||
"golang.org/x/crypto/chacha20poly1305"
|
||||
)
|
||||
|
||||
func init() {
|
||||
tools.Register(&tools.Tool{
|
||||
Info: &tools.ToolInfo{
|
||||
Name: "CHACHA20-POLY1305",
|
||||
Purpose: tools.PurposeIntegratedCipher,
|
||||
Options: []uint8{tools.OptionHasState},
|
||||
KeySize: chacha20poly1305.KeySize, // 256 bit
|
||||
NonceSize: chacha20poly1305.NonceSize,
|
||||
SecurityLevel: 128, // ChaCha20 is actually 256. Limiting to 128 for now because of Poly1305. TODO: do some more research on Poly1305
|
||||
Comment: "RFC 7539",
|
||||
Author: "Daniel J. Bernstein, 2008 and 2005",
|
||||
},
|
||||
Factory: func() tools.ToolLogic { return &ChaCha20Poly1305{} },
|
||||
})
|
||||
}
|
||||
|
||||
// ChaCha20Poly1305 implements the cryptographic interface for ChaCha20-Poly1305 encryption.
|
||||
type ChaCha20Poly1305 struct {
|
||||
tools.ToolLogicBase
|
||||
aead cipher.AEAD
|
||||
key, nonce []byte
|
||||
}
|
||||
|
||||
// Setup implements the ToolLogic interface.
|
||||
func (chapo *ChaCha20Poly1305) Setup() (err error) {
|
||||
// get key
|
||||
chapo.key, err = chapo.Helper().NewSessionKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// get nonce
|
||||
chapo.nonce, err = chapo.Helper().NewSessionNonce()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// get aead interface
|
||||
chapo.aead, err = chacha20poly1305.New(chapo.key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Reset implements the ToolLogic interface.
|
||||
func (chapo *ChaCha20Poly1305) Reset() error {
|
||||
// clean up keys
|
||||
chapo.Helper().Burn(chapo.key)
|
||||
chapo.Helper().Burn(chapo.nonce)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// AuthenticatedEncrypt implements the ToolLogic interface.
|
||||
func (chapo *ChaCha20Poly1305) AuthenticatedEncrypt(data, associatedData []byte) ([]byte, error) {
|
||||
// encrypt and authenticate
|
||||
data = chapo.aead.Seal(data[:0], chapo.nonce, data, associatedData)
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// AuthenticatedDecrypt implements the ToolLogic interface.
|
||||
func (chapo *ChaCha20Poly1305) AuthenticatedDecrypt(data, associatedData []byte) ([]byte, error) {
|
||||
// decrypt and authenticate
|
||||
var err error
|
||||
data, err = chapo.aead.Open(data[:0], chapo.nonce, data, associatedData)
|
||||
|
||||
return data, err
|
||||
}
|
173
tools/gostdlib/ed25519.go
Normal file
173
tools/gostdlib/ed25519.go
Normal file
|
@ -0,0 +1,173 @@
|
|||
package gostdlib
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ed25519"
|
||||
"errors"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
"github.com/safing/portbase/container"
|
||||
)
|
||||
|
||||
func init() {
|
||||
tools.Register(&tools.Tool{
|
||||
Info: &tools.ToolInfo{
|
||||
Name: "Ed25519",
|
||||
Purpose: tools.PurposeSigning,
|
||||
Options: []uint8{tools.OptionNeedsManagedHasher},
|
||||
SecurityLevel: 128,
|
||||
Comment: "",
|
||||
Author: "Daniel J. Bernstein, 2011",
|
||||
},
|
||||
Factory: func() tools.ToolLogic { return &Ed25519{} },
|
||||
})
|
||||
}
|
||||
|
||||
// Ed25519 implements the cryptographic interface for Ed25519 signatures.
|
||||
type Ed25519 struct {
|
||||
tools.ToolLogicBase
|
||||
}
|
||||
|
||||
// Sign implements the ToolLogic interface.
|
||||
func (ed *Ed25519) Sign(data, associatedData []byte, signet tools.SignetInt) ([]byte, error) {
|
||||
edPrivKey, ok := signet.PrivateKey().(ed25519.PrivateKey)
|
||||
if !ok {
|
||||
return nil, tools.ErrInvalidKey
|
||||
}
|
||||
if len(edPrivKey) != ed25519.PrivateKeySize {
|
||||
return nil, tools.ErrInvalidKey
|
||||
}
|
||||
|
||||
hashsum, err := ed.ManagedHashSum()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return ed25519.Sign(edPrivKey, hashsum), nil
|
||||
}
|
||||
|
||||
// Verify implements the ToolLogic interface.
|
||||
func (ed *Ed25519) Verify(data, associatedData, signature []byte, signet tools.SignetInt) error {
|
||||
edPubKey, ok := signet.PublicKey().(ed25519.PublicKey)
|
||||
if !ok {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
if len(edPubKey) != ed25519.PublicKeySize {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
|
||||
hashsum, err := ed.ManagedHashSum()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !ed25519.Verify(edPubKey, hashsum, signature) {
|
||||
return errors.New("signature invalid")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadKey implements the ToolLogic interface.
|
||||
func (ed *Ed25519) LoadKey(signet tools.SignetInt) error {
|
||||
var pubKey crypto.PublicKey
|
||||
var privKey ed25519.PrivateKey
|
||||
|
||||
key, public := signet.GetStoredKey()
|
||||
c := container.New(key)
|
||||
|
||||
// check serialization version
|
||||
version, err := c.GetNextN8()
|
||||
if err != nil || version != 1 {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
|
||||
// load public key
|
||||
data := c.CompileData()
|
||||
|
||||
// assign and check data
|
||||
if public {
|
||||
if len(data) != ed25519.PublicKeySize {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
pubKey = ed25519.PublicKey(data)
|
||||
} else {
|
||||
if len(data) != ed25519.PrivateKeySize {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
privKey = ed25519.PrivateKey(data)
|
||||
pubKey = privKey.Public()
|
||||
}
|
||||
|
||||
signet.SetLoadedKeys(pubKey, privKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
// StoreKey implements the ToolLogic interface.
|
||||
func (ed *Ed25519) StoreKey(signet tools.SignetInt) error {
|
||||
pubKey := signet.PublicKey()
|
||||
privKey := signet.PrivateKey()
|
||||
public := privKey == nil
|
||||
|
||||
// create storage with serialization version
|
||||
c := container.New()
|
||||
c.AppendNumber(1)
|
||||
|
||||
// store keys
|
||||
if public {
|
||||
pubKeyData, ok := pubKey.(ed25519.PublicKey)
|
||||
if !ok {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
c.Append(pubKeyData)
|
||||
} else {
|
||||
privKeyData, ok := privKey.(ed25519.PrivateKey)
|
||||
if !ok {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
c.Append(privKeyData)
|
||||
}
|
||||
|
||||
signet.SetStoredKey(c.CompileData(), public)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GenerateKey implements the ToolLogic interface.
|
||||
func (ed *Ed25519) GenerateKey(signet tools.SignetInt) error {
|
||||
// define variable types for API security
|
||||
var pubKey ed25519.PublicKey
|
||||
var privKey ed25519.PrivateKey
|
||||
var err error
|
||||
|
||||
// generate keys
|
||||
pubKey, privKey, err = ed25519.GenerateKey(ed.Helper().Random())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
signet.SetLoadedKeys(pubKey, privKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
// BurnKey implements the ToolLogic interface.
|
||||
func (ed *Ed25519) BurnKey(signet tools.SignetInt) error {
|
||||
pubKey := signet.PublicKey()
|
||||
privKey := signet.PrivateKey()
|
||||
|
||||
// burn public key
|
||||
if pubKey != nil {
|
||||
data, ok := pubKey.([]byte)
|
||||
if ok {
|
||||
ed.Helper().Burn(data)
|
||||
}
|
||||
}
|
||||
|
||||
// burn private key
|
||||
if privKey != nil {
|
||||
data, ok := privKey.([]byte)
|
||||
if ok {
|
||||
ed.Helper().Burn(data)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
68
tools/gostdlib/hkdf.go
Normal file
68
tools/gostdlib/hkdf.go
Normal file
|
@ -0,0 +1,68 @@
|
|||
package gostdlib
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
"github.com/safing/portbase/container"
|
||||
|
||||
"golang.org/x/crypto/hkdf"
|
||||
)
|
||||
|
||||
func init() {
|
||||
tools.Register(&tools.Tool{
|
||||
Info: &tools.ToolInfo{
|
||||
Name: "HKDF",
|
||||
Purpose: tools.PurposeKeyDerivation,
|
||||
Options: []uint8{tools.OptionNeedsDedicatedHasher},
|
||||
SecurityLevel: 0, // depends on used hash function
|
||||
Comment: "RFC 5869",
|
||||
Author: "Hugo Krawczyk, 2010",
|
||||
},
|
||||
Factory: func() tools.ToolLogic { return &HKDF{} },
|
||||
})
|
||||
}
|
||||
|
||||
// HKDF implements the cryptographic interface for HKDF key derivation.
|
||||
type HKDF struct {
|
||||
tools.ToolLogicBase
|
||||
reader io.Reader
|
||||
}
|
||||
|
||||
// InitKeyDerivation implements the ToolLogic interface.
|
||||
func (keyder *HKDF) InitKeyDerivation(nonce []byte, material ...[]byte) error {
|
||||
// hkdf arguments: hash func() hash.Hash, secret, salt, info []byte
|
||||
// `secret` and `salt` are used for the initial `extract` operation
|
||||
// `info` is mixed into every `expand` operation
|
||||
if len(material) < 1 || len(material[0]) == 0 || len(nonce) == 0 {
|
||||
return errors.New("must supply at least one key and a nonce as key material")
|
||||
}
|
||||
|
||||
keyder.reader = hkdf.New(
|
||||
keyder.HashTool().New,
|
||||
container.New(material...).CompileData(), // cryptographically secure master secret(s)
|
||||
nonce, // non-secret salt
|
||||
nil, // non-secret info
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeriveKey implements the ToolLogic interface.
|
||||
func (keyder *HKDF) DeriveKey(size int) ([]byte, error) {
|
||||
key := make([]byte, size)
|
||||
return key, keyder.DeriveKeyWriteTo(key)
|
||||
}
|
||||
|
||||
// DeriveKeyWriteTo implements the ToolLogic interface.
|
||||
func (keyder *HKDF) DeriveKeyWriteTo(new []byte) error {
|
||||
n, err := io.ReadFull(keyder.reader, new)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to generate key: %s", err)
|
||||
}
|
||||
if n != len(new) {
|
||||
return errors.New("failed to generate key: EOF")
|
||||
}
|
||||
return nil
|
||||
}
|
77
tools/gostdlib/hmac.go
Normal file
77
tools/gostdlib/hmac.go
Normal file
|
@ -0,0 +1,77 @@
|
|||
package gostdlib
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"errors"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
)
|
||||
|
||||
func init() {
|
||||
tools.Register(&tools.Tool{
|
||||
Info: &tools.ToolInfo{
|
||||
Name: "HMAC",
|
||||
Purpose: tools.PurposeMAC,
|
||||
Options: []uint8{
|
||||
tools.OptionNeedsDedicatedHasher,
|
||||
tools.OptionHasState,
|
||||
},
|
||||
SecurityLevel: 0, // depends on used hash function
|
||||
Comment: "RFC 2104, FIPS 198",
|
||||
Author: "Mihir Bellare et al., 1996",
|
||||
},
|
||||
Factory: func() tools.ToolLogic { return &HMAC{} },
|
||||
})
|
||||
}
|
||||
|
||||
// HMAC implements the cryptographic interface for HMAC message authentication codes.
|
||||
type HMAC struct {
|
||||
tools.ToolLogicBase
|
||||
key []byte
|
||||
}
|
||||
|
||||
// Setup implements the ToolLogic interface.
|
||||
func (hm *HMAC) Setup() (err error) {
|
||||
// get key
|
||||
hm.key, err = hm.Helper().NewSessionKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Reset implements the ToolLogic interface.
|
||||
func (hm *HMAC) Reset() error {
|
||||
// clean up key
|
||||
hm.Helper().Burn(hm.key)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MAC implements the ToolLogic interface.
|
||||
func (hm *HMAC) MAC(data, associatedData []byte) ([]byte, error) {
|
||||
// create MAC
|
||||
mac := hmac.New(hm.HashTool().New, hm.key)
|
||||
// write data
|
||||
n, err := mac.Write(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n != len(data) {
|
||||
return nil, errors.New("failed to fully write data to HMAC hasher")
|
||||
}
|
||||
// write associated data
|
||||
if len(associatedData) > 0 {
|
||||
n, err := mac.Write(associatedData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n != len(associatedData) {
|
||||
return nil, errors.New("failed to fully write associated data to HMAC hasher")
|
||||
}
|
||||
}
|
||||
|
||||
// return sum
|
||||
return mac.Sum(nil), nil
|
||||
}
|
47
tools/gostdlib/pbkdf2.go
Normal file
47
tools/gostdlib/pbkdf2.go
Normal file
|
@ -0,0 +1,47 @@
|
|||
package gostdlib
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"hash"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
)
|
||||
|
||||
func init() {
|
||||
tools.Register(&tools.Tool{
|
||||
Info: &tools.ToolInfo{
|
||||
Name: "PBKDF2-SHA2-256",
|
||||
Purpose: tools.PurposePassDerivation,
|
||||
Options: []uint8{tools.OptionNeedsDefaultKeySize},
|
||||
SecurityLevel: 0, // Security Level of SHA2-256
|
||||
Comment: "PKCS #5 v2.1, RFC 8018",
|
||||
Author: "Burt Kaliski, RSA Laboratories, 2000/2017",
|
||||
},
|
||||
Factory: func() tools.ToolLogic {
|
||||
return &PBKDF2{
|
||||
hashFactory: sha256.New,
|
||||
iterations: 20000,
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// PBKDF2 implements the cryptographic interface for PBKDF2 password derivation.
|
||||
type PBKDF2 struct {
|
||||
tools.ToolLogicBase
|
||||
hashFactory func() hash.Hash
|
||||
iterations int
|
||||
}
|
||||
|
||||
// DeriveKeyFromPassword implements the ToolLogic interface.
|
||||
func (pd *PBKDF2) DeriveKeyFromPassword(password []byte, salt []byte) ([]byte, error) {
|
||||
return pbkdf2.Key(
|
||||
password,
|
||||
salt,
|
||||
pd.iterations,
|
||||
pd.Helper().DefaultSymmetricKeySize(),
|
||||
pd.hashFactory,
|
||||
), nil
|
||||
}
|
75
tools/gostdlib/poly1305.go
Normal file
75
tools/gostdlib/poly1305.go
Normal file
|
@ -0,0 +1,75 @@
|
|||
package gostdlib
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
"golang.org/x/crypto/poly1305"
|
||||
)
|
||||
|
||||
func init() {
|
||||
tools.Register(&tools.Tool{
|
||||
Info: &tools.ToolInfo{
|
||||
Name: "POLY1305",
|
||||
Purpose: tools.PurposeMAC,
|
||||
Options: []uint8{tools.OptionHasState},
|
||||
KeySize: 32,
|
||||
SecurityLevel: 128, // TODO: do some more research
|
||||
Comment: "RFC 7539",
|
||||
Author: "Daniel J. Bernstein, 2005",
|
||||
},
|
||||
Factory: func() tools.ToolLogic { return &Poly1305{} },
|
||||
})
|
||||
}
|
||||
|
||||
// Poly1305 implements the cryptographic interface for Poly1305 message authentication codes.
|
||||
type Poly1305 struct {
|
||||
tools.ToolLogicBase
|
||||
key [32]byte
|
||||
}
|
||||
|
||||
// Setup implements the ToolLogic interface.
|
||||
func (poly *Poly1305) Setup() (err error) {
|
||||
// get key
|
||||
err = poly.Helper().FillNewSessionKey(poly.key[:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Reset implements the ToolLogic interface.
|
||||
func (poly *Poly1305) Reset() error {
|
||||
// clean up key
|
||||
poly.Helper().Burn(poly.key[:])
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MAC implements the ToolLogic interface.
|
||||
func (poly *Poly1305) MAC(data, associatedData []byte) ([]byte, error) {
|
||||
// create MAC
|
||||
mac := poly1305.New(&poly.key)
|
||||
// write data
|
||||
n, err := mac.Write(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n != len(data) {
|
||||
return nil, errors.New("failed to fully write data to Poly1305 MAC")
|
||||
}
|
||||
// write associated data
|
||||
if len(associatedData) > 0 {
|
||||
n, err := mac.Write(associatedData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n != len(associatedData) {
|
||||
return nil, errors.New("failed to fully write associated data to Poly1305 MAC")
|
||||
}
|
||||
}
|
||||
|
||||
// return sum
|
||||
return mac.Sum(nil), nil
|
||||
}
|
214
tools/gostdlib/rsa-keys.go
Normal file
214
tools/gostdlib/rsa-keys.go
Normal file
|
@ -0,0 +1,214 @@
|
|||
package gostdlib
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"math/big"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
|
||||
"github.com/safing/portbase/container"
|
||||
)
|
||||
|
||||
type rsaBase struct {
|
||||
tools.ToolLogicBase
|
||||
}
|
||||
|
||||
// LoadKey implements the ToolLogic interface.
|
||||
func (base *rsaBase) LoadKey(signet tools.SignetInt) error {
|
||||
var pubKey crypto.PublicKey
|
||||
var privKey *rsa.PrivateKey
|
||||
|
||||
key, public := signet.GetStoredKey()
|
||||
c := container.New(key)
|
||||
|
||||
// check serialization version
|
||||
version, err := c.GetNextN8()
|
||||
if err != nil || version != 1 {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
|
||||
// load key
|
||||
if public {
|
||||
pubKey, err = x509.ParsePKCS1PublicKey(c.CompileData())
|
||||
} else {
|
||||
privKey, err = x509.ParsePKCS1PrivateKey(c.CompileData())
|
||||
if err != nil {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
// check and assign keys
|
||||
err = privKey.Validate()
|
||||
if err == nil {
|
||||
pubKey = privKey.Public()
|
||||
}
|
||||
}
|
||||
|
||||
// check for error
|
||||
if err != nil {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
|
||||
signet.SetLoadedKeys(pubKey, privKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
// StoreKey implements the ToolLogic interface.
|
||||
func (base *rsaBase) StoreKey(signet tools.SignetInt) error {
|
||||
pubKey := signet.PublicKey()
|
||||
privKey := signet.PrivateKey()
|
||||
public := privKey == nil
|
||||
|
||||
// create storage with serialization version
|
||||
c := container.New()
|
||||
c.AppendNumber(1)
|
||||
|
||||
// store keys
|
||||
if public {
|
||||
rsaPubKey, ok := pubKey.(*rsa.PublicKey)
|
||||
if !ok {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
c.Append(x509.MarshalPKCS1PublicKey(rsaPubKey))
|
||||
|
||||
} else {
|
||||
rsaPrivKey, ok := privKey.(*rsa.PrivateKey)
|
||||
if !ok {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
c.Append(x509.MarshalPKCS1PrivateKey(rsaPrivKey))
|
||||
}
|
||||
|
||||
signet.SetStoredKey(c.CompileData(), public)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GenerateKey implements the ToolLogic interface.
|
||||
func (base *rsaBase) GenerateKey(signet tools.SignetInt) error {
|
||||
// get key size
|
||||
keySize := getRSAKeySizeBySecurityLevel(base.Helper().MaxSecurityLevel())
|
||||
if keySize < 0 {
|
||||
return fmt.Errorf("invalid security level of %d for rsa key - rsa based cryptography is only available for levels 112 to 256 (recommended only up to 192)", base.Helper().MaxSecurityLevel())
|
||||
}
|
||||
|
||||
// generate new private key
|
||||
privKey, err := rsa.GenerateKey(base.Helper().Random(), keySize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// get public key
|
||||
pubKey := privKey.Public()
|
||||
|
||||
signet.SetLoadedKeys(pubKey, privKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
// BurnKey implements the ToolLogic interface.
|
||||
func (base *rsaBase) BurnKey(signet tools.SignetInt) error {
|
||||
pubKey := signet.PublicKey()
|
||||
privKey := signet.PrivateKey()
|
||||
|
||||
// burn public key
|
||||
if pubKey != nil {
|
||||
rsaPubKey, ok := pubKey.(*rsa.PublicKey)
|
||||
if ok && rsaPubKey != nil {
|
||||
rsaPubKey.E = 0
|
||||
burnBigInt(rsaPubKey.N)
|
||||
}
|
||||
}
|
||||
|
||||
// burn private key
|
||||
if privKey != nil {
|
||||
rsaPrivKey, ok := privKey.(*rsa.PrivateKey)
|
||||
if ok && rsaPrivKey != nil {
|
||||
// private key
|
||||
burnBigInt(rsaPrivKey.D)
|
||||
for _, bigInt := range rsaPrivKey.Primes {
|
||||
burnBigInt(bigInt)
|
||||
}
|
||||
// precomputed values
|
||||
burnBigInt(rsaPrivKey.Precomputed.Dp)
|
||||
burnBigInt(rsaPrivKey.Precomputed.Dq)
|
||||
burnBigInt(rsaPrivKey.Precomputed.Qinv)
|
||||
for _, crtVal := range rsaPrivKey.Precomputed.CRTValues {
|
||||
burnBigInt(crtVal.Coeff)
|
||||
burnBigInt(crtVal.Exp)
|
||||
burnBigInt(crtVal.R)
|
||||
}
|
||||
// public key
|
||||
rsaPrivKey.PublicKey.E = 0
|
||||
burnBigInt(rsaPrivKey.PublicKey.N)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var zeroBigInt = big.NewInt(0)
|
||||
|
||||
func burnBigInt(i *big.Int) {
|
||||
if i != nil {
|
||||
i.Set(zeroBigInt)
|
||||
}
|
||||
}
|
||||
|
||||
// SecurityLevel implements the ToolLogic interface.
|
||||
func (base *rsaBase) SecurityLevel(signet tools.SignetInt) (int, error) {
|
||||
if signet == nil {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
pubkey := signet.PublicKey()
|
||||
if pubkey == nil {
|
||||
err := signet.LoadKey()
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to load key to calculate security level: %s", err)
|
||||
}
|
||||
pubkey = signet.PublicKey()
|
||||
}
|
||||
rsaPubKey, ok := pubkey.(*rsa.PublicKey)
|
||||
if !ok {
|
||||
return 0, tools.ErrInvalidKey
|
||||
}
|
||||
|
||||
level := getSecurityLevelByRSAKeySize(rsaPubKey.Size() * 8)
|
||||
if level < 0 {
|
||||
return 0, fmt.Errorf("rsa key is too small (%d bits) and can be broken trivially", rsaPubKey.Size()*8)
|
||||
}
|
||||
return level, nil
|
||||
}
|
||||
|
||||
func getRSAKeySizeBySecurityLevel(level int) (keySize int) {
|
||||
switch {
|
||||
case level <= 112:
|
||||
return 2048
|
||||
case level <= 128:
|
||||
return 3072
|
||||
case level <= 192:
|
||||
return 7680
|
||||
case level <= 256:
|
||||
return 15360
|
||||
default:
|
||||
return 256 // max level for rsa
|
||||
}
|
||||
}
|
||||
|
||||
func getSecurityLevelByRSAKeySize(keySize int) (level int) {
|
||||
switch {
|
||||
case keySize >= 15360:
|
||||
return 256
|
||||
case keySize >= 7680:
|
||||
return 192
|
||||
case keySize >= 3072:
|
||||
return 128
|
||||
case keySize >= 2048:
|
||||
return 112
|
||||
case keySize >= 1024:
|
||||
return 80
|
||||
case keySize >= 512:
|
||||
return 56
|
||||
default:
|
||||
return -1 // error
|
||||
}
|
||||
}
|
72
tools/gostdlib/rsa-oaep.go
Normal file
72
tools/gostdlib/rsa-oaep.go
Normal file
|
@ -0,0 +1,72 @@
|
|||
package gostdlib
|
||||
|
||||
import (
|
||||
"crypto/rsa"
|
||||
"fmt"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
)
|
||||
|
||||
func init() {
|
||||
tools.Register(&tools.Tool{
|
||||
Info: &tools.ToolInfo{
|
||||
Name: "RSA-OAEP",
|
||||
Purpose: tools.PurposeKeyEncapsulation,
|
||||
Options: []uint8{
|
||||
tools.OptionNeedsDedicatedHasher,
|
||||
tools.OptionNeedsSecurityLevel,
|
||||
},
|
||||
Comment: "", // TODO
|
||||
Author: "", // TODO
|
||||
},
|
||||
Factory: func() tools.ToolLogic { return &RsaOAEP{} },
|
||||
})
|
||||
}
|
||||
|
||||
// RsaOAEP implements the cryptographic interface for RSA OAEP encryption.
|
||||
type RsaOAEP struct {
|
||||
rsaBase
|
||||
}
|
||||
|
||||
// EncapsulateKey implements the ToolLogic interface.
|
||||
func (oaep *RsaOAEP) EncapsulateKey(key []byte, signet tools.SignetInt) ([]byte, error) {
|
||||
// transform public key
|
||||
rsaPubKey, ok := signet.PublicKey().(*rsa.PublicKey)
|
||||
if !ok {
|
||||
return nil, tools.ErrInvalidKey
|
||||
}
|
||||
|
||||
// check key length: The message must be no longer than the length of the public modulus minus twice the hash length, minus a further 2.
|
||||
maxMsgSize := rsaPubKey.Size() - (2 * oaep.HashTool().DigestSize) - 2
|
||||
if len(key) > maxMsgSize {
|
||||
return nil, fmt.Errorf(
|
||||
"key too long for encapsulation (rsa key would need to be at least %d bits in size to hold a key of %d bytes)",
|
||||
maxMsgSize*8,
|
||||
len(key),
|
||||
)
|
||||
}
|
||||
|
||||
return rsa.EncryptOAEP(
|
||||
oaep.HashTool().New(),
|
||||
oaep.Helper().Random(),
|
||||
rsaPubKey,
|
||||
key,
|
||||
nil, // label
|
||||
)
|
||||
}
|
||||
|
||||
// UnwrapKey implements the ToolLogic interface.
|
||||
func (oaep *RsaOAEP) UnwrapKey(wrappedKey []byte, signet tools.SignetInt) ([]byte, error) {
|
||||
rsaPrivKey, ok := signet.PrivateKey().(*rsa.PrivateKey)
|
||||
if !ok {
|
||||
return nil, tools.ErrInvalidKey
|
||||
}
|
||||
|
||||
return rsa.DecryptOAEP(
|
||||
oaep.HashTool().New(),
|
||||
oaep.Helper().Random(),
|
||||
rsaPrivKey,
|
||||
wrappedKey,
|
||||
nil, // label
|
||||
)
|
||||
}
|
70
tools/gostdlib/rsa-pss.go
Normal file
70
tools/gostdlib/rsa-pss.go
Normal file
|
@ -0,0 +1,70 @@
|
|||
package gostdlib
|
||||
|
||||
import (
|
||||
"crypto/rsa"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
)
|
||||
|
||||
func init() {
|
||||
tools.Register(&tools.Tool{
|
||||
Info: &tools.ToolInfo{
|
||||
Name: "RSA-PSS",
|
||||
Purpose: tools.PurposeSigning,
|
||||
Options: []uint8{
|
||||
tools.OptionNeedsManagedHasher,
|
||||
tools.OptionNeedsSecurityLevel,
|
||||
},
|
||||
Comment: "RFC 8017",
|
||||
Author: "Mihir Bellare, Phillip Rogaway, 1998",
|
||||
},
|
||||
Factory: func() tools.ToolLogic { return &RsaPSS{} },
|
||||
})
|
||||
}
|
||||
|
||||
// RsaPSS implements the cryptographic interface for RSA PSS signatures.
|
||||
type RsaPSS struct {
|
||||
rsaBase
|
||||
}
|
||||
|
||||
// Sign implements the ToolLogic interface.
|
||||
func (pss *RsaPSS) Sign(data, associatedData []byte, signet tools.SignetInt) ([]byte, error) {
|
||||
rsaPrivKey, ok := signet.PrivateKey().(*rsa.PrivateKey)
|
||||
if !ok {
|
||||
return nil, tools.ErrInvalidKey
|
||||
}
|
||||
|
||||
hashsum, err := pss.ManagedHashSum()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return rsa.SignPSS(
|
||||
pss.Helper().Random(),
|
||||
rsaPrivKey,
|
||||
pss.HashTool().Hash,
|
||||
hashsum,
|
||||
nil, // *rsa.PSSOptions
|
||||
)
|
||||
}
|
||||
|
||||
// Verify implements the ToolLogic interface.
|
||||
func (pss *RsaPSS) Verify(data, associatedData, signature []byte, signet tools.SignetInt) error {
|
||||
rsaPubKey, ok := signet.PublicKey().(*rsa.PublicKey)
|
||||
if !ok {
|
||||
return tools.ErrInvalidKey
|
||||
}
|
||||
|
||||
hashsum, err := pss.ManagedHashSum()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return rsa.VerifyPSS(
|
||||
rsaPubKey,
|
||||
pss.HashTool().Hash,
|
||||
hashsum,
|
||||
signature,
|
||||
nil, // *rsa.PSSOptions
|
||||
)
|
||||
}
|
72
tools/gostdlib/salsa20.go
Normal file
72
tools/gostdlib/salsa20.go
Normal file
|
@ -0,0 +1,72 @@
|
|||
package gostdlib
|
||||
|
||||
import (
|
||||
"github.com/safing/jess/tools"
|
||||
|
||||
"golang.org/x/crypto/salsa20"
|
||||
)
|
||||
|
||||
func init() {
|
||||
tools.Register(&tools.Tool{
|
||||
Info: &tools.ToolInfo{
|
||||
Name: "SALSA20",
|
||||
Purpose: tools.PurposeCipher,
|
||||
Options: []uint8{tools.OptionHasState},
|
||||
KeySize: 32, // 265 bits
|
||||
NonceSize: 8, // 64 bits
|
||||
SecurityLevel: 256,
|
||||
Comment: "",
|
||||
Author: "Daniel J. Bernstein, 2007",
|
||||
},
|
||||
Factory: func() tools.ToolLogic { return &Salsa20{} },
|
||||
})
|
||||
}
|
||||
|
||||
// Salsa20 implements the cryptographic interface for Salsa20 encryption.
|
||||
type Salsa20 struct {
|
||||
tools.ToolLogicBase
|
||||
key [32]byte
|
||||
nonce []byte
|
||||
}
|
||||
|
||||
// Setup implements the ToolLogic interface.
|
||||
func (salsa *Salsa20) Setup() (err error) {
|
||||
// get key
|
||||
err = salsa.Helper().FillNewSessionKey(salsa.key[:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// get nonce
|
||||
salsa.nonce, err = salsa.Helper().NewSessionNonce()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Reset implements the ToolLogic interface.
|
||||
func (salsa *Salsa20) Reset() error {
|
||||
// clean up keys
|
||||
salsa.Helper().Burn(salsa.key[:])
|
||||
salsa.Helper().Burn(salsa.nonce)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Encrypt implements the ToolLogic interface.
|
||||
func (salsa *Salsa20) Encrypt(data []byte) ([]byte, error) {
|
||||
// encrypt
|
||||
salsa20.XORKeyStream(data, data, salsa.nonce, &salsa.key)
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// Decrypt implements the ToolLogic interface.
|
||||
func (salsa *Salsa20) Decrypt(data []byte) ([]byte, error) {
|
||||
// decrypt
|
||||
salsa20.XORKeyStream(data, data, salsa.nonce, &salsa.key)
|
||||
|
||||
return data, nil
|
||||
}
|
57
tools/interfaces.go
Normal file
57
tools/interfaces.go
Normal file
|
@ -0,0 +1,57 @@
|
|||
package tools
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"io"
|
||||
)
|
||||
|
||||
// HelperInt is an interface to Helper.
|
||||
type HelperInt interface {
|
||||
// NewSessionKey returns a new session key (or nonce) in tool's specified length.
|
||||
NewSessionKey() ([]byte, error)
|
||||
|
||||
// FillNewSessionKey fills the given []byte slice with a new session key (or nonce).
|
||||
FillNewSessionKey(key []byte) error
|
||||
|
||||
// NewSessionNonce returns a new session nonce in tool's specified length.
|
||||
NewSessionNonce() ([]byte, error)
|
||||
|
||||
// Random returns the io.Reader for reading randomness.
|
||||
Random() io.Reader
|
||||
|
||||
// RandomBytes returns the specified amount of random bytes in a []byte slice.
|
||||
RandomBytes(n int) ([]byte, error)
|
||||
|
||||
// Burn gets rid of the given []byte slice(s).
|
||||
Burn(data ...[]byte)
|
||||
|
||||
// DefaultSymmetricKeySize returns the default key size for this session.
|
||||
DefaultSymmetricKeySize() int
|
||||
|
||||
// SecurityLevel returns the effective (ie. lowest) security level for this session.
|
||||
SecurityLevel() int
|
||||
|
||||
// MaxSecurityLevel returns the (highest) security level for this session.
|
||||
MaxSecurityLevel() int
|
||||
}
|
||||
|
||||
// SignetInt is a minimal interface to Signet.
|
||||
type SignetInt interface {
|
||||
// GetStoredKey returns the stored key and whether it is public.
|
||||
GetStoredKey() (key []byte, public bool)
|
||||
|
||||
// SetStoredKey sets a new stored key and whether it is public.
|
||||
SetStoredKey(new []byte, public bool)
|
||||
|
||||
// PublicKey returns the public key.
|
||||
PublicKey() crypto.PublicKey
|
||||
|
||||
// PrivateKey returns the private key or nil, if there is none.
|
||||
PrivateKey() crypto.PrivateKey
|
||||
|
||||
// SetLoadedKeys sets the loaded public and private keys.
|
||||
SetLoadedKeys(pubKey crypto.PublicKey, privKey crypto.PrivateKey)
|
||||
|
||||
// LoadKey loads the serialized key pair.
|
||||
LoadKey() error
|
||||
}
|
190
tools/tool.go
Normal file
190
tools/tool.go
Normal file
|
@ -0,0 +1,190 @@
|
|||
package tools
|
||||
|
||||
import "strings"
|
||||
|
||||
// Tool describes a cryptographic tool and is split into information and logic parts.
|
||||
type Tool struct {
|
||||
// Info is a globally shared instance of generic tool information.
|
||||
Info *ToolInfo
|
||||
|
||||
// StaticLogic holds a static (and possibly even nil) value of the tool logic in order to access certain handling methods.
|
||||
StaticLogic ToolLogic
|
||||
|
||||
// Factory returns an initialized (but not yet set up) instance of ToolLogic.
|
||||
// Setup is done after initialization by overriding Setup().
|
||||
Factory func() ToolLogic
|
||||
}
|
||||
|
||||
// ToolInfo holds generic information about a tool.
|
||||
type ToolInfo struct {
|
||||
Name string
|
||||
|
||||
Purpose uint8
|
||||
Options []uint8
|
||||
|
||||
KeySize int // in bytes
|
||||
NonceSize int // in bytes
|
||||
SecurityLevel int // approx. attack complexity as 2^n
|
||||
|
||||
Comment string
|
||||
Author string
|
||||
}
|
||||
|
||||
// Tool Purpose
|
||||
const (
|
||||
// Key Management and Creation, as well as Authenticity
|
||||
|
||||
// PurposeKeyDerivation declares key derivation capabilities.
|
||||
PurposeKeyDerivation uint8 = iota + 1
|
||||
|
||||
// PurposePassDerivation declares password derivation capabilties (make a secure key out of a password).
|
||||
// Provides SenderAuthentication, ReceiverAuthentication requirements.
|
||||
PurposePassDerivation
|
||||
|
||||
// PurposeKeyExchange declares (DH-style) key exchange capabilities.
|
||||
// A trusted key of the receiver must be supplied.
|
||||
// Provides ReceiverAuthentication attribute.
|
||||
PurposeKeyExchange
|
||||
|
||||
// PurposeKeyEncapsulation declares key encapsulation capabilities (key is encrypted with the receivers public key)
|
||||
// A trusted key of the receiver must be supplied.
|
||||
// Provides ReceiverAuthentication attribute.
|
||||
PurposeKeyEncapsulation
|
||||
|
||||
// PurposeSigning declares signing capabilities.
|
||||
// The receiver must already have the public key.
|
||||
// Provides SenderAuthentication attribute. Theoretically also provides integrity, but as signing is done after everything else, it will not be able to detect a wrong key during decryption.
|
||||
PurposeSigning
|
||||
|
||||
// Confidentiality and Integrity
|
||||
|
||||
// PurposeIntegratedCipher declares that the tool provides both encryption and integrity verification capabilities.
|
||||
// Provies Confidentiality and Integrity requirements.
|
||||
PurposeIntegratedCipher
|
||||
|
||||
// PurposeCipher declares that the tool provides encryption capabilities.
|
||||
// Provies Confidentiality attribute.
|
||||
PurposeCipher
|
||||
|
||||
// PurposeMAC declares that the tool provides integrity verification capabilities.
|
||||
// Provies Integrity attribute.
|
||||
PurposeMAC
|
||||
)
|
||||
|
||||
// Tool Options
|
||||
const (
|
||||
// Operation
|
||||
|
||||
// OptionStreaming declares that the tool can work with streaming data and might be given a io.Reader and io.Writer instead of just a []byte slice.
|
||||
// TODO: Implementation pending.
|
||||
OptionStreaming uint8 = iota + 1
|
||||
|
||||
// Needs
|
||||
|
||||
// OptionNeedsManagedHasher declares that the tool requires a hashing algorithm to work. It will automatically hash everything that needs to be authenticated and may be shared with other algorithms.
|
||||
OptionNeedsManagedHasher
|
||||
|
||||
// OptionNeedsDedicatedHasher declares that the tool requires a hashing algorithm to work. It will get its own instance and will have to do all the work itself.
|
||||
OptionNeedsDedicatedHasher
|
||||
|
||||
// OptionNeedsSecurityLevel declares that the tool requires a specified security level. This will be derived from the rest of the used tools, or must be specified by the user directly.
|
||||
OptionNeedsSecurityLevel
|
||||
|
||||
// OptionNeedsDefaultKeySize declares that the tool requires a default key size for operation. This will be derived from the rest of the used tools, or must be specified by the user directly.
|
||||
OptionNeedsDefaultKeySize
|
||||
|
||||
// OptionHasState declares that the tool has an internal state and requires the setup and reset routines to be run before/after usage. KeyDerivation tools do not have to declare this, their state is handled separately.
|
||||
OptionHasState
|
||||
)
|
||||
|
||||
// HasOption returns whether the *ToolInfo has the given option.
|
||||
func (ti *ToolInfo) HasOption(option uint8) bool {
|
||||
for _, optionEntry := range ti.Options {
|
||||
if option == optionEntry {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// With uses the original ToolInfo as a template for a new ToolInfo and returns the new ToolInfo.
|
||||
func (ti *ToolInfo) With(changes *ToolInfo) *ToolInfo {
|
||||
if changes.Name == "" {
|
||||
changes.Name = ti.Name
|
||||
}
|
||||
if changes.Purpose == 0 {
|
||||
changes.Purpose = ti.Purpose
|
||||
}
|
||||
if len(changes.Options) == 0 {
|
||||
changes.Options = ti.Options
|
||||
}
|
||||
if changes.KeySize == 0 {
|
||||
changes.KeySize = ti.KeySize
|
||||
}
|
||||
if changes.NonceSize == 0 {
|
||||
changes.NonceSize = ti.NonceSize
|
||||
}
|
||||
if changes.SecurityLevel == 0 {
|
||||
changes.SecurityLevel = ti.SecurityLevel
|
||||
}
|
||||
if changes.Comment == "" {
|
||||
changes.Comment = ti.Comment
|
||||
}
|
||||
if changes.Author == "" {
|
||||
changes.Author = ti.Author
|
||||
}
|
||||
|
||||
return changes
|
||||
}
|
||||
|
||||
// FormatPurpose returns the name of the declared purpose.
|
||||
func (ti *ToolInfo) FormatPurpose() string {
|
||||
switch ti.Purpose {
|
||||
case PurposeKeyDerivation:
|
||||
return "KeyDerivation"
|
||||
case PurposePassDerivation:
|
||||
return "PassDerivation"
|
||||
case PurposeKeyExchange:
|
||||
return "KeyExchange"
|
||||
case PurposeKeyEncapsulation:
|
||||
return "KeyEncapsulation"
|
||||
case PurposeSigning:
|
||||
return "Signing"
|
||||
case PurposeIntegratedCipher:
|
||||
return "IntegratedCipher"
|
||||
case PurposeCipher:
|
||||
return "Cipher"
|
||||
case PurposeMAC:
|
||||
return "MAC"
|
||||
default:
|
||||
return "UNKNOWN"
|
||||
}
|
||||
}
|
||||
|
||||
// FormatOptions returns a list of names of the declared options.
|
||||
func (ti *ToolInfo) FormatOptions() string {
|
||||
if len(ti.Options) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var s []string
|
||||
for _, optionID := range ti.Options {
|
||||
switch optionID {
|
||||
case OptionStreaming:
|
||||
s = append(s, "Streaming")
|
||||
case OptionNeedsManagedHasher:
|
||||
s = append(s, "NeedsManagedHasher")
|
||||
case OptionNeedsDedicatedHasher:
|
||||
s = append(s, "NeedsDedicatedHasher")
|
||||
case OptionNeedsSecurityLevel:
|
||||
s = append(s, "NeedsSecurityLevel")
|
||||
case OptionNeedsDefaultKeySize:
|
||||
s = append(s, "NeedsDefaultKeySize")
|
||||
case OptionHasState:
|
||||
s = append(s, "HasState")
|
||||
default:
|
||||
s = append(s, "UNKNOWN")
|
||||
}
|
||||
}
|
||||
return strings.Join(s, ", ")
|
||||
}
|
295
tools/toollogic.go
Normal file
295
tools/toollogic.go
Normal file
|
@ -0,0 +1,295 @@
|
|||
package tools
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/safing/jess/hashtools"
|
||||
)
|
||||
|
||||
// ToolLogic is the uniform interface for all tools.
|
||||
type ToolLogic interface {
|
||||
// Init and Meta methods
|
||||
|
||||
// Init is called by the internal tool initialized procedure and is called by New(). Do not override.
|
||||
Init(tool *Tool, helper HelperInt, hashTool *hashtools.HashTool, hashSumFn func() ([]byte, error))
|
||||
|
||||
// Info returns information about the Tool. Init is only called once per ToolLogic instance. Do not override.
|
||||
Info() *ToolInfo
|
||||
// Definition returns Tool's definition. Do not override.
|
||||
Definition() *Tool
|
||||
// Factory returns a new instance of the ToolLogic. Do not override.
|
||||
Factory() ToolLogic
|
||||
// Helper returns a Helper. Do not override.
|
||||
Helper() HelperInt
|
||||
// HashTool returns the assigned HashTool. Do not override.
|
||||
HashTool() *hashtools.HashTool
|
||||
// ManagedHashSum returns the hashsum of the managed hasher. Must be enabled by the tool by declaring FeatureNeedsManagedHasher. Do not override.
|
||||
ManagedHashSum() ([]byte, error)
|
||||
|
||||
// Setup is called after Init and can be used the tool to do some custom setup before being used. It is called before every use of the ToolLogic instance. Override at will.
|
||||
// If a Tool needs key material, it needs to be requested here.
|
||||
Setup() error
|
||||
|
||||
// Reset is called after all operations have finished and should be used to do some cleanup, burn all key material and prepare for the next usage. It is called after every use of the ToolLogic instance. Override at will.
|
||||
Reset() error
|
||||
|
||||
// Tool Logic Methods
|
||||
|
||||
// Key Creation
|
||||
|
||||
// DeriveKeyFromPassword takes a password and turns it into a key.
|
||||
// Must be overridden by tools that declare FeaturePassDerivation.
|
||||
DeriveKeyFromPassword(password []byte, salt []byte) ([]byte, error)
|
||||
|
||||
// InitKeyDerivation initializes the key generation.
|
||||
// Must be overridden by tools that declare FeatureKeyDerivation.
|
||||
InitKeyDerivation(nonce []byte, material ...[]byte) error
|
||||
|
||||
// DeriveKey derives a new key.
|
||||
// Must be overridden by tools that declare FeatureKeyDerivation.
|
||||
DeriveKey(size int) ([]byte, error)
|
||||
|
||||
// DeriveKeyWriteTo derives a new key and writes it into the given slice.
|
||||
// Must be overridden by tools that declare FeatureKeyDerivation.
|
||||
DeriveKeyWriteTo(new []byte) error
|
||||
|
||||
// Key Exchanging
|
||||
|
||||
// MakeSharedKey takes a local private key and a remote public key and generates a shared secret.
|
||||
// Must be overridden by tools that declare FeatureKeyExchange.
|
||||
MakeSharedKey(local SignetInt, remote SignetInt) ([]byte, error)
|
||||
|
||||
// EncapsulateKey wraps a key using the given Signet (remote public key).
|
||||
// Must be overridden by tools that declare FeatureKeyEncapsulation.
|
||||
EncapsulateKey(key []byte, remote SignetInt) ([]byte, error)
|
||||
|
||||
// EncapsulateKey unwraps an encapsulated key using the given Signet (local private key).
|
||||
// Must be overridden by tools that declare FeatureKeyEncapsulation.
|
||||
UnwrapKey(wrappedKey []byte, local SignetInt) ([]byte, error)
|
||||
|
||||
// Encryption and Authentication
|
||||
|
||||
// Encrypt encrypts the given data.
|
||||
// Must be overridden by tools that declare FeatureCipher.
|
||||
Encrypt(data []byte) ([]byte, error)
|
||||
|
||||
// Decrypt decrypts the given data.
|
||||
// Must be overridden by tools that declare FeatureCipher.
|
||||
Decrypt(data []byte) ([]byte, error)
|
||||
|
||||
// Encrypt encrypts the given data, and authenticates both data and associatedData.
|
||||
// Must be overridden by tools that declare FeatureIntegratedCipher.
|
||||
AuthenticatedEncrypt(data, associatedData []byte) ([]byte, error)
|
||||
|
||||
// Decrypt decrypts the given data, and authenticates both data and associatedData.
|
||||
// Must be overridden by tools that declare FeatureIntegratedCipher.
|
||||
AuthenticatedDecrypt(data, associatedData []byte) ([]byte, error)
|
||||
|
||||
// MAC returns a message authentication code for the given data and associatedData. If the Tool uses a managed hasher, it will be ready for fetching the sum of both. In that case, no data has to be processed again.
|
||||
// Must be overridden by tools that declare FeatureMAC.
|
||||
MAC(data, associatedData []byte) ([]byte, error)
|
||||
|
||||
// Signing
|
||||
|
||||
// Sign signs the data with the given Signet (local private key).
|
||||
// Must be overridden by tools that declare FeatureSigning.
|
||||
Sign(data, associatedData []byte, local SignetInt) ([]byte, error)
|
||||
|
||||
// Verify verifies the signature of the data using the given signature and Signet (remote public key).
|
||||
// Must be overridden by tools that declare FeatureSigning.
|
||||
Verify(data, associatedData, signature []byte, remote SignetInt) error
|
||||
|
||||
// Signet Handling
|
||||
|
||||
// LoadKey loads a key from the Signet's key storage (`Key`) into the Signet's cache (`Loaded*`). If the Signet is marked as public, the storage is expected to only have the public key present, only only it will be loaded.
|
||||
// Must work with a static (no Setup()) ToolLogic.
|
||||
// Must be overridden by tools that declare FeatureKeyExchange, FeatureKeyEncapsulation or FeatureSigning.
|
||||
LoadKey(SignetInt) error
|
||||
|
||||
// StoreKey stores a loaded key from the Signet's cache (`Loaded*`) in the Signet's key storage (`Key`). If the Signet is marked as public, only the public key will be stored.
|
||||
// Must work with a static (no Setup()) ToolLogic.
|
||||
// Must be overridden by tools that declare FeatureKeyExchange, FeatureKeyEncapsulation or FeatureSigning.
|
||||
StoreKey(SignetInt) error
|
||||
|
||||
// GenerateKey generates a new key pair and stores it in the given Signet. They key pair is not stored in the Signet's key storage (`Key`).
|
||||
// Must work with a static (no Setup()) ToolLogic.
|
||||
// Must be overridden by tools that declare FeatureKeyExchange, FeatureKeyEncapsulation or FeatureSigning.
|
||||
GenerateKey(signet SignetInt) error
|
||||
|
||||
// BurnKey deletes the loaded keys in the Signet.
|
||||
// Must work with a static (no Setup()) ToolLogic.
|
||||
// Must be overridden by tools that declare FeatureKeyExchange, FeatureKeyEncapsulation or FeatureSigning.
|
||||
BurnKey(signet SignetInt) error
|
||||
|
||||
// SecurityLevel returns the security level (approximate attack complexity as 2^n) of the given tool.
|
||||
// May be overridden if needed for custom calculation (ie. based on actual key size in signet or hash tool). Init() will be called before SecurityLevel() is called.
|
||||
SecurityLevel(signet SignetInt) (int, error)
|
||||
}
|
||||
|
||||
// ToolLogicBase covers all methods of the ToolLogic interface with dummy implementations to reduce boilerplate code.
|
||||
type ToolLogicBase struct {
|
||||
tool *Tool
|
||||
helper HelperInt
|
||||
hashTool *hashtools.HashTool
|
||||
hashSumFn func() ([]byte, error)
|
||||
}
|
||||
|
||||
// Init is called by the internal tool initialized procedure and is called by NewTool(). Do not override.
|
||||
func (tlb *ToolLogicBase) Init(tool *Tool, helper HelperInt, hashTool *hashtools.HashTool, hashSumFn func() ([]byte, error)) {
|
||||
tlb.tool = tool
|
||||
tlb.helper = helper
|
||||
tlb.hashTool = hashTool
|
||||
tlb.hashSumFn = hashSumFn
|
||||
}
|
||||
|
||||
// Info returns information about the Tool. Do not override.
|
||||
func (tlb *ToolLogicBase) Info() *ToolInfo {
|
||||
return tlb.tool.Info
|
||||
}
|
||||
|
||||
// Definition returns Tool's definition. Do not override.
|
||||
func (tlb *ToolLogicBase) Definition() *Tool {
|
||||
return tlb.tool
|
||||
}
|
||||
|
||||
// Factory returns a new instance of the ToolLogic. Do not override.
|
||||
func (tlb *ToolLogicBase) Factory() ToolLogic {
|
||||
return tlb.tool.Factory()
|
||||
}
|
||||
|
||||
// Helper returns a Helper. Do not override.
|
||||
func (tlb *ToolLogicBase) Helper() HelperInt {
|
||||
return tlb.helper
|
||||
}
|
||||
|
||||
// HashTool returns the assigned HashTool. Do not override.
|
||||
func (tlb *ToolLogicBase) HashTool() *hashtools.HashTool {
|
||||
return tlb.hashTool
|
||||
}
|
||||
|
||||
// ManagedHashSum returns the hashsum of the managed hasher. Must be enabled by the tool by declaring FeatureNeedsManagedHasher. Do not override.
|
||||
func (tlb *ToolLogicBase) ManagedHashSum() ([]byte, error) {
|
||||
if tlb.hashSumFn == nil {
|
||||
return nil, errors.New("managed hash not configured")
|
||||
}
|
||||
return tlb.hashSumFn()
|
||||
}
|
||||
|
||||
// Setup is called after Init and can be used the tool to do some custom setup before being used. Override at will.
|
||||
// If a Tool needs key material, it needs to be requested here.
|
||||
func (tlb *ToolLogicBase) Setup() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Reset is called after all operations have finished and should be used to do cleanup and burn all key material. Override at will.
|
||||
func (tlb *ToolLogicBase) Reset() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SecurityLevel returns the security level (approximate attack complexity as 2^n) of the given tool.
|
||||
// May be overridden if needed for custom calculation (ie. based on actual key size in signet or hash tool). Init() will be called before SecurityLevel() is called.
|
||||
func (tlb *ToolLogicBase) SecurityLevel(signet SignetInt) (int, error) {
|
||||
if tlb.hashTool != nil {
|
||||
// return the hashtool's security level, if tool does not have one
|
||||
if tlb.tool.Info.SecurityLevel == 0 {
|
||||
return tlb.hashTool.SecurityLevel, nil
|
||||
}
|
||||
// return the hashtool's security level, if it is lower than the tools' level
|
||||
if tlb.hashTool.SecurityLevel < tlb.tool.Info.SecurityLevel {
|
||||
return tlb.hashTool.SecurityLevel, nil
|
||||
}
|
||||
}
|
||||
return tlb.tool.Info.SecurityLevel, nil
|
||||
}
|
||||
|
||||
// Compliance Dummy Methods
|
||||
|
||||
// DeriveKeyFromPassword implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) DeriveKeyFromPassword(password []byte, salt []byte) ([]byte, error) {
|
||||
return nil, ErrNotImplemented
|
||||
}
|
||||
|
||||
// InitKeyDerivation implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) InitKeyDerivation(nonce []byte, material ...[]byte) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
// DeriveKey implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) DeriveKey(size int) ([]byte, error) {
|
||||
return nil, ErrNotImplemented
|
||||
}
|
||||
|
||||
// DeriveKeyWriteTo implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) DeriveKeyWriteTo(new []byte) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
// MakeSharedKey implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) MakeSharedKey(local SignetInt, remote SignetInt) ([]byte, error) {
|
||||
return nil, ErrNotImplemented
|
||||
}
|
||||
|
||||
// EncapsulateKey implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) EncapsulateKey(key []byte, remote SignetInt) ([]byte, error) {
|
||||
return nil, ErrNotImplemented
|
||||
}
|
||||
|
||||
// UnwrapKey implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) UnwrapKey(wrappedKey []byte, local SignetInt) ([]byte, error) {
|
||||
return nil, ErrNotImplemented
|
||||
}
|
||||
|
||||
// Encrypt implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) Encrypt(data []byte) ([]byte, error) {
|
||||
return nil, ErrNotImplemented
|
||||
}
|
||||
|
||||
// Decrypt implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) Decrypt(data []byte) ([]byte, error) {
|
||||
return nil, ErrNotImplemented
|
||||
}
|
||||
|
||||
// AuthenticatedEncrypt implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) AuthenticatedEncrypt(data, associatedData []byte) ([]byte, error) {
|
||||
return nil, ErrNotImplemented
|
||||
}
|
||||
|
||||
// AuthenticatedDecrypt implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) AuthenticatedDecrypt(data, associatedData []byte) ([]byte, error) {
|
||||
return nil, ErrNotImplemented
|
||||
}
|
||||
|
||||
// MAC implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) MAC(data, associatedData []byte) ([]byte, error) {
|
||||
return nil, ErrNotImplemented
|
||||
}
|
||||
|
||||
// Sign implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) Sign(data, associatedData []byte, local SignetInt) ([]byte, error) {
|
||||
return nil, ErrNotImplemented
|
||||
}
|
||||
|
||||
// Verify implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) Verify(data, associatedData, signature []byte, remote SignetInt) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
// LoadKey implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) LoadKey(SignetInt) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
// StoreKey implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) StoreKey(SignetInt) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
// GenerateKey implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) GenerateKey(signet SignetInt) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
// BurnKey implements the ToolLogic interface.
|
||||
func (tlb *ToolLogicBase) BurnKey(signet SignetInt) error {
|
||||
return ErrNotImplemented
|
||||
}
|
59
tools/tools.go
Normal file
59
tools/tools.go
Normal file
|
@ -0,0 +1,59 @@
|
|||
package tools
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
var (
|
||||
toolMap = make(map[string]*Tool)
|
||||
toolList = sortableToolList{}
|
||||
)
|
||||
|
||||
// Register registers a new Tool. This function may only be called in init() functions.
|
||||
func Register(tool *Tool) {
|
||||
// register in lists
|
||||
toolMap[tool.Info.Name] = tool
|
||||
toolList = append(toolList, tool)
|
||||
sort.Sort(toolList)
|
||||
}
|
||||
|
||||
// Get returns the Tool with the given name.
|
||||
func Get(name string) (*Tool, error) {
|
||||
tool, ok := toolMap[name]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Tool %s %w", name, ErrNotFound)
|
||||
}
|
||||
return tool, nil
|
||||
}
|
||||
|
||||
// New returns a new instance of a Tool's Logic with the given name.
|
||||
func New(name string) (ToolLogic, error) {
|
||||
tool, err := Get(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return tool.Factory(), nil
|
||||
}
|
||||
|
||||
// AsMap returns all Tools in a map. The returned map must not be modified.
|
||||
func AsMap() map[string]*Tool {
|
||||
return toolMap
|
||||
}
|
||||
|
||||
// AsList returns all Tools in a slice. The returned slice must not be modified.
|
||||
func AsList() []*Tool {
|
||||
return toolList
|
||||
}
|
||||
|
||||
type sortableToolList []*Tool
|
||||
|
||||
// Len implements sort.Interface.
|
||||
func (l sortableToolList) Len() int { return len(l) }
|
||||
|
||||
// Swap implements sort.Interface.
|
||||
func (l sortableToolList) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
|
||||
|
||||
// Less implements sort.Interface.
|
||||
func (l sortableToolList) Less(i, j int) bool { return l[i].Info.Name < l[j].Info.Name }
|
94
tools_test.go
Normal file
94
tools_test.go
Normal file
|
@ -0,0 +1,94 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/safing/jess/tools"
|
||||
|
||||
// import all tools for testing
|
||||
_ "github.com/safing/jess/tools/all"
|
||||
)
|
||||
|
||||
func TestConformity(t *testing.T) {
|
||||
|
||||
// Test that every tool only provides one primary feature, as this enables to automatically assign a distinct role to every tool.
|
||||
|
||||
for _, tool := range tools.AsList() {
|
||||
|
||||
// check for invalid FeatureNeedsSetupAndReset
|
||||
hasState := tool.Info.HasOption(tools.OptionHasState)
|
||||
needsState := tool.Info.Purpose == tools.PurposeCipher ||
|
||||
tool.Info.Purpose == tools.PurposeIntegratedCipher ||
|
||||
tool.Info.Purpose == tools.PurposeMAC
|
||||
|
||||
switch {
|
||||
case hasState == true && needsState == false:
|
||||
t.Errorf("tool %s may not declare FeatureHasState. Currently only allowed for: IntegratedCipher, Cipher and MAC tools", tool.Info.Name)
|
||||
case hasState == false && needsState == true:
|
||||
t.Errorf("tool %s may does not declare FeatureHasState, but is expected to", tool.Info.Name)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestSignetHandling(t *testing.T) {
|
||||
for _, tool := range tools.AsList() {
|
||||
switch tool.Info.Purpose {
|
||||
case tools.PurposeKeyExchange,
|
||||
tools.PurposeKeyEncapsulation,
|
||||
tools.PurposeSigning:
|
||||
|
||||
// create and generate signet
|
||||
signet := NewSignetBase(tool)
|
||||
err := tool.StaticLogic.GenerateKey(signet)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to generate key with %s: %s", tool.Info.Name, err)
|
||||
}
|
||||
|
||||
// store
|
||||
err = signet.StoreKey()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to store %s signet: %s", tool.Info.Name, err)
|
||||
}
|
||||
|
||||
// duplicate stored signet and load
|
||||
copiedSignet := &Signet{
|
||||
Scheme: tool.Info.Name,
|
||||
Key: signet.Key,
|
||||
Public: signet.Public,
|
||||
tool: tool,
|
||||
}
|
||||
err = copiedSignet.LoadKey()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to load %s signet: %s", tool.Info.Name, err)
|
||||
}
|
||||
|
||||
// transform to recipient
|
||||
rcpt, err := signet.AsRecipient()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get %s signet as recipient: %s", tool.Info.Name, err)
|
||||
}
|
||||
|
||||
// store recipient
|
||||
err = rcpt.StoreKey()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to store %s recipient: %s", tool.Info.Name, err)
|
||||
}
|
||||
|
||||
// duplicate stored rcpt and load
|
||||
copiedRcpt := &Signet{
|
||||
Scheme: tool.Info.Name,
|
||||
Key: rcpt.Key,
|
||||
Public: rcpt.Public,
|
||||
tool: tool,
|
||||
}
|
||||
err = copiedRcpt.LoadKey()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to load %s recipient: %s", tool.Info.Name, err)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
124
truststore.go
Normal file
124
truststore.go
Normal file
|
@ -0,0 +1,124 @@
|
|||
package jess
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// TrustStore filter options
|
||||
const (
|
||||
FilterAny uint8 = iota
|
||||
FilterSignetOnly
|
||||
FilterRecipientOnly
|
||||
)
|
||||
|
||||
// TrustStore errors
|
||||
var (
|
||||
ErrSignetNotFound = errors.New("could not find signet")
|
||||
ErrEnvelopeNotFound = errors.New("could not find envelope")
|
||||
)
|
||||
|
||||
// TrustStore holds a set of trusted Signets and Recipients.
|
||||
type TrustStore interface {
|
||||
// GetSignet returns the Signet with the given ID.
|
||||
GetSignet(id string, recipient bool) (*Signet, error)
|
||||
}
|
||||
|
||||
// MemTrustStore is a simple trust store using a Go map as backend.
|
||||
type MemTrustStore struct {
|
||||
lock sync.Mutex
|
||||
storage map[string]*Signet
|
||||
}
|
||||
|
||||
// GetSignet returns the Signet with the given ID.
|
||||
func (mts *MemTrustStore) GetSignet(id string, recipient bool) (*Signet, error) {
|
||||
mts.lock.Lock()
|
||||
defer mts.lock.Unlock()
|
||||
|
||||
// get from storage
|
||||
signet, ok := mts.storage[makeStorageID(id, recipient)]
|
||||
if !ok {
|
||||
return nil, ErrSignetNotFound
|
||||
}
|
||||
|
||||
return signet, nil
|
||||
}
|
||||
|
||||
// StoreSignet stores a Signet in the TrustStore.
|
||||
func (mts *MemTrustStore) StoreSignet(signet *Signet) error {
|
||||
// check for ID
|
||||
if signet.ID == "" {
|
||||
return errors.New("signets require an ID to be stored in a trust store")
|
||||
}
|
||||
|
||||
mts.lock.Lock()
|
||||
defer mts.lock.Unlock()
|
||||
|
||||
// store
|
||||
mts.storage[makeStorageID(signet.ID, signet.Public)] = signet
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteSignet deletes the Signet or Recipient with the given ID.
|
||||
func (mts *MemTrustStore) DeleteSignet(id string, recipient bool) error {
|
||||
mts.lock.Lock()
|
||||
defer mts.lock.Unlock()
|
||||
|
||||
// delete
|
||||
delete(mts.storage, makeStorageID(id, recipient))
|
||||
return nil
|
||||
}
|
||||
|
||||
// SelectSignets returns a selection of the signets in the trust store. Results are filtered by tool/algorithm and whether it you're looking for a signet (private key) or a recipient (public key).
|
||||
func (mts *MemTrustStore) SelectSignets(filter uint8, schemes ...string) ([]*Signet, error) {
|
||||
mts.lock.Lock()
|
||||
defer mts.lock.Unlock()
|
||||
|
||||
var selection []*Signet //nolint:prealloc
|
||||
for _, signet := range mts.storage {
|
||||
// check signet scheme
|
||||
if len(schemes) > 0 && !stringInSlice(signet.Scheme, schemes) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// check type filter
|
||||
switch filter {
|
||||
case FilterSignetOnly:
|
||||
if signet.Public {
|
||||
continue
|
||||
}
|
||||
case FilterRecipientOnly:
|
||||
if !signet.Public {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
selection = append(selection, signet)
|
||||
}
|
||||
|
||||
return selection, nil
|
||||
}
|
||||
|
||||
// NewMemTrustStore returns a new in-memory TrustStore.
|
||||
func NewMemTrustStore() *MemTrustStore {
|
||||
return &MemTrustStore{
|
||||
storage: make(map[string]*Signet),
|
||||
}
|
||||
}
|
||||
|
||||
func makeStorageID(id string, recipient bool) string {
|
||||
if recipient {
|
||||
return fmt.Sprintf("%s.recipient", id)
|
||||
}
|
||||
return fmt.Sprintf("%s.signet", id)
|
||||
}
|
||||
|
||||
func stringInSlice(s string, a []string) bool {
|
||||
for _, entry := range a {
|
||||
if entry == s {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
290
truststores/dir.go
Normal file
290
truststores/dir.go
Normal file
|
@ -0,0 +1,290 @@
|
|||
package truststores
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/safing/jess"
|
||||
)
|
||||
|
||||
const (
|
||||
signetSuffix = ".signet"
|
||||
recipientSuffix = ".recipient"
|
||||
envelopeSuffix = ".envelope"
|
||||
permittedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789- ._+@"
|
||||
)
|
||||
|
||||
// TrustStore errors
|
||||
var (
|
||||
errInvalidSignetIDChars = fmt.Errorf("this trust store only allows these characters in signet IDs: %s", permittedCharacters)
|
||||
errInvalidEnvelopeNameChars = fmt.Errorf("this trust store only allows these characters in envelope names: %s", permittedCharacters)
|
||||
)
|
||||
|
||||
// DirTrustStore is a simple trust store using a filesystem directory as the storage backend.
|
||||
type DirTrustStore struct {
|
||||
lock sync.Mutex
|
||||
storageDir string
|
||||
}
|
||||
|
||||
// GetSignet returns the Signet with the given ID.
|
||||
func (dts *DirTrustStore) GetSignet(id string, recipient bool) (*jess.Signet, error) {
|
||||
// check ID
|
||||
ok := NamePlaysNiceWithFS(id)
|
||||
if !ok {
|
||||
return nil, errInvalidSignetIDChars
|
||||
}
|
||||
|
||||
// synchronize fs access
|
||||
dts.lock.Lock()
|
||||
defer dts.lock.Unlock()
|
||||
|
||||
// read from storage
|
||||
filename := filepath.Join(dts.storageDir, makeStorageID(id, recipient))
|
||||
signet, err := LoadSignetFromFile(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return signet, nil
|
||||
}
|
||||
|
||||
// StoreSignet stores a Signet in the TrustStore.
|
||||
func (dts *DirTrustStore) StoreSignet(signet *jess.Signet) error {
|
||||
// synchronize fs access
|
||||
dts.lock.Lock()
|
||||
defer dts.lock.Unlock()
|
||||
|
||||
// write
|
||||
filename := filepath.Join(dts.storageDir, makeStorageID(signet.ID, signet.Public))
|
||||
return WriteSignetToFile(signet, filename)
|
||||
}
|
||||
|
||||
// DeleteSignet deletes the Signet or Recipient with the given ID.
|
||||
func (dts *DirTrustStore) DeleteSignet(id string, recipient bool) error {
|
||||
// check ID
|
||||
ok := NamePlaysNiceWithFS(id)
|
||||
if !ok {
|
||||
return errInvalidSignetIDChars
|
||||
}
|
||||
|
||||
// synchronize fs access
|
||||
dts.lock.Lock()
|
||||
defer dts.lock.Unlock()
|
||||
|
||||
// delete
|
||||
filename := filepath.Join(dts.storageDir, makeStorageID(id, recipient))
|
||||
return os.Remove(filename)
|
||||
}
|
||||
|
||||
// SelectSignets returns a selection of the signets in the trust store. Results are filtered by tool/algorithm and whether it you're looking for a signet (private key) or a recipient (public key).
|
||||
func (dts *DirTrustStore) SelectSignets(filter uint8, schemes ...string) ([]*jess.Signet, error) {
|
||||
dts.lock.Lock()
|
||||
defer dts.lock.Unlock()
|
||||
|
||||
var selection []*jess.Signet
|
||||
|
||||
// walk the storage
|
||||
err := filepath.Walk(dts.storageDir, func(path string, info os.FileInfo, err error) error {
|
||||
// consider errors
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// skip dirs
|
||||
if info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
|
||||
// check for suffix
|
||||
if !strings.HasSuffix(path, signetSuffix) &&
|
||||
!strings.HasSuffix(path, recipientSuffix) {
|
||||
return nil
|
||||
}
|
||||
|
||||
signet, err := LoadSignetFromFile(path)
|
||||
if err != nil {
|
||||
// add failed signet to list
|
||||
selection = append(selection, &jess.Signet{
|
||||
Info: &jess.SignetInfo{
|
||||
Name: "[failed to load]",
|
||||
},
|
||||
ID: strings.Split(filepath.Base(path), ".")[0],
|
||||
Public: strings.HasSuffix(path, recipientSuffix),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// check signet scheme
|
||||
if len(schemes) > 0 && !stringInSlice(signet.Scheme, schemes) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// check type filter
|
||||
switch filter {
|
||||
case jess.FilterSignetOnly:
|
||||
if signet.Public {
|
||||
return nil
|
||||
}
|
||||
case jess.FilterRecipientOnly:
|
||||
if !signet.Public {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
selection = append(selection, signet)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to access trust store entry: %s", err)
|
||||
}
|
||||
|
||||
return selection, nil
|
||||
}
|
||||
|
||||
// GetEnvelope returns the Envelope with the given name.
|
||||
func (dts *DirTrustStore) GetEnvelope(name string) (*jess.Envelope, error) {
|
||||
// check name
|
||||
ok := NamePlaysNiceWithFS(name)
|
||||
if !ok {
|
||||
return nil, errInvalidEnvelopeNameChars
|
||||
}
|
||||
|
||||
// synchronize fs access
|
||||
dts.lock.Lock()
|
||||
defer dts.lock.Unlock()
|
||||
|
||||
// read from storage
|
||||
filename := filepath.Join(dts.storageDir, name+envelopeSuffix)
|
||||
envelope, err := LoadEnvelopeFromFile(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return envelope, nil
|
||||
}
|
||||
|
||||
// StoreEnvelope stores an Envelope.
|
||||
func (dts *DirTrustStore) StoreEnvelope(envelope *jess.Envelope) error {
|
||||
// synchronize fs access
|
||||
dts.lock.Lock()
|
||||
defer dts.lock.Unlock()
|
||||
|
||||
// write
|
||||
filename := filepath.Join(dts.storageDir, envelope.Name+envelopeSuffix)
|
||||
return WriteEnvelopeToFile(envelope, filename)
|
||||
}
|
||||
|
||||
// DeleteEnvelope deletes the Envelope with the given name.
|
||||
func (dts *DirTrustStore) DeleteEnvelope(name string) error {
|
||||
// check name
|
||||
ok := NamePlaysNiceWithFS(name)
|
||||
if !ok {
|
||||
return errInvalidEnvelopeNameChars
|
||||
}
|
||||
|
||||
// synchronize fs access
|
||||
dts.lock.Lock()
|
||||
defer dts.lock.Unlock()
|
||||
|
||||
// delete
|
||||
filename := filepath.Join(dts.storageDir, name+envelopeSuffix)
|
||||
return os.Remove(filename)
|
||||
}
|
||||
|
||||
// AllEnvelopes returns all envelopes.
|
||||
func (dts *DirTrustStore) AllEnvelopes() ([]*jess.Envelope, error) {
|
||||
dts.lock.Lock()
|
||||
defer dts.lock.Unlock()
|
||||
|
||||
var all []*jess.Envelope
|
||||
|
||||
// walk the storage
|
||||
err := filepath.Walk(dts.storageDir, func(path string, info os.FileInfo, err error) error {
|
||||
// consider errors
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// skip dirs
|
||||
if info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
|
||||
// check for suffix
|
||||
if !strings.HasSuffix(path, envelopeSuffix) {
|
||||
return nil
|
||||
}
|
||||
|
||||
envelope, err := LoadEnvelopeFromFile(path)
|
||||
if err != nil {
|
||||
// add failed envelope to list
|
||||
all = append(all, &jess.Envelope{
|
||||
Name: fmt.Sprintf("%s [failed to load]",
|
||||
strings.TrimSuffix(filepath.Base(path), envelopeSuffix)),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
all = append(all, envelope)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to access trust store entry: %s", err)
|
||||
}
|
||||
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// NewDirTrustStore returns a new trust store using a filesystem directory as the storage backend.
|
||||
func NewDirTrustStore(storageDir string) (*DirTrustStore, error) {
|
||||
cleanedPath := filepath.Clean(storageDir)
|
||||
|
||||
// validate path
|
||||
info, err := os.Stat(cleanedPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("trust store does not exist: %s", err)
|
||||
}
|
||||
return nil, fmt.Errorf("failed to access trust store: %s", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return nil, errors.New("truststore storage dir is a file, not a directory")
|
||||
}
|
||||
|
||||
return &DirTrustStore{
|
||||
storageDir: cleanedPath,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// NamePlaysNiceWithFS checks if the given string plays nice with filesystems.
|
||||
func NamePlaysNiceWithFS(s string) (ok bool) {
|
||||
for _, c := range s {
|
||||
n := countRuneInString(permittedCharacters, c)
|
||||
if n == 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func countRuneInString(s string, r rune) (n int) {
|
||||
for {
|
||||
i := strings.IndexRune(s, r)
|
||||
if i < 0 {
|
||||
return
|
||||
}
|
||||
n++
|
||||
s = s[i+1:]
|
||||
}
|
||||
}
|
||||
|
||||
func makeStorageID(id string, recipient bool) string {
|
||||
if recipient {
|
||||
return id + recipientSuffix
|
||||
}
|
||||
return id + signetSuffix
|
||||
}
|
8
truststores/dir_test.go
Normal file
8
truststores/dir_test.go
Normal file
|
@ -0,0 +1,8 @@
|
|||
package truststores
|
||||
|
||||
func init() {
|
||||
// interface compliance test
|
||||
var testDirTrustStore ExtendedTrustStore
|
||||
testDirTrustStore, _ = NewDirTrustStore("/tmp")
|
||||
_ = testDirTrustStore
|
||||
}
|
34
truststores/extended.go
Normal file
34
truststores/extended.go
Normal file
|
@ -0,0 +1,34 @@
|
|||
package truststores
|
||||
|
||||
import (
|
||||
"github.com/safing/jess"
|
||||
)
|
||||
|
||||
// ExtendedTrustStore holds a set of trusted Signets, Recipients and Envelopes.
|
||||
type ExtendedTrustStore interface {
|
||||
jess.TrustStore
|
||||
|
||||
// GetSignet returns the Signet with the given ID.
|
||||
// GetSignet(id string, recipient bool) (*Signet, error)
|
||||
|
||||
// StoreSignet stores a Signet.
|
||||
StoreSignet(signet *jess.Signet) error
|
||||
|
||||
// DeleteSignet deletes the Signet or Recipient with the given ID.
|
||||
DeleteSignet(id string, recipient bool) error
|
||||
|
||||
// SelectSignets returns a selection of the signets in the trust store. Results are filtered by tool/algorithm and whether it you're looking for a signet (private key) or a recipient (public key).
|
||||
SelectSignets(filter uint8, schemes ...string) ([]*jess.Signet, error)
|
||||
|
||||
// GetEnvelope returns the Envelope with the given name.
|
||||
GetEnvelope(name string) (*jess.Envelope, error)
|
||||
|
||||
// StoreEnvelope stores an Envelope.
|
||||
StoreEnvelope(envelope *jess.Envelope) error
|
||||
|
||||
// DeleteEnvelope deletes the Envelope with the given name.
|
||||
DeleteEnvelope(name string) error
|
||||
|
||||
// AllEnvelopes returns all envelopes.
|
||||
AllEnvelopes() ([]*jess.Envelope, error)
|
||||
}
|
110
truststores/io.go
Normal file
110
truststores/io.go
Normal file
|
@ -0,0 +1,110 @@
|
|||
package truststores
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"github.com/safing/jess"
|
||||
"github.com/safing/portbase/formats/dsd"
|
||||
)
|
||||
|
||||
// WriteSignetToFile serializes the signet and writes it to the given file.
|
||||
func WriteSignetToFile(signet *jess.Signet, filename string) error {
|
||||
// check ID
|
||||
if signet.ID == "" {
|
||||
return errors.New("signets require an ID to be stored in a trust store")
|
||||
}
|
||||
ok := NamePlaysNiceWithFS(signet.ID)
|
||||
if !ok {
|
||||
return errInvalidSignetIDChars
|
||||
}
|
||||
|
||||
// serialize
|
||||
data, err := dsd.DumpIndent(signet, dsd.JSON, "\t")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// write
|
||||
err = ioutil.WriteFile(filename, data, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadSignetFromFile loads a signet from the given filepath.
|
||||
func LoadSignetFromFile(filename string) (*jess.Signet, error) {
|
||||
data, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, jess.ErrSignetNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signet := &jess.Signet{}
|
||||
_, err = dsd.Load(data, signet)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return signet, nil
|
||||
}
|
||||
|
||||
// WriteEnvelopeToFile serializes the envelope and writes it to the given file.
|
||||
func WriteEnvelopeToFile(envelope *jess.Envelope, filename string) error {
|
||||
// check name
|
||||
if envelope.Name == "" {
|
||||
return errors.New("envelopes require a name to be stored in a trust store")
|
||||
}
|
||||
ok := NamePlaysNiceWithFS(envelope.Name)
|
||||
if !ok {
|
||||
return errInvalidEnvelopeNameChars
|
||||
}
|
||||
|
||||
// serialize requirements
|
||||
envelope.SerializeRequirements()
|
||||
|
||||
// serialize
|
||||
data, err := dsd.DumpIndent(envelope, dsd.JSON, "\t")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// write to storage
|
||||
err = ioutil.WriteFile(filename, data, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadEnvelopeFromFile loads an envelope from the given filepath.
|
||||
func LoadEnvelopeFromFile(filename string) (*jess.Envelope, error) {
|
||||
data, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, jess.ErrEnvelopeNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// load envelope
|
||||
envelope := &jess.Envelope{}
|
||||
_, err = dsd.Load(data, envelope)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// parse requirements from "No"
|
||||
err = envelope.LoadRequirements()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return envelope, nil
|
||||
}
|
10
truststores/utils.go
Normal file
10
truststores/utils.go
Normal file
|
@ -0,0 +1,10 @@
|
|||
package truststores
|
||||
|
||||
func stringInSlice(s string, a []string) bool {
|
||||
for _, entry := range a {
|
||||
if entry == s {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
Loading…
Add table
Reference in a new issue