Skip to content

Commit

Permalink
Bug handle new plugin (#922)
Browse files Browse the repository at this point in the history
* Handle certification of brand new plugin.
* dos2unix, defer to ensure file closure.
* Defer to ensure file closure.
* Bump version.
* Certify generates sha256 directly now.
* Add more verbose logging.
* Adding null check
* Update to work around file handle leak.

---------

Co-authored-by: Karnveer Gill <karnveer_gill@trimble.com>
  • Loading branch information
joel-rieke and KarnveerSGill committed Jan 30, 2024
1 parent 61852dc commit ece05f0
Show file tree
Hide file tree
Showing 10 changed files with 172 additions and 156 deletions.
2 changes: 1 addition & 1 deletion atrium/vestibulum/cmd/trcplgtool/trcplgtool.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func main() {
tcopts.NewOptionsBuilder(tcopts.LoadOptions())
xencryptopts.NewOptionsBuilder(xencryptopts.LoadOptions())

fmt.Println("Version: " + "1.03")
fmt.Println("Version: " + "1.04")

flagset := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
flagset.Usage = func() {
Expand Down
294 changes: 147 additions & 147 deletions certs/generate_certs.go
Original file line number Diff line number Diff line change
@@ -1,147 +1,147 @@
package main

import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"math/big"
"net"
"os"
"time"
)

//CertPath is the path to the cert file directory
const CertPath = "./certs/cert_files/"

//GenerateCerts generates a root cert, a root key, a child cert, and a child key. It then validates the root cert and returns the http client
func main() {
//generate private key and write to .pem file
privateKey, err := CreatePrivateKey("root_key.pem")
if err != nil {
panic(err)
}
//get public key
publicKey := privateKey.Public()

//create cert template
rootCertTmpl, err := CertTemplate()
if err != nil {
panic(err)
}
rootCertTmpl.IsCA = true
rootCertTmpl.KeyUsage = x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature
rootCertTmpl.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}
rootCertTmpl.IPAddresses = []net.IP{net.ParseIP("127.0.0.1")}

//create cert and write to .pem file
rootCert, err := CreateCert(rootCertTmpl, rootCertTmpl, publicKey, privateKey, "root_cert.pem")
if err != nil {
panic(err)
}

servPrivateKey, err := CreatePrivateKey("serv_key.pem")
if err != nil {
panic(err)
}
//get public key
servPublicKey := servPrivateKey.Public()

servCertTmpl, err := CertTemplate()
if err != nil {
panic(err)
}
servCertTmpl.KeyUsage = x509.KeyUsageDigitalSignature
servCertTmpl.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
servCertTmpl.IPAddresses = []net.IP{net.ParseIP("127.0.0.1")}

//create cert and write to .pem file
_, err = CreateCert(servCertTmpl, rootCert, servPublicKey, privateKey, "serv_cert.pem")
if err != nil {
panic(err)
}
}

//CertTemplate generates a random serial number
func CertTemplate() (*x509.Certificate, error) {
// generate a random serial number (a real cert authority would have some logic behind this)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, errors.New("failed to generate serial number: " + err.Error())
}

tmpl := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Viewpoint, Inc."},
},
SignatureAlgorithm: x509.SHA256WithRSA,
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(0, 3, 0), // valid for a day
BasicConstraintsValid: true,
}
return &tmpl, nil
}

//CreatePrivateKey generates a private key and saves it to a .pem file
func CreatePrivateKey(fileName string) (privKey *rsa.PrivateKey, err error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}

//encode private key
pemPrivateBlock := &pem.Block{
Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
}

path := CertPath + fileName
//create new file for private key
pemPrivateFile, err := os.Create(path)
if err != nil {
return privateKey, err
}
//write to file and close it
err = pem.Encode(pemPrivateFile, pemPrivateBlock)
if err != nil {
return privateKey, err
}
pemPrivateFile.Close()
fmt.Println("private key generated and written to", path)
return privateKey, nil
}

//CreateCert creates a cert and saves it to a .pem file
func CreateCert(template, parent *x509.Certificate, pub interface{}, parentPriv interface{}, fileName string) (cert *x509.Certificate, err error) {
//cert *x509.Certificate,
certDER, err := x509.CreateCertificate(rand.Reader, template, parent, pub, parentPriv)
if err != nil {
return nil, err
}

cert, err = x509.ParseCertificate(certDER)
if err != nil {
return nil, err
}

pemCertBlock := &pem.Block{Type: "CERTIFICATE", Bytes: certDER}

path := CertPath + fileName
//create new file for private key
pemCertFile, err := os.Create(path)
if err != nil {
return cert, err
}
//write to file and close it
err = pem.Encode(pemCertFile, pemCertBlock)
if err != nil {
return cert, err
}
pemCertFile.Close()
fmt.Println("certificate generated and written to", path)
return cert, nil
}
package main

import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"math/big"
"net"
"os"
"time"
)

// CertPath is the path to the cert file directory
const CertPath = "./certs/cert_files/"

