blob: a303a659847b539f119249a630d2c33a4b67fc69 [file] [log] [blame]
Chip Boling6e27b352020-02-14 09:10:01 -06001/*
2 * Copyright (c) 2018 - present. Boling Consulting Solutions (bcsw.net)
Andrea Campanella7167ebb2020-02-24 09:56:38 +01003 * Copyright 2020-present Open Networking Foundation
4
Chip Boling6e27b352020-02-14 09:10:01 -06005 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
Andrea Campanella7167ebb2020-02-24 09:56:38 +01008
Chip Boling6e27b352020-02-14 09:10:01 -06009 * http://www.apache.org/licenses/LICENSE-2.0
Andrea Campanella7167ebb2020-02-24 09:56:38 +010010
Chip Boling6e27b352020-02-14 09:10:01 -060011 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
Chip Boling6e27b352020-02-14 09:10:01 -060016 */
17
18// Package omci provides a library of routines to create, manipulate, serialize, and
19// decode ITU-T G.988 OMCI messages/packets
20package omci
21
22import (
23 "encoding/binary"
24 "errors"
25 "fmt"
David K. Bainbridgeadf422d2021-04-09 16:06:41 +000026
Chip Boling6e27b352020-02-14 09:10:01 -060027 "github.com/aead/cmac/aes"
Chip Boling6e27b352020-02-14 09:10:01 -060028 "github.com/google/gopacket"
29 "github.com/google/gopacket/layers"
David K. Bainbridgeadf422d2021-04-09 16:06:41 +000030 me "github.com/opencord/omci-lib-go/generated"
Chip Boling6e27b352020-02-14 09:10:01 -060031)
32
33// DeviceIdent identifies the OMCI message format. Currently either baseline or extended.
34type DeviceIdent byte
35
36// LayerTypeOmci provide a gopacket LayerType for OMCI messages
37var (
38 LayerTypeOMCI gopacket.LayerType
39)
40
41func init() {
42 LayerTypeOMCI = gopacket.RegisterLayerType(1000,
43 gopacket.LayerTypeMetadata{
44 Name: "OMCI",
45 Decoder: gopacket.DecodeFunc(decodeOMCI),
46 })
47}
48
49const (
50 // Device Identifiers
51 _ = iota
52 // BaselineIdent message are composed of a fixed 40 octet packet + 8-octet trailer. All
53 // G-PON OLTs and ONUs support the baseline message set
54 BaselineIdent DeviceIdent = 0x0A
55
56 // ExtendedIdent messager are up to 1920 octets but may not be supported by all ONUs or OLTs.
57 ExtendedIdent DeviceIdent = 0x0B
58)
59
60var omciIK = []byte{0x18, 0x4b, 0x8a, 0xd4, 0xd1, 0xac, 0x4a, 0xf4,
61 0xdd, 0x4b, 0x33, 0x9e, 0xcc, 0x0d, 0x33, 0x70}
62
63func (di DeviceIdent) String() string {
64 switch di {
65 default:
66 return "Unknown"
67
68 case BaselineIdent:
69 return "Baseline"
70
71 case ExtendedIdent:
72 return "Extended"
73 }
74}
75
76// MaxBaselineLength is the maximum number of octets allowed in an OMCI Baseline
77// message. Depending on the adapter, it may or may not include the
78const MaxBaselineLength = 48
79
80// MaxExtendedLength is the maximum number of octets allowed in an OMCI Extended
81// message (including header).
82const MaxExtendedLength = 1980
83
84// MaxAttributeMibUploadNextBaselineLength is the maximum payload size for attributes for
85// a Baseline MIB Upload Next message.29
86const MaxAttributeMibUploadNextBaselineLength = MaxBaselineLength - 14 - 8
87
88// MaxAttributeGetNextBaselineLength is the maximum payload size for attributes for
89// a Baseline MIB Get Next message. This is just the attribute portion of the
90// message contents and does not include the Result Code & Attribute Mask.
91const MaxAttributeGetNextBaselineLength = MaxBaselineLength - 11 - 8
92
93// MaxManagedEntityMibUploadNextExtendedLength is the maximum payload size for ME
94// entries for an Extended MIB Upload Next message. Extended messages differ from
95// the baseline as multiple MEs can be reported in a single frame, just not multiple
96// attributes.
97const MaxManagedEntityMibUploadNextExtendedLength = MaxExtendedLength - 10 - 4
98
99// MaxAttributeGetNextExtendedLength is the maximum payload size for attributes for
100// a Extended MIB Get Next message. This is just the attribute portion of the
101// message contents and does not include the Result Code & Attribute Mask.
102const MaxAttributeGetNextExtendedLength = MaxExtendedLength - 13 - 4
103
104// NullEntityID is often used as the Null/void Managed Entity ID for attributes
105// that are used to refer to other Managed Entities but are currently not provisioned.
106const NullEntityID = uint16(0xffff)
107
108// OMCI defines the common protocol. Extended will be added once
109// I can get basic working (and layered properly). See ITU-T G.988 11/2017 section
110// A.3 for more information
111type OMCI struct {
112 layers.BaseLayer
113 TransactionID uint16
114 MessageType MessageType
115 DeviceIdentifier DeviceIdent
David K. Bainbridgeadf422d2021-04-09 16:06:41 +0000116 ResponseExpected bool // Significant for Download Section Request only
117 Payload []byte // TODO: Deprecated. Use layers.BaseLayer.Payload
118 padding []byte // TODO: Deprecated. Never Used
Chip Boling6e27b352020-02-14 09:10:01 -0600119 Length uint16
120 MIC uint32
121}
122
123func (omci *OMCI) String() string {
124 //msgType := me.MsgType(byte(omci.MessageType) & me.MsgTypeMask)
125 //if me.IsAutonomousNotification(msgType) {
126 // return fmt.Sprintf("OMCI: Type: %v:", msgType)
127 //} else if byte(omci.MessageType)&me.AK == me.AK {
128 // return fmt.Sprintf("OMCI: Type: %v Response", msgType)
129 //}
130 return fmt.Sprintf("Type: %v, TID: %d (%#x), Ident: %v",
131 omci.MessageType, omci.TransactionID, omci.TransactionID, omci.DeviceIdentifier)
132}
133
134// LayerType returns LayerTypeOMCI
135func (omci *OMCI) LayerType() gopacket.LayerType {
136 return LayerTypeOMCI
137}
138
139// LayerContents returns the OMCI specific layer information
140func (omci *OMCI) LayerContents() []byte {
Chip Bolingd8543b22021-03-08 08:34:26 -0600141 b := make([]byte, 4)
Chip Boling6e27b352020-02-14 09:10:01 -0600142 binary.BigEndian.PutUint16(b, omci.TransactionID)
143 b[2] = byte(omci.MessageType)
144 b[3] = byte(omci.DeviceIdentifier)
145 return b
146}
147
148// CanDecode returns the layers that this class can decode
149func (omci *OMCI) CanDecode() gopacket.LayerClass {
150 return LayerTypeOMCI
151}
152
153// NextLayerType returns the layer type contained by this DecodingLayer.
154func (omci *OMCI) NextLayerType() gopacket.LayerType {
155 return gopacket.LayerTypeZero
156}
157
158func decodeOMCI(data []byte, p gopacket.PacketBuilder) error {
159 // Allow baseline messages without Length & MIC, but no less
Chip Boling157c9b92021-04-21 09:58:36 -0500160 if len(data) < 4 {
Chip Boling6e27b352020-02-14 09:10:01 -0600161 return errors.New("frame header too small")
162 }
163 switch DeviceIdent(data[3]) {
164 default:
165 return errors.New("unsupported message type")
166
167 case BaselineIdent:
Chip Boling157c9b92021-04-21 09:58:36 -0500168 if len(data) < MaxBaselineLength-8 {
169 return errors.New("frame too small")
170 }
Chip Boling6e27b352020-02-14 09:10:01 -0600171 omci := &OMCI{}
172 return omci.DecodeFromBytes(data, p)
173
174 case ExtendedIdent:
Chip Boling157c9b92021-04-21 09:58:36 -0500175 if len(data) < 10 {
176 return errors.New("extended frame header too small")
177 }
Chip Boling6e27b352020-02-14 09:10:01 -0600178 omci := &OMCI{}
179 return omci.DecodeFromBytes(data, p)
180 }
181}
182
183func calculateMicAes128(data []byte) (uint32, error) {
184 // See if upstream or downstream
185 var downstreamCDir = [...]byte{0x01}
186 var upstreamCDir = [...]byte{0x02}
187
188 tid := binary.BigEndian.Uint16(data[0:2])
189 var sum []byte
190 var err error
191
192 if (data[2]&me.AK) == me.AK || tid == 0 {
193 sum, err = aes.Sum(append(upstreamCDir[:], data[:44]...), omciIK, 4)
194 } else {
195 sum, err = aes.Sum(append(downstreamCDir[:], data[:44]...), omciIK, 4)
196 }
197 if err != nil {
198 return 0, err
199 }
200 return binary.BigEndian.Uint32(sum), nil
201}
202
203/////////////////////////////////////////////////////////////////////////////
204// Baseline Message encode / decode
205
206// DecodeFromBytes will decode the OMCI layer of a packet/message
207func (omci *OMCI) DecodeFromBytes(data []byte, p gopacket.PacketBuilder) error {
208 if len(data) < 10 {
209 p.SetTruncated()
210 return errors.New("frame too small")
211 }
212 omci.TransactionID = binary.BigEndian.Uint16(data[0:])
213 omci.MessageType = MessageType(data[2])
214 omci.DeviceIdentifier = DeviceIdent(data[3])
Chip Boling8c8018e2021-02-22 15:56:00 -0600215 omci.ResponseExpected = byte(omci.MessageType)&me.AR == me.AR
Chip Boling6e27b352020-02-14 09:10:01 -0600216
217 isNotification := (int(omci.MessageType) & ^me.MsgTypeMask) == 0
218 if omci.TransactionID == 0 && !isNotification {
219 return errors.New("omci Transaction ID is zero for non-Notification type message")
220 }
221 // Decode length
222 var payloadOffset int
223 var micOffset int
Chip Boling157c9b92021-04-21 09:58:36 -0500224 var eomOffset int
Chip Boling6e27b352020-02-14 09:10:01 -0600225 if omci.DeviceIdentifier == BaselineIdent {
226 omci.Length = MaxBaselineLength - 8
227 payloadOffset = 8
228 micOffset = MaxBaselineLength - 4
Chip Boling157c9b92021-04-21 09:58:36 -0500229 eomOffset = MaxBaselineLength - 8
Chip Boling6e27b352020-02-14 09:10:01 -0600230
231 if len(data) >= micOffset {
232 length := binary.BigEndian.Uint32(data[micOffset-4:])
233 if uint16(length) != omci.Length {
234 return me.NewProcessingError("invalid baseline message length")
235 }
236 }
237 } else {
238 payloadOffset = 10
239 omci.Length = binary.BigEndian.Uint16(data[8:10])
240 micOffset = int(omci.Length) + payloadOffset
Chip Boling157c9b92021-04-21 09:58:36 -0500241 eomOffset = micOffset
Chip Boling6e27b352020-02-14 09:10:01 -0600242
Chip Boling157c9b92021-04-21 09:58:36 -0500243 if omci.Length > uint16(MaxExtendedLength-payloadOffset) {
Chip Boling6e27b352020-02-14 09:10:01 -0600244 return me.NewProcessingError("extended frame exceeds maximum allowed")
245 }
Chip Boling157c9b92021-04-21 09:58:36 -0500246 if len(data) < micOffset {
247 p.SetTruncated()
Chip Boling6e27b352020-02-14 09:10:01 -0600248 return me.NewProcessingError("extended frame too small")
249 }
250 }
251 // Extract MIC if present in the data
252 if len(data) >= micOffset+4 {
253 omci.MIC = binary.BigEndian.Uint32(data[micOffset:])
254 actual, _ := calculateMicAes128(data[:micOffset])
255 if omci.MIC != actual {
256 _ = fmt.Sprintf("invalid MIC, expected %#x, got %#x",
257 omci.MIC, actual)
258 //return errors.New(msg)
259 }
260 }
Chip Boling157c9b92021-04-21 09:58:36 -0500261 omci.BaseLayer = layers.BaseLayer{data[:4], data[4:eomOffset]}
Chip Boling6e27b352020-02-14 09:10:01 -0600262 p.AddLayer(omci)
Chip Boling157c9b92021-04-21 09:58:36 -0500263 nextLayer, err := MsgTypeToNextLayer(omci.MessageType, omci.DeviceIdentifier == ExtendedIdent)
Chip Boling6e27b352020-02-14 09:10:01 -0600264 if err != nil {
265 return err
266 }
267 return p.NextDecoder(nextLayer)
268}
269
270// SerializeTo writes the serialized form of this layer into the
271// SerializationBuffer, implementing gopacket.SerializableLayer.
272// See the docs for gopacket.SerializableLayer for more info.
273func (omci *OMCI) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error {
Chip Boling6e27b352020-02-14 09:10:01 -0600274 bytes, err := b.PrependBytes(4)
275 if err != nil {
276 return err
277 }
278 // OMCI layer error checks
279 isNotification := (int(omci.MessageType) & ^me.MsgTypeMask) == 0
280 if omci.TransactionID == 0 && !isNotification {
281 return errors.New("omci Transaction ID is zero for non-Notification type message")
282 }
283 if omci.DeviceIdentifier == 0 {
284 omci.DeviceIdentifier = BaselineIdent // Allow uninitialized device identifier
285 }
286 if omci.DeviceIdentifier == BaselineIdent {
287 if omci.Length == 0 {
288 omci.Length = MaxBaselineLength - 8 // Allow uninitialized length
289 } else if omci.Length != MaxBaselineLength-8 {
290 msg := fmt.Sprintf("invalid Baseline message length: %v", omci.Length)
291 return errors.New(msg)
292 }
293 } else if omci.DeviceIdentifier == ExtendedIdent {
Chip Boling157c9b92021-04-21 09:58:36 -0500294 omci.Length = uint16(len(b.Bytes()) - 10)
295
296 // Is length larger than maximum packet (less header and trailing MIC)
297 if omci.Length > MaxExtendedLength-10-4 {
298 msg := fmt.Sprintf("invalid Extended message length: %v", omci.Length)
Chip Boling6e27b352020-02-14 09:10:01 -0600299 return errors.New(msg)
300 }
301 } else {
302 msg := fmt.Sprintf("invalid device identifier: %#x, Baseline or Extended expected",
303 omci.DeviceIdentifier)
304 return errors.New(msg)
305 }
306 binary.BigEndian.PutUint16(bytes, omci.TransactionID)
Chip Boling8c8018e2021-02-22 15:56:00 -0600307 // Download section request can optionally have the AR bit set or cleared. If user passes in this
308 // message type and sets download requested, fix up the message type for them.
309 if omci.MessageType == DownloadSectionRequestType && omci.ResponseExpected {
310 bytes[2] = byte(DownloadSectionRequestWithResponseType)
311 } else {
312 bytes[2] = byte(omci.MessageType)
313 }
Chip Boling6e27b352020-02-14 09:10:01 -0600314 bytes[3] = byte(omci.DeviceIdentifier)
315 b.PushLayer(LayerTypeOMCI)
316
Chip Boling6e27b352020-02-14 09:10:01 -0600317 if omci.DeviceIdentifier == BaselineIdent {
Chip Boling157c9b92021-04-21 09:58:36 -0500318 bufLen := len(b.Bytes())
319 padSize := int(omci.Length) - bufLen + 4
320 if padSize < 0 {
321 msg := fmt.Sprintf("invalid OMCI Message Type length, exceeded allowed frame size by %d bytes",
322 -padSize)
323 return errors.New(msg)
324 }
325 padding, err := b.AppendBytes(padSize)
326 if err != nil {
327 return err
328 }
329 copy(padding, lotsOfZeros[:])
330
Chip Boling6e27b352020-02-14 09:10:01 -0600331 // For baseline, always provide the length
332 binary.BigEndian.PutUint32(b.Bytes()[MaxBaselineLength-8:], 40)
333 }
334 if opts.ComputeChecksums {
335 micBytes, err := b.AppendBytes(4)
336 if err != nil {
337 return err
338 }
339 omci.MIC, _ = calculateMicAes128(bytes[:MaxBaselineLength-4])
340 binary.BigEndian.PutUint32(micBytes, omci.MIC)
341 }
342 return nil
343}
344
345// hacky way to zero out memory... there must be a better way?
346var lotsOfZeros [MaxExtendedLength]byte // Extended OMCI messages may be up to 1980 bytes long, including headers