Skip to content

Commit

Permalink
feat(plc4go/opcua): work on encryption part
Browse files Browse the repository at this point in the history
  • Loading branch information
sruehl committed Jul 28, 2023
1 parent 431472e commit 7c21ea8
Show file tree
Hide file tree
Showing 6 changed files with 406 additions and 35 deletions.
150 changes: 150 additions & 0 deletions plc4go/internal/opcua/CertificateGenerator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
*
* https://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 opcua

import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"net"
"time"

"github.com/pkg/errors"
)

func generateCertificate() (*CertificateKeyPair, error) {
// From: https://gist.github.com/shaneutt/5e1995295cff6721c89a71d13a71c251
// set up our CA certificate
ca := &x509.Certificate{
SerialNumber: big.NewInt(40),
Subject: pkix.Name{
CommonName: "Apache PLC4X Driver Client",
Organization: []string{"Apache Software Foundation"},
OrganizationalUnit: []string{"dev"},
Locality: []string{""},
Country: []string{"US"},
Province: []string{""},
},
NotBefore: time.Now().Add(-24 * time.Hour),
NotAfter: time.Now().AddDate(25, 0, 0),
IsCA: true,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
}

// create our private and public key
caPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, errors.Wrap(err, "error generating key")
}

// create the CA
caBytes, err := x509.CreateCertificate(rand.Reader, ca, ca, &caPrivateKey.PublicKey, caPrivateKey)
if err != nil {
return nil, errors.Wrap(err, "error creating certificate")
}

// pem encode
caPEM := new(bytes.Buffer)
if err := pem.Encode(caPEM, &pem.Block{
Type: "CERTIFICATE",
Bytes: caBytes,
}); err != nil {
return nil, errors.Wrap(err, "error pem encode")
}

caPrivateKeyPEM := new(bytes.Buffer)
if err := pem.Encode(caPrivateKeyPEM, &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(caPrivateKey),
}); err != nil {
return nil, errors.Wrap(err, "error pem encode")
}

// set up our server certificate
cert := &x509.Certificate{
SerialNumber: big.NewInt(2019),
Subject: pkix.Name{
Organization: []string{"Company, INC."},
Country: []string{"US"},
Province: []string{""},
Locality: []string{"San Francisco"},
StreetAddress: []string{"Golden Gate Bridge"},
PostalCode: []string{"94016"},
},
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(10, 0, 0),
SubjectKeyId: []byte{1, 2, 3, 4, 6},
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature,
}

certPrivateKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return nil, errors.Wrap(err, "error generating key")
}

certBytes, err := x509.CreateCertificate(rand.Reader, cert, ca, &certPrivateKey.PublicKey, caPrivateKeyPEM)
if err != nil {
return nil, errors.Wrap(err, "error creating certificate")
}

certPEM := new(bytes.Buffer)
if err := pem.Encode(certPEM, &pem.Block{
Type: "CERTIFICATE",
Bytes: certBytes,
}); err != nil {
return nil, errors.Wrap(err, "error pem encode")
}

certPrivKeyPEM := new(bytes.Buffer)
if err := pem.Encode(certPrivKeyPEM, &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(certPrivateKey),
}); err != nil {
return nil, errors.Wrap(err, "error pem encode")
}

serverCert, err := tls.X509KeyPair(certPEM.Bytes(), certPrivKeyPEM.Bytes())
if err != nil {
return nil, errors.Wrap(err, "error building keypair")
}

serverTLSConf := &tls.Config{
Certificates: []tls.Certificate{serverCert},
}
_ = serverTLSConf

certpool := x509.NewCertPool()
certpool.AppendCertsFromPEM(caPEM.Bytes())
clientTLSConf := &tls.Config{
RootCAs: certpool,
}
_ = clientTLSConf

return NewCertificateKeyPair(caPrivateKey, cert), nil
}
11 changes: 6 additions & 5 deletions plc4go/internal/opcua/CertificateKeyPair.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,18 @@
package opcua

import (
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
)

type CertificateKeyPair struct {
keyPair x509.KeyUsage
certificate x509.Certificate
keyPair *rsa.PrivateKey
certificate *x509.Certificate
thumbprint []byte
}

