gtpv2

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2021 License: Apache-2.0 Imports: 7 Imported by: 0

README

Overview

This package provides a module for the GPRS Tunnel Protocol (GTP) version 2. GTPv2 is documented in 3GPP TS 29.274.

Installation

go get github.com/blorticus/gtpv2

Basic Usage

package main

import (
    gtpv2 "github.com/blorticus/gtpv2"
    "net"
    "fmt"
)

func main() {
    modifyBearerRequest := gtpv2.NewPDU(gtpv2.ModifyBearerRequest, 0x00001acc, []*gtpv2.IE{
        gtpv2.NewIEWithRawData(gtpv2.UserLocationInformation, []byte{
                0x18, 0x00, 0x11, 0x00, 0xff, 0x00, 0x00, 0x11,
                0x00, 0x0f, 0x42, 0x4d, 0x00,
        }),
        gtpv2.NewIEWithRawData(gtpv2.RATType, []byte{0x06}),
        gtpv2.NewIEWithRawData(gtpv2.DelayValue, []byte{0x00}),
        gtpv2.NewIEWithRawData(gtpv2.BearerContext, []byte{
                0x49, 0x00, 0x01, 0x00, 0x05, 0x57, 0x00, 0x09,
                0x00, 0x80, 0xe4, 0x03, 0xfb, 0x94, 0xac, 0x13,
                0x01, 0xb2,
        }),
        gtpv2.NewIEWithRawData(gtpv2.RecoveryRestartCounter, []byte{0x95}),
    })
    
    conn, err := net.Dial("udp", "10.1.10.10:2123")
    if err != nil {
        panic(err)
    }
    
    conn.Write(modifyBearerRequest.Encode())
    
    incomingByteStream := make([]byte, 65536)
    
    dgLength, err := conn.Read(incomingByteStream)
    if err != nil {
        panic(err)
    }
    
    incomingGtpPDU, piggybackedGtpPDU, err := gtpv2.DecodePDU(incomingByteStream[:dgLength])
    if err != nil {
        panic(err)
    }
    
    for _, ie := range incomingGtpPDU.InformationElements {
        fmt.Printf("IE name = (%s), value = (%02x)\n", gtpv2.NameOfIEForType(ie.Type), ie.Data)
    }
}

Information Elements

There is no support for interpretation of Information Elements. They are created, stored, and presented as a byte stream. So, for example, when one uses the IMSI IE, it is not decoded to its natural string representation.

Documentation

Index

Constants

