uasc

package
v0.6.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 22, 2025 License: MIT Imports: 20 Imported by: 2

Documentation

Overview

Package uasc provides encoding/decoding and automated secure channel and session handling for OPC UA Secure Conversation.

Index

Constants

View Source
const (
	MessageTypeMessage            = "MSG"
	MessageTypeOpenSecureChannel  = "OPN"
	MessageTypeCloseSecureChannel = "CLO"
)

MessageType definitions.

View Source
const (
	ChunkTypeIntermediate = 'C'
	ChunkTypeFinal        = 'F'
	ChunkTypeError        = 'A'
)

ChunkType definitions.

View Source
const (
	MaxTimeout = math.MaxUint32 * time.Millisecond
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AsymmetricSecurityHeader

type AsymmetricSecurityHeader struct {
	SecurityPolicyURI             string
	SenderCertificate             []byte
	ReceiverCertificateThumbprint []byte
}

AsymmetricSecurityHeader represents a Asymmetric Algorithm Security Header in OPC UA Secure Conversation.

func NewAsymmetricSecurityHeader

func NewAsymmetricSecurityHeader(uri string, cert, thumbprint []byte) *AsymmetricSecurityHeader

NewAsymmetricSecurityHeader creates a new OPC UA Secure Conversation Asymmetric Algorithm Security Header.

func (*AsymmetricSecurityHeader) Decode

func (h *AsymmetricSecurityHeader) Decode(b []byte) (int, error)

func (*AsymmetricSecurityHeader) Encode

func (h *AsymmetricSecurityHeader) Encode() ([]byte, error)

func (*AsymmetricSecurityHeader) Len

func (h *AsymmetricSecurityHeader) Len() int

Len returns the Header Length in bytes.

func (*AsymmetricSecurityHeader) String

func (a *AsymmetricSecurityHeader) String() string

String returns Header in string.

type Config

type Config struct {

	// SecurityPolicyURI is the URI of the Security Policy used to secure the Message.
	// This field is encoded as a UTF-8 string without a null terminator.
	SecurityPolicyURI string

	// Certificate is the X.509 v3 Certificate assigned to the sending application Instance.
	// This is a DER encoded blob.
	// The structure of an X.509 v3 Certificate is defined in X.509 v3.
	// The DER format for a Certificate is defined in X690.
	// This indicates what Private Key was used to sign the MessageChunk.
	// The Stack shall close the channel and report an error to the application if
	// the Certificate is too large for the buffer size supported by the
	// transport layer.
	// This field shall be null if the Message is not signed.
	Certificate []byte

	// LocalKey is a RSA Private Key which will be used to encrypt the OpenSecureChannel
	// messages.  It is the key associated with Certificate
	LocalKey *rsa.PrivateKey

	// UserKey is a RSA Private Key which will be used to sign the UserTokenSignature.
	// It is the key associated with AuthCertificate
	UserKey *rsa.PrivateKey

	// Thumbprint is the thumbprint of the X.509 v3 Certificate assigned to the receiving
	// application Instance.
	// The thumbprint is the CertificateDigest of the DER encoded form of the
	// Certificate.
	// This indicates what public key was used to encrypt the MessageChunk.
	// This field shall be null if the Message is not encrypted.
	Thumbprint []byte

	// RemoteCertificate is the X.509 Certificate for the receiving instance.
	// Used to encrypt the message chunks in the OpenSecureChannel phase.
	RemoteCertificate []byte

	// RequestIDSeed is the initial value for RequestID counter in each new SecureChannel
	RequestIDSeed uint32

	// SecurityMode is The type of security to apply to the messages. The type MessageSecurityMode
	// is defined in 7.15.
	// A SecureChannel may have to be created even if the securityMode is NONE. The exact behaviour
	// depends on the mapping used and is described in the Part 6.
	SecurityMode ua.MessageSecurityMode

	// AutoReconnect will make sure that once communication is restored,
	// the old session is used whenever possible and that Susbcription data is not missed.
	// You may choose to use AutoReconnect (true by default) or do it manually.
	// AutoReconnect will make the UaClient to try to reconnect to the server every second,
	// once the communication is broken. If you do it manually, you must be prepared to do it until it succeeds.
	AutoReconnect bool

	// ReconnectInterval is interval duration between each reconnection attempt,
	// ignored if AutoReconnect is set to false.
	ReconnectInterval time.Duration

	// Lifetime is the requested lifetime, in milliseconds, for the new SecurityToken when the
	// SecureChannel works as client. It specifies when the Client expects to renew the SecureChannel
	// by calling the OpenSecureChannel Service again. If a SecureChannel is not renewed, then all
	// Messages sent using the current SecurityTokens shall be rejected by the receiver.
	// Lifetime can also be the revised lifetime, the lifetime of the SecurityToken in milliseconds.
	// The UTC expiration time for the token may be calculated by adding the lifetime to the createdAt time.
	Lifetime uint32

	// RequestTimeout is timeout duration for all synchronous requests over SecureChannel.
	// If the Server doesn't respond within RequestTimeout time, Client returns StatusBadTimeout
	RequestTimeout time.Duration
}

Config represents a configuration which UASC client/server has in common.

type Header struct {
	MessageType     string
	ChunkType       byte
	MessageSize     uint32
	SecureChannelID uint32
}

Header represents a OPC UA Secure Conversation Header.

func NewHeader

func NewHeader(msgType string, chunkType byte, chanID uint32) *Header

NewHeader creates a new OPC UA Secure Conversation Header.

func (*Header) Decode

func (h *Header) Decode(b []byte) (int, error)

func (*Header) Encode

func (h *Header) Encode() ([]byte, error)

func (*Header) String

func (h *Header) String() string

String returns Header in string.

type Message

type Message struct {
	*MessageHeader
	TypeID  *ua.ExpandedNodeID
	Service interface{}
}

Message represents a OPC UA Secure Conversation message.

func (*Message) Decode

func (m *Message) Decode(b []byte) (int, error)

func (*Message) Encode

func (m *Message) Encode() ([]byte, error)

func (*Message) EncodeChunks added in v0.2.0

func (m *Message) EncodeChunks(maxBodySize uint32) ([][]byte, error)

type MessageAbort

type MessageAbort struct {
	ErrorCode uint32
	Reason    string
}

MessageAbort represents a non-terminal OPC UA Secure Channel error.

Specification: Part6, 7.3

func (*MessageAbort) Decode

func (m *MessageAbort) Decode(b []byte) (int, error)

func (*MessageAbort) Encode

func (m *MessageAbort) Encode() ([]byte, error)

func (*MessageAbort) MessageAbort

func (m *MessageAbort) MessageAbort() string

type MessageBody added in v0.6.0

type MessageBody struct {
	RequestID       uint32
	SecureChannelID uint32
	Err             error
	// contains filtered or unexported fields
}

MessageBody is the content of a secure channel message sent between a client and a server and represents a service request or response.

func (MessageBody) Request added in v0.6.0

func (b MessageBody) Request() ua.Request

func (MessageBody) Response added in v0.6.0

func (b MessageBody) Response() ua.Response

type MessageChunk

type MessageChunk struct {
	*MessageHeader
	Data []byte
}

func (*MessageChunk) Decode

func (m *MessageChunk) Decode(b []byte) (int, error)

type MessageHeader

func (*MessageHeader) Decode

func (m *MessageHeader) Decode(b []byte) (int, error)

type ResponseHandler added in v0.6.0

type ResponseHandler func(ua.Response) error

ResponseHandler handles the response of a service request and is used by the client.

type SecureChannel

type SecureChannel struct {
	// contains filtered or unexported fields
}

func NewSecureChannel

func NewSecureChannel(endpoint string, c *uacp.Conn, cfg *Config, errCh chan<- error) (*SecureChannel, error)

func NewServerSecureChannel added in v0.6.0

func NewServerSecureChannel(endpoint string, c *uacp.Conn, cfg *Config, errCh chan<- error, secureChannelID, sequenceNumber, securityTokenID uint32) (*SecureChannel, error)

func (*SecureChannel) Close

func (s *SecureChannel) Close() (err error)

Close closes an existing secure channel

func (*SecureChannel) EncryptUserPassword

func (s *SecureChannel) EncryptUserPassword(policyURI, password string, cert, nonce []byte) ([]byte, string, error)

EncryptUserPassword issues a new signature for the client to send in ActivateSessionRequest

func (*SecureChannel) LocalEndpoint

func (s *SecureChannel) LocalEndpoint() string

func (*SecureChannel) NewSessionSignature

func (s *SecureChannel) NewSessionSignature(cert, nonce []byte) ([]byte, string, error)

NewSessionSignature issues a new signature for the client to send on the next ActivateSessionRequest

func (*SecureChannel) NewUserTokenSignature

func (s *SecureChannel) NewUserTokenSignature(policyURI string, cert, nonce []byte) ([]byte, string, error)

NewUserTokenSignature issues a new signature for the client to send in ActivateSessionRequest The security policy for the SecureChannel is used if policyURI value is null or empty https://reference.opcfoundation.org/Core/Part4/v104/docs/7.37

func (*SecureChannel) Open

func (s *SecureChannel) Open(ctx context.Context) error

func (*SecureChannel) Receive added in v0.1.1

func (s *SecureChannel) Receive(ctx context.Context) *MessageBody

Receive receives message chunks from the secure channel, decodes and forwards them to the registered callback channel, if there is one. Otherwise, the message is dropped.

func (*SecureChannel) RemoteAddr added in v0.6.0

func (s *SecureChannel) RemoteAddr() net.Addr

func (*SecureChannel) Renew added in v0.1.7

func (s *SecureChannel) Renew(ctx context.Context) error

func (*SecureChannel) SendMsgWithContext added in v0.6.0

func (s *SecureChannel) SendMsgWithContext(ctx context.Context, instance *channelInstance, reqID uint32, resp any) error

func (*SecureChannel) SendRequest added in v0.1.6

func (s *SecureChannel) SendRequest(ctx context.Context, req ua.Request, authToken *ua.NodeID, h ResponseHandler) error

func (*SecureChannel) SendRequestWithTimeout added in v0.1.6

func (s *SecureChannel) SendRequestWithTimeout(ctx context.Context, req ua.Request, authToken *ua.NodeID, timeout time.Duration, h ResponseHandler) error

func (*SecureChannel) SendResponseWithContext added in v0.6.0

func (s *SecureChannel) SendResponseWithContext(ctx context.Context, reqID uint32, resp ua.Response) error

func (*SecureChannel) VerifySessionSignature

func (s *SecureChannel) VerifySessionSignature(cert, nonce, signature []byte) error

VerifySessionSignature checks the integrity of a Create/Activate Session response's signature

type SequenceHeader

type SequenceHeader struct {
	SequenceNumber uint32
	RequestID      uint32
}

SequenceHeader represents a Sequence Header in OPC UA Secure Conversation.

func NewSequenceHeader

func NewSequenceHeader(seq, req uint32) *SequenceHeader

NewSequenceHeader creates a new OPC UA Secure Conversation Sequence Header.

func (*SequenceHeader) Decode

func (h *SequenceHeader) Decode(b []byte) (int, error)

func (*SequenceHeader) Encode

func (h *SequenceHeader) Encode() ([]byte, error)

func (*SequenceHeader) String

func (s *SequenceHeader) String() string

String returns Header in string.

type SessionConfig

type SessionConfig struct {
	// AuthenticationToken is the secret Session identifier used to verify that the request is
	// associated with the Session. The SessionAuthenticationToken type is defined in 7.31.
	AuthenticationToken *ua.NodeID

	// ClientDescription is the information that describes the Client application.
	// The type ApplicationDescription is defined in 7.1.
	ClientDescription *ua.ApplicationDescription

	// ServerEndpoints is the list of Endpoints that the Server supports.
	// The Server shall return a set of EndpointDescriptions available for the serverUri
	// specified in the request. The EndpointDescription type is defined in 7.10. The Client
	// shall verify this list with the list from a DiscoveryEndpoint if it used a
	// DiscoveryEndpoint to fetch the EndpointDescriptions.
	// It is recommended that Servers only include the server.applicationUri, endpointUrl,
	// securityMode, securityPolicyUri, userIdentityTokens, transportProfileUri and
	// securityLevel with all other parameters set to null. Only the recommended
	// parameters shall be verified by the client.
	ServerEndpoints []*ua.EndpointDescription

	// LocaleIDs is the list of locale ids in priority order for localized strings. The first
	// LocaleId in the list has the highest priority. If the Server returns a localized string
	// to the Client, the Server shall return the translation with the highest priority that
	// it can. If it does not have a translation for any of the locales identified in this list,
	// then it shall return the string value that it has and include the locale id with the
	// string. See Part 3 for more detail on locale ids. If the Client fails to specify at least
	// one locale id, the Server shall use any that it has.
	// This parameter only needs to be specified during the first call to ActivateSession during
	// a single application Session. If it is not specified the Server shall keep using the
	// current localeIds for the Session.
	LocaleIDs []string

	// UserIdentityToken is the credentials of the user associated with the Client application.
	// The Server uses these credentials to determine whether the Client should be allowed to
	// activate a Session and what resources the Client has access to during this Session.
	// The UserIdentityToken is an extensible parameter type defined in 7.36.
	// The EndpointDescription specifies what UserIdentityTokens the Server shall accept.
	// Null or empty user token shall always be interpreted as anonymous.
	UserIdentityToken interface{}

	// If the Client specified a user identity token that supports digital signatures, then it
	// shall create a signature and pass it as this parameter. Otherwise the parameter is null.
	// The SignatureAlgorithm depends on the identity token type.
	// The SignatureData type is defined in 7.32.
	UserTokenSignature *ua.SignatureData

	// SessionName is an optional name of the session.
	// The default is a unique value for every new session.
	SessionName string

	// If Session works as a client, SessionTimeout is the requested maximum number of milliseconds
	// that a Session should remain open without activity. If the Client fails to issue a Service
	// request within this interval, then the Server shall automatically terminate the Client Session.
	// If Session works as a server, SessionTimeout is an actual maximum number of milliseconds
	// that a Session shall remain open without activity. The Server should attempt to honour the
	// Client request for this parameter,but may negotiate this value up or down to meet its own constraints.
	SessionTimeout time.Duration

	// Stored version of the password to authenticate against a server
	// todo: storing passwords in memory seems wrong
	AuthPassword string

	// PolicyURI to use when encrypting secrets for the User Identity Token
	// Could be different from the secure channel's policy
	AuthPolicyURI string
}

SessionConfig is a set of common configurations used in Session.

type SymmetricSecurityHeader

type SymmetricSecurityHeader struct {
	TokenID uint32
}

SymmetricSecurityHeader represents a Symmetric Algorithm Security Header in OPC UA Secure Conversation.

func NewSymmetricSecurityHeader

func NewSymmetricSecurityHeader(token uint32) *SymmetricSecurityHeader

NewSymmetricSecurityHeader creates a new OPC UA Secure Conversation Symmetric Algorithm Security Header.

func (*SymmetricSecurityHeader) Decode

func (h *SymmetricSecurityHeader) Decode(b []byte) (int, error)

func (*SymmetricSecurityHeader) Encode

func (h *SymmetricSecurityHeader) Encode() ([]byte, error)

func (*SymmetricSecurityHeader) Len

func (h *SymmetricSecurityHeader) Len() int

Len returns the Header Length in bytes.

func (*SymmetricSecurityHeader) String

func (h *SymmetricSecurityHeader) String() string

String returns Header in string.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL