Skip to content

Commit

Permalink
Delete log.Fatal calls and replace with error returns. (influxdata#9086)
Browse files Browse the repository at this point in the history
* Delete log.Fatal calls and replace with error returns.

* Update opcua_util.go

* Update opcua_util.go
  • Loading branch information
ivorybilled authored Apr 6, 2021
1 parent 868befc commit ef2def2
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 118 deletions.
9 changes: 6 additions & 3 deletions plugins/inputs/opcua/opcua_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -440,13 +440,16 @@ func (o *OpcUA) setupOptions() error {

if o.Certificate == "" && o.PrivateKey == "" {
if o.SecurityPolicy != "None" || o.SecurityMode != "None" {
o.Certificate, o.PrivateKey = generateCert("urn:telegraf:gopcua:client", 2048, o.Certificate, o.PrivateKey, (365 * 24 * time.Hour))
o.Certificate, o.PrivateKey, err = generateCert("urn:telegraf:gopcua:client", 2048, o.Certificate, o.PrivateKey, (365 * 24 * time.Hour))
if err != nil {
return err
}
}
}

o.opts = generateClientOpts(endpoints, o.Certificate, o.PrivateKey, o.SecurityPolicy, o.SecurityMode, o.AuthMethod, o.Username, o.Password, time.Duration(o.RequestTimeout))
o.opts, err = generateClientOpts(endpoints, o.Certificate, o.PrivateKey, o.SecurityPolicy, o.SecurityMode, o.AuthMethod, o.Username, o.Password, time.Duration(o.RequestTimeout))

return nil
return err
}

func (o *OpcUA) getData() error {
Expand Down
64 changes: 35 additions & 29 deletions plugins/inputs/opcua/opcua_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ func newTempDir() (string, error) {
return dir, err
}

func generateCert(host string, rsaBits int, certFile, keyFile string, dur time.Duration) (string, string) {
func generateCert(host string, rsaBits int, certFile, keyFile string, dur time.Duration) (cert string, key string, err error) {
dir, _ := newTempDir()

if len(host) == 0 {
log.Fatalf("Missing required host parameter")
return "", "", fmt.Errorf("missing required host parameter")
}
if rsaBits == 0 {
rsaBits = 2048
Expand All @@ -49,7 +49,7 @@ func generateCert(host string, rsaBits int, certFile, keyFile string, dur time.D

priv, err := rsa.GenerateKey(rand.Reader, rsaBits)
if err != nil {
log.Fatalf("failed to generate private key: %s", err)
return "", "", fmt.Errorf("failed to generate private key: %s", err)
}

notBefore := time.Now()
Expand All @@ -58,7 +58,7 @@ func generateCert(host string, rsaBits int, certFile, keyFile string, dur time.D
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: %s", err)
return "", "", fmt.Errorf("failed to generate serial number: %s", err)
}

template := x509.Certificate{
Expand Down Expand Up @@ -88,33 +88,33 @@ func generateCert(host string, rsaBits int, certFile, keyFile string, dur time.D

derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
if err != nil {
log.Fatalf("Failed to create certificate: %s", err)
return "", "", fmt.Errorf("failed to create certificate: %s", err)
}

certOut, err := os.Create(certFile)
if err != nil {
log.Fatalf("failed to open %s for writing: %s", certFile, err)
return "", "", fmt.Errorf("failed to open %s for writing: %s", certFile, err)
}
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
log.Fatalf("failed to write data to %s: %s", certFile, err)
return "", "", fmt.Errorf("failed to write data to %s: %s", certFile, err)
}
if err := certOut.Close(); err != nil {
log.Fatalf("error closing %s: %s", certFile, err)
return "", "", fmt.Errorf("error closing %s: %s", certFile, err)
}

keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Printf("failed to open %s for writing: %s", keyFile, err)
return "", ""
return "", "", nil
}
if err := pem.Encode(keyOut, pemBlockForKey(priv)); err != nil {
log.Fatalf("failed to write data to %s: %s", keyFile, err)
return "", "", fmt.Errorf("failed to write data to %s: %s", keyFile, err)
}
if err := keyOut.Close(); err != nil {
log.Fatalf("error closing %s: %s", keyFile, err)
return "", "", fmt.Errorf("error closing %s: %s", keyFile, err)
}

return certFile, keyFile
return certFile, keyFile, nil
}

func publicKey(priv interface{}) interface{} {
Expand Down Expand Up @@ -144,9 +144,8 @@ func pemBlockForKey(priv interface{}) *pem.Block {
}
}

// OPT FUNCTIONS

func generateClientOpts(endpoints []*ua.EndpointDescription, certFile, keyFile, policy, mode, auth, username, password string, requestTimeout time.Duration) []opcua.Option {
//revive:disable-next-line
func generateClientOpts(endpoints []*ua.EndpointDescription, certFile, keyFile, policy, mode, auth, username, password string, requestTimeout time.Duration) ([]opcua.Option, error) {
opts := []opcua.Option{}
appuri := "urn:telegraf:gopcua:client"
appname := "Telegraf"
Expand All @@ -157,9 +156,13 @@ func generateClientOpts(endpoints []*ua.EndpointDescription, certFile, keyFile,

opts = append(opts, opcua.RequestTimeout(requestTimeout))

var err error
if certFile == "" && keyFile == "" {
if policy != "None" || mode != "None" {
certFile, keyFile = generateCert(appuri, 2048, certFile, keyFile, (365 * 24 * time.Hour))
certFile, keyFile, err = generateCert(appuri, 2048, certFile, keyFile, (365 * 24 * time.Hour))
if err != nil {
return nil, err
}
}
}

Expand All @@ -172,7 +175,7 @@ func generateClientOpts(endpoints []*ua.EndpointDescription, certFile, keyFile,
} else {
pk, ok := c.PrivateKey.(*rsa.PrivateKey)
if !ok {
log.Fatalf("Invalid private key")
return nil, fmt.Errorf("invalid private key")
}
cert = c.Certificate[0]
opts = append(opts, opcua.PrivateKey(pk), opcua.Certificate(cert))
Expand All @@ -190,11 +193,15 @@ func generateClientOpts(endpoints []*ua.EndpointDescription, certFile, keyFile,
secPolicy = ua.SecurityPolicyURIPrefix + policy
policy = ""
default:
log.Fatalf("Invalid security policy: %s", policy)
return nil, fmt.Errorf("invalid security policy: %s", policy)
}

// Select the most appropriate authentication mode from server capabilities and user input
authMode, authOption := generateAuth(auth, cert, username, password)
authMode, authOption, err := generateAuth(auth, cert, username, password)
if err != nil {
return nil, err
}

opts = append(opts, authOption)

var secMode ua.MessageSecurityMode
Expand All @@ -210,7 +217,7 @@ func generateClientOpts(endpoints []*ua.EndpointDescription, certFile, keyFile,
secMode = ua.MessageSecurityModeSignAndEncrypt
mode = ""
default:
log.Fatalf("Invalid security mode: %s", mode)
return nil, fmt.Errorf("invalid security mode: %s", mode)
}

// Allow input of only one of sec-mode,sec-policy when choosing 'None'
Expand Down Expand Up @@ -252,24 +259,23 @@ func generateClientOpts(endpoints []*ua.EndpointDescription, certFile, keyFile,
}

if serverEndpoint == nil { // Didn't find an endpoint with matching policy and mode.
log.Printf("unable to find suitable server endpoint with selected sec-policy and sec-mode")
log.Fatalf("quitting")
return nil, fmt.Errorf("unable to find suitable server endpoint with selected sec-policy and sec-mode")
}

secPolicy = serverEndpoint.SecurityPolicyURI
secMode = serverEndpoint.SecurityMode

// Check that the selected endpoint is a valid combo
err := validateEndpointConfig(endpoints, secPolicy, secMode, authMode)
err = validateEndpointConfig(endpoints, secPolicy, secMode, authMode)
if err != nil {
log.Fatalf("error validating input: %s", err)
return nil, fmt.Errorf("error validating input: %s", err)
}

opts = append(opts, opcua.SecurityFromEndpoint(serverEndpoint, authMode))
return opts
return opts, nil
}

func generateAuth(a string, cert []byte, un, pw string) (ua.UserTokenType, opcua.Option) {
func generateAuth(a string, cert []byte, un, pw string) (ua.UserTokenType, opcua.Option, error) {
var err error

var authMode ua.UserTokenType
Expand All @@ -284,13 +290,13 @@ func generateAuth(a string, cert []byte, un, pw string) (ua.UserTokenType, opcua

if un == "" {
if err != nil {
log.Fatalf("error reading username input: %s", err)
return 0, nil, fmt.Errorf("error reading the username input: %s", err)
}
}

if pw == "" {
if err != nil {
log.Fatalf("error reading username input: %s", err)
return 0, nil, fmt.Errorf("error reading the password input: %s", err)
}
}

Expand All @@ -311,7 +317,7 @@ func generateAuth(a string, cert []byte, un, pw string) (ua.UserTokenType, opcua
authOption = opcua.AuthAnonymous()
}

return authMode, authOption
return authMode, authOption, nil
}

func validateEndpointConfig(endpoints []*ua.EndpointDescription, secPolicy string, secMode ua.MessageSecurityMode, authMode ua.UserTokenType) error {
Expand Down
Loading

0 comments on commit ef2def2

Please sign in to comment.