View Source
const (
	InternationalMobileSubscriberIdentity                = 1
	IMSI                                                 = 1
	Cause                                                = 2
	RecoveryRestartCounter                               = 3
	STNSR                                                = 51
	AccessPointName                                      = 71
	APN                                                  = 71
	AggregateMaximumBitRate                              = 72
	AMBR                                                 = 72
	EPSBearerID                                          = 73
	EBI                                                  = 73
	IPAddress                                            = 74
	MobileEquipmentIdentity                              = 75
	MEI                                                  = 75
	MSISDN                                               = 76
	Indication                                           = 77
	ProtocolConfigurationOptions                         = 78
	PCI                                                  = 78
	PDNAddressAllocation                                 = 79
	PAA                                                  = 79
	BearerLevelQualityofService                          = 80
	BearerQoS                                            = 80
	FlowQualityofService                                 = 81
	FlowQoS                                              = 81
	RATType                                              = 82
	ServingNetwork                                       = 83
	EPSBearerLevelTrafficFlowTemplate                    = 84
	BearerTFT                                            = 84
	TrafficAggregationDescription                        = 85
	TAD                                                  = 85
	UserLocationInformation                              = 86
	ULI                                                  = 86
	FullyQualifiedTunnelEndpointIdentifier               = 87
	FTEID                                                = 87
	TMSI                                                 = 88
	GlobalCNId                                           = 89
	S103PDNDataForwardingInfo                            = 90
	S103PDF                                              = 90
	S1UDataForwardingInfo                                = 91
	S1UDF                                                = 91
	DelayValue                                           = 92
	BearerContext                                        = 93
	ChargingID                                           = 94
	ChargingCharacteristics                              = 95
	TraceInformation                                     = 96
	BearerFlags                                          = 97
	PDNType                                              = 99
	ProcedureTransactionID                               = 100
	MMContextGSMKeyandTriplets                           = 103
	MMContextUMTSKeyUsedCipherandQuintuplets             = 104
	MMContextGSMKeyUsedCipherandQuintuplets              = 105
	MMContextUMTSKeyandQuintuplets                       = 106
	MMContextEPSSecurityContextQuadrupletsandQuintuplets = 107
	MMContextUMTSKeyQuadrupletsandQuintuplets            = 108
	PDNConnection                                        = 109
	PDUNumbers                                           = 110
	PTMSI                                                = 111
	PTMSISignature                                       = 112
	HopCounter                                           = 113
	UETimeZone                                           = 114
	TraceReference                                       = 115
	CompleteRequestMessage                               = 116
	GUTI                                                 = 117
	FContainer                                           = 118
	FCause                                               = 119
	PLMNID                                               = 120
	TargetIdentification                                 = 121
	PacketFlowID                                         = 123
	RABContext                                           = 124
	SourceRNCPDCPContextInfo                             = 125
	PortNumber                                           = 126
	APNRestriction                                       = 127
	SelectionMode                                        = 128
	SourceIdentification                                 = 129
	ChangeReportingAction                                = 131
	FullyQualifiedPDNConnectionSetIdentifier             = 132
	FQCSID                                               = 132
	Channelneeded                                        = 133

	NodeType                               = 135
	FullyQualifiedDomainName               = 136
	FQDN                                   = 136
	TransactionIdentifier                  = 137
	TI                                     = 137
	MBMSSessionDuration                    = 138
	MBMSServiceArea                        = 139
	MBMSSessionIdentifier                  = 140
	MBMSFlowIdentifier                     = 141
	MBMSIPMulticastDistribution            = 142
	MBMSDistributionAcknowledge            = 143
	RFSPIndex                              = 144
	UserCSGInformation                     = 145
	UCI                                    = 145
	CSGInformationReportingAction          = 146
	CSGID                                  = 147
	CSGMembershipIndication                = 148
	CMI                                    = 148
	Serviceindicator                       = 149
	DetachType                             = 150
	LocalDistiguishedName                  = 151
	LDN                                    = 151
	NodeFeatures                           = 152
	MBMSTimetoDataTransfer                 = 153
	Throttling                             = 154
	AllocationRetentionPriority            = 155
	ARP                                    = 155
	EPCTimer                               = 156
	SignallingPriorityIndication           = 157
	TemporaryMobileGroupIdentity           = 158
	TMGI                                   = 158
	AdditionalMMcontextforSRVCC            = 159
	AdditionalflagsforSRVCC                = 160
	MDTConfiguration                       = 162
	AdditionalProtocolConfigurationOptions = 163
	APCO                                   = 163
	AbsoluteTimeofMBMSDataTransfer         = 164
	HeNBInformationReporting               = 165
	IPv4ConfigurationParameters            = 166
	IP4CP                                  = 166
	ChangetoReportFlags                    = 167
	ActionIndication                       = 168
	TWANIdentifier                         = 169
	ULITimestamp                           = 170
	MBMSFlags                              = 171
	RANNASCause                            = 172
	CNOperatorSelectionEntity              = 173
	TrustedWLANModeIndication              = 174
	NodeNumber                             = 175
	NodeIdentifier                         = 176
	PresenceReportingAreaAction            = 177
	PresenceReportingAreaInformation       = 178
	TWANIdentifierTimestamp                = 179
	OverloadControlInformation             = 180
	LoadControlInformation                 = 181
	Metric                                 = 182
	SequenceNumber                         = 183
	APNandRelativeCapacity                 = 184
	WLANOffloadabilityIndication           = 185
	PagingandServiceInformation            = 186
	IntegerNumber                          = 187
	MillisecondTimeStamp                   = 188
	MonitoringEventInformation             = 189
	ECGIList                               = 190
	RemoteUEContext                        = 191
	RemoteUserID                           = 192
	RemoteUEIPinformation                  = 193
	CIoTOptimizationsSupportIndication     = 194
	SCEFPDNConnection                      = 195
	HeaderCompressionConfiguration         = 196
	ExtendedProtocolConfigurationOptions   = 197

	ServingPLMNRateControl             = 198
	Counter                            = 199
	MappedUEUsageType                  = 200
	SecondaryRATUsageDataReport        = 201
	UPFunctionSelectionIndicationFlags = 202
	ExtensionType                      = 254
	PrivateExtension                   = 255
)

These represent possible GTPv2 IE types. In some cases, includes the full name and its abbreviation (e.g., for IMSI)

Variables

This section is empty.

Functions

func DecodePDU

func DecodePDU(stream []byte) (pdu *PDU, piggybackedPdu *PDU, err error)

DecodePDU decodes a stream of bytes that contain either exactly one well-formed GTPv2 PDU, or two GTPv2 PDUs when the piggyback flag on the first is set to true. Returns an error if the stream cannot be decoded into one or two PDUs.

func NameOfIEForType

func NameOfIEForType(ieType IEType) string

NameOfIEForType returns a string identifier (from TS 29.274 section 8.1) for a GTPv2 IE based on the type integer

func NameOfMessageForType

func NameOfMessageForType(msgType MessageType) string

NameOfMessageForType returns a string identifier (from TS 29.274 section 8.1) for a GTPv2 IE based on the type integer value

Types

type GtpDefinitionRootYaml

type GtpDefinitionRootYaml struct {
	Gtpv2Pdus []Gtpv2PduYaml
}

type Gtpv2PduYaml

type Gtpv2PduYaml struct {
	Name string   `yaml:"Name"`
	Type string   `yaml:"Type"`
	IEs  []IEYaml `yaml:"IEs"`
}

type IE

type IE struct {
	Type           IEType
	TotalLength    uint16
	InstanceNumber uint8
	Data           []byte
}

IE is a GTPv2 Information Element. DataLength is the length of just the contained data, in bytes. TotalLength is the DataLength plus the header length. InstanceNumber is actually uint4. Data is the BigEndian data bytes.

func DecodeIE

func DecodeIE(stream []byte) (*IE, error)

DecodeIE consumes bytes from the start of stream to produce a GTPv2 IE. The TotalLength field of the resulting IE provides the count of bytes from stream that are consumed to produce this IE. Return an error if decoding fails.

func ExtractGroupedIEsFrom added in v0.1.1

func ExtractGroupedIEsFrom(groupedIE *IE) ([]*IE, error)

func NewGroupedIE

func NewGroupedIE(ieType IEType, groupedIEs []*IE) *IE

NewGroupedIE is a convenience method to generate a grouped IE (e.g., BearerContext) from IE sub-elements inside the group. Panics if an error occurs.

func NewGroupedIEErrorable

func NewGroupedIEErrorable(ieType IEType, groupedIEs []*IE) (*IE, error)

NewGroupedIEErrorable is the same as NewGroupedIE(), but returns an error if one occurs, rather than panicing.

func NewIEWithRawData

func NewIEWithRawData(ieType IEType, data []byte) *IE

NewIEWithRawData creates a new GTPv2 IE, providing it with the data as a raw byte array. The data are not validated for length or value. The instance number is set to 0, but may be changed directly or as the result of encoding order. The data are not copied, so if you require that, you must manually copy() the data first. The data must be in network byte order (i.e., big endian order). This method panics on an error. Use NewV2IEWithRawDataErrorable() to make the error catchable.

func NewIEWithRawDataErrorable

func NewIEWithRawDataErrorable(ieType IEType, data []byte) (*IE, error)

NewIEWithRawDataErrorable does the same as NewV2IEWithRawData() but returns an error if it occurs, rather than panicing.

func (*IE) Encode

func (ie *IE) Encode() []byte

Encode encodes the Information Element as a series of bytes in network byte order. There is no effort to validate that the IE Data field is correct for the type. This permits the creation of structurally correct but semantically incorrect. The IE TotalLength field is ignored for encoding and the actual length is recalculated.

func (*IE) TypedDataErrorable

func (ie *IE) TypedDataErrorable() (TypedIE, error)

type IEType

type IEType uint8

IEType represents the various IE types for GTPv2

type IEYaml

type IEYaml struct {
	Type  string      `yaml:"Type"`
	Value interface{} `yaml:"Value"`
}

type MessageType

type MessageType uint8

MessageType represents possible GTPv2 message type values

const (
	EchoRequest                                MessageType = 1
	EchoResponse                               MessageType = 2
	CreateSessionRequest                       MessageType = 32
	CreateSessionResponse                      MessageType = 33
	ModifyBearerRequest                        MessageType = 34
	ModifyBearerResponse                       MessageType = 35
	DeleteSessionRequest                       MessageType = 36
	DeleteSessionResponse                      MessageType = 37
	RemoteUEReportNotification                 MessageType = 40
	RemoteUEReportAcknowlegement               MessageType = 41
	ChangeNotificationRequest                  MessageType = 38
	ChangeNotificationResponse                 MessageType = 39
	ModifyBearerCommand                        MessageType = 64
	ModifyBearerFailureIndication              MessageType = 65
	DeleteBearerCommand                        MessageType = 66
	DeleteBearerFailureIndication              MessageType = 67
	BearerResourceCommand                      MessageType = 68
	BearerResourceFailureIndication            MessageType = 69
	DownlinkDataNotificationFailureIndication  MessageType = 70
	TraceSessionActivation                     MessageType = 71
	TraceSessionDeactivation                   MessageType = 72
	StopPagingIndication                       MessageType = 73
	CreateBearerRequest                        MessageType = 95
	CreateBearerResponse                       MessageType = 96
	UpdateBearerRequest                        MessageType = 97
	UpdateBearerResponse                       MessageType = 98
	DeleteBearerRequest                        MessageType = 99
	DeleteBearerResponse                       MessageType = 100
	DeletePDNConnectionSetRequest              MessageType = 101
	DeletePDNConnectionSetResponse             MessageType = 102
	PGWDownlinkTriggeringNotification          MessageType = 103
	PGWDownlinkTriggeringAcknowledge           MessageType = 104
	IdentificationRequest                      MessageType = 128
	IdentificationResponse                     MessageType = 129
	ContextRequest                             MessageType = 130
	ContextResponse                            MessageType = 131
	ContextAcknowledge                         MessageType = 132
	ForwardRelocationRequest                   MessageType = 133
	ForwardRelocationResponse                  MessageType = 134
	ForwardRelocationCompleteNotification      MessageType = 135
	ForwardRelocationCompleteAcknowledge       MessageType = 136
	ForwardAccessContextNotification           MessageType = 137
	ForwardAccessContextAcknowledge            MessageType = 138
	RelocationCancelRequest                    MessageType = 139
	RelocationCancelResponse                   MessageType = 140
	ConfigurationTransferTunnel                MessageType = 141
	DetachNotification                         MessageType = 149
	DetachAcknowledge                          MessageType = 150
	CSPagingIndication                         MessageType = 151
	RANInformationRelay                        MessageType = 152
	AlertMMENotification                       MessageType = 153
	AlertMMEAcknowledge                        MessageType = 154
	UEActivityNotification                     MessageType = 155
	UEActivityAcknowledge                      MessageType = 156
	ISRStatusIndication                        MessageType = 157
	UERegistrationQueryRequest                 MessageType = 158
	UERegistrationQueryResponse                MessageType = 159
	CreateForwardingTunnelRequest              MessageType = 160
	CreateForwardingTunnelResponse             MessageType = 161
	SuspendNotification                        MessageType = 162
	SuspendAcknowledge                         MessageType = 163
	ResumeNotification                         MessageType = 164
	ResumeAcknowledge                          MessageType = 165
	CreateIndirectDataForwardingTunnelRequest  MessageType = 166
	CreateIndirectDataForwardingTunnelResponse MessageType = 167
	DeleteIndirectDataForwardingTunnelRequest  MessageType = 168
	DeleteIndirectDataForwardingTunnelResponse MessageType = 169
	ReleaseAccessBearersRequest                MessageType = 170
	ReleaseAccessBearersResponse               MessageType = 171
	DownlinkDataNotification                   MessageType = 176
	DownlinkDataNotificationAcknowledge        MessageType = 177
	PGWRestartNotification                     MessageType = 179
	PGWRestartNotificationAcknowledge          MessageType = 180
	UpdatePDNConnectionSetRequest              MessageType = 200
	UpdatePDNConnectionSetResponse             MessageType = 201
)

