Implemented lan connection string functionality

Also added more robust testing
This commit is contained in:
Samuel Hawksby-Robinson 2022-04-29 13:41:41 +01:00
parent 33a127e208
commit 7c57a2b65c
3 changed files with 298 additions and 0 deletions

View File

@ -3,11 +3,16 @@ package server
import (
"context"
"crypto/tls"
"encoding/asn1"
"fmt"
"math/big"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/btcsuite/btcutil/base58"
"go.uber.org/zap"
"github.com/status-im/status-go/logutils"
@ -117,6 +122,77 @@ func (s *Server) SetHandlers(handlers HandlerPatternMap) {
s.handlers = handlers
}
// MakeQRData generates a string required for generating a secure connection to another Status device.
//
// The returned string will look like below:
// - "4FHRnp:H6G:6jpbvo2ucrtrnpXXF4DQYuysh697isH9ppd2aT8uSRDh:eQUriVtGtkWhPJFeLZjF"
//
// Format bytes encoded into a base58 string, delimited by ":"
// - net.IP
// - port
// - ecdsa.PrivateKey D field
// - asn1.Marshal time.Time
func (s *PairingServer) MakeQRData() (string, error) {
switch {
case s.cert == nil:
return "", fmt.Errorf("server has no cert set")
case s.cert.Leaf == nil:
return "", fmt.Errorf("server cert has no Leaf set")
case s.cert.Leaf.NotBefore.IsZero():
return "", fmt.Errorf("server cert Leaf has a zero value NotBefore")
}
netIP := net.ParseIP(s.hostname)
if netIP == nil {
return "", fmt.Errorf("invalid ip address given '%s'", s.hostname)
}
ip := base58.Encode(netIP)
p := base58.Encode(new(big.Int).SetInt64(int64(s.port)).Bytes())
k := base58.Encode(s.pk.D.Bytes())
tb, err := asn1.Marshal(s.cert.Leaf.NotBefore.UTC())
if err != nil {
return "", err
}
t := base58.Encode(tb)
return fmt.Sprintf("%s:%s:%s:%s", ip, p, k, t), nil
}
// ParseQRData parses a QR code data string required for to securely connect to another Status device.
// This function take a connection string generated by MakeQRData and returns a *url.URL and encoded pem.Block
func ParseQRData(data string) (*url.URL, []byte, error) {
// TODO should probably be a function of the future Client struct
sData := strings.Split(data, ":")
if len(sData) != 4 {
return nil, nil, fmt.Errorf("expected data '%s' to have length of '%d', received '%d'", data, 4, len(sData))
}
// Decode and build URL data
ip := net.IP(base58.Decode(sData[0]))
p := new(big.Int).SetBytes(base58.Decode(sData[1])).Int64()
u := &url.URL{
Scheme: "https",
Host: fmt.Sprintf("%s:%d", ip, p),
}
// Decode and build timestamp data
t := time.Time{}
_, err := asn1.Unmarshal(base58.Decode(sData[3]), &t)
if err != nil {
return nil, nil, err
}
// Decode and build ecdsa.PrivateKey, generate cert PEM
_, pem, err := GenerateCertFromKey(ToECDSA(base58.Decode(sData[2])), t, ip.String())
if err != nil {
return nil, nil, err
}
return u, pem, nil
}
func (s *Server) MakeBaseURL() *url.URL {
return &url.URL{
Scheme: "https",

View File

@ -1,8 +1,12 @@
package server
import (
"crypto/ecdsa"
"crypto/x509"
"encoding/pem"
"testing"
"github.com/davecgh/go-spew/spew"
"github.com/stretchr/testify/suite"
)
@ -13,6 +17,7 @@ func TestServerURLSuite(t *testing.T) {
type ServerURLSuite struct {
suite.Suite
TestKeyComponents
TestCertComponents
server *MediaServer
serverNoPort *MediaServer
@ -21,6 +26,10 @@ type ServerURLSuite struct {
func (s *ServerURLSuite) SetupSuite() {
s.SetupKeyComponents(s.T())
s.SetupCertComponents(s.T())
cert, _, err := GenerateCertFromKey(s.PK, s.NotBefore, defaultIP.String())
s.Require().NoError(err)
s.server = &MediaServer{Server: Server{
hostname: defaultIP.String(),
@ -29,6 +38,47 @@ func (s *ServerURLSuite) SetupSuite() {
s.serverNoPort = &MediaServer{Server: Server{
hostname: defaultIP.String(),
}}
s.pairingServer = &PairingServer{
Server: Server{cert: &cert, hostname: defaultIP.String()},
pk: s.PK,
}
}
func (s *ServerURLSuite) TestServer_MakeQRData() {
qr, err := s.pairingServer.MakeQRData()
s.Require().NoError(err)
s.Require().Regexp(
"^4FHRnp:[1-9|A-Z|a-z]{1,4}:6jpbvo2ucrtrnpXXF4DQYuysh697isH9ppd2aT8uSRDh:eQUriVtGtkWhPJFeLZjF$",
qr)
}
func (s *ServerURLSuite) TestServer_ParseQRData() {
u, c, err := ParseQRData("4FHRnp:H6G:6jpbvo2ucrtrnpXXF4DQYuysh697isH9ppd2aT8uSRDh:eQUriVtGtkWhPJFeLZjF")
s.Require().NoError(err)
s.Require().Equal("https://127.0.0.1:54129", u.String())
s.Require().Equal(defaultIP.String(), u.Hostname())
s.Require().Equal("54129", u.Port())
// Parse cert PEM into x509 cert
block, _ := pem.Decode(c)
s.Require().NotNil(block)
cert, err := x509.ParseCertificate(block.Bytes)
s.Require().NoError(err)
// Compare cert values
cl := s.server.cert.Leaf
s.Require().NotEqual(cl.Signature, cert.Signature)
s.Require().Zero(cl.PublicKey.(*ecdsa.PublicKey).X.Cmp(cert.PublicKey.(*ecdsa.PublicKey).X))
s.Require().Zero(cl.PublicKey.(*ecdsa.PublicKey).Y.Cmp(cert.PublicKey.(*ecdsa.PublicKey).Y))
s.Require().Equal(cl.Version, cert.Version)
s.Require().Zero(cl.SerialNumber.Cmp(cert.SerialNumber))
s.Require().Exactly(cl.NotBefore, cert.NotBefore)
s.Require().Exactly(cl.NotAfter, cert.NotAfter)
s.Require().Exactly(cl.IPAddresses, cert.IPAddresses)
spew.Dump(cl, cert)
}
func (s *ServerURLSuite) TestServer_MakeBaseURL() {

View File

@ -0,0 +1,172 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build ignore
// Generate a self-signed X.509 certificate for a TLS server. Outputs to
// 'cert.pem' and 'key.pem' and will overwrite existing files.
package main
import (
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"flag"
"log"
"math/big"
"net"
"os"
"strings"
"time"
)
var (
host = flag.String("host", "", "Comma-separated hostnames and IPs to generate a certificate for")
validFrom = flag.String("start-date", "", "Creation date formatted as Jan 1 15:04:05 2011")
validFor = flag.Duration("duration", 365*24*time.Hour, "Duration that certificate is valid for")
isCA = flag.Bool("ca", false, "whether this cert should be its own Certificate Authority")
rsaBits = flag.Int("rsa-bits", 2048, "Size of RSA key to generate. Ignored if --ecdsa-curve is set")
ecdsaCurve = flag.String("ecdsa-curve", "", "ECDSA curve to use to generate a key. Valid values are P224, P256 (recommended), P384, P521")
ed25519Key = flag.Bool("ed25519", false, "Generate an Ed25519 key")
)
func publicKey(priv any) any {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &k.PublicKey
case *ecdsa.PrivateKey:
return &k.PublicKey
case ed25519.PrivateKey:
return k.Public().(ed25519.PublicKey)
default:
return nil
}
}
func main() {
flag.Parse()
if len(*host) == 0 {
log.Fatalf("Missing required --host parameter")
}
var priv any
var err error
switch *ecdsaCurve {
case "":
if *ed25519Key {
_, priv, err = ed25519.GenerateKey(rand.Reader)
} else {
priv, err = rsa.GenerateKey(rand.Reader, *rsaBits)
}
case "P224":
priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
case "P256":
priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
case "P384":
priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
case "P521":
priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
default:
log.Fatalf("Unrecognized elliptic curve: %q", *ecdsaCurve)
}
if err != nil {
log.Fatalf("Failed to generate private key: %v", err)
}
// ECDSA, ED25519 and RSA subject keys should have the DigitalSignature
// KeyUsage bits set in the x509.Certificate template
keyUsage := x509.KeyUsageDigitalSignature
// Only RSA subject keys should have the KeyEncipherment KeyUsage bits set. In
// the context of TLS this KeyUsage is particular to RSA key exchange and
// authentication.
if _, isRSA := priv.(*rsa.PrivateKey); isRSA {
keyUsage |= x509.KeyUsageKeyEncipherment
}
var notBefore time.Time
if len(*validFrom) == 0 {
notBefore = time.Now()
} else {
notBefore, err = time.Parse("Jan 2 15:04:05 2006", *validFrom)
if err != nil {
log.Fatalf("Failed to parse creation date: %v", err)
}
}
notAfter := notBefore.Add(*validFor)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
log.Fatalf("Failed to generate serial number: %v", err)
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Acme Co"},
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: keyUsage,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
hosts := strings.Split(*host, ",")
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, h)
}
}
if *isCA {
template.IsCA = true
template.KeyUsage |= x509.KeyUsageCertSign
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
if err != nil {
log.Fatalf("Failed to create certificate: %v", err)
}
certOut, err := os.Create("cert.pem")
if err != nil {
log.Fatalf("Failed to open cert.pem for writing: %v", err)
}
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
log.Fatalf("Failed to write data to cert.pem: %v", err)
}
if err := certOut.Close(); err != nil {
log.Fatalf("Error closing cert.pem: %v", err)
}
log.Print("wrote cert.pem\n")
keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatalf("Failed to open key.pem for writing: %v", err)
return
}
privBytes, err := x509.MarshalPKCS8PrivateKey(priv)
if err != nil {
log.Fatalf("Unable to marshal private key: %v", err)
}
if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil {
log.Fatalf("Failed to write data to key.pem: %v", err)
}
if err := keyOut.Close(); err != nil {
log.Fatalf("Error closing key.pem: %v", err)
}
log.Print("wrote key.pem\n")
}