// GenerateCerts generates a root cert, a root key, a child cert, and a child key. It then validates the root cert and returns the http client
func main() {
//generate private key and write to .pem file
privateKey, err := CreatePrivateKey("root_key.pem")
if err != nil {
panic(err)
}
//get public key
publicKey := privateKey.Public()

//create cert template
rootCertTmpl, err := CertTemplate()
if err != nil {
panic(err)
}
rootCertTmpl.IsCA = true
rootCertTmpl.KeyUsage = x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature
rootCertTmpl.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}
rootCertTmpl.IPAddresses = []net.IP{net.ParseIP("127.0.0.1")}

//create cert and write to .pem file
rootCert, err := CreateCert(rootCertTmpl, rootCertTmpl, publicKey, privateKey, "root_cert.pem")
if err != nil {
panic(err)
}

servPrivateKey, err := CreatePrivateKey("serv_key.pem")
if err != nil {
panic(err)
}
//get public key
servPublicKey := servPrivateKey.Public()

servCertTmpl, err := CertTemplate()
if err != nil {
panic(err)
}
servCertTmpl.KeyUsage = x509.KeyUsageDigitalSignature
servCertTmpl.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
servCertTmpl.IPAddresses = []net.IP{net.ParseIP("127.0.0.1")}

//create cert and write to .pem file
_, err = CreateCert(servCertTmpl, rootCert, servPublicKey, privateKey, "serv_cert.pem")
if err != nil {
panic(err)
}
}

// CertTemplate generates a random serial number
func CertTemplate() (*x509.Certificate, error) {
// generate a random serial number (a real cert authority would have some logic behind this)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, errors.New("failed to generate serial number: " + err.Error())
}

tmpl := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Viewpoint, Inc."},
},
SignatureAlgorithm: x509.SHA256WithRSA,
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(0, 3, 0), // valid for a day
BasicConstraintsValid: true,
}
return &tmpl, nil
}

// CreatePrivateKey generates a private key and saves it to a .pem file
func CreatePrivateKey(fileName string) (privKey *rsa.PrivateKey, err error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}

//encode private key
pemPrivateBlock := &pem.Block{
Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
}

path := CertPath + fileName
//create new file for private key
pemPrivateFile, err := os.Create(path)
if err != nil {
return privateKey, err
}
defer pemPrivateFile.Close()
//write to file and close it
err = pem.Encode(pemPrivateFile, pemPrivateBlock)
if err != nil {
return privateKey, err
}
fmt.Println("private key generated and written to", path)
return privateKey, nil
}

