Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add util functions for tokens #152

Merged
merged 5 commits into from
Mar 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.13

require (
github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd // indirect
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/golang/protobuf v1.3.3
github.com/google/uuid v1.1.1
github.com/grpc-ecosystem/grpc-opentracing v0.0.0-20180507213350-8e809c8a8645
Expand Down
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfc
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
Expand Down
1 change: 1 addition & 0 deletions pkg/tools/security/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@ import (
// Provider - interface for tls.Config provider
type Provider interface {
GetTLSConfig(ctx context.Context) (*tls.Config, error)
GetCertificate(ctx context.Context) (*tls.Certificate, error)
}
8 changes: 8 additions & 0 deletions pkg/tools/security/spire.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,11 @@ func NewSpireProvider(addr string) (Provider, error) {
func (p *spireProvider) GetTLSConfig(ctx context.Context) (*tls.Config, error) {
return p.peer.GetConfig(ctx, spiffe.ExpectAnyPeer())
}

func (p *spireProvider) GetCertificate(ctx context.Context) (*tls.Certificate, error) {
if err := p.peer.WaitUntilReady(ctx); err != nil {
return nil, err
}

return p.peer.GetCertificate()
}
38 changes: 38 additions & 0 deletions pkg/tools/security/test/provider.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Copyright (c) 2020 Doc.ai and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package securitytest

import (
"context"
"crypto/tls"
)

// Provider is a struct for testing purposes allows to pass method implementation from tests
type Provider struct {
GetTLSConfigFunc func(ctx context.Context) (*tls.Config, error)
GetCertificateFunc func(ctx context.Context) (*tls.Certificate, error)
}

// GetTLSConfig implements security.Provider interface
func (t *Provider) GetTLSConfig(ctx context.Context) (*tls.Config, error) {
return t.GetTLSConfigFunc(ctx)
}

// GetCertificate implements security.Provider interface
func (t *Provider) GetCertificate(ctx context.Context) (*tls.Certificate, error) {
return t.GetCertificateFunc(ctx)
}
138 changes: 138 additions & 0 deletions pkg/tools/security/test/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
// Copyright (c) 2020 Doc.ai and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package securitytest contains auxiliary methods for testing security
package securitytest

import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"math/big"
"time"
)

const (
nameTypeURI = 6
)

// GenerateCA generates Certificate Authority
func GenerateCA() (tls.Certificate, error) {
ca := &x509.Certificate{
SerialNumber: big.NewInt(1653),
Subject: pkix.Name{
Organization: []string{"ORGANIZATION_NAME"},
Country: []string{"COUNTRY_CODE"},
Province: []string{"PROVINCE"},
Locality: []string{"CITY"},
StreetAddress: []string{"ADDRESS"},
PostalCode: []string{"POSTAL_CODE"},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(10, 0, 0),
IsCA: true,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
SignatureAlgorithm: x509.ECDSAWithSHA256,
BasicConstraintsValid: true,
}

priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return tls.Certificate{}, err
}
pub := &priv.PublicKey

certBytes, err := x509.CreateCertificate(rand.Reader, ca, ca, pub, priv)
if err != nil {
return tls.Certificate{}, err
}

certPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certBytes})
keyBytes, err := x509.MarshalECPrivateKey(priv)
if err != nil {
return tls.Certificate{}, err
}
keyPem := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: keyBytes})
return tls.X509KeyPair(certPem, keyPem)
}

func marshalSAN(spiffeID string) ([]byte, error) {
return asn1.Marshal([]asn1.RawValue{{Tag: nameTypeURI, Class: 2, Bytes: []byte(spiffeID)}})
}

// GenerateKeyPair generates tls.Certificate for the passed 'spiffeID' and signed by 'caTLS'
func GenerateKeyPair(spiffeID, domain string, caTLS *tls.Certificate) (tls.Certificate, error) {
san, err := marshalSAN(spiffeID)
if err != nil {
return tls.Certificate{}, nil
}

oidSanExtension := []int{2, 5, 29, 17}
cert := &x509.Certificate{
SerialNumber: big.NewInt(1658),
Subject: pkix.Name{
Organization: []string{"ORGANIZATION_NAME"},
Country: []string{"COUNTRY_CODE"},
Province: []string{"PROVINCE"},
Locality: []string{"CITY"},
StreetAddress: []string{"ADDRESS"},
PostalCode: []string{"POSTAL_CODE"},
CommonName: domain,
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(10, 0, 0),
SubjectKeyId: []byte{1, 2, 3, 4, 6},
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
ExtraExtensions: []pkix.Extension{
{
Id: oidSanExtension,
Value: san,
},
},
SignatureAlgorithm: x509.ECDSAWithSHA256,
KeyUsage: x509.KeyUsageDigitalSignature,
}

priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return tls.Certificate{}, nil
}
pub := &priv.PublicKey

ca, err := x509.ParseCertificate(caTLS.Certificate[0])
if err != nil {
return tls.Certificate{}, nil
}

certBytes, err := x509.CreateCertificate(rand.Reader, cert, ca, pub, caTLS.PrivateKey)
if err != nil {
return tls.Certificate{}, nil
}

certPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certBytes})
keyBytes, err := x509.MarshalECPrivateKey(priv)
if err != nil {
return tls.Certificate{}, err
}
keyPem := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes})
return tls.X509KeyPair(certPem, keyPem)
}
47 changes: 47 additions & 0 deletions pkg/tools/security/token.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright (c) 2020 Doc.ai and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package security