func NewCertificateKeyPair(keyPair x509.KeyUsage, certificate x509.Certificate) *CertificateKeyPair {
func NewCertificateKeyPair(keyPair *rsa.PrivateKey, certificate *x509.Certificate) *CertificateKeyPair {
thumbprint := sha1.Sum(certificate.Raw)
return &CertificateKeyPair{
keyPair: keyPair,
Expand All @@ -39,11 +40,11 @@ func NewCertificateKeyPair(keyPair x509.KeyUsage, certificate x509.Certificate)
}
}

func (p *CertificateKeyPair) getKeyPair() x509.KeyUsage {
func (p *CertificateKeyPair) getKeyPair() *rsa.PrivateKey {
return p.keyPair
}

func (p *CertificateKeyPair) getCertificate() x509.Certificate {
func (p *CertificateKeyPair) getCertificate() *x509.Certificate {
return p.certificate
}

Expand Down
44 changes: 38 additions & 6 deletions plc4go/internal/opcua/Configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,14 @@
package opcua

import (
readWriteModel "github.com/apache/plc4x/plc4go/protocols/opcua/readwrite/model"
"github.com/pkg/errors"
"os"
"path"
"reflect"
"strconv"

readWriteModel "github.com/apache/plc4x/plc4go/protocols/opcua/readwrite/model"

"github.com/pkg/errors"
"github.com/rs/zerolog"
)

Expand All @@ -46,7 +49,9 @@ type Configuration struct {
keyStoreFile string
certDirectory string
keyStorePassword string
ckp CertificateKeyPair
ckp *CertificateKeyPair

log zerolog.Logger `ignore:"true"`
}

func ParseFromOptions(log zerolog.Logger, options map[string][]string) (Configuration, error) {
Expand Down Expand Up @@ -74,13 +79,40 @@ func ParseFromOptions(log zerolog.Logger, options map[string][]string) (Configur
}
}
}
configuration.log = log
return configuration, nil
}

func (c *Configuration) openKeyStore() {
func (c *Configuration) openKeyStore() error {
c.isEncrypted = true
// TODO: load keystore yada yada
// TODO: NewCertificateKeyPair()
securityTempDir := path.Join(c.certDirectory, "security")
if _, err := os.Stat(securityTempDir); errors.Is(err, os.ErrNotExist) {
if err := os.Mkdir(securityTempDir, 700); err != nil {
return errors.New("Unable to create directory please confirm folder permissions on " + securityTempDir)
}
}

serverKeyStore := path.Join(securityTempDir, c.keyStoreFile)
if _, err := os.Stat(securityTempDir); errors.Is(err, os.ErrNotExist) {
var err error
c.ckp, err = generateCertificate()
if err != nil {
return errors.Wrap(err, "error generating certificate")
}
c.log.Info().Str("serverKeyStore", serverKeyStore).Msg("Creating keystore")
// TODO: not sure how to do that in golang. Seems pkc12 can only decode for now
_ = os.WriteFile(serverKeyStore, []byte{0xA}, 0700)
} else {
c.log.Info().Str("serverKeyStore", serverKeyStore).Msg("Loading keystore")
serverKeyStoreContent, err := os.ReadFile(serverKeyStore)
if err != nil {
return errors.Wrap(err, "error reading "+serverKeyStore)
}
// TODO: here we can parse with "golang.org/x/crypto/pkcs12" Decode
_ = serverKeyStoreContent
}

return nil
}

func createDefaultConfiguration() Configuration {
Expand Down
4 changes: 3 additions & 1 deletion plc4go/internal/opcua/Driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,9 @@ func (m *Driver) GetConnectionWithContext(ctx context.Context, transportUrl url.
configuration.endpoint = "opc." + transportCode + "://" + transportHost + ":" + transportPort + "" + transportEndpoint

if configuration.securityPolicy != "" && configuration.securityPolicy != "None" {
configuration.openKeyStore()
if err := configuration.openKeyStore(); err != nil {
return m.reportError(errors.Wrap(err, "error opening key store"))
}
}

driverContext := NewDriverContext(configuration)
Expand Down
Loading

0 comments on commit 7c21ea8

Please sign in to comment.