From 11ef987c8195cbd8f5b2e01456169c9ebede8aef Mon Sep 17 00:00:00 2001 From: Serge Bazanski Date: Fri, 20 Nov 2020 16:42:06 +0100 Subject: [PATCH] Initial commit. --- .gitignore | 4 + COPYING | 202 ++++++++++++++++++++++++++++++++++++++++++++ README.md | 83 ++++++++++++++++++ cmd/pktls/main.go | 60 +++++++++++++ cmd/testcl/main.go | 60 +++++++++++++ cmd/testsrv/main.go | 97 +++++++++++++++++++++ config.go | 120 ++++++++++++++++++++++++++ go.mod | 9 ++ go.sum | 14 +++ keys.go | 88 +++++++++++++++++++ keys_test.go | 79 +++++++++++++++++ tls.go | 170 +++++++++++++++++++++++++++++++++++++ 12 files changed, 986 insertions(+) create mode 100644 .gitignore create mode 100644 COPYING create mode 100644 README.md create mode 100644 cmd/pktls/main.go create mode 100644 cmd/testcl/main.go create mode 100644 cmd/testsrv/main.go create mode 100644 config.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 keys.go create mode 100644 keys_test.go create mode 100644 tls.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ab57089 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +pktls +testsrv +testcl +**.swp diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/COPYING @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..39b2d2f --- /dev/null +++ b/README.md @@ -0,0 +1,83 @@ +pktls +===== + +**DO NOT USE THIS (YET), UNAUDITED, PRE-RELEASE.** + +Description +----------- + +A Go library to allow using wireguard-style asymmetric keys to configure mutual TLS authentication. + + + .-------------. + | Server | + |-------------| .--------------. + | server.priv | | Client 1 | + | | <---- TLS -----.---- |--------------| + | client1.pub | | | client1.priv | + | client2.pub | | | server.pub | + '-------------' | '--------------' + | .--------------. + | | Client 2 | + '---- |--------------| + | client2.priv | + | server.pub | + '--------------' + +No more having to deal with openssl, CAs, expiring certificates, and complex x509 bootstrap - just use genkey/pubkey! + +Under the hood, it uses ED25519 to generate self-signed certificates for both sides.o + +Key Generation +-------------- + + go get code.hackerspace.pl/q3k/pktls + go build code.hackerspace.pl/q3k/pkgtls/cmd/pktls + + ./pktls genkey > server.priv + ./pktls pubkey < server.priv > server.pub + +The resulting keys look very much like wireguard keys, but are _not compatible_. pktls keys will not work as wireguard keys, and vice-versa. + +Library usage +------------- + +On the server side: + + pk, err := pktls.ServerFromString("", []string{"", ""}) + config := tls.Config{} + pk.Configure(&config) + // Use config with tls.Listen, grpc/credentials.NewTLS, etc. + +On the client side: + + pk, err := pktls.ClientFromString("", "") + config := tls.Config{} + pk.Configure(&config) + // Use config with tls.Dial, grpc/credentials.NewTLS, etc. + +For example code, see cmd/test{srv,cl}. + +Sample client/server +-------------------- + +To test this library without writing Go, you can run a pktls server/client pair as following: + + + go get code.hackerspace.pl/q3k/pktls + go build code.hackerspace.pl/q3k/pkgtls/cmd/pktls + + ./pktls genkey > server.priv + ./pktls pubkey < server.priv > server.pub + ./pktls genkey > client.priv + ./pktls pubkey < client.priv > client.pub + + go build code.hackerspace.pl/q3k/pkgtls/cmd/testsrv + ./testsrv -private_key $(cat server.priv) -allowed $(cat client.pub) -listen 127.0.0.1:1337 + + # and on another terminal: + go build code.hackerspace.pl/q3k/pkgtls/cmd/testcl + ./testcl -private_key $(cat client.priv) -remote_key $(cat server.pub) -remote 127.0.0.1:1337 + +You should observe the client receiving a hello message from the server (”yo”), and the server being able to introspect the identity of the client. + diff --git a/cmd/pktls/main.go b/cmd/pktls/main.go new file mode 100644 index 0000000..bd892d2 --- /dev/null +++ b/cmd/pktls/main.go @@ -0,0 +1,60 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "log" + "os" + + "code.hackerspace.pl/q3k/pktls" +) + +func usage(cmd string) { + fmt.Fprintf(os.Stderr, `Usage: %s + +Available subcommands: + genkey: Generates a new private key and writes it to stdout + pubkey: Reads a private key from stdin and writes a public key to stdout +`, cmd) +} + +func main() { + switch len(os.Args) { + case 0: + // This should never happen. + panic("no argv?") + case 1: + usage(os.Args[0]) + default: + switch os.Args[1] { + case "genkey": + genkey() + case "pubkey": + pubkey() + default: + usage(os.Args[0]) + } + } +} + +func genkey() { + key, err := pktls.PrivateGenerate() + if err != nil { + log.Fatalf("Generation failed: %v", err) + } + fmt.Printf("%s\n", key.String()) +} + +func pubkey() { + r := bufio.NewReader(os.Stdin) + data, err := r.ReadString('\n') + if err != nil && err != io.EOF { + log.Fatalf("Read from stdin failed: %v", err) + } + priv, err := pktls.PrivateFromString(data) + if err != nil { + log.Fatalf("Private key read failed: %v", err) + } + fmt.Printf("%s\n", priv.Public().String()) +} diff --git a/cmd/testcl/main.go b/cmd/testcl/main.go new file mode 100644 index 0000000..633f0f4 --- /dev/null +++ b/cmd/testcl/main.go @@ -0,0 +1,60 @@ +package main + +import ( + "crypto/tls" + "flag" + "io" + "os" + + "code.hackerspace.pl/q3k/pktls" + "github.com/golang/glog" +) + +var ( + flagRemote string + flagPrivateKey string + flagRemoteKey string +) + +func init() { + flag.Set("logtostderr", "true") +} + +func main() { + flag.StringVar(&flagRemote, "remote", "127.0.0.1:1337", "Server address") + // In production code, do not accept private key literals on the command line, + // instead read them from a file. + flag.StringVar(&flagPrivateKey, "private_key", "", "Client private key") + flag.StringVar(&flagRemoteKey, "remote_key", "", "Server public key") + flag.Parse() + + if flagPrivateKey == "" { + glog.Exitf("-private_key must be set") + } + + if flagRemoteKey == "" { + glog.Exitf("-remote_key must be set") + } + + pk, err := pktls.ClientFromString(flagPrivateKey, flagRemoteKey) + if err != nil { + glog.Exitf("loading keys failed: %v", err) + } + + glog.Infof("Connecting with pubkey %s", pk.PrivateKey.Public().String()) + + config := tls.Config{} + err = pk.Configure(&config) + if err != nil { + glog.Exitf("pki.Configure: %v", err) + } + + conn, err := tls.Dial("tcp", flagRemote, &config) + if err != nil { + glog.Exitf("Dial: %v", err) + } + _, err = io.Copy(os.Stdout, conn) + if err != nil && err != io.EOF { + glog.Exitf("Copy failed: %v", err) + } +} diff --git a/cmd/testsrv/main.go b/cmd/testsrv/main.go new file mode 100644 index 0000000..aeacc3e --- /dev/null +++ b/cmd/testsrv/main.go @@ -0,0 +1,97 @@ +package main + +import ( + "crypto/tls" + "flag" + "fmt" + "net" + "strings" + "time" + + "code.hackerspace.pl/q3k/pktls" + "github.com/golang/glog" +) + +var ( + flagListen string + flagPrivate string + flagAllowed string +) + +func init() { + flag.Set("logtostderr", "true") +} + +func main() { + flag.StringVar(&flagListen, "listen", "0.0.0.0:1337", "Listen on address") + // In production code, do not accept private key literals on the command line, + // instead read them from a file. + flag.StringVar(&flagPrivate, "private_key", "", "Server private key") + flag.StringVar(&flagAllowed, "allowed", "", "Comma-separated list of allowed client public keys") + flag.Parse() + + if flagPrivate == "" { + glog.Exitf("-private_key must be set") + } + + // Parse allowed keys, making them unique and stripping whitespace. + allowedRaw := strings.Split(flagAllowed, ",") + allowedSet := make(map[string]bool) + for _, pk := range allowedRaw { + pk = strings.TrimSpace(pk) + if len(pk) == 0 { + continue + } + allowedSet[pk] = true + } + var allowed []string + for pk, _ := range allowedSet { + allowed = append(allowed, pk) + } + + pk, err := pktls.ServerFromString(flagPrivate, allowed) + if err != nil { + glog.Exitf("loading keys failed: %v", err) + } + + glog.Infof("Starting with pubkey %s", pk.PrivateKey.Public().String()) + + config := tls.Config{} + err = pk.Configure(&config) + if err != nil { + glog.Exitf("pki.Configure: %v", err) + } + + listener, err := tls.Listen("tcp", flagListen, &config) + if err != nil { + glog.Exitf("tcp.Listen(%q): %v", flagListen, err) + } + defer listener.Close() + + glog.Infof("Listening on %v", flagListen) + + for { + cl, err := listener.Accept() + if err != nil { + glog.Exitf("Accept failed: %v", err) + } + + handle(cl) + } +} + +func handle(cl net.Conn) { + defer cl.Close() + + identity, err := pktls.ClientPubkey(cl) + if err != nil { + glog.Infof("%v: could not get identity: %v", cl.RemoteAddr(), err) + return + } + glog.Infof("%v: connected (%v)", cl.RemoteAddr(), identity) + + t := time.NewTicker(1 * time.Second) + defer t.Stop() + + fmt.Fprintf(cl, "yo\n") +} diff --git a/config.go b/config.go new file mode 100644 index 0000000..74608e1 --- /dev/null +++ b/config.go @@ -0,0 +1,120 @@ +package pktls + +import ( + "crypto/tls" + "crypto/x509" + "errors" + "fmt" +) + +type Config struct { + PrivateKey PrivateKey +} + +type ServerConfig struct { + Config + Allowed []PublicKey +} + +type ClientConfig struct { + Config + Server PublicKey +} + +func ServerFromString(privkey string, allowed []string) (*ServerConfig, error) { + if len(allowed) == 0 { + return nil, fmt.Errorf("no allowed keys set, server will accept no clients") + } + priv, err := PrivateFromString(privkey) + if err != nil { + return nil, fmt.Errorf("server private key: %w", err) + } + + allowedKeys := make([]PublicKey, len(allowed)) + for i, pk := range allowed { + public, err := PublicFromString(pk) + if err != nil { + return nil, fmt.Errorf("allowed key %d: %w", i, err) + } + allowedKeys[i] = public + } + cfg := &ServerConfig{ + Config: Config{ + PrivateKey: priv, + }, + Allowed: allowedKeys, + } + + return cfg, nil +} + +func ClientFromString(privkey string, server string) (*ClientConfig, error) { + priv, err := PrivateFromString(privkey) + if err != nil { + return nil, fmt.Errorf("client private key: %w", err) + } + serverKey, err := PublicFromString(server) + if err != nil { + return nil, fmt.Errorf("server public key: %w", err) + } + cfg := &ClientConfig{ + Config: Config{ + PrivateKey: priv, + }, + Server: serverKey, + } + + return cfg, nil +} +func (s *ServerConfig) Configure(config *tls.Config) error { + tlsCert, err := s.PrivateKey.GenerateTLS(TLSServer) + if err != nil { + return fmt.Errorf("generating TLS certificate/keypair failed: %w", err) + } + config.Certificates = []tls.Certificate{*tlsCert} + config.ClientAuth = tls.RequireAnyClientCert + config.VerifyPeerCertificate = s.VerifyPeerCertificate + return nil +} + +func (s *ServerConfig) VerifyPeerCertificate(rawCerts [][]byte, _ [][]*x509.Certificate) error { + if len(rawCerts) != 1 { + return fmt.Errorf("need exacty one client certificate") + } + cert := rawCerts[0] + + lastErr := ErrWrongIdentity + for _, allowed := range s.Allowed { + err := allowed.Verify(TLSServer, cert) + switch { + case err == nil: + return nil + case errors.Is(err, ErrWrongIdentity): + lastErr = err + continue + default: + return err + } + } + + return lastErr +} + +func (c *ClientConfig) Configure(config *tls.Config) error { + tlsCert, err := c.PrivateKey.GenerateTLS(TLSClient) + if err != nil { + return fmt.Errorf("generating TLS certificate/keypair failed: %w", err) + } + config.Certificates = []tls.Certificate{*tlsCert} + config.InsecureSkipVerify = true + config.VerifyPeerCertificate = c.VerifyPeerCertificate + return nil +} + +func (c *ClientConfig) VerifyPeerCertificate(rawCerts [][]byte, _ [][]*x509.Certificate) error { + if len(rawCerts) != 1 { + return fmt.Errorf("need exacty one server certificate") + } + cert := rawCerts[0] + return c.Server.Verify(TLSClient, cert) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..924fbf2 --- /dev/null +++ b/go.mod @@ -0,0 +1,9 @@ +module code.hackerspace.pl/q3k/pktls + +go 1.14 + +require ( + github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b + github.com/jorrizza/ed2curve25519 v0.1.0 + golang.org/x/crypto v0.0.0-20201117144127-c1f2f97bffc9 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..1b53db7 --- /dev/null +++ b/go.sum @@ -0,0 +1,14 @@ +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/jorrizza/ed2curve25519 v0.1.0 h1:P58ZEiVKW4vknYuGyOXuskMm82rTJyGhgRGrMRcCE8E= +github.com/jorrizza/ed2curve25519 v0.1.0/go.mod h1:27VPNk2FnNqLQNvvVymiX41VE/nokPyn5HHP7gtfYlo= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201117144127-c1f2f97bffc9 h1:phUcVbl53swtrUN8kQEXFhUxPlIlWyBfKmidCu7P95o= +golang.org/x/crypto v0.0.0-20201117144127-c1f2f97bffc9/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= diff --git a/keys.go b/keys.go new file mode 100644 index 0000000..367d0d2 --- /dev/null +++ b/keys.go @@ -0,0 +1,88 @@ +package pktls + +import ( + "crypto/ed25519" + "crypto/rand" + "encoding/base64" + "fmt" + "strings" +) + +const ( + b64PrefixPublic = "p1" + b64PrefixPrivate = "s1" + + keyLength = 32 +) + +type PublicKey ed25519.PublicKey + +type PrivateKey ed25519.PrivateKey + +func (p PrivateKey) String() string { + return b64PrefixPrivate + base64.StdEncoding.EncodeToString(ed25519.PrivateKey(p).Seed()) +} + +func privateFromBytes(seed []byte) PrivateKey { + if len(seed) != keyLength { + panic("seed must be 32 bytes long") + } + return PrivateKey(ed25519.NewKeyFromSeed(seed)) +} + +func PrivateGenerate() (PrivateKey, error) { + var seed [keyLength]byte + _, err := rand.Read(seed[:]) + if err != nil { + return nil, fmt.Errorf("rand.Read: %v", err) + } + return privateFromBytes(seed[:]), nil +} + +func PrivateFromString(s string) (PrivateKey, error) { + if !strings.HasPrefix(s, b64PrefixPrivate) { + if strings.HasPrefix(s, b64PrefixPublic) { + return nil, fmt.Errorf("invalid key: looks like a public key?") + } + return nil, fmt.Errorf("invalid key: not a pktls key") + } + s = s[len(b64PrefixPrivate):] + bytes, err := base64.StdEncoding.DecodeString(s) + if err != nil { + return nil, fmt.Errorf("invalid key: base64 decode failed") + } + if len(bytes) != keyLength { + return nil, fmt.Errorf("invalid key: wrong length") + } + return privateFromBytes(bytes), nil +} + +func (p PrivateKey) Public() PublicKey { + return PublicKey(ed25519.PrivateKey(p).Public().(ed25519.PublicKey)) +} + +func publicFromBytes(pk []byte) PublicKey { + return PublicKey(pk) +} + +func PublicFromString(s string) (PublicKey, error) { + if !strings.HasPrefix(s, b64PrefixPublic) { + if strings.HasPrefix(s, b64PrefixPrivate) { + return nil, fmt.Errorf("invalid key: looks like a private key?") + } + return nil, fmt.Errorf("invalid key: not a pktls key") + } + s = s[len(b64PrefixPublic):] + bytes, err := base64.StdEncoding.DecodeString(s) + if err != nil { + return nil, fmt.Errorf("invalid key: base64 decode failed") + } + if len(bytes) != keyLength { + return nil, fmt.Errorf("invalid key: wrong length") + } + return publicFromBytes(bytes), nil +} + +func (p PublicKey) String() string { + return b64PrefixPublic + base64.StdEncoding.EncodeToString(p) +} diff --git a/keys_test.go b/keys_test.go new file mode 100644 index 0000000..5110a62 --- /dev/null +++ b/keys_test.go @@ -0,0 +1,79 @@ +package pktls + +import ( + "bytes" + "crypto" + "crypto/ed25519" + "crypto/rand" + "testing" +) + +func TestPrivateIO(t *testing.T) { + priv1, err := PrivateGenerate() + if err != nil { + t.Fatalf("PrivateGenerate: %v", err) + } + + str := priv1.String() + priv2, err := PrivateFromString(str) + if err != nil { + t.Fatalf("PrivateFromString: %v", err) + } + + // TODO(q3k): use ed25519.PrivateKey.Equal when go 1.15 becomes a bit more mainstream + if !bytes.Equal(priv1, priv2) { + t.Fatalf("private key re-read from string differs from original") + } +} + +func TestPublicIO(t *testing.T) { + priv1, err := PrivateGenerate() + if err != nil { + t.Fatalf("PrivateGenerate: %v", err) + } + pub1 := priv1.Public() + + str := pub1.String() + pub2, err := PublicFromString(str) + if err != nil { + t.Fatalf("PublicFromString: %v", err) + } + + // TODO(q3k): use ed25519.PublicKey.Equal when go 1.15 becomes a bit more mainstream + if !bytes.Equal(pub1, pub2) { + t.Fatalf("public key re-read from string differs from original") + } +} + +func TestE2E(t *testing.T) { + // genkey equivalent + priv1, err := PrivateGenerate() + if err != nil { + t.Fatalf("PrivateGenerate: %v", err) + } + priv := priv1.String() + + // pubkey equivalent + priv2, err := PrivateFromString(priv) + if err != nil { + t.Fatalf("PrivateFromString: %v", err) + } + pub := priv2.Public().String() + + // sender equivalent + msg := []byte("ahou") + sig, err := ed25519.PrivateKey(priv2).Sign(rand.Reader, msg, crypto.Hash(0)) + if err != nil { + t.Fatalf("Sign: %v", err) + } + + // receiver equivalent + pub1, err := PublicFromString(pub) + if err != nil { + t.Fatalf("PublicFromString: %v", err) + } + + if !ed25519.Verify(ed25519.PublicKey(pub1), msg, sig) { + t.Fatalf("Signature verification failed") + } +} diff --git a/tls.go b/tls.go new file mode 100644 index 0000000..8f26a5a --- /dev/null +++ b/tls.go @@ -0,0 +1,170 @@ +package pktls + +import ( + "bytes" + "crypto" + "crypto/ed25519" + "crypto/rand" + "crypto/sha1" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/asn1" + "encoding/pem" + "errors" + "fmt" + "math/big" + "net" + "time" +) + +type TLSMode int + +const ( + TLSServer TLSMode = iota + TLSClient +) + +var ( + // From RFC 5280 Section 4.1.2.5 + unknownNotAfter = time.Unix(253402300799, 0) + + ErrWrongIdentity = errors.New("unknown identity") +) + +// Workaround for https://github.com/golang/go/issues/26676 in Go's crypto/x509. Specifically Go +// violates Section 4.2.1.2 of RFC 5280 without this. +// Fixed for 1.15 in https://go-review.googlesource.com/c/go/+/227098/. +// +// Taken from https://github.com/FiloSottile/mkcert/blob/master/cert.go#L295 written by one of Go's +// crypto engineers +func calculateSKID(pubKey crypto.PublicKey) ([]byte, error) { + spkiASN1, err := x509.MarshalPKIXPublicKey(pubKey) + if err != nil { + return nil, err + } + + var spki struct { + Algorithm pkix.AlgorithmIdentifier + SubjectPublicKey asn1.BitString + } + _, err = asn1.Unmarshal(spkiASN1, &spki) + if err != nil { + return nil, err + } + skid := sha1.Sum(spki.SubjectPublicKey.Bytes) + return skid[:], nil +} + +func (p PrivateKey) GenerateTLS(mode TLSMode) (*tls.Certificate, error) { + private := ed25519.PrivateKey(p) + public := private.Public() + + serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 127) + serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) + if err != nil { + return nil, fmt.Errorf("failed to generate serial number: %w", err) + } + + skid, err := calculateSKID(public) + if err != nil { + return nil, fmt.Errorf("failed to calculate subject key DI: %w", err) + } + + template := x509.Certificate{ + SerialNumber: serialNumber, + Subject: pkix.Name{ + Organization: []string{"pktls"}, + }, + NotBefore: time.Now(), + NotAfter: unknownNotAfter, + KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, + BasicConstraintsValid: true, + SubjectKeyId: skid, + AuthorityKeyId: skid, + } + + switch mode { + case TLSServer: + template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} + case TLSClient: + template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth} + default: + return nil, fmt.Errorf("invalid TLS mode argument") + } + + certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, public, private) + if err != nil { + return nil, fmt.Errorf("failed to sign certificate: %w", err) + } + + keyDER, err := x509.MarshalPKCS8PrivateKey(private) + if err != nil { + return nil, fmt.Errorf("failed to marshal private key: %w", err) + } + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}) + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER}) + + tlsCert, err := tls.X509KeyPair(certPEM, keyPEM) + if err != nil { + return nil, fmt.Errorf("failed to use new certificate: %w", err) + } + return &tlsCert, nil +} + +func parseCertificate(cert *x509.Certificate) (PublicKey, error) { + if cert.PublicKeyAlgorithm != x509.Ed25519 { + return nil, fmt.Errorf("certificate subject public key algorithm not ED25519") + } + presented := cert.PublicKey.(ed25519.PublicKey) + if len(presented) != keyLength { + return nil, fmt.Errorf("%w: pubkey invalid", ErrWrongIdentity) + } + return publicFromBytes(presented), nil +} + +func (p PublicKey) Verify(mode TLSMode, pem []byte) error { + cert, err := x509.ParseCertificate(pem) + if err != nil { + return err + } + presented, err := parseCertificate(cert) + if err != nil { + return err + } + if !bytes.Equal(presented, p) { + return fmt.Errorf("%w: pubkey %s", ErrWrongIdentity, presented.String()) + } + + for _, ku := range cert.ExtKeyUsage { + switch mode { + case TLSServer: + if ku == x509.ExtKeyUsageClientAuth { + return nil + } + case TLSClient: + if ku == x509.ExtKeyUsageServerAuth { + return nil + } + } + } + + return fmt.Errorf("%w: pubkey not valid for this mode", ErrWrongIdentity) +} + +func ClientPubkey(c net.Conn) (*PublicKey, error) { + inner, ok := c.(*tls.Conn) + if !ok { + return nil, fmt.Errorf("not a TLS connection") + } + if err := inner.Handshake(); err != nil { + return nil, fmt.Errorf("handshake failed: %w", err) + } + + state := inner.ConnectionState() + pubkey, err := parseCertificate(state.PeerCertificates[0]) + if err != nil { + return nil, fmt.Errorf("internal error: invalid certificate: %w", err) + } + return &pubkey, nil +}