import (
"context"
"crypto/x509"
"time"

"github.com/dgrijalva/jwt-go"
)

// GenerateToken generates JWT token based on tls.Certificate from security.Provider
func GenerateToken(ctx context.Context, p Provider, expiresAt time.Duration) (string, error) {
crt, err := p.GetCertificate(ctx)
if err != nil {
return "", err
}

claims := jwt.StandardClaims{
ExpiresAt: time.Now().Add(expiresAt).Unix(),
}

return jwt.NewWithClaims(jwt.SigningMethodES256, claims).SignedString(crt.PrivateKey)
}

// VerifyToken verifies JWT 'token' using x509.Certificate
func VerifyToken(token string, x509crt *x509.Certificate) error {
_, err := new(jwt.Parser).Parse(token, func(token *jwt.Token) (interface{}, error) {
return x509crt.PublicKey, nil
})
return err
}
129 changes: 129 additions & 0 deletions pkg/tools/security/token_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// Copyright (c) 2020 Doc.ai and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package security_test

import (
"context"
"crypto/tls"
"crypto/x509"
"testing"
"time"

"github.com/stretchr/testify/suite"

securitytest "github.com/networkservicemesh/sdk/pkg/tools/security/test"

"github.com/dgrijalva/jwt-go"

"github.com/networkservicemesh/sdk/pkg/tools/security"
)

const (
spiffeID = "spiffe://test.com/workload"
)

type TokenTestSuite struct {
suite.Suite
TestCA tls.Certificate
TestTLSCertificate tls.Certificate
}

func (s *TokenTestSuite) SetupSuite() {
var err error
s.TestCA, err = securitytest.GenerateCA()
if err != nil {
panic(err)
}

s.TestTLSCertificate, err = securitytest.GenerateKeyPair(spiffeID, "test.com", &s.TestCA)
if err != nil {
panic(err)
}
}

func TestTokenTestSuite(t *testing.T) {
suite.Run(t, new(TokenTestSuite))
}

type testProvider struct {
GetCertificateFunc func(ctx context.Context) (*tls.Certificate, error)
}

func (t *testProvider) GetTLSConfig(ctx context.Context) (*tls.Config, error) {
panic("implement me")
}

func (t *testProvider) GetCertificate(ctx context.Context) (*tls.Certificate, error) {
return t.GetCertificateFunc(ctx)
}

func (s *TokenTestSuite) TestGenerateToken() {
p := &testProvider{
GetCertificateFunc: func(ctx context.Context) (certificate *tls.Certificate, e error) {
return &s.TestTLSCertificate, nil
},
}

token, err := security.GenerateToken(context.Background(), p, 0)
s.Nil(err)

x509crt, err := x509.ParseCertificate(s.TestTLSCertificate.Certificate[0])
s.Nil(err)

_, err = new(jwt.Parser).Parse(token, func(token *jwt.Token) (interface{}, error) {
return x509crt.PublicKey, nil
})
s.Nil(err)
}

func (s *TokenTestSuite) TestGenerateToken_Expire() {
p := &testProvider{
GetCertificateFunc: func(ctx context.Context) (certificate *tls.Certificate, e error) {
return &s.TestTLSCertificate, nil
},
}

token, err := security.GenerateToken(context.Background(), p, 3*time.Second)
s.Nil(err)

<-time.After(5 * time.Second)

x509crt, err := x509.ParseCertificate(s.TestTLSCertificate.Certificate[0])
s.Nil(err)

_, err = new(jwt.Parser).Parse(token, func(token *jwt.Token) (interface{}, error) {
return x509crt.PublicKey, nil
})
s.NotNil(err)
}

func (s *TokenTestSuite) TestVerifyToken() {
token, err := jwt.New(jwt.SigningMethodES256).SignedString(s.TestTLSCertificate.PrivateKey)
s.Nil(err)

x509crt, err := x509.ParseCertificate(s.TestTLSCertificate.Certificate[0])
s.Nil(err)

err = security.VerifyToken(token, x509crt)
s.Nil(err)

invalidX509crt, err := x509.ParseCertificate(s.TestCA.Certificate[0])
s.Nil(err)

err = security.VerifyToken(token, invalidX509crt)
s.NotNil(err)
}