GTPv2 MessageTypes

type PDU

type PDU struct {
	IsCarryingPiggybackedPDU bool
	TEIDFieldIsPresent       bool
	PriorityFieldIsPresent   bool
	Type                     MessageType
	TotalLength              uint16
	TEID                     uint32
	SequenceNumber           uint32
	Priority                 uint8
	InformationElements      []*IE
}

PDU represents a GTPv2 PDU. Version field is omitted because it is always '2'. TEID should be 0 if TEIDFieldIsPresent is false. Similarly, Priority should be 0 if PriorityFieldIsPresent is false. TotalLength includes complete header length, and body length, but does not include a piggybacked message length if IsCarryingPiggybackedPDU is true. The SequenceNumber is actually a uint24 value. Priority is actually a uint4 value. For these two, upper bits beyond the actual encode size are ignored and should be zero.

func NewPDU

func NewPDU(pduType MessageType, sequenceNumber uint32, ies []*IE) *PDU

NewPDU constructs a new base GTPv2 PDU. It uses a builder pattern to add non-mandatory elements, including a TEID and a priority. A piggybacked PDU is added at the time of encoding and revealed on decoding. If you change struct values after construction, Encode() may not operate as expected and may even panic, so the struct values should usually be treated as read-only. This version of the constructor will panic if the length of the IEs exceeds the maximum PDU length. If you want to be able to catch this condition, construct the PDU struct manually.

func (*PDU) AddPriority

func (pdu *PDU) AddPriority(priority uint8) *PDU

AddPriority sets the priority field and the priority presence flag

func (*PDU) AddTEID

func (pdu *PDU) AddTEID(teid uint32) *PDU

AddTEID sets the TEID field and the teid presence flag

func (*PDU) Encode

func (pdu *PDU) Encode() []byte

Encode encodes the GTPv2 PDU as a byte stream in network byte order, suitable for trasmission.

type Template

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

t := gtpv2.ReadYamlTemplateFromFile( "/path/to/file.yaml" ) csr := t.GeneratePDUByName( "CSR01" )

func ReadYamlTemplateFromFile

func ReadYamlTemplateFromFile(filePath string) (*Template, error)

func ReadYamlTemplateFromString

func ReadYamlTemplateFromString(yamlDefinition string) (*Template, error)

type TypedFTEID

type TypedFTEID struct {
	IPv4Addr      net.IP
	IPv6Addr      net.IP
	InterfaceType uint8
	Key           uint32
}

TypedFTEID is a structured version of an F-TEID IE

func (*TypedFTEID) ToIE

func (fteid *TypedFTEID) ToIE() *IE

ToIE creates an IE from the structured version of an F-TEID, and panics if there is an error

func (*TypedFTEID) ToIEErrorable

func (fteid *TypedFTEID) ToIEErrorable() (*IE, error)

ToIEErrorable is the same as ToIE, but returns an error if one occurs, rather than panicing

type TypedIE

type TypedIE interface {
	ToIE() *IE
	ToIEErrorable() (*IE, error)
}

TypedIE represents any IE that has its encoded value converted to a typed struct

type TypedIMSI

type TypedIMSI struct {
	AsString string
}

TypedIMSI is a structured version of an IMSI IE

func (*TypedIMSI) ToIE

func (imsi *TypedIMSI) ToIE() *IE

ToIE creates an IE from the structured version of an F-TEID, and panics if there is an error

func (*TypedIMSI) ToIEErrorable

func (imsi *TypedIMSI) ToIEErrorable() (*IE, error)

ToIEErrorable is the same as ToIE, but returns an error if one occurs, rather than panicing

Jump to

Keyboard shortcuts

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