|
| 1 | +package client |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "io/ioutil" |
| 7 | + "strings" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/skilld-labs/opcua" |
| 11 | + "github.com/skilld-labs/opcua/errors" |
| 12 | + "github.com/skilld-labs/opcua/ua" |
| 13 | + "github.com/skilld-labs/telemetry-opcua-exporter/config" |
| 14 | + "github.com/skilld-labs/telemetry-opcua-exporter/log" |
| 15 | +) |
| 16 | + |
| 17 | +func NewClientFromServerConfig(cfg config.ServerConfig, logger log.Logger) *opcua.Client { |
| 18 | + opts := []opcua.Option{} |
| 19 | + authMode := *cfg.Auth |
| 20 | + switch authMode { |
| 21 | + case "Certificate": |
| 22 | + return NewCertificateClient(*cfg.CertFile, *cfg.KeyFile, cfg, logger) |
| 23 | + case "UserName": |
| 24 | + return NewBasicAuthClient(*cfg.Username, *cfg.Password, cfg, logger) |
| 25 | + default: |
| 26 | + *cfg.Auth = "Anonymous" |
| 27 | + opts = append(opts, opcua.AuthAnonymous()) |
| 28 | + } |
| 29 | + return getClientWithOptions(cfg, opts, logger) |
| 30 | +} |
| 31 | + |
| 32 | +func NewCertificateClient(certfile, keyfile string, cfg config.ServerConfig, logger log.Logger) *opcua.Client { |
| 33 | + return getClientWithOptions(cfg, certificateOptions(certfile, keyfile, logger), logger) |
| 34 | +} |
| 35 | + |
| 36 | +func NewBasicAuthClient(username, password string, cfg config.ServerConfig, logger log.Logger) *opcua.Client { |
| 37 | + return getClientWithOptions(cfg, []opcua.Option{opcua.AuthUsername(username, password)}, logger) |
| 38 | +} |
| 39 | + |
| 40 | +func getClientWithOptions(cfg config.ServerConfig, opts []opcua.Option, logger log.Logger) *opcua.Client { |
| 41 | + clientSecurityOpts, err := clientSecurityOptions(cfg, logger) |
| 42 | + if err != nil { |
| 43 | + logger.Err("%v", err) |
| 44 | + } |
| 45 | + opts = append(opts, clientSecurityOpts...) |
| 46 | + opts = append(opts, opcua.Lifetime(10*time.Minute), opcua.RequestTimeout(5*time.Second), opcua.AutoReconnect(true)) |
| 47 | + |
| 48 | + c := opcua.NewClient(*cfg.Endpoint, opts...) |
| 49 | + if err := c.Connect(context.Background()); err != nil { |
| 50 | + logger.Err("cannot connect opcua client %v", err) |
| 51 | + } |
| 52 | + return c |
| 53 | +} |
| 54 | + |
| 55 | +func certificateOptions(certfile, keyfile string, logger log.Logger) []opcua.Option { |
| 56 | + opts := []opcua.Option{} |
| 57 | + if keyfile != "" { |
| 58 | + opts = append(opts, opcua.PrivateKeyFile(keyfile)) |
| 59 | + } |
| 60 | + cert, err := ioutil.ReadFile(certfile) |
| 61 | + if err != nil { |
| 62 | + logger.Err("cannot read certfile : %v", err) |
| 63 | + } |
| 64 | + if certfile != "" { |
| 65 | + opts = append(opts, opcua.Certificate(cert)) |
| 66 | + } |
| 67 | + return opts |
| 68 | +} |
| 69 | + |
| 70 | +func clientSecurityOptions(cfg config.ServerConfig, logger log.Logger) ([]opcua.Option, error) { |
| 71 | + savePolicy := *cfg.Policy |
| 72 | + endpoints, err := opcua.GetEndpoints(*cfg.Endpoint) |
| 73 | + if err != nil { |
| 74 | + return nil, fmt.Errorf("%v", err) |
| 75 | + } |
| 76 | + authMode := ua.UserTokenTypeFromString(*cfg.Auth) |
| 77 | + opts := []opcua.Option{} |
| 78 | + var secPolicy string |
| 79 | + switch { |
| 80 | + case *cfg.Policy == "auto": |
| 81 | + case strings.HasPrefix(*cfg.Policy, ua.SecurityPolicyURIPrefix): |
| 82 | + secPolicy = *cfg.Policy |
| 83 | + *cfg.Policy = "" |
| 84 | + case *cfg.Policy == "None" || *cfg.Policy == "Basic128Rsa15" || *cfg.Policy == "Basic256" || *cfg.Policy == "Basic256Sha256" || *cfg.Policy == "Aes128_Sha256_RsaOaep" || *cfg.Policy == "Aes256_Sha256_RsaPss": |
| 85 | + secPolicy = ua.SecurityPolicyURIPrefix + *cfg.Policy |
| 86 | + *cfg.Policy = "" |
| 87 | + default: |
| 88 | + return nil, fmt.Errorf("invalid security.Policy: %s", *cfg.Policy) |
| 89 | + } |
| 90 | + |
| 91 | + var secMode ua.MessageSecurityMode |
| 92 | + switch strings.ToLower(*cfg.Mode) { |
| 93 | + case "auto": |
| 94 | + case "none": |
| 95 | + secMode = ua.MessageSecurityModeNone |
| 96 | + *cfg.Mode = "" |
| 97 | + case "sign": |
| 98 | + secMode = ua.MessageSecurityModeSign |
| 99 | + *cfg.Mode = "" |
| 100 | + case "signandencrypt": |
| 101 | + secMode = ua.MessageSecurityModeSignAndEncrypt |
| 102 | + *cfg.Mode = "" |
| 103 | + default: |
| 104 | + return nil, fmt.Errorf("invalid security.Mode: %s", *cfg.Mode) |
| 105 | + } |
| 106 | + |
| 107 | + // Allow input of only one of sec.Mode,sec.Policy when choosing 'None' |
| 108 | + if secMode == ua.MessageSecurityModeNone || secPolicy == ua.SecurityPolicyURINone { |
| 109 | + secMode = ua.MessageSecurityModeNone |
| 110 | + secPolicy = ua.SecurityPolicyURINone |
| 111 | + } |
| 112 | + |
| 113 | + // Find the best endpoint based on our input and server recommendation (highest SecurityMode+SecurityLevel) |
| 114 | + var serverEndpoint *ua.EndpointDescription |
| 115 | + switch { |
| 116 | + case *cfg.Mode == "auto" && *cfg.Policy == "auto": // No user selection, choose best |
| 117 | + for _, e := range endpoints { |
| 118 | + if serverEndpoint == nil || (e.SecurityMode >= serverEndpoint.SecurityMode && e.SecurityLevel >= serverEndpoint.SecurityLevel) { |
| 119 | + serverEndpoint = e |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + case *cfg.Mode != "auto" && *cfg.Policy == "auto": // User only cares about.Mode, select highest securitylevel with that.Mode |
| 124 | + for _, e := range endpoints { |
| 125 | + if e.SecurityMode == secMode && (serverEndpoint == nil || e.SecurityLevel >= serverEndpoint.SecurityLevel) { |
| 126 | + serverEndpoint = e |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + case *cfg.Mode == "auto" && *cfg.Policy != "auto": // User only cares about.Policy, select highest securitylevel with that.Policy |
| 131 | + for _, e := range endpoints { |
| 132 | + if e.SecurityPolicyURI == secPolicy && (serverEndpoint == nil || e.SecurityLevel >= serverEndpoint.SecurityLevel) { |
| 133 | + serverEndpoint = e |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + default: // User cares about both |
| 138 | + for _, e := range endpoints { |
| 139 | + if e.SecurityPolicyURI == secPolicy && e.SecurityMode == secMode && (serverEndpoint == nil || e.SecurityLevel >= serverEndpoint.SecurityLevel) { |
| 140 | + serverEndpoint = e |
| 141 | + } |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + *cfg.Policy = savePolicy |
| 146 | + |
| 147 | + if serverEndpoint == nil { |
| 148 | + return nil, fmt.Errorf("unable to find suitable server.Endpoint with selected sec.Policy and sec.Mode") |
| 149 | + } |
| 150 | + |
| 151 | + if validateEndpointConfig(endpoints, serverEndpoint.SecurityPolicyURI, serverEndpoint.SecurityMode, authMode); err != nil { |
| 152 | + return nil, fmt.Errorf("error validating input: %s", err) |
| 153 | + } |
| 154 | + |
| 155 | + opts = append(opts, opcua.SecurityFromEndpoint(serverEndpoint, authMode)) |
| 156 | + logger.Info("using config: Endpoint: %s, Security.Mode: %s, %s auth.Mode : %s", serverEndpoint.EndpointURL, serverEndpoint.SecurityPolicyURI, serverEndpoint.SecurityMode, authMode) |
| 157 | + return opts, nil |
| 158 | +} |
| 159 | + |
| 160 | +func validateEndpointConfig(endpoints []*ua.EndpointDescription, secPolicy string, secMode ua.MessageSecurityMode, authMode ua.UserTokenType) error { |
| 161 | + for _, e := range endpoints { |
| 162 | + if e.SecurityMode == secMode && e.SecurityPolicyURI == secPolicy { |
| 163 | + for _, t := range e.UserIdentityTokens { |
| 164 | + if t.TokenType == authMode { |
| 165 | + return nil |
| 166 | + } |
| 167 | + } |
| 168 | + } |
| 169 | + } |
| 170 | + return errors.Errorf("server does not support an.Endpoint with security : %s , %s", secPolicy, secMode) |
| 171 | +} |
0 commit comments