// CreateCert creates a cert and saves it to a .pem file
func CreateCert(template, parent *x509.Certificate, pub interface{}, parentPriv interface{}, fileName string) (cert *x509.Certificate, err error) {
//cert *x509.Certificate,
certDER, err := x509.CreateCertificate(rand.Reader, template, parent, pub, parentPriv)
if err != nil {
return nil, err
}

cert, err = x509.ParseCertificate(certDER)
if err != nil {
return nil, err
}

pemCertBlock := &pem.Block{Type: "CERTIFICATE", Bytes: certDER}

path := CertPath + fileName
//create new file for private key
pemCertFile, err := os.Create(path)
if err != nil {
return cert, err
}
defer pemCertFile.Close()
//write to file and close it
err = pem.Encode(pemCertFile, pemCertBlock)
if err != nil {
return cert, err
}
fmt.Println("certificate generated and written to", path)
return cert, nil
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ require (
github.com/Azure/azure-sdk-for-go/sdk/containers/azcontainerregistry v0.2.0
github.com/go-git/go-billy/v5 v5.4.1
github.com/graphql-go/graphql v0.8.1-0.20220614210743-09272f350067
github.com/trimble-oss/tierceron-hat v1.0.1
github.com/trimble-oss/tierceron-hat v1.0.2
)

require (
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,8 @@ github.com/trimble-oss/tierceron-hat v1.0.0 h1:JaZ7jWcLh/m4+bfuYYQ6g/rp2nmo6Hy3X
github.com/trimble-oss/tierceron-hat v1.0.0/go.mod h1:tGBWlLEwe9A9JvWYqMkC9cHeWWqF0RWJ7wVtijuK8hE=
github.com/trimble-oss/tierceron-hat v1.0.1 h1:WC5JDDeWpiI6zsy/tT0jXb2we4jLuquigctJ4C7pujM=
github.com/trimble-oss/tierceron-hat v1.0.1/go.mod h1:tGBWlLEwe9A9JvWYqMkC9cHeWWqF0RWJ7wVtijuK8hE=
github.com/trimble-oss/tierceron-hat v1.0.2 h1:UlPuMa1OVU4MHvAxjgPiTx8a6YJGcyOmGiO7Tyl8l3I=
github.com/trimble-oss/tierceron-hat v1.0.2/go.mod h1:tGBWlLEwe9A9JvWYqMkC9cHeWWqF0RWJ7wVtijuK8hE=
github.com/trimble-oss/tierceron/atrium v0.0.0-20240126223816-e0ce721b2e97 h1:R3aUZ76Kj69adXoniq5WflzNYtrra7jquPl/Ku3x0N8=
github.com/trimble-oss/tierceron/atrium v0.0.0-20240126223816-e0ce721b2e97/go.mod h1:YyFJRydD6ZKU3guNgqy4vmEkTWy66C7vMymHCPgtxi8=
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ fi
if [ "$PRE_CERTIFY" = "Y" ] || [ "$PRE_CERTIFY" = "yes" ] || [ "$PRE_CERTIFY" = "y" ]; then
if [ "$VAULT_AGENT" = 'Y' ] || [ "$VAULT_AGENT" = 'y' ]; then
echo "Certifying agent deployment tool plugin..."
trcplgtool -env=$VAULT_ENV -certify -addr=$SECRET_VAULT_ADDR -token=$SECRET_VAULT_ENV_TOKEN -pluginName=$TRC_PLUGIN_NAME -sha256=$(cat target/$TRC_PLUGIN_NAME.sha256) -pluginType=agent
trcplgtool -env=$VAULT_ENV -certify -addr=$SECRET_VAULT_ADDR -token=$SECRET_VAULT_ENV_TOKEN -pluginName=$TRC_PLUGIN_NAME -sha256=target/$TRC_PLUGIN_NAME -pluginType=agent
certifystatus=$?
if [ $certifystatus -eq 0 ]; then
echo "No certification problems encountered."
Expand All @@ -90,7 +90,7 @@ if [ "$PRE_CERTIFY" = "Y" ] || [ "$PRE_CERTIFY" = "yes" ] || [ "$PRE_CERTIFY" =
fi
else
echo "Certifying vault type plugin..."
trcplgtool -env=$VAULT_ENV -certify -addr=$SECRET_VAULT_ADDR -token=$SECRET_VAULT_ENV_TOKEN -pluginName=$TRC_PLUGIN_NAME -sha256=$(cat target/$TRC_PLUGIN_NAME.sha256)
trcplgtool -env=$VAULT_ENV -certify -addr=$SECRET_VAULT_ADDR -token=$SECRET_VAULT_ENV_TOKEN -pluginName=$TRC_PLUGIN_NAME -sha256=target/$TRC_PLUGIN_NAME
certifystatus=$?
if [ $certifystatus -eq 0 ]; then
echo "No certification problems encountered."
Expand All @@ -111,7 +111,7 @@ then
else
echo "Checking plugin deploy status."
echo "Checking deployment status on plugin for env $VAULT_ENV."
trcplgtool -env=$VAULT_ENV -checkDeployed -addr=$SECRET_VAULT_ADDR -token=$SECRET_VAULT_ENV_TOKEN -pluginName=$TRC_PLUGIN_NAME -sha256=$(cat target/$TRC_PLUGIN_NAME.sha256)
trcplgtool -env=$VAULT_ENV -checkDeployed -addr=$SECRET_VAULT_ADDR -token=$SECRET_VAULT_ENV_TOKEN -pluginName=$TRC_PLUGIN_NAME -sha256=target/$TRC_PLUGIN_NAME
status=$?
echo "Plugin deployment had status result $status."

Expand Down
2 changes: 1 addition & 1 deletion pkg/cli/trcconfigbase/utils/configinator.go
Original file line number Diff line number Diff line change
Expand Up @@ -471,12 +471,12 @@ func writeToFile(config *eUtils.DriverConfig, data string, path string) {
//create new file
newFile, err = os.Create(path)
eUtils.CheckError(config, err, true)
defer newFile.Close()
//write to file
_, err = newFile.Write(byteData)
eUtils.CheckError(config, err, true)
err = newFile.Sync()
eUtils.CheckError(config, err, true)
newFile.Close()
}
}

Expand Down
3 changes: 3 additions & 0 deletions pkg/core/util/properties.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,9 @@ func (p *Properties) WritePluginData(pluginData map[string]interface{}, replaced
if readErr != nil {
return readErr
}
if writeMap == nil {
writeMap = map[string]interface{}{}
}

for field, value := range pluginData {
writeMap[field] = value
Expand Down
11 changes: 11 additions & 0 deletions pkg/core/util/repository/azrcr.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,17 @@ import (
)

func getImageSHA(config *eUtils.DriverConfig, svc *azidentity.ClientSecretCredential, pluginToolConfig map[string]interface{}) error {

if pluginToolConfig["acrrepository"].(string) != null && len(pluginToolConfig["acrrepository"].(string)) == 0 {
config.Log.Printf("Acr repository undefined. Refusing to continue.\n")
return errors.New("undefined acr repository")
}

if pluginToolConfig["trcplugin"].(string) != null && len(pluginToolConfig["trcplugin"].(string)) == 0 {
config.Log.Printf("Trcplugin undefined. Refusing to continue.\n")
return errors.New("undefined trcplugin")
}

client, err := azcontainerregistry.NewClient(
pluginToolConfig["acrrepository"].(string),
svc, nil)
Expand Down
Loading

0 comments on commit ece05f0

Please sign in to comment.