blob: 7a162d6e60cfd9ef4dc72f9c07976514850d2292 [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"
26 "github.com/aead/cmac/aes"
Andrea Campanella7167ebb2020-02-24 09:56:38 +010027 me "github.com/opencord/omci-lib-go/generated"
Chip Boling6e27b352020-02-14 09:10:01 -060028 "github.com/google/gopacket"
29 "github.com/google/gopacket/layers"
30)
31
32// DeviceIdent identifies the OMCI message format. Currently either baseline or extended.
33type DeviceIdent byte
34
35// LayerTypeOmci provide a gopacket LayerType for OMCI messages
36var (
37 LayerTypeOMCI gopacket.LayerType
38)
39
40func init() {
41 LayerTypeOMCI = gopacket.RegisterLayerType(1000,
42 gopacket.LayerTypeMetadata{
43 Name: "OMCI",
44 Decoder: gopacket.DecodeFunc(decodeOMCI),
45 })
46}
47
48const (
49 // Device Identifiers
50 _ = iota
51 // BaselineIdent message are composed of a fixed 40 octet packet + 8-octet trailer. All
52 // G-PON OLTs and ONUs support the baseline message set
53 BaselineIdent DeviceIdent = 0x0A
54
55 // ExtendedIdent messager are up to 1920 octets but may not be supported by all ONUs or OLTs.
56 ExtendedIdent DeviceIdent = 0x0B
57)
58
59var omciIK = []byte{0x18, 0x4b, 0x8a, 0xd4, 0xd1, 0xac, 0x4a, 0xf4,
60 0xdd, 0x4b, 0x33, 0x9e, 0xcc, 0x0d, 0x33, 0x70}
61
62func (di DeviceIdent) String() string {
63 switch di {
64 default:
65 return "Unknown"
66
67 case BaselineIdent:
68 return "Baseline"
69
70 case ExtendedIdent:
71 return "Extended"
72 }
73}
74
75// MaxBaselineLength is the maximum number of octets allowed in an OMCI Baseline
76// message. Depending on the adapter, it may or may not include the
77const MaxBaselineLength = 48
78
79// MaxExtendedLength is the maximum number of octets allowed in an OMCI Extended
80// message (including header).
81const MaxExtendedLength = 1980
82
83// MaxAttributeMibUploadNextBaselineLength is the maximum payload size for attributes for
84// a Baseline MIB Upload Next message.29
85const MaxAttributeMibUploadNextBaselineLength = MaxBaselineLength - 14 - 8
86
87// MaxAttributeGetNextBaselineLength is the maximum payload size for attributes for
88// a Baseline MIB Get Next message. This is just the attribute portion of the
89// message contents and does not include the Result Code & Attribute Mask.
90const MaxAttributeGetNextBaselineLength = MaxBaselineLength - 11 - 8
91
92// MaxManagedEntityMibUploadNextExtendedLength is the maximum payload size for ME
93// entries for an Extended MIB Upload Next message. Extended messages differ from
94// the baseline as multiple MEs can be reported in a single frame, just not multiple
95// attributes.
96const MaxManagedEntityMibUploadNextExtendedLength = MaxExtendedLength - 10 - 4
97
98// MaxAttributeGetNextExtendedLength is the maximum payload size for attributes for
99// a Extended MIB Get Next message. This is just the attribute portion of the
100// message contents and does not include the Result Code & Attribute Mask.
101const MaxAttributeGetNextExtendedLength = MaxExtendedLength - 13 - 4
102
103// NullEntityID is often used as the Null/void Managed Entity ID for attributes
104// that are used to refer to other Managed Entities but are currently not provisioned.
105const NullEntityID = uint16(0xffff)
106
107// OMCI defines the common protocol. Extended will be added once
108// I can get basic working (and layered properly). See ITU-T G.988 11/2017 section
109// A.3 for more information
110type OMCI struct {
111 layers.BaseLayer
112 TransactionID uint16
113 MessageType MessageType
114 DeviceIdentifier DeviceIdent
115 Payload []byte
116 padding []byte
117 Length uint16
118 MIC uint32
119}
120
121func (omci *OMCI) String() string {
122 //msgType := me.MsgType(byte(omci.MessageType) & me.MsgTypeMask)
123 //if me.IsAutonomousNotification(msgType) {
124 // return fmt.Sprintf("OMCI: Type: %v:", msgType)
125 //} else if byte(omci.MessageType)&me.AK == me.AK {
126 // return fmt.Sprintf("OMCI: Type: %v Response", msgType)
127 //}
128 return fmt.Sprintf("Type: %v, TID: %d (%#x), Ident: %v",
129 omci.MessageType, omci.TransactionID, omci.TransactionID, omci.DeviceIdentifier)
130}
131
132// LayerType returns LayerTypeOMCI
133func (omci *OMCI) LayerType() gopacket.LayerType {
134 return LayerTypeOMCI
135}
136
137// LayerContents returns the OMCI specific layer information
138func (omci *OMCI) LayerContents() []byte {
139 b := make([]byte, 8)
140 binary.BigEndian.PutUint16(b, omci.TransactionID)
141 b[2] = byte(omci.MessageType)
142 b[3] = byte(omci.DeviceIdentifier)
143 return b
144}
145
146// CanDecode returns the layers that this class can decode
147func (omci *OMCI) CanDecode() gopacket.LayerClass {
148 return LayerTypeOMCI
149}
150
151// NextLayerType returns the layer type contained by this DecodingLayer.
152func (omci *OMCI) NextLayerType() gopacket.LayerType {
153 return gopacket.LayerTypeZero
154}
155
156func decodeOMCI(data []byte, p gopacket.PacketBuilder) error {
157 // Allow baseline messages without Length & MIC, but no less
158 if len(data) < MaxBaselineLength-8 {
159 return errors.New("frame header too small")
160 }
161 switch DeviceIdent(data[3]) {
162 default:
163 return errors.New("unsupported message type")
164
165 case BaselineIdent:
166 //omci := &BaselineMessage{}
167 omci := &OMCI{}
168 return omci.DecodeFromBytes(data, p)
169
170 case ExtendedIdent:
171 //omci := &ExtendedMessage{}
172 omci := &OMCI{}
173 return omci.DecodeFromBytes(data, p)
174 }
175}
176
177func calculateMicAes128(data []byte) (uint32, error) {
178 // See if upstream or downstream
179 var downstreamCDir = [...]byte{0x01}
180 var upstreamCDir = [...]byte{0x02}
181
182 tid := binary.BigEndian.Uint16(data[0:2])
183 var sum []byte
184 var err error
185
186 if (data[2]&me.AK) == me.AK || tid == 0 {
187 sum, err = aes.Sum(append(upstreamCDir[:], data[:44]...), omciIK, 4)
188 } else {
189 sum, err = aes.Sum(append(downstreamCDir[:], data[:44]...), omciIK, 4)
190 }
191 if err != nil {
192 return 0, err
193 }
194 return binary.BigEndian.Uint32(sum), nil
195}
196
197/////////////////////////////////////////////////////////////////////////////
198// Baseline Message encode / decode
199
200// DecodeFromBytes will decode the OMCI layer of a packet/message
201func (omci *OMCI) DecodeFromBytes(data []byte, p gopacket.PacketBuilder) error {
202 if len(data) < 10 {
203 p.SetTruncated()
204 return errors.New("frame too small")
205 }
206 omci.TransactionID = binary.BigEndian.Uint16(data[0:])
207 omci.MessageType = MessageType(data[2])
208 omci.DeviceIdentifier = DeviceIdent(data[3])
209
210 isNotification := (int(omci.MessageType) & ^me.MsgTypeMask) == 0
211 if omci.TransactionID == 0 && !isNotification {
212 return errors.New("omci Transaction ID is zero for non-Notification type message")
213 }
214 // Decode length
215 var payloadOffset int
216 var micOffset int
217 if omci.DeviceIdentifier == BaselineIdent {
218 omci.Length = MaxBaselineLength - 8
219 payloadOffset = 8
220 micOffset = MaxBaselineLength - 4
221
222 if len(data) >= micOffset {
223 length := binary.BigEndian.Uint32(data[micOffset-4:])
224 if uint16(length) != omci.Length {
225 return me.NewProcessingError("invalid baseline message length")
226 }
227 }
228 } else {
229 payloadOffset = 10
230 omci.Length = binary.BigEndian.Uint16(data[8:10])
231 micOffset = int(omci.Length) + payloadOffset
232
233 if omci.Length > MaxExtendedLength {
234 return me.NewProcessingError("extended frame exceeds maximum allowed")
235 }
236 if int(omci.Length) != micOffset {
237 if int(omci.Length) < micOffset {
238 p.SetTruncated()
239 }
240 return me.NewProcessingError("extended frame too small")
241 }
242 }
243 // Extract MIC if present in the data
244 if len(data) >= micOffset+4 {
245 omci.MIC = binary.BigEndian.Uint32(data[micOffset:])
246 actual, _ := calculateMicAes128(data[:micOffset])
247 if omci.MIC != actual {
248 _ = fmt.Sprintf("invalid MIC, expected %#x, got %#x",
249 omci.MIC, actual)
250 //return errors.New(msg)
251 }
252 }
253 omci.BaseLayer = layers.BaseLayer{data[:4], data[4:]}
254 p.AddLayer(omci)
255 nextLayer, err := MsgTypeToNextLayer(omci.MessageType)
256 if err != nil {
257 return err
258 }
259 return p.NextDecoder(nextLayer)
260}
261
262// SerializeTo writes the serialized form of this layer into the
263// SerializationBuffer, implementing gopacket.SerializableLayer.
264// See the docs for gopacket.SerializableLayer for more info.
265func (omci *OMCI) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error {
266 // TODO: Hardcoded for baseline message format for now. Will eventually need to support
267 // the extended message format.
268 bytes, err := b.PrependBytes(4)
269 if err != nil {
270 return err
271 }
272 // OMCI layer error checks
273 isNotification := (int(omci.MessageType) & ^me.MsgTypeMask) == 0
274 if omci.TransactionID == 0 && !isNotification {
275 return errors.New("omci Transaction ID is zero for non-Notification type message")
276 }
277 if omci.DeviceIdentifier == 0 {
278 omci.DeviceIdentifier = BaselineIdent // Allow uninitialized device identifier
279 }
280 if omci.DeviceIdentifier == BaselineIdent {
281 if omci.Length == 0 {
282 omci.Length = MaxBaselineLength - 8 // Allow uninitialized length
283 } else if omci.Length != MaxBaselineLength-8 {
284 msg := fmt.Sprintf("invalid Baseline message length: %v", omci.Length)
285 return errors.New(msg)
286 }
287 } else if omci.DeviceIdentifier == ExtendedIdent {
288 if omci.Length == 0 {
289 omci.Length = uint16(len(bytes) - 10) // Allow uninitialized length
290 }
291 if omci.Length > MaxExtendedLength {
292 msg := fmt.Sprintf("invalid Baseline message length: %v", omci.Length)
293 return errors.New(msg)
294 }
295 } else {
296 msg := fmt.Sprintf("invalid device identifier: %#x, Baseline or Extended expected",
297 omci.DeviceIdentifier)
298 return errors.New(msg)
299 }
300 binary.BigEndian.PutUint16(bytes, omci.TransactionID)
301 bytes[2] = byte(omci.MessageType)
302 bytes[3] = byte(omci.DeviceIdentifier)
303 b.PushLayer(LayerTypeOMCI)
304
305 bufLen := len(b.Bytes())
306 padSize := int(omci.Length) - bufLen + 4
307 if padSize < 0 {
308 msg := fmt.Sprintf("invalid OMCI Message Type length, exceeded allowed frame size by %d bytes",
309 -padSize)
310 return errors.New(msg)
311 }
312 padding, err := b.AppendBytes(padSize)
313 copy(padding, lotsOfZeros[:])
314
315 if omci.DeviceIdentifier == BaselineIdent {
316 // For baseline, always provide the length
317 binary.BigEndian.PutUint32(b.Bytes()[MaxBaselineLength-8:], 40)
318 }
319 if opts.ComputeChecksums {
320 micBytes, err := b.AppendBytes(4)
321 if err != nil {
322 return err
323 }
324 omci.MIC, _ = calculateMicAes128(bytes[:MaxBaselineLength-4])
325 binary.BigEndian.PutUint32(micBytes, omci.MIC)
326 }
327 return nil
328}
329
330// hacky way to zero out memory... there must be a better way?
331var lotsOfZeros [MaxExtendedLength]byte // Extended OMCI messages may be up to 1980 bytes long, including headers