Documentation
¶
Overview ¶
Package cosem is a DLMS/COSEM client (logical name referencing, and short name referencing with Referencing "sn", sn.go; the ACCESS service, access.go): the application association (AARQ, AARE, RLRQ, RLRE) with low-level and high-level security authentication (mechanisms 1 to 7), the security suites 0 to 2 with service-specific, general-glo, general-ded and general ciphering, general signing, third-party protection and V.44 compression (IEC 62056-5-3:2023, the DLMS UA Green Book), get, set and action with block transfer, the security setup object (class 64: key transfer and agreement, certificates), push reception (data-notification, general block transfer, HDLC pushes), the gateway protocol of IEC 62056-5-3 annex C for meters behind a data concentrator, profile reading by range, meter-initiated connections, local serial lines with the IEC 62056-21 mode E opening, and invocation counters kept across restarts.
The xDLMS services are those of gosem (gitlab.com/circutor-library/gosem, MIT), configured without ciphering: SecureTransport sits between gosem and the supporting layers (packages wrapper, hdlc, phy and gateway of this module) and applies the protection itself, so every combination of suite, policy, key and ciphering form works.
The main entry points:
- SecurityConfig turns text settings into the HLS value an association uses; Associate opens one association over a transport the caller opened; Client keeps one meter's associations, its invocation counter and the system title it named.
- ICReservation, Counter and PushCounter keep invocation counters through an iotsec.Store, so a restart never repeats one.
- OpenProtectedPush, DecodeDataNotification, PushSetupOf and MapPush open and map pushes; ServeHDLCPushes reads pushes in HDLC frames; InboundConn carries a meter-initiated connection.
- Gateway is the shared connection to a DCU (gateway or logical-device mode).
- ReadCaptureObjects, ReadProfileRange and ProfileRow read profiles.
- SecuritySetup runs the methods of the security setup object.
- NewPortClient runs a client over a port another protocol opened (an optical head after an IEC 62056-21 mode E switch).
- Seal, Open, Request and Exchange carry DLMS APDUs inside another protocol (wireless and wired M-Bus).
A crypto policy (iotsec.CryptoPolicy) may veto an authentication mechanism at association time (AssociationConfig.Policy, MechanismAlgorithm). Refusals of pushes for their protection are *PushSecurityError with a stable event name for a security log (iotsec.SecurityEvent).
Comments cite the clauses they implement; "F-nnnn" names a finding in SigmaM2M's register of specification defects (see PROVENANCE.md).
Index ¶
- Constants
- Variables
- func BitsSet(d axdr.DlmsData) []int
- func CheckHDLCAddresses(client, upper, lower, size int) error
- func ClockStatus(s string) (byte, bool)
- func CommError(err error) bool
- func DateTime(hexs string, loc *time.Location) (time.Time, bool)
- func DecodeLength(b []byte) (n, size int)
- func DefaultClientAddress(mech byte) int
- func DefaultProfile(phases int) string
- func DescribeEvent(row map[string]any, code int)
- func DropOctets(b []byte, at []int) []byte
- func EncodeAXDR(d *axdr.DlmsData) (r, g []byte, strays []int)
- func EncodeDateTime(t time.Time, loc *time.Location) []byte
- func EncodeResponse(r Response) ([]byte, error)
- func EncodeUnconfirmedSet(class uint16, obis string, attr int8, data *axdr.DlmsData) ([]byte, error)
- func GeneralErrorFlags(v uint16) []string
- func IsGatewayDown(err error) bool
- func IsGeneralError(code string, class uint16, attr int8) bool
- func IsTimeColumn(c Capture) bool
- func KeyTransferItem(id byte, wrapped []byte) *axdr.DlmsData
- func LimiterThreshold(class uint16, attr int8) bool
- func MechanismAlgorithm(mech byte) (alg iotsec.Algorithm, ok bool)
- func MonitoredValue(d axdr.DlmsData) (uint16, string, bool)
- func NameOf(code string, class uint16, attr int8) string
- func NeedsPassword(mech byte) bool
- func Number(d axdr.DlmsData) (float64, bool)
- func OBISFromHex(h string) (string, error)
- func Open(apdu []byte, keys *Keys) (plain, systemTitle []byte, ic uint32, err error)
- func OpenSerialLine(device string, s SerialSettings, timeout time.Duration) (net.Conn, error)
- func PEMBlock(v string) (*pem.Block, error)
- func PEMCertificates(v string) []*x509.Certificate
- func ParseOBIS(s string) ([6]byte, error)
- func ParsePushObjectList(d axdr.DlmsData) []is15959.Column
- func PointName(obis string, class uint16, attr int8) string
- func PolicyBits(policy byte, signing bool) byte
- func ProfileRow(r *axdr.DlmsData, cols []Capture, x RowScalers) (map[string]any, time.Time)
- func Protect(suite Suite, policy byte, key, ak, systemTitle []byte, ic uint32, plain []byte) ([]byte, error)
- func PushSetupOf(sp *is15959.Spec, items []*axdr.DlmsData, ...) (*is15959.PushSetup, error)
- func PushTag(apdu []byte) bool
- func RangeDescriptor(c Capture, from, to time.Time, loc *time.Location) *axdr.DlmsData
- func ReadCapturePeriod(c gdlms.Client, profile string) uint32
- func ReadInvocationCounter(tr gdlms.Transport, obis string, timeout time.Duration, name, where string) (uint32, error)
- func ReadProfileRange(c gdlms.Client, profile string, tc Capture, from, to time.Time, ...) ([]*axdr.DlmsData, error)
- func ReadScaled(c gdlms.Client, o Object, loc *time.Location) (v any, unit string, err error)
- func Readable(d axdr.DlmsData, loc *time.Location, asDateTime bool) any
- func Rejected(err error) bool
- func SNMethodOffset(class uint16, m int8) (uint16, bool)
- func Scaled(v float64, scaler int8) float64
- func ScaledValue(class uint16, attr int8) bool
- func ScalerAttr(class uint16) int8
- func ScalerProfile(rows []*axdr.DlmsData, cols []Capture) map[string]Scaler
- func ScalerUnit(d axdr.DlmsData) (int8, uint8, error)
- func Seal(keys *Keys, systemTitle []byte, ic uint32, apdu []byte) ([]byte, error)
- func SerialDevice(address string) (string, bool)
- func ServeHDLCPushes(ctx context.Context, c net.Conn, set HDLCPushConfig, ...)
- func SetSerialOpener(f func(SerialConfig) (io.ReadWriteCloser, error)) (restore func())
- func TextOf(d axdr.DlmsData) string
- func TimeColumn(cols []Capture) (int, bool)
- func TypedData(typ string, v any) (*axdr.DlmsData, error)
- func UnitSymbol(u uint8) string
- func Unprotect(suite Suite, key, ak, systemTitle, payload []byte) (plain []byte, ic uint32, err error)
- func UnprotectKeys(suite Suite, key, bkey, ak, systemTitle, payload, extra []byte) (plain []byte, ic uint32, err error)
- func UnwrapKey(kek, wrapped []byte) ([]byte, error)
- func Value(d axdr.DlmsData, loc *time.Location, asDateTime bool) any
- func WrapKey(kek, key []byte) ([]byte, error)
- type Access
- type AccessItem
- type AccessKind
- type AccessRequest
- type AccessResponse
- type AccessResult
- type Association
- func (a *Association) Access(items ...AccessItem) ([]AccessResult, error)
- func (a *Association) ActionSN(class uint16, base uint16, m int8, param *axdr.DlmsData) (axdr.DlmsData, error)
- func (a *Association) BaseName(class uint16, obis string) (uint16, error)
- func (a *Association) Exchange(apdu []byte) ([]byte, error)
- func (a *Association) GetSN(class uint16, obis string, attr int8) (axdr.DlmsData, error)
- func (a *Association) ReadObjectListSN() error
- func (a *Association) ReadSN(name uint16) (axdr.DlmsData, error)
- func (a *Association) ReadSNParameterized(name uint16, selector uint8, param *axdr.DlmsData) (axdr.DlmsData, error)
- func (a *Association) SetSN(class uint16, obis string, attr int8, v *axdr.DlmsData) error
- func (a *Association) ShortNames() bool
- func (a *Association) WriteSN(name uint16, v *axdr.DlmsData) error
- type AssociationConfig
- type BlockTransfer
- type Broadcaster
- type Capture
- type CertID
- type CertInfo
- type Client
- func (c *Client) Access(items ...AccessItem) ([]AccessResult, error)
- func (c *Client) Association() *Association
- func (c *Client) Close()
- func (c *Client) Connect() error
- func (c *Client) Get(class uint16, obis string, attr int8) (axdr.DlmsData, error)
- func (c *Client) LastIC() uint32
- func (c *Client) MeterSystemTitle() []byte
- func (c *Client) Secure() *SecureTransport
- func (c *Client) SetLastIC(ic uint32)
- func (c *Client) TransferImage(it ImageTransfer) (ImageResult, error)
- type ClientConfig
- type ClientRotationLink
- type CommandAccess
- type CommandRequest
- type Compression
- type CompressionParams
- type Counter
- type ErrorBit
- type Exchange
- type FrameCounterObject
- type GBTAssembler
- type Gateway
- func (l *Gateway) Close()
- func (l *Gateway) Dials() int
- func (l *Gateway) Ensure() error
- func (l *Gateway) Health() GatewayHealth
- func (l *Gateway) Online() int8
- func (l *Gateway) Run(ctx context.Context, every time.Duration)
- func (l *Gateway) Transport(d GatewayDest) gdlms.Transport
- func (l *Gateway) Unreachable() bool
- type GatewayConfig
- type GatewayDest
- type GatewayDown
- type GatewayEvent
- type GatewayHealth
- type HDLCPushConfig
- type HLS
- type ICReservation
- type IdentityCheck
- type ImageResult
- type ImageTransfer
- type InboundConn
- func (ic *InboundConn) Bound() bool
- func (ic *InboundConn) Deliver(h wrapper.Header, apdu []byte) bool
- func (ic *InboundConn) DropHeld()
- func (ic *InboundConn) HoldUnlessBound(n *Notification) bool
- func (ic *InboundConn) IsClosed() bool
- func (ic *InboundConn) SetState(from, to int8) bool
- func (ic *InboundConn) Shut()
- func (ic *InboundConn) TakeHeldOrBind() []*Notification
- func (ic *InboundConn) Transport(client, server int, timeout time.Duration) gdlms.Transport
- type ItemResult
- type KeyRotation
- type KeySet
- type KeyWarning
- type Keys
- type MBusTunnel
- type Notification
- type NotificationValue
- type Object
- type PortClient
- type PortOptions
- type PushCounter
- type PushReport
- type PushSecurityError
- type PushSource
- type PushValue
- type RawSetTransport
- type Request
- type Responder
- func (r *Responder) AnswerThirdParty(t *ThirdPartyTransaction, resp []byte) ([]byte, error)
- func (r *Responder) IsThirdParty(plain []byte) bool
- func (r *Responder) OpenGeneral(apdu, clientST []byte) (plain []byte, ic uint32, ex *Transaction, err error)
- func (r *Responder) OpenGloDed(key, clientST, content []byte, compressionAllowed bool) (plain []byte, ic uint32, compressed bool, err error)
- func (r *Responder) OpenSigned(apdu, clientST []byte) ([]byte, *Transaction, error)
- func (r *Responder) OpenThirdParty(apdu []byte) ([]byte, *ThirdPartyTransaction, error)
- func (r *Responder) SealGeneral(ex *Transaction, policy byte, ic uint32, resp []byte) ([]byte, error)
- func (r *Responder) SealGloDed(policy byte, key []byte, ic uint32, resp []byte) ([]byte, error)
- func (r *Responder) Sign(ex *Transaction, resp []byte) ([]byte, error)
- type ResponderThirdParty
- type Response
- type Result
- type RotationLink
- type RotationMethod
- type RotationState
- type RotationStatus
- type RowScalers
- type Scaler
- type SecureTransport
- func (t *SecureTransport) BroadcastKey() []byte
- func (t *SecureTransport) Challenge() (meterST, stoc []byte)
- func (t *SecureTransport) Exchange(apdu []byte, timeout time.Duration) ([]byte, error)
- func (t *SecureTransport) LastFailure() error
- func (t *SecureTransport) Release() (ciphered, verified bool)
- func (t *SecureTransport) Send(src []byte) error
- func (t *SecureTransport) SendBroadcastIC(apdu []byte, ic uint32) error
- func (t *SecureTransport) SetLogger(l *log.Logger)
- func (t *SecureTransport) SetReception(dc gdlms.DataChannel)
- func (t *SecureTransport) TakeAction() []byte
- func (t *SecureTransport) UsedIC() uint32
- type Security
- type SecurityConfig
- type SecuritySetup
- func (s SecuritySetup) Action(method int8, param *axdr.DlmsData) (*axdr.DlmsData, error)
- func (s SecuritySetup) Activate(bits byte) error
- func (s SecuritySetup) AgreeKeys(sec *Security, ids []byte) (map[byte][]byte, error)
- func (s SecuritySetup) CertificateRequest(kind byte) (*x509.CertificateRequest, error)
- func (s SecuritySetup) Certificates() ([]CertInfo, error)
- func (s SecuritySetup) ExportCertificate(id CertID) (*x509.Certificate, error)
- func (s SecuritySetup) GenerateKeyPair(kind byte) error
- func (s SecuritySetup) ImportCertificate(c *x509.Certificate) error
- func (s SecuritySetup) RemoveCertificate(id CertID) error
- func (s SecuritySetup) TransferKeys(masterKey []byte, keys map[byte][]byte) error
- type SerialConfig
- type SerialSettings
- type Suite
- type ThirdParty
- type ThirdPartyLayer
- type ThirdPartyTransaction
- type Transaction
- type TunnelRecord
Examples ¶
Constants ¶
const ( TagAccessRequest byte = 0xD9 TagAccessResponse byte = 0xDA )
APDU tags of the ACCESS service.
const ( AccessHighPriority uint32 = 1 << 31 AccessConfirmed uint32 = 1 << 30 AccessBreakOnError uint32 = 1 << 29 AccessSelfDescribing uint32 = 1 << 28 )
Bits of the long invoke ID and priority.
const ( ClassData = is15959.ClassData ClassRegister = is15959.ClassRegister ClassExtendedRegister = is15959.ClassExtendedRegister ClassDemandRegister = is15959.ClassDemandRegister ClassProfileGeneric = is15959.ClassProfileGeneric ClassClock = is15959.ClassClock ClassDisconnect = is15959.ClassDisconnect )
Interface classes used here.
const ( GroupNameplate = is15959.GroupNameplate GroupInstantaneous = is15959.GroupInstantaneous GroupEnergy = is15959.GroupEnergy GroupBlockLoad = is15959.GroupBlockLoad GroupDailyLoad = is15959.GroupDailyLoad GroupBilling = is15959.GroupBilling GroupEvents = is15959.GroupEvents GroupProgrammable = is15959.GroupProgrammable GroupScalers = is15959.GroupScalers GroupPush = is15959.GroupPush GroupSecurity = is15959.GroupSecurity GroupCommunication = is15959.GroupCommunication )
Groups a meter can read (settings "groups").
const ( // GatewayMalformed is a gateway prefix from the DCU that does not // parse. GatewayMalformed = "malformed" // GatewayAddressMismatch is an answer from another address than the // meter's, given to the only request waiting. GatewayAddressMismatch = "address-mismatch" // GatewayUnknownAddress is an answer or push from an address no meter // is known at. GatewayUnknownAddress = "unknown-address" )
Kinds of GatewayEvent.
const ( TagGeneralGlo byte = 0xDB TagGeneralDed byte = 0xDC TagGeneralCiphering byte = 0xDD TagGeneralSigning byte = 0xDF )
APDU tags.
const ( KeyGlobalUnicast byte = 0 KeyGlobalBroadcast byte = 1 KeyAuthentication byte = 2 KeyMaster byte = 3 )
Key IDs of identified-key and of the security setup key methods.
const ( ImageNotInitiated = 0 ImageInitiated = 1 ImageVerificationInitiated = 2 ImageVerificationOK = 3 ImageVerificationFailed = 4 ImageActivationInitiated = 5 ImageActivationOK = 6 ImageActivationFailed = 7 )
Image transfer status values (attribute 6).
const ( OpGet = "get" OpSet = "set" OpAction = "action" )
Operations.
const ( MechNone = 0 MechLow = 1 MechHLS = 2 MechMD5 = 3 MechSHA1 = 4 MechGMAC = 5 MechSHA256 = 6 MechECDSA = 7 )
Authentication mechanism IDs (the last arc of the mechanism name).
const ( SecAuthentication byte = 0x10 SecEncryption byte = 0x20 SecBroadcastKey byte = 0x40 // key set: the global broadcast key SecCompressed byte = 0x80 // the protected APDU is V.44 compressed )
Security policy bits of the security control byte.
const ( ContextAuto byte = 0 ContextLN byte = 1 // logical name referencing, no ciphering ContextLNCiphering byte = 3 // logical name referencing with ciphering )
Application contexts the AARQ can propose (the last arc of the application context name, IEC 62056-5-3:2023 7.3.7.1).
const ( CipherServiceSpecific byte = iota CipherGeneralGlo CipherGeneralDed CipherGeneral )
Ciphering forms.
const ( GenKeyIdentified byte = iota GenKeyWrapped GenKeyOnePass GenKeyStatic )
General-ciphering key-info choices we send.
const ( PolicyAuthRequest byte = 0x04 PolicyEncRequest byte = 0x08 PolicySignRequest byte = 0x10 PolicyAuthResponse byte = 0x20 PolicyEncResponse byte = 0x40 PolicySignResponse byte = 0x80 PolicyAuthenticated = PolicyAuthRequest | PolicyAuthResponse PolicyEncrypted = PolicyEncRequest | PolicyEncResponse PolicySigned = PolicySignRequest | PolicySignResponse )
Security policy bits (security setup version 1).
const ( ContextSN byte = 2 ContextSNCiphering byte = 4 )
Application contexts for short name referencing (the last arc).
const ( ConformanceGeneralProtection uint32 = 1 << 22 ConformanceGeneralBlockTransfer uint32 = 1 << 21 ConformanceRead uint32 = 1 << 20 ConformanceWrite uint32 = 1 << 19 ConformanceUnconfirmedWrite uint32 = 1 << 18 ConformanceAttribute0Set uint32 = 1 << 15 ConformancePriorityMgmt uint32 = 1 << 14 ConformanceAttribute0Get uint32 = 1 << 13 ConformanceBlockGetOrRead uint32 = 1 << 12 ConformanceBlockSetOrWrite uint32 = 1 << 11 ConformanceBlockAction uint32 = 1 << 10 ConformanceMultipleReferences uint32 = 1 << 9 ConformanceInformationReport uint32 = 1 << 8 ConformanceDataNotification uint32 = 1 << 7 ConformanceAccess uint32 = 1 << 6 ConformanceParameterizedAccess uint32 = 1 << 5 ConformanceGet uint32 = 1 << 4 ConformanceSet uint32 = 1 << 3 ConformanceSelectiveAccess uint32 = 1 << 2 ConformanceEventNotification uint32 = 1 << 1 ConformanceAction uint32 = 1 << 0 )
Conformance block bits (IEC 62056-5-3:2023 7.3.1, bit 0 the most significant of 24).
const AssociationSNBaseName = 0xFA00
AssociationSNBaseName is the base name of the current association SN object.
const ClassHDLCSetup = 23
ClassHDLCSetup is the IEC HDLC setup interface class (IEC 62056-6-2:2023 4.7.2).
const ClassLimiter = 71
ClassLimiter is the limiter interface class (IEC 62056-6-2:2023 4.5.9).
const ClassSecuritySetup = 64
ClassSecuritySetup is the security setup interface class.
const ClockOBIS = is15959.ClockOBIS
ClockOBIS is the meter clock (class 8).
const DefaultICWindow = 100000
DefaultICWindow is how far ICReservation reserves ahead.
const DefaultSystemTitle = "53474D0000000001"
DefaultSystemTitle is the system title SecurityConfig uses when none is given ("SGM" and a serial number).
const DisconnectControl = is15959.DisconnectControl
DisconnectControl is the disconnect control object (class 70).
const GeneralErrorOBIS = "0.0.97.97.0.255"
GeneralErrorOBIS is the general error object of annex A of EN 13757-1:2021 (Tables A.1 to A.4).
const HDLCSetupInactivity = 8
HDLCSetupInactivity is its inactivity_time_out attribute, in seconds, 0 when not operational (4.7.2.2.8).
const InvokeUnconfirmed byte = 0x01
InvokeUnconfirmed is invoke-id-and-priority for an unconfirmed request: invoke id 1, service class (bit 6) 0, normal priority.
const MaxGBT = maxGBT
MaxGBT bounds an APDU joined from blocks.
const MaxListItems = 64
MaxListItems bounds the items of one request with list (ours).
const RecentPushICs = 64
RecentPushICs bounds the counters of unauthenticated pushes a PushCounter keeps.
const SerialPrefix = "serial://"
SerialPrefix starts an address naming a local serial port.
const TagGBT byte = 0xE0
TagGBT is the general-block-transfer APDU tag.
Variables ¶
var ( // ErrRotationPending: an earlier rotation is not settled; call Resume. ErrRotationPending = errors.New("an earlier key rotation is not settled yet") // ErrRotationRolledBack: the new keys did not work; the old keys are // active (the error wraps the cause). ErrRotationRolledBack = errors.New("the new keys were not taken; the old keys are kept") // ErrRotationUnconfirmed: neither key set works now; both are stored // and Resume tries them again. ErrRotationUnconfirmed = errors.New("neither the new nor the old keys work yet") )
Errors of a key rotation.
var CertEntities = map[string]byte{"server": 0, "client": 1, "ca": 2, "other": 3}
CertEntities names the certificate entities.
var ErrCompressed = errors.New("the APDU is compressed (security control bit 7, ITU-T V.44) where IEC 62056-5-3:2023 has no compression: only general-glo, general-ded and general ciphering with security suite 1 or 2 carry compressed APDUs (5.3.6, Table 26, Table 9)")
ErrCompressed refuses APDUs whose security control has the compression bit set where no compression can be: IEC 62056-5-3:2023 applies V.44 in general-glo, general-ded and general ciphering (5.3.6, Figures 31 and 32) and only with suites 1 and 2 (Table 9).
var ErrCompressionOff = errors.New("the meter sent a V.44 compressed APDU (security control bit 7) and compression is not enabled for it (set compression.enabled, with the meter's V.44 codewords, maxStringLength and history)")
ErrCompressionOff refuses compressed APDUs from a meter whose settings do not enable compression.
var ErrInboundClosed = errors.New("the meter's inbound connection is closed")
ErrInboundClosed is the error of a request on a closed connection.
var ErrNoKeys = errors.New("the DLMS APDU is protected and no key is configured (dlmsKey)")
ErrNoKeys is returned for a protected APDU when no key is configured.
var GeneralErrorBits = []ErrorBit{
{15, "alert_unacknowledged"}, {14, "warning_unacknowledged"}, {13, "indication_unacknowledged"},
{7, "alert_pending"}, {6, "warning_pending"}, {5, "indication_pending"},
}
GeneralErrorBits are the named bits of the general error object.
var KeyNames = map[string]byte{"unicast": KeyGlobalUnicast, "broadcast": KeyGlobalBroadcast, "authentication": KeyAuthentication}
KeyNames name the keys key_transfer and key_agreement change.
var KeyPairs = map[string]byte{"signing": 0, "key-agreement": 1, "tls": 2}
KeyPairs names the key pairs of generate_key_pair and generate_certificate_request.
var MechanismNames = map[string]byte{ "": MechNone, "none": MechNone, "low": MechLow, "hls": MechHLS, "hls-aes": MechHLS, "hls-md5": MechMD5, "hls-sha1": MechSHA1, "high": MechGMAC, "hls-gmac": MechGMAC, "gmac": MechGMAC, "hls-sha256": MechSHA256, "hls-ecdsa": MechECDSA, "ecdsa": MechECDSA, }
MechanismNames maps the names of authentication mechanisms (as SecurityConfig.Authentication takes them) to their IDs.
Functions ¶
func BitsSet ¶
BitsSet lists the bit numbers set in a bit string (bit 0 first, the most significant bit of the first byte), as IS 15959 numbers the event status word.
func CheckHDLCAddresses ¶
CheckHDLCAddresses checks the addresses of a connection (IEC 62056-46 6.4.2.3, Tables 3 and 4): a client address of one octet that is neither no-station nor all-station; an upper address naming one logical device (the management logical device 1, or 16 up to below all-station); a lower address naming one physical device (16 up to below CALLING), or CALLING when the meter called us.
func ClockStatus ¶
ClockStatus is the clock_status octet of a 12-octet COSEM date-time in hex (its last octet), unless it is 0xFF, not specified.
func CommError ¶
CommError reports errors after which the association is dropped: all but the meter refusing a get, set or action, or a parameter.
func DateTime ¶
DateTime decodes a COSEM date-time (12-byte octet string, as hex). An unspecified deviation (0x8000) means the meter's local time in loc; a given deviation is minutes of UTC minus local time.
func DefaultClientAddress ¶
DefaultClientAddress is the client address of an association by its mechanism, as IS 15959 numbers them (table 3 of Part 1, table 2 of Part 2): 16 the public client without authentication, 32 the meter reader with low-level security, 48 the utility settings client with HLS.
func DefaultProfile ¶
DefaultProfile is the profile of a meter without a "profile" setting.
func DescribeEvent ¶
DescribeEvent adds what IS 16444 readers need of an event code to its log row: the key applications label it by, its compartment, occurrence or restoration, the condition it belongs to and whether we class it as a tamper (is15959.EventInfo). Codes no part defines get none of these.
func DropOctets ¶
DropOctets returns b without the octets at the given (ascending) positions.
func EncodeAXDR ¶
EncodeAXDR returns the correct A-XDR encoding of d (r), gosem's encoding of it (g) and the positions in g of the octets gosem adds.
func EncodeDateTime ¶
EncodeDateTime is the inverse of DateTime for loc: a COSEM date-time (IEC 62056-6-2:2023 4.1.6.1) in local time with the deviation not specified, hundredths 0, and clock_status bit 7 (daylight saving active) set when loc is on daylight saving time at t.
func EncodeResponse ¶
EncodeResponse builds a response-normal (the meter's side): a GET with data, or a result code.
func EncodeUnconfirmedSet ¶
func EncodeUnconfirmedSet(class uint16, obis string, attr int8, data *axdr.DlmsData) ([]byte, error)
EncodeUnconfirmedSet encodes a set-request-normal for one attribute that asks for no answer (invoke-id-and-priority with service class 0), as a broadcast set sends it.
func GeneralErrorFlags ¶
GeneralErrorFlags names the set bits of a general error object value; reserved bits that are set are named "reserved_<bit>".
func IsGatewayDown ¶
IsGatewayDown reports an error of an unreachable DCU (retrying the meter does not help).
func IsGeneralError ¶
IsGeneralError reports the general error object's value attribute.
func IsTimeColumn ¶
IsTimeColumn reports a capture object holding a date-time that times a profile's entries: the clock's time (IEC 62056-6-2:2023 4.5.1), or the time stamp of the billing period (6.2.3: a Data object, or a register or extended register with scaler 0 and no unit).
func KeyTransferItem ¶
KeyTransferItem is one {key_id, wrapped key} of key_transfer.
func LimiterThreshold ¶
LimiterThreshold reports the limiter attributes holding thresholds (threshold_active, threshold_normal, threshold_emergency: 3, 4, 5), which are in the units of the value the limiter monitors.
func MechanismAlgorithm ¶
MechanismAlgorithm describes the cryptography of an authentication mechanism for a crypto policy (iotsec.CryptoPolicy): mechanism 2 is AES-128 in ECB mode, 3 MD5, 4 SHA-1, 5 AES-GMAC, 6 SHA-256 and 7 ECDSA. none and low use none (ok is false).
func MonitoredValue ¶
MonitoredValue reads a limiter's monitored_value: {class_id, logical_name, attribute_index}.
func NameOf ¶
NameOf returns the catalogue name of an attribute; for an object the catalogue does not list, the name the OBIS model derives (IEC 62056-6-1:2023, package obis) with the class's attribute suffix; and the OBIS code for a code without a standard meaning (manufacturer, utility, country specific or reserved). The class picks the row where one code names objects of several classes (IEC 62056-6-2:2023 clause 6).
func NeedsPassword ¶
NeedsPassword reports the mechanisms that need a password or secret: low-level security and HLS mechanisms 2, 3, 4 and 6.
func OBISFromHex ¶
OBISFromHex writes a logical name given as 12 hex digits (as gosem gives octet strings) as a dotted OBIS code.
func Open ¶
Open removes general-glo-ciphering (an APDU in the clear comes back as it is, with a nil system title).
func OpenSerialLine ¶
OpenSerialLine opens the line of a meter on device: with optical, the IEC 62056-21 mode E sign-on and switch to HDLC first.
func PEMCertificates ¶
func PEMCertificates(v string) []*x509.Certificate
PEMCertificates are the certificates in v (inline or a file path), in order; blocks of other types are skipped.
func ParseOBIS ¶
ParseOBIS reads an OBIS code written as six numbers 0 to 255 separated by ".", "-" or ":".
func ParsePushObjectList ¶
ParsePushObjectList reads a push setup's push_object_list (class 40 attribute 2) as columns named by the catalogue; nil when an entry is not in the expected form.
func PointName ¶
PointName names an attribute as the catalogue does (catalogue name, OBIS model name, else the code).
func PolicyBits ¶
PolicyBits is the version 1 security_policy for an APDU policy and signing.
func ProfileRow ¶
ProfileRow is a profile entry as written: each capture object's value by its name, register values scaled by the meter's scaler_unit with the units under "units", an event code named, and the entry's time from its first time column (zero when it has none).
func Protect ¶
func Protect(suite Suite, policy byte, key, ak, systemTitle []byte, ic uint32, plain []byte) ([]byte, error)
Protect applies the security policy to plain, returning SC ‖ IC ‖ body.
Example ¶
The security suite 0 example of the DLMS UA Green Book: a GET request authenticated and encrypted with AES-GCM-128 under system title 4D4D4D0000BC614E and invocation counter 01234567.
package main
import (
"encoding/hex"
"fmt"
"github.com/cB-Sigma/dlms/cosem"
)
func main() {
hexb := func(s string) []byte {
b, err := hex.DecodeString(s)
if err != nil {
panic(err)
}
return b
}
p, err := cosem.Protect(0, cosem.SecAuthentication|cosem.SecEncryption,
hexb("000102030405060708090A0B0C0D0E0F"), hexb("D0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF"),
hexb("4D4D4D0000BC614E"), 0x01234567, hexb("C0010000080000010000FF0200"))
if err != nil {
panic(err)
}
fmt.Printf("%X\n", p)
}
Output: 3001234567411312FF935A47566827C467BC7D825C3BE4A77C3FCC056B6B
func PushSetupOf ¶
func PushSetupOf(sp *is15959.Spec, items []*axdr.DlmsData, read func(obis string) ([]is15959.Column, bool)) (*is15959.PushSetup, error)
PushSetupOf finds the push setup of a profile a notification came from: the element captured from a class 40 logical name names it; otherwise the one push setup whose capture list has as many elements. read, when not nil, gives the push_object_list read from the meter for a push setup, which then replaces the profile's capture list.
func PushTag ¶
PushTag reports APDUs a meter sends unasked: data-notification, general-glo-ciphering (a protected push) and general block transfer.
func RangeDescriptor ¶
RangeDescriptor is the selective access by range of a profile's buffer (IEC 62056-6-2:2023 4.3.6.2.9, access selector 1): restricted by the profile's own time column (a capture_object_definition with data index 0), from and to as date-time octet strings in the meter's local time, and every column (an empty selected_values).
func ReadCapturePeriod ¶
ReadCapturePeriod reads a profile's capture_period (IEC 62056-6-2:2023 profile generic, class 7 attribute 4, seconds): 0 when it is asynchronous or cannot be read.
func ReadInvocationCounter ¶
func ReadInvocationCounter(tr gdlms.Transport, obis string, timeout time.Duration, name, where string) (uint32, error)
ReadInvocationCounter reads the frame counter a meter keeps for a client (class 1 value attribute at obis) through a public association on tr, which it closes. name and where name the meter in errors.
func ReadProfileRange ¶
func ReadProfileRange(c gdlms.Client, profile string, tc Capture, from, to time.Time, loc *time.Location) ([]*axdr.DlmsData, error)
ReadProfileRange reads the entries of a profile's buffer from from to to, by its time column tc (selective access by range).
func ReadScaled ¶
ReadScaled reads one attribute. A register's value (class 3 or 4 attribute 2, class 5 attributes 2 and 3) is scaled by its scaler_unit (attribute 3, or 4 for class 5), whose unit is returned; clock values and 12-byte date-times are returned as RFC 3339 text.
func Readable ¶
Readable is Value for an object's own reading: an octet string whose bytes are all printable ASCII is text (IS 15959 keeps the serial number, manufacturer name, device ID and firmware version in octet strings), a 12-byte one that is a valid COSEM date-time (the capture time of a maximum demand register) is a time, and any other stays hexadecimal (keys, system titles, bit fields). SigmaM2M finding F-2600 (PROVENANCE.md).
func Rejected ¶
Rejected reports a DLMS error that concerns one object (the meter refused the request) rather than the link.
func SNMethodOffset ¶ added in v0.2.0
SNMethodOffset is the offset of method m of class from the object's base name.
func ScaledValue ¶
ScaledValue reports the attributes scaled by the scaler_unit: the value of a register or extended register, and the current and last average values of a demand register.
func ScalerAttr ¶
ScalerAttr is the scaler_unit attribute of a class: 3 for the register and extended register, 4 for the demand register (IEC 62056-6-2:2023 4.3.2 to 4.3.4); 0 for classes without one.
func ScalerProfile ¶
ScalerProfile reads the scalers a scaler profile's entry holds (IS 15959 Part 1 annexes C to G, Part 2 and 3 "scaler profile" clauses): the scaler_unit of each register of the profile it belongs to, by the register's logical name, from the last entry of rows.
func ScalerUnit ¶
ScalerUnit decodes a register's scaler_unit attribute.
func Seal ¶
Seal protects an APDU with general-glo-ciphering: authenticated and encrypted when the keys have an authentication key, encrypted only otherwise.
func SerialDevice ¶
SerialDevice returns the port an address names (serial:///dev/ttyUSB0, serial://COM3), and whether it names one.
func ServeHDLCPushes ¶
func ServeHDLCPushes(ctx context.Context, c net.Conn, set HDLCPushConfig, handle func(from net.Addr, apdu []byte))
ServeHDLCPushes reads pushes in HDLC frames from a connection a meter (or a converter in front of it) opened, until it closes or stays silent for the inactivity time, and hands each APDU, its LLC header removed, to handle. UI frames are taken as they come (segmented ones joined); I frames are acknowledged with RR. It closes c, also when ctx ends.
func SetSerialOpener ¶
func SetSerialOpener(f func(SerialConfig) (io.ReadWriteCloser, error)) (restore func())
SetSerialOpener replaces the function that opens local serial ports (goburrow/serial by default): for tests with a simulated line, or a platform with its own serial driver. It returns a function restoring the previous one.
func TextOf ¶
TextOf returns a string or octet string's text (octet strings holding printable characters are read as text).
func TimeColumn ¶
TimeColumn returns the first time column of a profile.
func UnitSymbol ¶
UnitSymbol is the symbol of a COSEM unit code (IEC 62056-6-2 unit table), empty for codes without one.
func Unprotect ¶
func Unprotect(suite Suite, key, ak, systemTitle, payload []byte) (plain []byte, ic uint32, err error)
Unprotect checks and removes the protection from SC ‖ IC ‖ body sent by the holder of systemTitle.
func UnprotectKeys ¶
func UnprotectKeys(suite Suite, key, bkey, ak, systemTitle, payload, extra []byte) (plain []byte, ic uint32, err error)
UnprotectKeys is unprotectAAD that opens APDUs protected with the broadcast key (security control bit 6) with bkey. Compressed content is refused: callers where compression exists use unprotectGeneral.
Types ¶
type Access ¶
type Access struct {
Selector byte
// Range: the restricting column (default the clock 0.0.1.0.0.255,
// class 8, attribute 2) and the date-times from and to.
RestrictClass uint16
RestrictOBIS string
RestrictAttr int8
From, To time.Time
Loc *time.Location
// Entry: from and to entry (1-based; to 0 is the last).
FromEntry, ToEntry uint32
}
Access is a selective access of a GET (IEC 62056-6-2:2023 profile generic buffer: selector 1 by range, 2 by entry).
type AccessItem ¶ added in v0.2.0
type AccessItem struct {
Kind AccessKind
Class uint16
OBIS string
// ID is the attribute (get, set) or method (action).
ID int8
// Selector and Parameters are the selective access of the "with
// selection" kinds.
Selector uint8
Parameters *axdr.DlmsData
// Data is the value of a set or the parameter of an action; nil sends
// null-data (always for a get).
Data *axdr.DlmsData
}
AccessItem is one operation of an ACCESS request.
type AccessKind ¶ added in v0.2.0
type AccessKind byte
AccessKind is the operation of one access request specification.
const ( AccessGet AccessKind = 1 AccessSet AccessKind = 2 AccessAction AccessKind = 3 AccessGetWithSelection AccessKind = 4 AccessSetWithSelection AccessKind = 5 )
Access request specifications.
func (AccessKind) String ¶ added in v0.2.0
func (k AccessKind) String() string
type AccessRequest ¶ added in v0.2.0
type AccessRequest struct {
// InvokeID is the long invoke ID and priority.
InvokeID uint32
// Time, when not nil, is the request's date-time (12 octets).
Time []byte
Items []AccessItem
}
AccessRequest is an ACCESS request.
func DecodeAccessRequest ¶ added in v0.2.0
func DecodeAccessRequest(apdu []byte) (*AccessRequest, error)
DecodeAccessRequest reads an ACCESS request APDU.
func (*AccessRequest) Encode ¶ added in v0.2.0
func (r *AccessRequest) Encode() ([]byte, error)
Encode is the APDU of the request.
type AccessResponse ¶ added in v0.2.0
type AccessResponse struct {
InvokeID uint32
Time []byte
Results []AccessResult
}
AccessResponse is an ACCESS response.
func DecodeAccessResponse ¶ added in v0.2.0
func DecodeAccessResponse(apdu []byte) (*AccessResponse, error)
DecodeAccessResponse reads an ACCESS response APDU.
func (*AccessResponse) Encode ¶ added in v0.2.0
func (r *AccessResponse) Encode() ([]byte, error)
Encode is the APDU of the response (the optional copy of the request's specifications is left out).
type AccessResult ¶ added in v0.2.0
type AccessResult struct {
Kind AccessKind
Result byte
Data axdr.DlmsData
}
AccessResult is the outcome of one operation: the result code (a data-access-result or action-result, 0 success) and the data (the value read, the action's return parameter, or null-data).
func (AccessResult) String ¶ added in v0.2.0
func (r AccessResult) String() string
String names the result code.
type Association ¶
type Association struct {
Client gdlms.Client
Secure *SecureTransport
Raw *RawSetTransport
// Link is the supporting layers under the secure transport.
Link gdlms.Transport
// contains filtered or unexported fields
}
Association is an open application association: gosem's client over our secure transport.
func Associate ¶
func Associate(cfg AssociationConfig) (*Association, error)
Associate opens an association. On failure the returned association, when not nil, still tells the invocation counters used (Secure.usedIC) so the next attempt never repeats one.
func (*Association) Access ¶ added in v0.2.0
func (a *Association) Access(items ...AccessItem) ([]AccessResult, error)
Access is Client.Access on this association.
func (*Association) ActionSN ¶ added in v0.2.0
func (a *Association) ActionSN(class uint16, base uint16, m int8, param *axdr.DlmsData) (axdr.DlmsData, error)
ActionSN invokes method m of an object of class at base name base (a read with parameterized access, selector 0) and returns the method's return data.
func (*Association) BaseName ¶ added in v0.2.0
func (a *Association) BaseName(class uint16, obis string) (uint16, error)
BaseName is the base name of an object, from the object list (read first if needed).
func (*Association) Exchange ¶ added in v0.2.0
func (a *Association) Exchange(apdu []byte) ([]byte, error)
Exchange sends one APDU on the association and returns the meter's answer, with the association's protection applied both ways (the services gosem does not offer: ACCESS, short name referencing).
func (*Association) GetSN ¶ added in v0.2.0
GetSN reads attribute attr of a logical name through its base name.
func (*Association) ReadObjectListSN ¶ added in v0.2.0
func (a *Association) ReadObjectListSN() error
ReadObjectListSN reads the association SN object list (base name, class, version, logical name of each object) and keeps it for GetSN.
func (*Association) ReadSN ¶ added in v0.2.0
func (a *Association) ReadSN(name uint16) (axdr.DlmsData, error)
ReadSN reads the variable at base name name (an attribute's, base + 8(i-1)) with a ReadRequest, following data blocks.
func (*Association) ReadSNParameterized ¶ added in v0.2.0
func (a *Association) ReadSNParameterized(name uint16, selector uint8, param *axdr.DlmsData) (axdr.DlmsData, error)
ReadSNParameterized reads a variable with parameterized access: a selective access of an attribute (a profile's buffer by range is selector 1) or, selector 0, a method that returns data.
func (*Association) SetSN ¶ added in v0.2.0
SetSN writes attribute attr of a logical name through its base name.
func (*Association) ShortNames ¶ added in v0.2.0
func (a *Association) ShortNames() bool
ShortNames reports an association that uses short name referencing.
type AssociationConfig ¶
type AssociationConfig struct {
// Transport is the supporting layers for the client address (a
// wrapper, HDLC or gateway transport); Associate owns it from now on.
Transport gdlms.Transport
// Mechanism is the authentication mechanism (MechNone to MechECDSA).
// Password is the low-level password (MechLow).
Mechanism byte
Password []byte
// HLS holds the mechanism's secret and keys (mechanisms 2 to 7) and
// the APDU protection (Security) of the association.
HLS *HLS
// FirstIC is the invocation counter the association starts at (see
// ICReservation and ReadInvocationCounter).
FirstIC uint32
// ExpectSystemTitle, when set, is the meter's system title: an AARE
// naming another is refused.
ExpectSystemTitle []byte
// Timeout bounds each request (default 10s).
Timeout time.Duration
// Writes, when set, counts the set and action requests sent.
Writes *atomic.Int64
// Alive, when set, says whether the link is still up when a request
// is sent (a request sent on a link known closed never arrived).
Alive func() bool
// Check, when set, runs on the open association before it is
// returned (an identity check, say); an error releases it.
Check func(gdlms.Client) error
// Policy, when set, is asked whether the mechanism's algorithm may be
// used (Use names the use) before anything is sent.
Policy iotsec.CryptoPolicy
Use string
// Name names the meter and Where its address in errors.
Name, Where string
// Conformance, when not 0, is the conformance block proposed instead
// of the default (Conformance* bits).
Conformance uint32
}
AssociationConfig is what Associate needs.
type BlockTransfer ¶
type BlockTransfer struct {
Size int
// contains filtered or unexported fields
}
BlockTransfer is one request's general block transfer on a request/answer link; a zero Size sends APDUs whole (answers in blocks are still joined).
func (*BlockTransfer) Blocks ¶
func (b *BlockTransfer) Blocks() (sent, received int)
Blocks reports how many blocks we sent and how many of the meter's general-block-transfer APDUs carried data.
func (*BlockTransfer) Receive ¶
func (b *BlockTransfer) Receive(w []byte) (next, answer []byte, err error)
Receive takes the meter's APDU: the next APDU to send (our next block or an acknowledgement), or the whole answer once it is complete.
func (*BlockTransfer) Send ¶
func (b *BlockTransfer) Send(apdu []byte) []byte
Send starts sending a (protected) APDU: whole, or its first block.
type Broadcaster ¶
type Broadcaster struct {
Send func(apdu []byte) error
Security Security // suite, policy, systemTitle, ak, broadcastKey, ciphering
Password []byte // low-level security; nil: no authentication
IC uint32 // next invocation counter under the broadcast key
// contains filtered or unexported fields
}
Broadcaster runs an unconfirmed application association with a group of meters or all meters (IEC 62056-5-3:2023 4.1.5, 7.2.4.3, 7.3.2.1): the AARQ proposes response-allowed FALSE and nothing is ever answered, so only the client can authenticate (none or low-level security), only the client's system title is sent (4.1.3.4), and only unconfirmed services are used. Everything is protected with the global broadcast key: the initiate request and service-specific or general-glo APDUs with the key-set bit, general-ciphering with identified-key 1 (the key- set bit 0) and an empty recipient-system-title (6.x, Recipient_System_ Title). Where the APDUs go (a group or the all-station address) is the supporting layer's business: send delivers one APDU there.
func (*Broadcaster) Associate ¶
func (b *Broadcaster) Associate() error
Associate sends the AARQ of the unconfirmed AA; no AARE is awaited.
func (*Broadcaster) Release ¶
func (b *Broadcaster) Release() error
Release sends the RLRQ, carrying the initiate request protected as in the AARQ; an unconfirmed AA's release is not answered.
func (*Broadcaster) Request ¶
func (b *Broadcaster) Request(apdu []byte) error
Request sends an unconfirmed set or action request under the broadcast key in the configured ciphering form.
type Capture ¶
Capture is one column of a profile: the attribute it captures and its catalogue name.
func ParseCaptureObjects ¶
ParseCaptureObjects reads a profile's capture_objects (class 7 attribute 3): {class_id, logical_name, attribute_index, data_index} per column; columns are named by the catalogue.
type CertID ¶
type CertID struct {
BySerial bool
Entity, Type byte
SystemTitle []byte
Serial *big.Int
Issuer []byte // DER issuer name
}
CertID identifies a certificate on the meter: by entity, type and system title, or by serial number and issuer.
type CertInfo ¶
type CertInfo struct {
Entity byte `json:"entity"`
Type byte `json:"type"`
Serial string `json:"serial"`
Issuer string `json:"issuer"`
Subject string `json:"subject"`
}
CertInfo is one entry of the certificates attribute.
type Client ¶
type Client struct {
Config ClientConfig
// contains filtered or unexported fields
}
Client is a client of one meter. It is not safe for concurrent use: callers run one exchange at a time.
Example ¶
A client with HLS-GMAC (mechanism 5) and authenticated and encrypted APDUs under a dedicated key reads a voltage register from a meter over the wrapper on TCP. The meter's frame counter for the client is read first through the public client, so the association starts past it. (It needs a meter, so it is compiled but not run; the dlms-sim module runs the same steps against its simulated meter.)
package main
import (
"fmt"
"time"
gdlms "gitlab.com/circutor-library/gosem/pkg/dlms"
"github.com/cB-Sigma/dlms/cosem"
"github.com/cB-Sigma/dlms/wrapper"
)
func main() {
key := []byte("0123456789ABCDEF")
ak := []byte("FEDCBA9876543210")
addr := "192.0.2.10:4059"
sec := cosem.SecurityConfig{Name: "M1", Authentication: "hls-gmac", Security: "authenticated-encrypted",
BlockCipherKey: fmt.Sprintf("%X", key), AuthenticationKey: fmt.Sprintf("%X", ak), DedicatedKey: true}
hls, _, err := sec.Build()
if err != nil {
panic(err)
}
c := cosem.NewClient(cosem.ClientConfig{
Transport: func(client int) (gdlms.Transport, error) {
return wrapper.New("tcp", addr, client, 1, 5*time.Second)
},
ClientAddress: cosem.DefaultClientAddress(cosem.MechGMAC), // 48
HLS: hls,
InvocationCounter: &cosem.FrameCounterObject{OBIS: "0.0.43.1.3.255"},
Name: "M1", Where: addr,
})
if err := c.Connect(); err != nil {
panic(err)
}
defer c.Close()
v, err := c.Get(3, "1.0.32.7.0.255", 2)
if err != nil {
panic(err)
}
s, err := cosem.ReadScaler(c.Association().Client, 3, "1.0.32.7.0.255")
if err != nil {
panic(err)
}
n, _ := cosem.Number(v)
fmt.Println(cosem.Scaled(n, s.Exponent), s.Unit)
}
Output:
func NewClient ¶
func NewClient(cfg ClientConfig) *Client
NewClient returns a client; nothing is sent until Connect.
func (*Client) Access ¶ added in v0.2.0
func (c *Client) Access(items ...AccessItem) ([]AccessResult, error)
Access sends one ACCESS request (confirmed, normal priority) on the open association and returns one result per item, in order. An item the meter refused has a non-zero Result; the error is for the exchange itself.
func (*Client) Association ¶
func (c *Client) Association() *Association
Association is the open association, nil when there is none.
func (*Client) Close ¶
func (c *Client) Close()
Close releases the open association, if any, and disconnects.
func (*Client) Connect ¶
Connect opens an association with the current settings, closing any open one first.
func (*Client) LastIC ¶
LastIC is the next invocation counter the client would use; SetLastIC sets it (a counter kept elsewhere).
func (*Client) MeterSystemTitle ¶
MeterSystemTitle is the system title the meter named in its first association (nil before).
func (*Client) Secure ¶
func (c *Client) Secure() *SecureTransport
Secure is the secure transport of the last association attempted.
func (*Client) TransferImage ¶ added in v0.2.0
func (c *Client) TransferImage(it ImageTransfer) (ImageResult, error)
TransferImage sends an image to the meter on the open association.
type ClientConfig ¶
type ClientConfig struct {
// Transport opens the supporting layers for a client address.
Transport func(client int) (gdlms.Transport, error)
// ClientAddress is the association's client address.
ClientAddress int
// HLS is the authentication and APDU protection (SecurityConfig.Build);
// it is read at every Connect, so a key change takes effect on the
// next association. Password is the low-level password.
HLS *HLS
Password []byte
// InvocationCounter, when set, is read before each protected
// association.
InvocationCounter *FrameCounterObject
// Reserve, when set, raises an association's first invocation counter
// to a stored reservation and keeps the reservation ahead of it
// (ICReservation.Reserve); first is true until the client has used a
// counter.
Reserve func(ic uint32, first bool) (uint32, error)
// ExpectSystemTitle is the meter's system title; when nil, the one it
// names in its first association is expected afterwards.
ExpectSystemTitle []byte
// Timeout bounds each request (default 10s).
Timeout time.Duration
// Writes, Alive, Check, Policy and Use are as in AssociationConfig.
Writes *atomic.Int64
Alive func() bool
Check func(gdlms.Client) error
Policy iotsec.CryptoPolicy
Use string
// Name and Where name the meter and its address in errors.
Name, Where string
// Conformance is as in AssociationConfig.
Conformance uint32
}
ClientConfig configures a Client.
type ClientRotationLink ¶ added in v0.3.0
ClientRotationLink is a RotationLink over a Client: Open sets the keys of Client.Config.HLS.Security (so the client keeps the last keys opened) and connects; Check reads security_policy of the security setup object.
func (*ClientRotationLink) Agree ¶ added in v0.3.0
func (l *ClientRotationLink) Agree(ids []byte) (KeySet, error)
Agree runs key_agreement on the open association with the client's signing keys and system title.
func (*ClientRotationLink) Check ¶ added in v0.3.0
func (l *ClientRotationLink) Check() error
Check reads security_policy (attribute 2) through the association.
func (*ClientRotationLink) Close ¶ added in v0.3.0
func (l *ClientRotationLink) Close()
Close closes the client's association.
func (*ClientRotationLink) Open ¶ added in v0.3.0
func (l *ClientRotationLink) Open(keys KeySet) error
Open applies keys to the client's security and associates.
type CommandAccess ¶
type CommandAccess struct {
Selector string `json:"selector"`
From string `json:"from"`
To string `json:"to"`
FromEntry uint32 `json:"fromEntry"`
ToEntry uint32 `json:"toEntry"`
Restrict *struct {
Class int `json:"class"`
OBIS string `json:"obis"`
Attribute int `json:"attribute"`
} `json:"restrict"`
}
CommandAccess is the selective access of a dlms command.
type CommandRequest ¶
type CommandRequest struct {
Op string `json:"op"` // get (default), set or action
Class int `json:"class"`
OBIS string `json:"obis"`
Attribute *int `json:"attribute"` // get, set: 1 to 127, default 2
Method int `json:"method"` // action: the method id
Value string `json:"value"` // set: the value; action: the parameters (optional); A-XDR in hex
// Access is the selective access of a get: {"selector": "range",
// "from", "to" (RFC 3339), "restrict": {"class", "obis",
// "attribute"}} or {"selector": "entry", "fromEntry", "toEntry"}.
Access *CommandAccess `json:"access"`
// List adds further attributes (get, set) or methods (action) of the
// same operation, each {"class", "obis", "attribute" or "method",
// "value", "access"}; the request then goes "with list".
List []CommandRequest `json:"list,omitempty"`
}
CommandRequest is a DLMS request as an M-Bus application takes it: a GET or SET of one attribute.
func (CommandRequest) Request ¶
func (b CommandRequest) Request() (Request, error)
Request checks the command and builds its request (invoke-id 0).
type Compression ¶
type Compression struct {
Enabled bool `json:"enabled"`
CompressRequests bool `json:"compressRequests,omitempty"`
Codewords int `json:"codewords,omitempty"`
MaxStringLength int `json:"maxStringLength,omitempty"`
History int `json:"history,omitempty"`
}
Compression is a meter's V.44 setting.
func (*Compression) Apply ¶
func (c *Compression) Apply(meterID string, sec *Security) error
Apply checks the setting against the security settings and stores it in sec. A nil or disabled setting leaves compression off.
func (*Compression) Params ¶ added in v0.3.0
func (c *Compression) Params() (*CompressionParams, error)
Params checks a V.44 setting and returns it in the form Responder and Security use (Apply does the same and also checks it against a client's security settings).
type CompressionParams ¶
type CompressionParams struct {
// contains filtered or unexported fields
}
CompressionParams is the checked setting a secure transport uses.
type Counter ¶
type Counter struct {
Store iotsec.Store
Name string // the meter, in errors
// contains filtered or unexported fields
}
Counter hands out the invocation counters of the APDUs a client protects for one meter (general-glo-ciphering never reuses a counter with a key): each counter is stored before it is used, so a restart continues above it. The stored value is {"ic": n}.
type ErrorBit ¶
ErrorBit is one named bit of the general error object of EN 13757-1:2021 10.3.2 (0.b.97.97.0.255, class 1, unsigned16; annex A lists it for every basic meter): per condition (alert, warning, indication) a non-acknowledged bit (15, 14, 13) and a pending bit (7, 6, 5); the other bits are reserved.
type Exchange ¶
type Exchange struct {
Req Request
// contains filtered or unexported fields
}
Exchange runs one request.
func (*Exchange) Outcome ¶
Outcome is what a finished exchange writes: the attribute's point and value (a GET that brought data; empty otherwise) and the dlmsResult record.
type FrameCounterObject ¶
FrameCounterObject is the object holding a client's invocation counter in the meter (class 1, value attribute), read through an unauthenticated association of ClientAddress (default 16, the public client) before a protected association, so the client's counter never falls behind the meter's.
type GBTAssembler ¶
type GBTAssembler struct {
// contains filtered or unexported fields
}
GBTAssembler joins one sender's blocks.
type Gateway ¶
type Gateway struct {
// contains filtered or unexported fields
}
Gateway is the shared connection to a DCU and its health.
func NewGateway ¶
func NewGateway(cfg GatewayConfig) *Gateway
NewGateway prepares a gateway; nothing is dialled until a transport connects or Ensure is called.
func (*Gateway) Close ¶
func (l *Gateway) Close()
Close closes the DCU's connection and waits for its reader.
func (*Gateway) Ensure ¶
Ensure opens the DCU's connection if it is not open. After a failed attempt, requests within the DCU's timeout fail at once with the same error instead of each dialling again.
func (*Gateway) Health ¶
func (l *Gateway) Health() GatewayHealth
Health reports the DCU's connection state.
func (*Gateway) Online ¶
Online reports the DCU's last known state: -1 unknown, 0 unreachable, 1 connected.
func (*Gateway) Run ¶
Run keeps trying an unreachable DCU every interval until ctx ends, so its meters' state is known without waiting for their reads.
func (*Gateway) Transport ¶
func (l *Gateway) Transport(d GatewayDest) gdlms.Transport
Transport is a gosem transport to a meter behind the DCU. Connect joins the DCU's connection (dialling it when needed); Disconnect ends the association's use of it without closing it.
func (*Gateway) Unreachable ¶
Unreachable reports whether the DCU's last connection attempt failed.
type GatewayConfig ¶
type GatewayConfig struct {
// ID names the DCU in messages.
ID string
// Address is the host:port of the DCU's wrapper port, Network tcp
// (default) or udp.
Address, Network string
// MaxOutstanding is how many requests may wait for an answer at once,
// across its meters (default 1: the meters in turn).
MaxOutstanding int
// Timeout bounds connecting (default 10s). After a failed attempt,
// requests within it fail at once with the same error.
Timeout time.Duration
// Dial opens the connection (default net.DialTimeout).
Dial func(network, address string, timeout time.Duration) (net.Conn, error)
// Logger receives debug and warning lines (nil: none).
Logger *slog.Logger
// Event receives GatewayEvents (nil: logged only).
Event func(GatewayEvent)
// Push receives an APDU a meter sent unasked through the DCU: pre is
// its gateway prefix (nil when it came without one), src its source
// wPort (the logical device in logical-device mode).
Push func(pre *gateway.Prefix, src uint16, apdu []byte)
// HasMeter reports whether a gateway-mode meter is configured at a
// network and physical address (pushes some DCUs forward as answers
// are recognised by it).
HasMeter func(network byte, address []byte) bool
// Health is called after every connection attempt, outside the
// gateway's locks, with the state before it (-1 unknown, 0
// unreachable, 1 connected) and the attempt's error.
Health func(was int8, err error)
}
GatewayConfig configures a Gateway.
type GatewayDest ¶
type GatewayDest struct {
Logical bool
Network byte
Address []byte
Client, Server uint16
// Name names the meter in messages.
Name string
// Timeout bounds each request (default 20s).
Timeout time.Duration
}
GatewayDest names one association's peer behind a DCU: a logical device of the DCU (Logical, at Server) or a meter at a network and physical address (gateway mode).
type GatewayDown ¶
type GatewayDown struct {
// contains filtered or unexported fields
}
GatewayDown is the error of a DCU that cannot be reached.
func (*GatewayDown) Error ¶
func (e *GatewayDown) Error() string
Error says which DCU is down and why.
type GatewayEvent ¶
type GatewayEvent struct {
Kind, Message, Detail string
}
GatewayEvent is something about a DCU's traffic an application may want to show: Kind is one of the Gateway constants, Message says what happened, and Detail is the address concerned.
type GatewayHealth ¶
type GatewayHealth struct {
Online int8 // -1 unknown, 0 unreachable, 1 connected
LastErr string
Since time.Time // when Online last changed
LastOK time.Time // the last successful connection
}
GatewayHealth is a DCU's connection state.
type HDLCPushConfig ¶
type HDLCPushConfig struct {
// Answer answers a Hayes modem's RING (ATA, then CONNECT; IEC 62056-42
// A.2.3) before anything else; Identify runs the identification
// service (6.3.3) and refuses another stack than COSEM; Trigger sends
// the empty UI frame that gives the calling meter the right to talk,
// with server addresses of AddressSize octets (1, 2 or 4).
Answer, Identify, Trigger bool
AddressSize int
// Inactivity closes a connection silent this long (default 10m).
Inactivity time.Duration
// Logger receives the refusals (nil: none).
Logger *slog.Logger
}
HDLCPushConfig is how ServeHDLCPushes takes a call.
type HLS ¶
type HLS struct {
Mechanism byte
Secret []byte
Security Security
SignKey *ecdsa.PrivateKey // ours (mechanism 7)
MeterKey *ecdsa.PublicKey // the meter's (mechanism 7)
}
HLS is everything passes 3 and 4 need.
func (*HLS) Answer ¶ added in v0.2.0
func (h *HLS) Answer(systemTitle, peerST, challenge, ownChallenge []byte, ic uint32) ([]byte, error)
Answer is f(challenge), the HLS pass 3 or 4 answer of the party whose system title is systemTitle to the challenge of the party peerST, which answers ownChallenge (the challenge this party issued); ic is the invocation counter of a mechanism 5 answer. Either side uses it: a client answering the meter's StoC, a server answering the client's CtoS.
type ICReservation ¶
type ICReservation struct {
Store iotsec.Store
Window uint32 // default DefaultICWindow
// Name names the meter in errors.
Name string
// contains filtered or unexported fields
}
ICReservation keeps a reservation, "next", above every invocation counter the process may have used for an association's key. Each association starts at least there, and the reservation moves Window ahead whenever fewer than half of it remain, so one write covers many associations and a restart skips at most Window. The stored value is {"next": n}.
Example ¶
Invocation counters across a restart: the reservation is stored ahead of the counters used, and the first association after a restart starts at the stored reservation.
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/cB-Sigma/dlms/cosem"
"github.com/cB-Sigma/iotsec"
)
// memStore is an iotsec.Store in memory (an application keeps it in a
// database, a file or the cloud).
type memStore struct{ b []byte }
func (m *memStore) Load(_ context.Context, v any) error {
if m.b == nil {
return iotsec.ErrNotStored
}
return json.Unmarshal(m.b, v)
}
func (m *memStore) Save(_ context.Context, v any) error {
b, err := json.Marshal(v)
m.b = b
return err
}
func main() {
store := &memStore{}
ctx := context.Background()
r := &cosem.ICReservation{Store: store, Window: 1000, Name: "M1"}
ic, _ := r.Reserve(ctx, 1, true)
fmt.Println("first association starts at", ic, "stored", string(store.b))
// The process restarts: a new reservation reads the stored one.
r = &cosem.ICReservation{Store: store, Window: 1000, Name: "M1"}
ic, _ = r.Reserve(ctx, 1, true)
fmt.Println("after the restart it starts at", ic)
}
Output: first association starts at 1 stored {"next":1001} after the restart it starts at 1001
type IdentityCheck ¶
type IdentityCheck struct {
Expect string `json:"expect,omitempty"`
OBIS string `json:"obis,omitempty"`
OnMismatch string `json:"onMismatch,omitempty"`
}
IdentityCheck is a meter's identity check: Expect is the value expected, OBIS the Data object read (default 0.0.96.1.0.255, the serial number; 0.0.42.0.0.255 is the logical device name), and OnMismatch refuse (default: the association is not used) or warn.
type ImageResult ¶ added in v0.2.0
type ImageResult struct {
BlockSize uint32
Blocks uint32 // blocks in the image
Sent uint32 // blocks sent, resends included
Resumed bool // the meter already held part of this image
Status uint8 // the last transfer status read
}
ImageResult says what a transfer did.
type ImageTransfer ¶ added in v0.2.0
type ImageTransfer struct {
// OBIS is the image transfer object (default 0.0.44.0.0.255).
OBIS string
Identifier []byte
Image []byte
// Activate runs image_activate after a successful verification.
Activate bool
// Poll is the interval of status reads while the meter verifies or
// activates (default 1s); Wait bounds each wait (default 5 minutes).
Poll, Wait time.Duration
// Progress, when set, is told of each block sent.
Progress func(sent, total uint32)
}
ImageTransfer is one image to send.
type InboundConn ¶
InboundConn is a meter-initiated TCP connection. The push listener reads it; WPDUs for an open association go to that association's transport, everything else is handled as a push.
func NewInboundConn ¶
func NewInboundConn(c net.Conn) *InboundConn
NewInboundConn wraps a connection a meter opened; the caller reads it (wrapper.ReadWPDU) and hands each WPDU to Deliver.
func (*InboundConn) Bound ¶
func (ic *InboundConn) Bound() bool
Bound reports whether the caller's identity is proven.
func (*InboundConn) Deliver ¶
func (ic *InboundConn) Deliver(h wrapper.Header, apdu []byte) bool
Deliver hands a WPDU to the association it answers, if one is open.
func (*InboundConn) DropHeld ¶
func (ic *InboundConn) DropHeld()
DropHeld forgets the pushes held for the proof (an impostor's: never mapped, never counted).
func (*InboundConn) HoldUnlessBound ¶
func (ic *InboundConn) HoldUnlessBound(n *Notification) bool
HoldUnlessBound keeps a push while the connection's identity is not proven yet (it is neither mapped nor counted); false when bound.
func (*InboundConn) IsClosed ¶
func (ic *InboundConn) IsClosed() bool
IsClosed reports whether Shut closed the connection.
func (*InboundConn) SetState ¶
func (ic *InboundConn) SetState(from, to int8) bool
SetState moves the connection from one binding state to another.
func (*InboundConn) Shut ¶
func (ic *InboundConn) Shut()
Shut marks the connection closed and closes the socket.
func (*InboundConn) TakeHeldOrBind ¶
func (ic *InboundConn) TakeHeldOrBind() []*Notification
TakeHeldOrBind returns the held pushes, or binds the connection when none are left, so pushes arriving meanwhile keep their order.
type ItemResult ¶
ItemResult is one list item's outcome: a data-access-result (GET, SET) or action-result (ACTION), and the data a GET or ACTION returned.
type KeyRotation ¶ added in v0.3.0
type KeyRotation struct {
Link RotationLink
// Store keeps the rotation record; StorageKey (an AES key) wraps every
// key in it (RFC 3394), so the store never holds a key in clear.
Store iotsec.Store
StorageKey []byte
// Method is RotateByTransfer (the default) or RotateByAgreement.
Method RotationMethod
// KeyLen is the length of generated keys: by default that of the
// current unicast key, else 16.
KeyLen int
// Rand generates keys (default crypto/rand).
Rand io.Reader
// OnState, when set, learns of every state stored.
OnState func(RotationStatus)
// contains filtered or unexported fields
}
KeyRotation changes keys on one meter. It is not safe for concurrent use; run one rotation per meter at a time.
func (*KeyRotation) Resume ¶ added in v0.3.0
func (r *KeyRotation) Resume(ctx context.Context) (KeySet, RotationStatus, error)
Resume settles a rotation a stopped process left: it proves the new keys or the old ones and stores the outcome. With nothing stored it returns nil keys and RotationIdle; a settled rotation returns its active keys.
func (*KeyRotation) Rotate ¶ added in v0.3.0
Rotate changes the keys named by ids (key_ids 0 to 3) from current, which must hold the keys the meter takes now (the master key too for key_transfer), and returns the keys active afterwards: the new ones, or with ErrRotationRolledBack the old ones, or nil with ErrRotationUnconfirmed. An unsettled earlier rotation is refused with ErrRotationPending.
func (*KeyRotation) Status ¶ added in v0.3.0
func (r *KeyRotation) Status() RotationStatus
Status is the state of the last rotation run or resumed.
type KeySet ¶ added in v0.3.0
KeySet holds keys by key_id (KeyGlobalUnicast, KeyGlobalBroadcast, KeyAuthentication, KeyMaster).
type KeyWarning ¶
type KeyWarning struct {
Setting, Message string
}
KeyWarning is an optional key that could not be used: the meter runs without the feature it serves. Setting names the field.
type Keys ¶
type Keys struct {
Suite Suite
Key []byte // global unicast encryption key
AuthKey []byte // authentication key (empty: none)
BroadcastKey []byte // global broadcast key (optional)
// SystemTitle is the sender's system title when the APDU does not
// carry one (service-specific ciphering); general-glo carries its own.
SystemTitle []byte
// contains filtered or unexported fields
}
Keys are the global keys to open a protected APDU with.
func ParseKeys ¶
ParseKeys reads a meter's DLMS keys of a security suite (IEC 62056-5-3:2023 Table 9: suites 0 and 1 AES-128, suite 2 AES-256; the authentication key has the same length, or none).
func (*Keys) SetCompression ¶
func (k *Keys) SetCompression(c *Compression) error
SetCompression applies a meter's V.44 compression setting to general-glo ciphering with these keys (IEC 62056-5-3:2023 5.3.6; compression.go): Open decompresses APDUs with security control bit 7 and, with compressRequests, Seal compresses before ciphering when that makes the APDU smaller. Suites 1 and 2 only (Table 9). A nil or empty setting turns compression off.
type MBusTunnel ¶
MBusTunnel is one tunnelled M-Bus frame.
func DecodeMBusTunnel ¶
func DecodeMBusTunnel(d axdr.DlmsData) (MBusTunnel, error)
DecodeMBusTunnel reads the value of a tunnelling Data object.
func (MBusTunnel) IsMBusFrame ¶
func (m MBusTunnel) IsMBusFrame() bool
IsMBusFrame reports rx_types whose data is an M-Bus frame from its CI field on (0 to 31).
type Notification ¶
type Notification struct {
InvokeID uint32
Time time.Time // zero when the meter sent none
Body axdr.DlmsData
// SystemTitle is the sender's system title when the APDU was
// protected, IC its invocation counter, and Authenticated whether its
// authentication tag was verified with the meter's keys.
SystemTitle []byte
IC uint32
Authenticated bool
}
Notification is a decoded data-notification.
func DecodeDataNotification ¶
func DecodeDataNotification(apdu []byte, loc *time.Location) (*Notification, error)
DecodeDataNotification decodes a plain data-notification APDU: long-invoke-id-and-priority (4 bytes), date-time (an octet string, empty or 12 bytes; a leading octet-string tag 0x09 is tolerated), then the notification body as tagged A-XDR data.
func OpenNotification ¶
OpenNotification decodes a data-notification (tag 0Fh) or a general-glo-ciphering APDU (DBh) holding one; dates are read in loc.
func OpenProtectedPush ¶
func OpenProtectedPush(apdu []byte, sources []PushSource, named func(*Notification) int) (int, *Notification, error)
OpenProtectedPush removes general-glo-ciphering from a pushed APDU with the keys of the first source it opens with, in the order given, and decodes the data-notification inside. named returns the index in sources of the meter a notification's device ID element names, or -1.
An encryption-only push (no authentication tag; the IS 15959 Part 2 push association) proves nothing about its sender, and global keys may be shared between meters: it is taken only from a source that accepts such pushes, only from that source's configured system title, and only when it names no other source. Refusals for the protection are *PushSecurityError. The notification's SystemTitle, IC and Authenticated are filled in.
func (*Notification) Values ¶
func (n *Notification) Values(loc *time.Location) []NotificationValue
Values flattens a notification body into its leaf values in order: a structure or array element's path is its parent's path, a dot and its position.
type NotificationValue ¶
type NotificationValue struct {
Path string // "1", "2.3": the element's position (1-based) in the body
Value any // as Value renders it
}
NotificationValue is one value of a notification body.
type Object ¶
type Object struct {
Name string `json:"name"`
OBIS string `json:"obis"`
Class uint16 `json:"class"`
Attribute int8 `json:"attribute,omitempty"` // default 2 (value or buffer)
Unit string `json:"unit,omitempty"` // overrides the meter's scaler_unit
Group string `json:"-"`
}
Object is one COSEM attribute a client reads.
func Catalogue ¶
Catalogue returns the objects of the given groups of the Part 2 smart meter of the given phases (1 or 3).
func ProfileCatalogue ¶
ProfileCatalogue returns what a client reads of the given groups of an IS 15959 profile: the objects of each group, and for block load, daily load, billing, events and scalers their profile generic buffers.
type PortClient ¶
PortClient is a DLMS client (logical name referencing) over HDLC on an already open port: gosem's client over our HDLC layer (package hdlc).
func NewPortClient ¶
func NewPortClient(rwc io.ReadWriteCloser, o PortOptions) (*PortClient, error)
NewPortClient builds a DLMS client over HDLC on rwc, which it owns from now on. Nothing is sent until Connect (the SNRM) and Associate (the AARQ). Close ends the association and the link and closes rwc.
func (*PortClient) Close ¶
func (p *PortClient) Close()
Close releases the association, disconnects the HDLC link and closes the port. It is safe to call more than once.
type PortOptions ¶
type PortOptions struct {
// ClientAddress is our HDLC client address (default 16, the public
// client, without authentication; 32 with low-level security).
ClientAddress int
// ServerAddress is the logical device, the HDLC upper address
// (default 1).
ServerAddress int
// HDLCAddress is the physical device, the HDLC lower address; it is
// sent only with a 2 or 4 byte server address.
HDLCAddress int
// HDLCAddressSize is the server address length: 1 (default: logical
// device only, usual on a point-to-point optical port), 2 or 4.
HDLCAddressSize int
// Authentication is "none" (default) or "low"; high-level security
// over a handed-over port is not supported.
Authentication string
Password string
// Timeout bounds each reply (default 10s).
Timeout time.Duration
}
PortOptions configures NewPortClient.
func (PortOptions) Check ¶
func (o PortOptions) Check() error
Check reports options NewPortClient would refuse.
type PushCounter ¶
type PushCounter struct {
Store iotsec.Store
Name string // the meter, in errors
// contains filtered or unexported fields
}
PushCounter keeps the invocation counter of the last protected push accepted from a meter. A push is accepted only after its counter is stored, so a replayed push is refused after a restart too.
An authenticated push (its tag verified with the meter's keys) moves the stored counter ("ic"), and every later push must be past it. An encryption-only push proves nothing about its sender: anyone holding shared global keys could send one with a counter far ahead and so block the meter's own pushes. It therefore never moves "ic"; it is refused if its counter is at or below "ic", or is one of the recent unauthenticated counters kept ("recent", ascending, the newest RecentPushICs), or, once that list is full, at or below its smallest. A counter far ahead only takes one place in the list, so the meter's next push is still taken. The stored value is {"last": n, "ic": n, "recent": [n...]}.
type PushReport ¶
type PushReport struct {
Time time.Time
Row map[string]any
Values []PushValue
Events []map[string]any
LastGasp bool
FirstBreath bool
}
PushReport is a notification mapped by its push setup's capture objects. Time is the notification's time, the time of a captured clock, or the time it was mapped. Row holds the push setup's logical name ("pushSetup"), every value by name and the events ("events"); Values are the values in capture order (clock and push setup elements left out); LastGasp and FirstBreath say the event status word reported a power failure or its end.
func MapPush ¶
func MapPush(n *Notification, setup *is15959.PushSetup, sp *is15959.Spec, loc *time.Location, scaler func(obis string) (Scaler, bool)) *PushReport
MapPush maps a notification by its push setup. Register values are scaled with scaler (from an earlier read of the register) and carry its unit; without one they are marked "unscaled". Event status word bits are named by the profile sp.
type PushSecurityError ¶
PushSecurityError is a push refused for its protection. Event is a stable name for a security log ("dlms_push_unauthenticated_refused", "dlms_push_system_title_refused"), Meter the source it was checked against (empty when none was) and SystemTitle the sender's, when known.
func (*PushSecurityError) Error ¶
func (e *PushSecurityError) Error() string
Error is the refusal's reason.
func (*PushSecurityError) Unwrap ¶
func (e *PushSecurityError) Unwrap() error
Unwrap returns the reason.
type PushSource ¶
type PushSource struct {
ID string
Security *Security
SystemTitle []byte
AcceptUnauthenticated bool
Location *time.Location
}
PushSource is a meter a protected push may come from: its keys, the system title it is configured with (nil: not configured), whether it may push encryption-only APDUs, and the time zone of its clock.
type PushValue ¶
type PushValue struct {
Name string
Class uint16
OBIS string
Value any
Unit string
Quality string // "unscaled" when a register's scaler is not known yet
}
PushValue is one captured value of a push.
type RawSetTransport ¶
RawSetTransport sits between gosem's client and the secure transport. When armed with a value, it rewrites gosem's encoding of that value (g) into ours (r) in the set-request that carries it.
func (*RawSetTransport) Arm ¶
func (t *RawSetTransport) Arm(g, r []byte, strays []int)
Arm makes the transport replace g, gosem's encoding of a value, with r, ours, in the next set-request (strays: the octets gosem adds).
func (*RawSetTransport) Send ¶
func (t *RawSetTransport) Send(src []byte) error
Send rewrites an armed value, then sends.
type Request ¶
type Request struct {
Op string // OpGet (default), OpSet, OpAction
Set bool // OpSet (kept for callers that set it alone)
Class uint16
OBIS string
Attr int8 // the attribute, or the method of an ACTION
Value *axdr.DlmsData // SET: the value; ACTION: the parameters (nil: none)
Access *Access // GET: selective access
Invoke byte // invoke-id-and-priority (low four bits the id)
// List holds further items of the same operation, sent "with list"
// after this one (mbuslist.go); their Invoke is not used.
List []Request
}
Request is one GET, SET or ACTION.
func ParseRequest ¶
ParseRequest reads a plain get- or set-request-normal without selective access (a test meter's side).
type Responder ¶ added in v0.3.0
type Responder struct {
Suite Suite
SystemTitle []byte // the server's, 8 octets
// Key and AuthKey are the global unicast and authentication keys,
// BroadcastKey the global broadcast key, MasterKey the KEK that wraps
// the content keys of wrapped-key general ciphering.
Key, AuthKey, BroadcastKey, MasterKey []byte
// SignKey and KAKey are the server's signing and key agreement keys;
// ClientSignKey and ClientKAKey the client's public ones.
SignKey *ecdsa.PrivateKey
KAKey *ecdsa.PrivateKey
ClientSignKey *ecdsa.PublicKey
ClientKAKey *ecdsa.PublicKey
// Compression is the server's V.44 setting (nil: compressed requests
// are refused); CompressAnswers compresses answers in general-glo,
// general-ded and general ciphering when that makes them smaller.
Compression *CompressionParams
CompressAnswers bool
// ThirdParties are the third parties whose layers the server accepts
// inside the client's protection.
ThirdParties []ResponderThirdParty
}
Responder holds a server's keys for one client.
func (*Responder) AnswerThirdParty ¶ added in v0.3.0
func (r *Responder) AnswerThirdParty(t *ThirdPartyTransaction, resp []byte) ([]byte, error)
AnswerThirdParty puts the server's layers for the third party around an answer: general-signing when it signed and SignAnswers is set, inside general-ciphering under a newly agreed key when it ciphered; with neither, general-ciphering with no protection (annex J.3).
func (*Responder) IsThirdParty ¶ added in v0.3.0
IsThirdParty says whether a deciphered request carries a layer from one of the server's third parties (general-ciphering or general-signing with one of their system titles as originator).
func (*Responder) OpenGeneral ¶ added in v0.3.0
func (r *Responder) OpenGeneral(apdu, clientST []byte) (plain []byte, ic uint32, ex *Transaction, err error)
OpenGeneral opens a general-ciphering request from the holder of clientST: the content key from its key-info (identified, wrapped, one-pass or static agreed), then the content, decompressed when the compression bit is set.
func (*Responder) OpenGloDed ¶ added in v0.3.0
func (r *Responder) OpenGloDed(key, clientST, content []byte, compressionAllowed bool) (plain []byte, ic uint32, compressed bool, err error)
OpenGloDed opens the ciphered content of a general-glo or general-ded request (or a service-specific one, where compression is refused) under key, from the holder of clientST; the broadcast key opens content whose key-set bit is set.
func (*Responder) OpenSigned ¶ added in v0.3.0
func (r *Responder) OpenSigned(apdu, clientST []byte) ([]byte, *Transaction, error)
OpenSigned checks a general-signing request from the holder of clientST with ClientSignKey and returns its content.
func (*Responder) OpenThirdParty ¶ added in v0.3.0
func (r *Responder) OpenThirdParty(apdu []byte) ([]byte, *ThirdPartyTransaction, error)
OpenThirdParty removes a third party's layers (general-ciphering with an agreed key outside, general-signing inside) from a request the client's own layer carried.
func (*Responder) SealGeneral ¶ added in v0.3.0
func (r *Responder) SealGeneral(ex *Transaction, policy byte, ic uint32, resp []byte) ([]byte, error)
SealGeneral answers a general-ciphering request: the same transaction-id, from the server to the client, under a fresh key of the kind the request used, with policy and the server's counter ic.
func (*Responder) SealGloDed ¶ added in v0.3.0
SealGloDed protects an answer for general-glo or general-ded ciphering: compressed first when CompressAnswers is set and it helps.
type ResponderThirdParty ¶ added in v0.3.0
type ResponderThirdParty struct {
SystemTitle []byte
// SignKey checks its general-signing layer and the ephemeral keys it
// offers; KAKey is its static key agreement key; AuthKey the
// authentication key of its general-ciphering layer.
SignKey *ecdsa.PublicKey
KAKey *ecdsa.PublicKey
AuthKey []byte
// SignAnswers signs the answers for it when it signed the request
// (annex J.2); otherwise a signed request gets an unsigned layer.
SignAnswers bool
}
ResponderThirdParty is a third party as the server knows it.
type Response ¶
type Response struct {
Set bool
Invoke byte
Data *axdr.DlmsData // GET: the value
Result int // data-access-result (0 success)
}
Response is a decoded get- or set-response-normal.
func ParseResponse ¶
ParseResponse reads a plain get- or set-response-normal.
type Result ¶
type Result struct {
Data *axdr.DlmsData // GET: the value; ACTION: the return parameters
Result int // data-access-result (GET, SET) or action-result (ACTION); 0 success
// Blocks counts the blocks received (GET, ACTION answers) and Sent the
// blocks sent (SET, ACTION requests).
Blocks, Sent int
// Items are the results of a request with list, in order; Result is
// then the first item's non-zero result, or 0.
Items []ItemResult
}
Result is what a finished exchange brought.
type RotationLink ¶ added in v0.3.0
type RotationLink interface {
// Open associates with the given keys (closing any open association).
Open(keys KeySet) error
// Transfer runs key_transfer with keys wrapped under master.
Transfer(master []byte, keys KeySet) error
// Agree runs key_agreement for the key_ids and returns the keys.
Agree(ids []byte) (KeySet, error)
// Check proves the open association works through its protection.
Check() error
// Close releases the open association.
Close()
}
RotationLink is what a rotation drives: associations opened with a key set and the security setup methods on the open one.
type RotationMethod ¶ added in v0.3.0
type RotationMethod string
RotationMethod is how new keys reach the meter.
const ( RotateByTransfer RotationMethod = "transfer" // key_transfer (method 2) RotateByAgreement RotationMethod = "agreement" // key_agreement (method 3) )
Rotation methods.
type RotationState ¶ added in v0.3.0
type RotationState string
RotationState is a step of a key rotation.
const ( RotationIdle RotationState = "idle" RotationPrepared RotationState = "prepared" RotationInvoked RotationState = "invoked" RotationDone RotationState = "done" RotationRolledBack RotationState = "rolled-back" RotationUnconfirmed RotationState = "unconfirmed" )
Rotation states (see the package comment above).
type RotationStatus ¶ added in v0.3.0
type RotationStatus struct {
State RotationState
Method RotationMethod
IDs []byte // the key_ids being changed
Err string // why the rotation stopped short, when it did
}
RotationStatus is the state of a rotation as callers see it.
type RowScalers ¶
type RowScalers struct {
Location *time.Location
Scaler func(class uint16, obis string) Scaler
Limiter func(obis string) Scaler
EventName func(code int) string
}
RowScalers gives ProfileRow what it needs beyond the entry: the time zone of the meter's clock (deviation unspecified), a register's scaler (Scaler), the scaler of the value a limiter monitors (Limiter, for its thresholds; nil: unscaled) and an event code's name (EventName; nil: is15959.CodeName).
type Scaler ¶
Scaler is a register's scaler_unit: values are multiplied by 10^Exponent and carry Unit; OK is false when it is not known.
type SecureTransport ¶
SecureTransport protects and unprotects APDUs between gosem and the meter, and records what passes 2 and 4 of HLS need.
func (*SecureTransport) BroadcastKey ¶
func (t *SecureTransport) BroadcastKey() []byte
BroadcastKey is the global broadcast key the transport protects broadcasts with (nil: none).
func (*SecureTransport) Challenge ¶
func (t *SecureTransport) Challenge() (meterST, stoc []byte)
Challenge is the system title and the challenge (StoC) of the meter's AARE.
func (*SecureTransport) Exchange ¶ added in v0.2.0
Exchange sends apdu, protected as configured, and returns the meter's next APDU, its protection removed, without gosem seeing either. Callers run one exchange at a time and none while gosem has a request out.
func (*SecureTransport) LastFailure ¶
func (t *SecureTransport) LastFailure() error
LastFailure is why the last incoming APDU was refused (nil: none was).
func (*SecureTransport) Release ¶
func (t *SecureTransport) Release() (ciphered, verified bool)
Release says whether the last release was ciphered and whether the meter's RLRE proved it deciphered it.
func (*SecureTransport) Send ¶
func (t *SecureTransport) Send(src []byte) error
Send protects an outgoing APDU.
func (*SecureTransport) SendBroadcastIC ¶
func (t *SecureTransport) SendBroadcastIC(apdu []byte, ic uint32) error
SendBroadcastIC is sendBroadcast with the invocation counter to use under the broadcast key (0: the association's next counter).
func (*SecureTransport) SetLogger ¶
func (t *SecureTransport) SetLogger(l *log.Logger)
SetLogger passes gosem's logger to the transport below.
func (*SecureTransport) SetReception ¶
func (t *SecureTransport) SetReception(dc gdlms.DataChannel)
SetReception unprotects incoming APDUs before gosem sees them.
func (*SecureTransport) TakeAction ¶
func (t *SecureTransport) TakeAction() []byte
TakeAction returns the last action-response seen, plain, and forgets it (gosem does not return an action's data).
func (*SecureTransport) UsedIC ¶
func (t *SecureTransport) UsedIC() uint32
UsedIC is the next invocation counter this transport would have used, counting the one a ciphered RLRQ will still take: callers record it before the release is sent.
type Security ¶
type Security struct {
Suite Suite
Policy byte // 0: APDUs are not protected
SystemTitle []byte // ours
Key []byte // global unicast (block cipher) key
AuthKey []byte // authentication key
Dedicated bool // agree a dedicated key per association
Ciphering byte // cipherServiceSpecific, cipherGeneralGlo, cipherGeneralDed or cipherGeneral
GeneralKey byte // general-ciphering key-info: genKeyIdentified, genKeyWrapped, genKeyOnePass, genKeyStatic
MasterKey []byte // the KEK the meter holds now
// rootKey is the configured masterKey: it wraps a changed master key
// in the key store and keys the store's base fingerprint.
RootKey []byte
// broadcastKey is the global broadcast key, known once rotated.
BroadcastKey []byte
Signing bool // general-signing on every request and response
// ECDSA keys: ours and the meter's for signing, ours and the meter's
// for key agreement.
SignKey *ecdsa.PrivateKey
MeterSignKey *ecdsa.PublicKey
KAKey *ecdsa.PrivateKey
MeterKAKey *ecdsa.PublicKey
// tp, when set, signs every request for the meter as a third party
// inside our own protection (thirdparty.go).
ThirdParty *ThirdPartyLayer
// compression, when set, is the meter's V.44 setting (compression.go).
Compression *CompressionParams
// Context is the application context the AARQ proposes: ContextAuto
// (0, the default) names logical name referencing with ciphering
// whenever our system title is sent (protected APDUs or mechanism 5
// and above) and without it otherwise; ContextLN and
// ContextLNCiphering name one or the other whatever is sent.
// ContextSN and ContextSNCiphering name short name referencing.
Context byte
// ShortNames makes the association use short name referencing (sn.go):
// with Context automatic, the short name context with or without
// ciphering as for logical names.
ShortNames bool
}
Security is one meter's application-layer security settings.
type SecurityConfig ¶
type SecurityConfig struct {
Name string
Authentication string
Password string
Security string
Suite int
SystemTitle string
BlockCipherKey string
AuthenticationKey string
DedicatedKey bool
SigningKey string
MeterSigningKey string
Ciphering string
GeneralKey string
MasterKey string
BroadcastKey string
Signing bool
KeyAgreementKey string
MeterKAKey string
ThirdParty *ThirdParty
Compression *Compression
// ApplicationContext is "auto" (or empty: the ciphering context whenever
// our system title is sent, as with mechanism 5 and protected APDUs),
// "ln" (logical name referencing without ciphering: HLS-GMAC with
// unprotected APDUs, as many meters and Gurux expect) or "ln-ciphering".
ApplicationContext string
// Referencing is "ln" (logical names, the default) or "sn" (short
// names: Client.Get reads through base names from the association SN
// object list); "sn" with ApplicationContext auto picks the short name
// context with or without ciphering as auto does for logical names.
// ApplicationContext "sn" and "sn-ciphering" imply it.
Referencing string
}
SecurityConfig is a meter's authentication and APDU protection as text.
Authentication none, low, hls-aes (hls), hls-md5, hls-sha1, hls-gmac, hls-sha256, hls-ecdsa Password the low-level password, or the HLS secret (aes, md5, sha1, sha256) Security none, authenticated, encrypted or authenticated-encrypted Suite security suite 0, 1 or 2 (hls-ecdsa needs 1 or 2) SystemTitle ours, 8 bytes hex (default 53474D0000000001) BlockCipherKey the global unicast key, hex (16 bytes; 32 in suite 2) AuthenticationKey the authentication key, hex DedicatedKey agree a fresh dedicated key per association SigningKey our EC private key (PEM text or a file path): hls-ecdsa, signing, one-pass agreement MeterSigningKey the meter's signing public key or certificate Ciphering service-specific (default), general-glo, general-ded or general GeneralKey general: identified (default), wrapped, agreed-one-pass or agreed-static MasterKey the KEK, hex: wrapped keys and key_transfer BroadcastKey the global broadcast key, hex Signing general-signing on every request and response (suite 1 or 2) KeyAgreementKey our static key agreement key (PEM or path) MeterKAKey the meter's key agreement public key or certificate ThirdParty requests protected for a third party inside our layer Compression V.44 (suite 1 or 2, general ciphering) ApplicationContext auto (default), ln, ln-ciphering, sn or sn-ciphering: the context the AARQ proposes Referencing ln (default) or sn: logical or short name referencing
Name names the meter in errors.
func (*SecurityConfig) Build ¶
func (c *SecurityConfig) Build() (*HLS, []KeyWarning, error)
Build checks and decodes the settings, filling in their defaults (Security "none", SystemTitle). A key a configured feature needs (hls-ecdsa, signing, an agreed general key) must be usable; any other key that cannot be read or parsed is left out with a KeyWarning.
type SecuritySetup ¶
type SecuritySetup struct {
Client gdlms.Client
Secure *SecureTransport
OBIS string
}
SecuritySetup is the security setup object (class 64, version 1) of an open association: Client and Secure are the association's, OBIS the object's logical name (0.0.43.0.e.255).
func (SecuritySetup) Action ¶
Action invokes a security setup method and returns its return data (nil when it has none).
func (SecuritySetup) Activate ¶
func (s SecuritySetup) Activate(bits byte) error
Activate raises the meter's security policy.
func (SecuritySetup) AgreeKeys ¶
AgreeKeys runs key_agreement for the given key IDs with the signing keys and system title of sec and returns the agreed keys.
func (SecuritySetup) CertificateRequest ¶
func (s SecuritySetup) CertificateRequest(kind byte) (*x509.CertificateRequest, error)
CertificateRequest asks the meter for a PKCS #10 request for one of its key pairs and checks its signature.
func (SecuritySetup) Certificates ¶
func (s SecuritySetup) Certificates() ([]CertInfo, error)
Certificates reads the certificates attribute (6).
func (SecuritySetup) ExportCertificate ¶
func (s SecuritySetup) ExportCertificate(id CertID) (*x509.Certificate, error)
ExportCertificate reads a certificate the meter holds.
func (SecuritySetup) GenerateKeyPair ¶
func (s SecuritySetup) GenerateKeyPair(kind byte) error
GenerateKeyPair asks the meter to generate a key pair (0 signing, 1 key agreement, 2 TLS).
func (SecuritySetup) ImportCertificate ¶
func (s SecuritySetup) ImportCertificate(c *x509.Certificate) error
ImportCertificate gives the meter a certificate.
func (SecuritySetup) RemoveCertificate ¶
func (s SecuritySetup) RemoveCertificate(id CertID) error
RemoveCertificate removes a certificate from the meter.
func (SecuritySetup) TransferKeys ¶
func (s SecuritySetup) TransferKeys(masterKey []byte, keys map[byte][]byte) error
TransferKeys sends new keys (by key_id) wrapped with the master key.
type SerialConfig ¶
SerialConfig is one opening of a port.
type SerialSettings ¶
type SerialSettings struct {
Baud int `json:"baud,omitempty"`
DataBits int `json:"dataBits,omitempty"`
Parity string `json:"parity,omitempty"`
StopBits int `json:"stopBits,omitempty"`
Optical bool `json:"optical,omitempty"`
SignOnAddress string `json:"signOnAddress,omitempty"`
}
SerialSettings are the line settings of a meter on a local serial port.
func (*SerialSettings) Defaults ¶
func (s *SerialSettings) Defaults() error
Defaults fills in the defaults (9600 baud, 8N1) and checks the settings.
type Suite ¶
type Suite byte
Suite is a DLMS security suite.
type ThirdParty ¶
type ThirdParty struct {
// SystemTitle is the TP's system title, 16 hex digits.
SystemTitle string `json:"systemTitle"`
// SigningKey is the TP's ECDSA private key (PEM text or a file path)
// on the suite's curve; the meter holds its certificate. It signs the
// requests (unless Sign is false) and the ephemeral key of one-pass
// agreement.
SigningKey string `json:"signingKey,omitempty"`
// Sign applies the TP's general-signing layer (default true).
Sign *bool `json:"sign,omitempty"`
// Security is the TP's general-ciphering layer: none (default),
// authenticated, encrypted or authenticated-encrypted.
Security string `json:"security,omitempty"`
// GeneralKey is the key agreement of that layer: agreed-one-pass
// (default) or agreed-static.
GeneralKey string `json:"generalKey,omitempty"`
// KeyAgreementKey is the TP's static key agreement private key (PEM
// or a file path): needed for agreed-static, and to open the meter's
// one-pass ciphered answers.
KeyAgreementKey string `json:"keyAgreementKey,omitempty"`
// AuthenticationKey is the global authentication key the TP uses
// (hex), when its layer is authenticated.
AuthenticationKey string `json:"authenticationKey,omitempty"`
// SignedResponses asks for the meter's answers to be signed for the
// TP (default: when the TP signs); CipheredResponses asks for them to
// be ciphered for the TP (default: when the TP ciphers). With neither,
// an unprotected layer for the TP is accepted (annex J.3).
SignedResponses *bool `json:"signedResponses,omitempty"`
CipheredResponses *bool `json:"cipheredResponses,omitempty"`
}
ThirdParty is the "thirdParty" setting of a meter: the identity on whose behalf requests are protected.
func (*ThirdParty) Build ¶
func (tp *ThirdParty) Build(sec *Security) (*ThirdPartyLayer, error)
Build checks the setting against the rest of the security settings and returns the TP layers.
type ThirdPartyLayer ¶
type ThirdPartyLayer struct {
// contains filtered or unexported fields
}
ThirdPartyLayer is a validated ThirdParty.
type ThirdPartyTransaction ¶ added in v0.3.0
type ThirdPartyTransaction struct {
// contains filtered or unexported fields
}
ThirdPartyTransaction records the layers a third party put on a request.
func (*ThirdPartyTransaction) Policy ¶ added in v0.3.0
func (t *ThirdPartyTransaction) Policy() byte
Policy is the A and E bits of the third party's general-ciphering layer.
func (*ThirdPartyTransaction) Signed ¶ added in v0.3.0
func (t *ThirdPartyTransaction) Signed() bool
Signed says the third party signed the request; Policy is the protection of its ciphering layer (0: none).
type Transaction ¶ added in v0.3.0
type Transaction struct {
// Broadcast: the request was under the global broadcast key (never
// answered).
Broadcast bool
// Compressed: the request was compressed.
Compressed bool
// contains filtered or unexported fields
}
Transaction is a request the server opened: what its answer must repeat.
func (*Transaction) TransactionID ¶ added in v0.3.0
func (e *Transaction) TransactionID() []byte
TransactionID is the request's transaction-id.
Source Files
¶
- access.go
- assoc.go
- axdrraw.go
- broadcast.go
- catalogue.go
- client.go
- compression.go
- config.go
- counters.go
- doc.go
- gateway.go
- gbt.go
- general.go
- generalerror.go
- hdlcaddress.go
- identitycheck.go
- image.go
- inbound.go
- keyrotation.go
- keys.go
- limiter.go
- mbusapdu.go
- mbusexchange.go
- mbusgbt.go
- mbuslist.go
- mbustunnel.go
- mechanisms.go
- obiscode.go
- profile.go
- push.go
- pushhdlc.go
- responder.go
- rwc.go
- secure.go
- securitysetup.go
- serialline.go
- sn.go
- thirdparty.go
- values.go