227
Project Group Names: Ahmed Saieed [email protected] Aya Salah Salem [email protected] Basma Hesham [email protected] Bassam Tarek [email protected] Gehad Abu Seada [email protected] Ghada Abu Zed [email protected] Mostafa Mabrouk [email protected] Rukia Wadaat [email protected] Salma Samy [email protected]

Adding Support for Authentication and Encryption to Openbts

Embed Size (px)

DESCRIPTION

OpenBTS is asystem that is specifically designed for use in under-developed areas: as the equipment ischeap and easy to transport. OpenBTS is software based therefore it is simple to assemble andno complex/expensive hardware is needed, this is why OpenBTS may be considered as a low-cost GSM implementation.

Citation preview

Page 1: Adding Support for Authentication and Encryption to Openbts

Project Group Names:

Ahmed Saieed [email protected]

Aya Salah Salem [email protected]

Basma Hesham [email protected]

Bassam Tarek [email protected]

Gehad Abu Seada [email protected]

Ghada Abu Zed [email protected]

Mostafa Mabrouk [email protected]

Rukia Wadaat [email protected]

Salma Samy [email protected]

Page 2: Adding Support for Authentication and Encryption to Openbts

Acknowledgement First and foremost we would like to thank Allah for giving us insight and discernment to choose this project; we would also like to thank Allah for driving to complete the project with great personal satisfaction. Without Allah, none of this would have been possible. . We would like to thank Dr. Karim Gomaa, our project adviser for the assistance and encouragement to pursue to this study. We have been amazingly fortunate to have an advisor who gave us the freedom to explore on our own and at the same time guide us to recover when our steps failed. Most importantly, we would like to thank our families for their love and support. Our families have been a constant source of love, concern and support even when the times were stressful. This work would not have been possible without the support of the National Telecommunications Regulatory Authority (NTRA) and the Bibliotheca Alexandrina's Planetarium Science Center.

Page 3: Adding Support for Authentication and Encryption to Openbts

Preface This book is the result of our work in the 5th year at the Department of Communication and Electronics at the Faculty of Engineering, Alexandria University – Egypt. The motivation and aim for this book was originally explain briefly what OpenBTS is and show our work in securing it. Hopefully, this book will be informative and useful as a starting point for people wanting to learn more about the Authentication and Encryption aspects of GSM, and specifically, OpenBTS.

Page 4: Adding Support for Authentication and Encryption to Openbts

Introduction and motivation A connection between two people – a caller and the other person – is the basic service of all telephone networks. Mobile phones connected to the GSM cellular network are used on a daily basis by hundreds of millions of users worldwide; GSM provide connections over a radio links. Traditional GSM equipment is not designed for use in under-developed & developing nations: it is too expensive both to install and run for the number of users reached. Even if there GSM network coverage, after any call – connection – is terminated, the calling end is charged for the service used and the cost would be too expensive for the people to afford. OpenBTS is a system that is specifically designed for use in under-developed areas: as the equipment is cheap and easy to transport. OpenBTS is software based therefore it is simple to assemble and no complex/expensive hardware is needed, this is why OpenBTS may be considered as a low-cost GSM implementation. However, ciphering and authentication algorithms were not implemented in OpenBTS and it is highly important that reasonable technological security measures are taken to ensure the privacy of user‘s phone calls and text messages (and data), as well to prevent unauthorized use of the service. We wrote this book to mention the facts of how we implemented the appropriate security measures. We included chapters explaining the GSM Network Basics, Authentication and Encryption Basics and OpenBTS codes used. We also included all of the challenges that we faced while working on the project and the future work that may be done to improve it.

Page 5: Adding Support for Authentication and Encryption to Openbts

Table of Contents

1. Chapter 1: About GSM 1

1.1. GSM History 1

1.2. GSM Architecture 2

1.2.1. Mobile Station 3

1.2.2. Base-Station Subsystem 4

1.2.3. Network and Switching Subsystem 8

1.1. OSI Model 15

1.1.1. Physical Layer 16

1.1.2. Data Link Layer 16

1.1.3. Network Layer 16

1.1.4. Transport Layer 17

1.1.5. Session Layer 17

1.1.6. Presentation layer 17

1.1.7. Application Layer 17

1.1.8. Protocol Stacks 19

1.2. GSM Air Interface 21

1.2.1. Radio Spectrum a scarce resource 21

1.2.2. Multiple Access Scheme 21

1.2.3. TDMA Frame Structure 23

1.2.4. What is a burst? 24

1.2.5. Timing Advance and Power Control 26

1.3. GSM Air Interface Protocols 28

1.4. GSM Control Channels 30

1.4.1. Air Interface – Layer 1 32

1.4.2. Air Interface – Layer 2 33

1.4.2.1. What is LAPDm? 33

1.4.2.2. Different Modes of Operation 38

1.4.2.3. Data Link Connection Identifiers (DLC) 39

1.4.2.4. Frame Format Peer-to-Peer Communications 42

1.4.3. Air Interface – Layer 3 46

1.4.3.1. Radio Resource Management 47

1.4.3.2. Mobility Management 48

1.4.3.3. Layer 3 – Frame Structure 49

1.4.4. Mobile Originating Call 52

1.4.5. Mobile Terminating Call 57

1.4.6. Location Update 61

1.4.7. Call Clearing 64

2. About OpenBTS 66

2.1. Introduction 66

Page 6: Adding Support for Authentication and Encryption to Openbts

2.2. What‘s OpenBTS? 66

2.3. Main Components and their functions 66

2.4. Clock Modification 68

2.5. Installation of OpenBTS on Linux (Ubuntu) 68

2.5.1. GNU Radio Installation 68

2.5.2. OpenBTS Installation 70

2.5.3. Adding User Permissions to work with the USRP 70

2.5.4. Testing the USRP 70

2.6. Finding an Unused Frequency Band 72

2.7. Configure OpenBTS 72

2.8. Installing & Configuring smqueue 78

2.9. Asterisk Configuration 79

2.10. Software Architecture of OpenBTS 80

2.11. Using OpenBTS 86

2.12. Community Support 88

3. Mobile Network Security 90

3.1. Importance of Security in mobile networks 90

3.2. Security in OpenBTS 90

3.3. Cryptography 91

3.4. GSM Security Mechanism 93

3.5. Ciphering 94

3.5.1. Stream Ciphers 95

3.6. GSM Encryption Algorithms 97

3.6.1. Frame Number 99

3.6.2. Overview 102

3.6.3. A3 - Authentication Algorithm 103

3.6.4. A8 - Cipher Key Generating Algorithm 103

3.6.5. Comp 128 104

3.6.6. A5 – Ciphering Algorithm 110

3.7. Summary: Authentication and Encryption 113

4. Code Implementation of Encryption 115

4.1. Authentication 115

4.2. User data and Signaling Protection 115

4.3. Individual Subscriber Authentication Key (Ki) 116

4.3.1. Ki Code Implementation 116

4.4. Random Challenge (RAND) 119

4.4.1. Challenges introduced in this scope 119

4.5. A3A8 Algorithm 120

4.5.1. Functionality 121

4.5.2. A3A8 Implementation 121

4.6. Frame Number (FN) 129

Page 7: Adding Support for Authentication and Encryption to Openbts

4.6.1. Our Modifications 130

4.7. A5/1 Algorithm 130

4.7.1. Functionality 130

4.7.2. A5/1 Implementation 131

4.8. XORing Stage – Conversion from plain text to cipher text 134

4.8.1. Forward Error Correction and Radio Modem in L1 134

4.8.2. Normal Burst 140

4.8.3. SDCCH Channel Mapping 141

4.8.4. The Ciphering Process 142

4.8.5. Ciphering/Deciphering Code Parts 143

4.9. XORing in Details with Code implementations 144

5. Authentication and Ciphering Messages 152

5.1. Authentication 152

5.1.1. Where is authentication applied? 154

5.1.2. Authentication during network malfunction 154

5.2. Ciphering in GSM 155

5.2.1. Ciphering mode setting 156

5.3. Authentication and Ciphering Implementations 157

5.3.1. Important Definitions 157

5.3.2. Reference of Functions 157

5.3.3. Information Elements 159

5.3.3.1. Preference requirements of information elements 159

5.3.3.2. Information Element Formats 159

5.3.3.3. Common Information Elements 160

5.3.4. Authentication Messages and Codes 162

5.3.4.1. Authentication Request 162

5.3.4.2. Authentication Response 168

5.3.4.3. Authentication Reject 172

5.3.5. Ciphering Messages and Codes 174

5.3.5.1. Cipher Mode Command 174

5.3.5.2. Cipher Mode Complete 178

5.3.6. Places of Authentication and Ciphering Implementations 183

5.3.6.1. Location Updating 183

5.3.6.2. Mobile Originating Call Establishment 184

5.3.6.3. Mobile Terminating Call Establishment 186

5.3.7. Authentication and Ciphering Procedures 188

5.3.7.1. The Purpose 188

5.3.7.2. Definitions 188

5.3.7.3. Reference of Functions 188

5.3.7.4. Codes 189

5.3.7.4.1. Authentication Procedure 189

Page 8: Adding Support for Authentication and Encryption to Openbts

5.3.7.4.2. Ciphering Procedure 195

6. Challenges 198

6.1. Attacking A5/1 198

6.1.1. History 198

6.1.2. Hellman‘s Time-Memory trade-off 199

6.1.3. A Cryptanalytic Time/Memory/Data Trade-off for Stream Ciphers 202

6.1.4. Clocking Back A5/1 203

6.1.5. Our Contribution 206

6.2. Lack of Information 206

6.2.1. Extracting the Ki from the SIM 207

6.2.2. Encrypted Frame 207

6.2.3. Comp128 and A5/1 Algorithms 207

6.3. Error in the GSM Standards 208

7. Future Work 210

7.1. Flaws of the A3/A8 and A5/1 Security System in OpenBTS: 210

7.1.1. Flaws in A5/1 210

7.1.2. A5/2 210

7.1.3. A5/3 213

7.1.4. Conclusion 214

7.2. Flaws due to errors in the OpenBTS codes (fix me‘s) 214

7.2.1. Ciphering Key Sequence Number (CKSN) 214

7.2.2. RAND 215

7.2.3. Timers 217

Page 9: Adding Support for Authentication and Encryption to Openbts

1 OpenBTS

Chapter 1: About GSM 1.1 GSM history

At the beginning of the 1980s it was realized that the European countries were using many different, incompatible mobile phone systems, these systems are related to as 1G (first generation) systems. With the passage of time, the need for telecommunication services was remarkably increased. Due to this, CEPT (the Conference of European Posts and Telegraphs) founded a group to specify a common mobile system for the Western Europe. This group was named ―Groupe Spécial Mobile‖. Originally, the acronym GSM stood for Groupe Spécial Mobile, and the system name GSM arose. This abbreviation has since been interpreted in other ways, but the most common expression nowadays s Global System for Mobile communications. GSM is a 2G (second generation) system, the way the system is implemented up until the year 2001. During the time the GSM system was being specified, national telecommunication markets we deregulated. Requirements for openness and competition were built into the specifications as follows:

There should be several network operators in each Country, this would lead to competition in service provisions and it would ensure the rapid expansion of the GSM system.

The GSM system must be an open system, meaning that it should contain well-defined interfaces between different system parts.

GSM networks must be built without causing any major changes to the existing Public Switched Telephone Network (PSTN)

Other objectives:

The system must maintain a good speech quality

The system must use radio frequencies as efficiently as possible

The system must have adequate capacity

The system must maintain good security for both the subscriber and the transmitted information

Mobile services based on GSM technology were first launched in Finland in 1991. Today, more than 690 mobile networks provide GSM services across 213 countries and GSM represents 82.4% of all global mobile connections. According to GSM World, there are now more than 2 billion GSM mobile phone users worldwide. GSM uses a variation of time division multiple access (TDMA). GSM digitizes and compresses data, then sends it down a channel with two other streams of user data, each in its own time slot. It operates at either the 900 MHz or 1800 MHz frequency band.

Page 10: Adding Support for Authentication and Encryption to Openbts

2 Introduction to GSM

Since many GSM network operators have roaming agreements with foreign operators, users can often continue to use their mobile phones when they travel to other countries.

1.2 GSM architecture A GSM network is made up of multiple components and interfaces that facilitate sending and receiving of signaling and traffic messages. The GSM architecture is made up of a collection of transceivers, controllers, switches, routers, and registers. The GSM network architecture as defined in the GSM specifications can be grouped into three main areas:

Mobile station (MS) Base-station subsystem (BSS) Network and Switching Subsystem (NSS)

Figure 1.1: GSM architecture

Page 11: Adding Support for Authentication and Encryption to Openbts

3 OpenBTS

1.2.1 Mobile Station (MS): The MS (Mobile Station) is a combination of terminal equipment and subscriber data. The terminal equipment is the mobile equipment (ME) and the subscriber data is stored on the Subscriber Identity Module (SIM). Therefore, MS = ME + SIM Figure 1.2: Mobile Station

Mobile Equipment (ME): This refers to the physical phone itself. The hardware itself

contains the main elements of the mobile phone including the display, case, battery,

and the electronics used to generate the signal, and process the data receiver and to be

transmitted.

Each phone is uniquely identified by the International Mobile Equipment Identity (IMEI)

number. This is installed in the phone at manufacture and "cannot" be changed. The

IMEI can usually be found by removing the battery of the phone and reading the panel

in the battery well. It is accessed by the network during registration to check whether the

equipment has been reported as stolen.

Subscriber Identity Module (SIM) – The SIM is a small smart card that is inserted into

the phone it contains the identification numbers of the user and a list of available

networks. The SIM card also contains tools needed for authentication and Ciphering.

The SIM carries information specific to the subscriber, such as IMSI, TMSI, Ki (used for

encryption), Service Provider Name (SPN), and Local Area Identity(LAI). The SIM can

also store phone numbers (storage size depends on the type of SIM used),

the Kc (used for encryption), phone books, and data for other applications. A SIM card

can be removed from one phone, inserted into another GSM capable phone and the

subscriber will get the same service as always.

Page 12: Adding Support for Authentication and Encryption to Openbts

4 Introduction to GSM

1.2.2 Base Station Subsystem (BSS): The BSS is the link between the MS‘s of a defined area and the Network Switching System (NSS). The BSS consists of:

1. A minimum of one BTS (Base Transceiver Station) 2. One BSC (Base Station Controller) 3. One TRAU (Transcoding Rate and Adaption Unit)

Figure 1.3: Base Station System

Base Transceiver Station (BTS):

The BTS is the Mobile Station's

access point to the network it

handles the radio interface to the

mobile station. The BTS is the radio

equipment that corresponds to the

transceivers and antennas used to

provide the service each cell in the

network.

The interface between the MS and the BTS is known as the Um Interface or the Air Interface.

Figure 1.4: Base Transceiver Station

Page 13: Adding Support for Authentication and Encryption to Openbts

5 OpenBTS

One BTS usually covers a single 120 degree sector of an area. So that a tower that has 3 BTSs will cover all 360 degrees around the tower. However, depending on geography and user demand of an area, a cell may be divided up into one or two sectors, or a cell may be serviced by several BTSs with redundant sector coverage.

Figure 1.5: 3 BTS for one tower

A BTS is usually placed in the center of a cell. Its transmitting power defines the size of a cell. Each BTS serves a single cell. BTS‘s also includes the following functions:

Encoding, encrypting, multiplexing (TDMA), modulating (and Demodulation), and feeding the RF signals to the antenna.

Transcoding and rate adaptation Time and frequency synchronizing Voice through full- or half-rate services Decoding, decrypting, and equalizing received signals Random access detection Timing advances Uplink channel measurements

In a large urban area, there will potentially be a large number of BTSs deployed. The requirements for a BTS are reliability, portability, and minimum cost. A BTS will have between 1 and 16 Transceivers (TRX), depending on the geography and user demand of an area. Each TRX represents one ARFCN. A group of BTSs are controlled by a BSC.

120 ° Sector

Page 14: Adding Support for Authentication and Encryption to Openbts

6 Introduction to GSM

Base Station Controller (BSC): The BSC forms the next stage back into the GSM network. It controls a group of BTSs. It manages the radio resources for one or more BTSs. It communicates with the BTSs over what is termed the Abis interface.

The BSC assigns and releases frequencies and time slots for the MS. The BSC also handles intercell handover. It controls the power transmission of the BSS and MS in its area. The function of the BSC is to allocate the necessary time slots between the BTS and the MSC. It is a switching device that handles the radio resources. Additional functions include:

Control of frequency hopping Performing traffic concentration to reduce the number of lines from the MSC Providing an interface to the Operations and Maintenance Center for the BSS Reallocation of frequencies among BTSs Time and frequency synchronization Power management Time-delay measurements of received signals from the MS

Transcoder and Adaptation Unit (TRAU): The Transcoder is the equipment in which coding and decoding is carried out as well as rate adaptation in case of data. Although the specifications consider the TRAU as a subpart of the BTS, it can be sited away from the BTS (at MSC), and even between the BSC and the MSC. In the air interface (between the MS and BTS), the media carrying the traffic is a radio frequency. To enable an efficient transmission of digital speech information over the air interface, the igital speech signal is compressed. We must however also be able to communicate with and through the fixed network, where the speech compression format is different. Somewhere between the BTS and the fixed network, we therefore have to convert from one speech compression format to another, and this is where the Transcoder comes in.

Page 15: Adding Support for Authentication and Encryption to Openbts

7 OpenBTS

For transmission over the air interface, the speech signal is compressed by the MS to 13 Kbits/s full Rate or 5.6 Kbits/s half Rate. However, the standard bit rate for speech in the PSTN is 64 Kbits/s. The TRAU adapts the 64 Kbps from the MSC to the comparatively low transmission rate of the radio interface. It is able to compress speech from 64 Kbps to 16 Kbps, in the case of a full rate channel and to 8 Kbps in the case of a half rate channel. The following figure shows the possible locations where the TRAU could be inserted:

Figure 1.6: The possible locations where the TRAU could be inserted

Page 16: Adding Support for Authentication and Encryption to Openbts

8 Introduction to GSM

1.2.3 Network and Switching Subsystem (NSS): The GSM network subsystem contains a variety of different elements, and is often termed the core network. It provides the main control and interfacing for the whole mobile network. The major elements within the core network and the interfaces used between them are as follows:

Figure 1.7: Network and Switching Subsystem The NSS as we said is the core of every mobile network. As we already discussed before the BSS provides the radio link between the network and the MS, however the NSS is responsible for the control and database functions required to set up a call using one or more features: encryption, authentication and roaming.

Page 17: Adding Support for Authentication and Encryption to Openbts

9 OpenBTS

Mobile Switching services Centre (MSC):

Figure 1.8: Mobile Switching Services

The main part of the NSS is the Mobile Switching Center (MSC), as it performs the switching of calls between the mobile and other fixed or mobile network users. It acts like a normal switching node of the PSTN or ISDN, and in addition provides all the functionality needed to handle a mobile subscriber, such as registration, authentication, location updating, handovers, and call routing to a roaming subscriber. It also provides an interface to the PSTN so that calls can be routed from the mobile network to a phone connected to a landline. Interfaces to other MSCs are provided to enable calls to be made to mobiles on different networks. The interface between the BSC and the MSC is known as the A Interface

The interface between two Mobile Switching Centers (MSC) is called the E Interface

Page 18: Adding Support for Authentication and Encryption to Openbts

10 Introduction to GSM

Gateway Mobile Switching Centre (GMSC):

Figure 1.9: Gateway Mobile Switching Center

The GMSC is the point in the PLMN where calls to mobile subscribers enter the GSM network. Therefore each ME terminating call must be routed via a GMSC in the home PLMN of the called MS.

The GMSC contains signaling functions for retrieving information from the concerned HLR, which tells how to proceed with call set-up. Depending on the interrogation result, the call is either re-routed by GMSC to the MSC where the mobile subscriber is located or forwarded according to the forward-to number.

Figure 1.10: Connections between Two Networks

Page 19: Adding Support for Authentication and Encryption to Openbts

11 OpenBTS

Home Location Register (HLR): The HLR is a database used for storage and management of subscriptions. It contains all the administrative information about each subscriber including their current location. The administrative information includes permanent data about subscribers, including a subscriber's service profile, and activity status. When an individual buys a subscription in the form of SIM then all the information about this subscription is registered in the HLR of that operator. In this way, the GSM network is able to route calls to the relevant base station for the MS. When a user switches on their phone, the phone registers with the network and from this it is possible to determine which BTS it communicates with so that incoming calls can be routed appropriately. Even when the phone is not active (but switched on) it re-registers periodically to ensure that the network (HLR) is aware of its latest position. There is one HLR per network, although it may be distributed across various sub-centers to for operational reasons. Within the HLR, subscriber specific parameters are maintained, such as the Ki, wish is part of the security handling system and is never transmitted on any interface, it is only known to the HLR and SIM.

Each subscriber is assigned to one specific HLR, which acts as a fixed reference point

and where information on the current location of the user is stored. To reduce the

overload on the HLR, the VLR was introduced.

Page 20: Adding Support for Authentication and Encryption to Openbts

12 Introduction to GSM

Visitor Location Register (VLR): The VLR is a database that contains a subset of the information located on the HLR. It

contains similar information as the HLR, but only for subscribers currently in its Location

Area. There is a VLR for every Location Area. The VLR reduces the overall number of

queries to the HLR and thus reduces network traffic.

Figure 1.11: Visitor Location Register

Equipment Identity Register (EIR): Each mobile equipment has a number known as the International Mobile Equipment Identity. This number, is installed in the equipment and is checked by the network during registration. According to the IMEI, the mobile may be allocated one of three states - allowed onto the network, barred access, or monitored.

There is only one EIR per network. It is composed of three lists. The white list, the gray list, and the black list.

Page 21: Adding Support for Authentication and Encryption to Openbts

13 OpenBTS

Figure 1.12: Equipment Identity Register

Authentication Centre (AuC):

The AuC is a protected database that handles the authentication and encryption tasks for the network. The AuC generates 3 cryptovariables: RAND, SRES, and Kc. These cryptovariables are also known as the triplets. Although it is not required, the Auc is normally physically collocated with the HLR.

Page 22: Adding Support for Authentication and Encryption to Openbts

14 Introduction to GSM

SMS Gateway (SMS-G): Short Message Serving Center is the entity which does the job of storing and forwarding of messages to and from the mobile station. Chargeback Center (CBC): Provides a service or an activity of corporate-wide benefit for internal convenience

o is organizationally established within its own contract o is accounted for as a distinct fully recoverable cost center

Full GSM Architecture:

Page 23: Adding Support for Authentication and Encryption to Openbts

15 OpenBTS

1.3 OSI Reference Model Under its official name, the Open Systems Interconnection Reference Model (known as the OSI model), was developed by the International Organization for Standardization (known as ISO). And, yes, the full acronym of the OSI is ISO OSI What is the OSI Model? The OSI model is a layered model that describes how information moves from networked device to another. When we communicate by telephone or letters, we usually are not concerned with the details of the physical transfer of the information. We just want to be able to send and receive information; in other words communicate. The same applies to the layers of the OSI Model; each layer has a fixed role in the process of communications. The OSI model deals with the following issues:

How a device on a network sends/receives its data How a device on a network knows where to send/look for its data How devices on a network are physically connected to each other

The 7 OSI Models:

1. Physical Layer 2. Data Link Layer 3. Network Layer 4. Transport Layer 5. Session Layer 6. Presentation layer 7. Application Layer

The OSI model breaks the network communications process into seven separate layers according to, the following rules:

1. Each of the 7 layers has a unique task to perform 2. Similar functions are all combined together in the same layer 3. A layer uses the services and information of the layer below it only 4. A layer provides serves and information to the layer above it only

Page 24: Adding Support for Authentication and Encryption to Openbts

16 Introduction to GSM

OSI Layers in details: 1.3.1 Physical Layer: The physical layer is at the bottom networking model. It deals with data that is in the form of electrical signals. The data bits are sent as 0's and 1's. 0's correspond to low voltage signals and 1's correspond to high voltage signals. The mechanical aspects of communication, such as wires or connectors come under this layer. The physical layer also deals with how these wires, connectors, and voltage electrical signals work. It associates with any part of the network structure that doesn't process information in any way. 1.3.2 The Data Link Layer: The transmission of the data over the communication medium is the responsibility of this layer. The 0's and 1's that are used in the communication are grouped into logical encapsulation. This encapsulation is called frames. The data is transported in frames. The responsibility of these frames is that of the data link layer. The Data Link layer accepts data from the Network Layer, packages that data into frames, and sends them to the Physical Layer for distribution. In the same way, it receives frames from the physical layer of a receiving computer, and changes them into packets before sending them to the Network Layer. 1.3.3 Network Layer: This layer is responsible for making routing decisions and forwards packets that are further than one link away. By making the network layer responsible for this function, every other layer of the OSI model can send packets without dealing with where exactly the system happens to be on the network, whether it be 1 hop or 10 hops away. In order to provide its services to the data link layer, it must convert the logical network address into physical machine addresses, and vice versa on the receiving computer. This is done so that no relaying, routing, or networking information must be processed by a level higher in the model then this level. The network layer is also responsible for determining routing and message priority. By having this single layer responsible for prioritization, the other layers of the OSI model remain separated from routing decisions. This layer is also responsible for breaking large packets into smaller chucks when the original packet is bigger than the Data Link is set. Similarly, it re-assembles the packet on the receiving computer into the original-sized packet.

Page 25: Adding Support for Authentication and Encryption to Openbts

17 OpenBTS

1.3.4 Transport Layer: The transport layer ensures quality and reliability of the communication. The data packet switching is entirely handled by the transport layer

The transport layer's main duty is to ensure that packets are sent error-free to the receiving device in proper sequence with no data loss. This is accomplished by the protocol stack sending send and receive acknowledgements, and proper checksum/parity/synchronization of data being maintained. The transport layer is also responsible for breaking large messages into smaller packets for the network layer, and for re-assembling the packets when they are received from the network layer for processing by the session layer. 1.3.5 The Sessions Layer: The session layer is mainly responsible for creating, maintaining and destroying the communication link. The session layer also determines who can send data and who can receive data at every point in the communication. Without the dialogue between the two session layers, neither computer would know when to start sending data and when to look for it in the network traffic. 1.3.6 Presentation Layer: The presentation layer is responsible for protocol conversation, data translation, compression, encryption, character set conversion, and graphical command interpretation between the device and the network. There are various techniques of data compression which are used to send and receive the optimized data. For example, if certain data is repeating itself for a number of times, then it is logical to send the data only once, and specify the number of times it is repeated. This bundling of the repeated data is one of the techniques of compressions. The compression and decompression of the data is handled by the presentation layer. 1.3.7 Application Layer: This is the topmost layer of the OSI reference model. This layer comes into picture whenever a user invokes any application and all of the associated processes are run also, when an application wants to communicate with another application, then there has to be communication between these associated processes. The application layer is responsible for this communication. The application layer provides services that support user applications, such as database access, e-mail services, and file transfers.

Page 26: Adding Support for Authentication and Encryption to Openbts

18 Introduction to GSM

Summary of OSI Layer Functions:

Application Layer

• This layer serves as the window for users and application processes to access network services. It also identifies communication partners, determines resource availability, and synchronizescommunication.

Presentation Layer

• This layer is concerned with data representation and code formatting.

Session Layer

• The Session layer establishes, maintains, and manages the communication session between computers.

Transport Layer

• The functions defined in this layer provide for the reliable transmission of data segments, as well as the disassembly and assembly of the data before and after transmission.

Network Layer

• The Network layer defines the processes used to route data across the network and the structure and use of logical addressing.

Data Link Layer

• This layer is concerned with the linkages and mechanisms used to move data about the network, including the topology, such as Ethernet or Token Ring, and deals with the ways in which data is reliably transmitted.

Physical Layer

• This layer defines the electrical and physical specifications for the networking media that carry the data bits across a network.

Page 27: Adding Support for Authentication and Encryption to Openbts

19 OpenBTS

1.3.8 Protocol Stacks In order for each layer of the model to communicate with the levels above and below it, certain rules were developed. These rules are called Protocols, and each protocol assigns to a specific set of tasks /services to a specific layer of the model. Each layer of the model has its own set of protocols. When you have a set of protocols that create a complete OSI model, it is called a Protocol Stack. Each layer of the OSI model formats the data it receives to suit the functions to be performed on that layer. In general, the package of data that moves through the layers is called a Protocol Data Unit (PDU).

Figure 1.13: OSI Model and Protocol date unit

Application

Presentation

Session

Transport

Network

Data link

Physical

LayerData

Data

Data

Segments

Packet

Fran

Bit

PDU

Page 28: Adding Support for Authentication and Encryption to Openbts

20 Introduction to GSM

When a message is sent from one device to another, it travels down the protocol stack/

model layers, and then up the layers of the other device. As the data travels down the

stack, it picks up headers from each layer (Except the physical layer). Headers contain

information that is read by the peer layer on the stack of the other device.

Figure 1.14: Data travel down in layer in it's way to send it.

As the data travels up the levels of the peer device, each header is removed by its

equivalent protocol. These headers contain different information depending on the layer

they receive the header from, but tell the peer layer important information, including

packet size and frames. Each layer's header and data are called data packages, or

service data units. Although it may seem confusing, each layer has a different name for

its service data unit.

Page 29: Adding Support for Authentication and Encryption to Openbts

21 OpenBTS

1.4 Structure of Air Interface in GSM

1.4.1 Radio Spectrum a scarce resource The radio interface is the interface between the mobile stations and the fixed infrastructure. It is probably the most important interface of the GSM system, as it is the key element to enable mobility and wireless access. One of the main objectives of GSM is roaming. Therefore, in order to obtain a complete compatibility between mobile stations and networks of different manufacturers and operators, the radio interface must be completely defined. As we know the radio spectrum is a limited resource shared by all users, the spectrum has administrative as well as economic, technical and physical parameters; the effective utilization of the spectrum requires favorable conditions at all 4 levels. One radio communication system is considered more "spectrum efficient" than another if it conveys the desired information using less of the spectrum resource. Spectrum efficiency also involves the arrangement of communication systems within the spectrum resource. In other words, the spectrum is used inefficiently when systems are not packed together as tightly as possible in frequency bands (as when excessive guard bands are used). The allocation of frequency bands, the development of channeling plans, and the assignment of frequencies to specific systems all affect spectrum efficiency.

1.4.2 Multiple Access Scheme: Since the radio frequency spectrum, is a finite natural resource that has greater demands placed on it every day. In an effort to make the most efficient use of this resource, various technologies have been developed so that multiple, simultaneous users can be supported in a finite amount of spectrum. This concept is called "multiple access." The three most commonly used access methods are frequency division multiple access (FDMA), time division multiple access (TDMA), and code division multiple access (CDMA). A mix of Frequency Division Multiple Access (FDMA) and Time Division Multiple Access (TDMA), combined with frequency hopping, has been adopted as the multiple access scheme for GSM. The TDMA multiple access scheme on a carrier frequency together with the GMSK modulation used by GSM, a 200KHz carrier spacing is required to provide the necessary bit rate per carrier frequency. The 200kHz carrier spacing yields 124 carriers from the 25MHz spectrum allocation. Because some of the energy in a GMSK modulated signal lies outside the nominal 200KHz band, GSM recommends that carriers 1 and 124 will not normally be used (guard band of 200 KHz) in order to protect services using adjacent spectrum bands.

Page 30: Adding Support for Authentication and Encryption to Openbts

22 Introduction to GSM

These 124 possible carriers are defined for the uplink (Fu) and downlink (Fd) as follows: Fu(n) = 890.2 MHz + 0.2(n-1) MHz (1< n < 124) Fd(n) = 925.2 MHz + 0.2(n-1) MHz (1< n < 124)

Figure 1.15: FDMA/TDMA concept

Page 31: Adding Support for Authentication and Encryption to Openbts

23 OpenBTS

1.4.3 TDMA Frame Structure: Each of the frequency carriers is divided into frames of 8 timeslots of approximately 577ms (15/26 ms) duration with 156.25 bits per timeslot. The duration of a TDMA frame is 4.615ms (577ms x 8 = 4.615 ms). The bits per timeslot and frame duration yield a gross bit rate of about 271kbps per TDMA frame. TDMA frames are grouped into two types of multiframes:

26-frame multiframe (4.615ms x 26 = 120 ms) comprising of 26 TDMA frames. This multiframe is used to carry traffic channels and their associated control channels.

51-frame multiframe (4.615ms x 51 @ 235.4 ms) comprising 51 TDMA frames. This multiframe is exclusively used for control channels.

The multiframe structure is further multiplexed into a single superframe of duration of 6.12 seconds. This means a superframe consists of:

51 multiframes of 26 frames.

26 multiframes of 51 frames. The last multiplexing level of the frame hierarchy, consisting of 2048 superframes (2715648 TDMA frames), is a hyperframe. This long time period is needed to support the GSM data encryption mechanisms.

Figure 1.16: Frame Hierarchy

Page 32: Adding Support for Authentication and Encryption to Openbts

24 Introduction to GSM

1.4.4 What is a Burst? Each carrier frequency used in GSM is divided into 8 independent timeslots and into each of these timeslots a burst is placed. The modulating bit rate for a GSM carrier is 270.8 Kbits/s (1625/ 6 Kbits/s) which means that the timeslot of approximately 577ms corresponds to 156.25 bits. During the time slot period a frequency carrier is modulated by a stream of data bits organized into blocks, called a burst. A burst is made up of a useful part and a guard period. In the guard period nothing is transmitted and its purpose is to allow for a variation in the arrival time of the radio signal. The guard period avoids that adjacently (in time) received burst have their useful parts overlapping. If the useful parts of two received bursts overlap then their data will be corrupted. In addition to the guard period an adaptive time alignment process is used by the MS for all bursts except the access burst. This is used to vary the time of start of transmission of bursts to avoid overlapping with adjacent bursts at the receiver, e.g. BS. Five types of bursts are defined by GSM; four full bursts (i.e. with long useful parts) and one short burst Types of Bursts: Normal burst: This burst consists of 8.25 bits guard period and 116 data bits, the data bits may be encrypted, if encryption has been initiated by the network. The coded data bits correspond to two groups of 57 bits each, containing signaling or user data. The stealing flags (S) indicate to the receiver whether the information carried by the burst is traffic or signaling data. The training sequence has a length of 26 bits and is used for channel quality estimation and equalization. The remaining bits are used as start and stop tail bits. These tail bits are a group of three bits set to zero and placed at the beginning and the end of the burst. The tail bits are used to cover the periods of ramping up and down of the mobile transmitter‘s power amplifier.

Figure 1.17: Normal burst

Frequency correction burst: This burst has the same guard period, start bits and stop bits as the normal burst, but instead of a sequence of encrypted data bits and training sequence, the remaining bits (142) form a fixed series of zeros. This burst is used for frequency synchronization of the mobile.

Figure 1.18: Frequency correction burst

Page 33: Adding Support for Authentication and Encryption to Openbts

25 OpenBTS

Synchronization burst: This burst is used for time synchronization of the mobile station. It contains the same start and stop bits as the frequency correction burst but uses an ‗extended training sequence‘ of 64 bits and a consequently reduced set of data bits.

Figure 1.19: Synchronization burst

Dummy burst: This burst has the same structure as the normal burst but it carries no data. It is used in place of a normal burst when no other data need be sent. Access burst: This burst is used by the mobile for initial access to the system. The burst is shorter than the others, because it does not require the MS to be fully synchronous with the BS. It is characterized by an extended guard period of 68.25 bits to cater for burst transmission without knowledge the timing advance. The maximum spatial distance accommodated by the 68.25 bits is ca. 75.6km, which is well in excess of the maximum cell radius anticipated for GSM radio cells.

Figure 1.20: Access burst

Page 34: Adding Support for Authentication and Encryption to Openbts

26 Introduction to GSM

1.4.5 Timing Advance and Power Control: To simplify the design of the mobile, the GSM Recommendations specify an offset of three time-slots between the BSS and MS timing thus avoiding the necessity for the mobile to transmit and receive simultaneously. However, the synchronization of a TDMA system is critical because bursts have to be transmitted and received within the "real-time" time slots allotted to them. The further the MS is from the BSS then, obviously, the longer it will take for the bursts to travel the distance between them. The GSM BSS caters for this problem by instructing the MS to advance its timing (i.e. transmit earlier) to compensate for the increased propagation delay. This advance is then superimposed upon the 3 time-slot nominal offset, as shown in the following diagram. ―Power Control" allows the operator to not only compensate for the distance from MS to BSS, but can also cause the BSS and MS to adjust their power output to take account of that distance. The closer the MS is to the BSS, the less the power it and the BSS will be required to transmit. This feature saves radio battery power at the MS, and helps to reduce co-channel and adjacent channel interference. GSM Recommendations state that uplink power control is mandatory, whereas downlink power control is optional.

Figure 1.21: Timing Advance and Power Control

Page 35: Adding Support for Authentication and Encryption to Openbts

27 OpenBTS

The transfer of signaling information in GSM follows the layered OSI model (as previously explained):

Layer 1 (Physical Layer) Layer 2 (Data Link Layer) Layer 3 (Networking or Messaging Layer)

Page 36: Adding Support for Authentication and Encryption to Openbts

28 Introduction to GSM

1.5 GSM Air Interface Protocols: The diagram below shows the layer relationship between the MS - BTS. From the diagram we can see that traffic channels are catered for with other functional units. The Data Link Layer (Layer 2) is where the control channels are supported (PCH+AGCH, SACCH etc.); Layer 2 frames are also passed from the Data Link Layer to the Physical Layer. The Physical Layer also communicates directly to the Radio Resources Management layer for the purposes of channel assignment, physical system layer information (including, measurement results, timing advance etc).

Figure 1.22: Air interface protocol

Air interface-Layer1: The Physical layer provides support for bit transfer over the air interface. Layer 1 services are offered to Layer 2 via a ‗logical gateway‘ known as a Service Access Point (SAP). The SAP provides both control (channel establishment and release) of the entity providing the service, and data bit transfer. GSM SAPs differ from OSI SAPs in that they are controlled by the Radio Resource Management Layer (RR - Layer 3) as opposed to the Data Link Layer (Layer 2). Each control channel used on the air interface has a SAP defined between the Physical Layer and Data Link Layer.

Page 37: Adding Support for Authentication and Encryption to Openbts

29 OpenBTS

Figure 1.23: Air interface

Communication between Layer 1 and Layer 2 is achieved by the use of Primitives: • Request - Used by the layer requesting services from a lower layer. • Indication - When the services of a layer are requested, its activities are notified to the layer requesting via the Indication primitive. • Response - This is the acknowledgement by a layer of receipt of the Indication primitive. • Confirm - Once the requested services have been completed, the providing layer will inform the requesting layer via the Confirm primitive.

Figure 1.24: SAPs between the Physical Layer and the Data Link Layer

Page 38: Adding Support for Authentication and Encryption to Openbts

30 Introduction to GSM

1.6 GSM Control Channels What are Control Channels? Control channels are communication channels used in a system (such as a radio control channel), which are dedicated to the sending and/or receiving of command messages between devices (such as a base station and a mobile radio). On the GSM system, the control channel sends messages that include paging (alerting), access control (channel assignment) and system broadcast information (access parameters and system identification).

Control Channels

BCHBroadcast Channels

BCCH

FCCH

SCH

CBCH

CCCHCommon Control

Channels

PCH

RACH

AGCH

DCCHDedicated

Control Channels

SDCCH

SACCH

Page 39: Adding Support for Authentication and Encryption to Openbts

31 OpenBTS

Broadcast Channels (BCH): Broadcast Control Channel (BCCH) - DOWNLINK - This channel contains system parameters needed to identify the network and gain access. These parameters include the Location Area Code (LAC), the Mobile Network Code (MNC), the frequencies of neighboring cells, and access parameters. Frequency Correction Channel (FCCH) - DOWNLINK - This channel is used by the MS as a frequency reference. This channel contains frequency correction bursts. Synchronization Channel (SCH) - DOWNLINK - This channel is used by the MS to learn the Base Station Information Code (BSIC) as well as the TDMA frame number (FN). This lets the MS know what TDMA frame they are on within the hyperframe. Cell Broadcast Channel (CBCH) – DOWNLINK - The CBCH is for point-to-omnipoint messages. It is used to broadcast specific information to network subscribers; such as weather, traffic, sports, stocks, etc. Messages are normally public service type messages or announcements. The CBCH isn't allocated a slot for itself; it is assigned to an SDCCH. It only occurs on the downlink.

Common Control Channels (CCCH)

Paging Channel (PCH) - DOWNLINK - This channel is used to inform the MS that it has incoming traffic. The traffic could be a voice call, SMS, or some other form of traffic. Random Access Channel (RACH) - UPLINK This channel is used by a MS to request an initial dedicated channel from the BTS. This would be the first transmission made by a MS to access the network and request radio resources. The MS sends an Access Burst on this channel in order to request access. Access Grant Channel (AGCH) - DOWNLINK - This channel is used by a BTS to notify the MS of the assignment of an initial SDCCH for initial signaling.

Dedicated control channels:

Standalone Dedicated Control Channel (SDCCH) - UPLINK/DOWNLINK - This channel is used for signaling and call setup between the MS and the BTS. Fast Associated Control Channel (FACCH) - UPLINK/DOWNLINK - This channel is used for control requirements such as handoffs. There is no TS and frame allocation dedicated to a FAACH. The FAACH is a burst-stealing channel, it steals a Timeslot from a Traffic Channel (TCH).

Page 40: Adding Support for Authentication and Encryption to Openbts

32 Introduction to GSM

Slow Associated Control Channel (SACCH) - UPLINK/DOWNLINK - This channel is a continuous stream channel that is used for control and supervisory signals associated with the traffic channels.

1.6.1 Air-interface - Layer 1 (SACCH) All SACCH blocks carry a 2 octet header at the physical layer. In the downlink direction, this contains the ‗ordered' power level and timing advance information. Ordered power control is given as a 5-bit number with a value of between 0 (maximum power) and 31. For stepping up of power, each value indicates an increase of power between 2dB, 4dB .......12dB, 14dB. For stepping down of power, each value represents a reduction of either 2dB or 4 dB. These steps are dependent on database parameter settings. The timing advance field is coded with a 7-bit number. ‗1111111' represents no TA information is given. If no timing advance is to be applied, then the value will be ‗0000000'. Values from decimal 1 to 63 relate to an increase in distance of 550m for each increase of 1. Decimal 64 to 126 are reserved values.

Figure 1.25: SACCH Block Format (UL & DL)

Page 41: Adding Support for Authentication and Encryption to Openbts

33 OpenBTS

1.6.2 Air-interface - Layer 2 The Data Link Layer is the OSI layer 2 entity on the air interface. The Data Link Layer provides services to Layer 3 and is served by the Physical Layer. 1.6.2.1 What‟s LAPDm? LAPDM stands for Link Access Protocol on Delta channel, m stands for modified. Where Delta channel rates are:16kb/s or 64 kb/s. The Data Link Layer uses LAPDm on all the control channels except the RACH. LAPDm is designed to specifically support:

Multiple Layer 3 entities Multiple Physical Layer entities BCCH signaling PCH signaling AGCH signaling DCCH (SDCCH, SACCH, FACCH) signaling

LAPDm includes functions for:

Provision of single or multiple Data Link Connections on a Dm channel and the use of a Data Link

Connection Identifier (DLCI) to discriminate between the links if more than one is provisioned

Recognition of frame type Transparent message transfer between layer 3 entities The organisation of layer 3 information into frames Peer to Peer transmission of signalling data in defined frame formats Establishment, maintenance (supervision) and termination of one or more (parallel) signalling channels on data links Acknowledgement of transmission and reception of information frames (I-

frames) Unacknowledged transmission and reception of Unnumbered Information

frames (UI-frames) Flow control Detection of format and data errors on a data link Contention resolution when establishing data link after an access request has been made on the RACH

Page 42: Adding Support for Authentication and Encryption to Openbts

34 Introduction to GSM

Control Field Frame Formats: The control field indicates the frame type, sequence numbers and whether the frame is a command or response.

• There are three types of control field format: I. Information format : used for numbered information transfer type frames

(I-frames) between layer 3 entities II. Supervisory format :used for Data Link supervisory tasks such as I-

frame acknowledgement, I-frame re-transmit request or I-frame transmission suspension

III. Unnumbered format : Provides unacknowledged information transfer and additional Data Link control functions.

Figure 1.26: Frame Formats The P/F bit is used in both Command and Response frames.

– In a Command frame, it is known as the ‗P' bit. – In Response frames, it becomes the „F' bit.

When the Data Link layer requires a response from the far entity, it will set the ‗P' bit to ‗1' to indicate the that entity that a response is required. The responding entity will then set the ‗F' bit to „1' to indicate that this is the response. N(S) - Send Sequence Number

This value identifies the frame number. It is used in I-frames only. N(R) - Receive Sequence Number

This indicates the number of the next frame expected by the entity. It is used in both I-frames and S-frames. A value of N(R) received by an entity gives acknowledgement of all I-frames sent from that entity up to and including N(R)-1.

S - Supervisory Function Bit(s) It is defined using bit 3 and 4 of the control field.

Page 43: Adding Support for Authentication and Encryption to Openbts

35 OpenBTS

Figure 1.27: supervisory commands/responses bits RR - Receiver Ready

• The RR frame is used by the Data Link Layer entity to indicate: – it is ready to receive I frames – acknowledge previously received I frames up to and including N(R)-1 – Clear a busy condition which was previously indicated by a RNR frame

sent by the same data link entity. • In addition an RR frame with the "P" bit set to a "1" may be used by the Data Link

Layer entity to ask for the status of its peer Data Link Layer entity. • No information field is permitted in the RR frame.

REJ - Reject Command/response

• The REJ command is used to request retransmission of one or more I-frames. • The re-transmission should start with the frame number equal to N(R). • If bit 5 (P bit) is set to ‗1', this indicates a request for the status of the peer layer 2

entity. The REJ frame contains no information. RNR - Receiver Not Ready

• The RNR frame is used by the Data Link Layer to indicate to the peer layer a busy condition,

• for instance a full buffer that requires a temporary suspension of transmission from the peer entity.

• As in the REJ frames, no information is permitted in the RNR frame.

U - Unnumbered Function Bit

Page 44: Adding Support for Authentication and Encryption to Openbts

36 Introduction to GSM

Figure 1.28: Unnumbered Function Bit SABM

• SABM is used to establish multi-frame acknowledged operation between layer 2 entities.

• Multi-frame operation must be established between two entities before I-frames can be exchanged.

• A SABM can also contain layer 3 information. • SABM frame cannot carry segmented layer 3 information only an entire

message. • The distant entity will respond to a SABM normally with an unnumbered

acknowledgement (UA) frame. • On acceptance of the SABM, the entity will set both N(S)

and N(R) to ‗0', if there are any unacknowledged I-frames, they will be discarded. The responsibility for recovery of this information lies with higher layers.

DISC - Disconnect Command Modes of Operation The DISC command is used to terminate multi-frame operation. The originating entity will cease multi-frame operation when it receives either a DM or UA from the distant entity.

UI - Unnumbered Information Command • UI is used to transfer information without affecting the values of N(S) and N(R). • If a UI frame is lost, it is not recovered. • UI frames would be used where loss of the information within is not critical.

UA Unnumbered Acknowledgement Response

• When an entity is ready to accept I-frames via multiframe operation, it will reply to a SABM with the UA response.

• UA can also be used to clear a previous RNR condition.

DM - Disconnect Mode Response • If a condition exists whereby an entity is unable to continue multi-frame

operation, it will respond to any valid command that it cannot action using the DM response.

• The DM frame cannot carry layer 3 information.

Page 45: Adding Support for Authentication and Encryption to Openbts

37 OpenBTS

Length Indicator

Figure 1.29: Length Indicator

EL - Extension Bit

• EL set to ‗0' indicates that there is more than one octet of Length Indication data. • If set to ‗1',this indicates that it is the last or only octet of Length Indication data.

M - More Data Bits The M bit indicates whether the layer 3 information is segmented or not.

• If set to ‗0' and the previous frame also had the M bit set to ‗0', this indicates that the frame contains a complete layer 3 message.

• If the bit is set to ‗0' and the previous frame had it set to ‗1', this indicates that this frame contains the last segment of a segmented layer 3 message.

• If the M bit is set to ‗1', all available information octets contain layer 3 information. Length - length Field bits

• The value of bits 3 to 8 will indicate the number of octets of layer 3 information. • For format A frames, the length eld will always be coded ‗000000' i.e. there is no

layer 3 information carried in the frame. • For format B frames, the length eld will be coded between ‗000001' and ‗010100'

(decimal 1 - 20). • The maximum value possible for a frame carrying a SACCH message is ‗010010'

(decimal 18).

Information Field The information field may contain layer 3 data or fill bits.

These fill bits are coded as follows: • Downlink - 2Bh (00101011) • Uplink - 2Bh or FF (11111111) - decided by the MS.

Page 46: Adding Support for Authentication and Encryption to Openbts

38 Introduction to GSM

1.6.2.2 Different modes of operation in Air interface-Layer2:

1. Unacknowledged Operation: In Unacknowledged mode, Unnumbered Information (UI) frames are used for the transfer of layer 3 information. The UI frames are not acknowledged by layer 2 and there is no error recovery or flow control procedures defined.

2. Acknowledged Operation: In Acknowledged mode, only one mode of information transfer is defined. This is Multiple Frame Operation. Each frame is acknowledged by the Data Link layer in the receiving entity. Error recovery and flow control procedures are defined. Any errors not recoverable by layer 2 are reported to layer 3. Layer 3 information is sent in numbered Information (I) frames and several frames may be sent before acknowledgement is received depending on the setting of the ‗k' value. Over the air interface, k=1 which requires that each I-frame is acknowledged before the transmission of the next. Multi-frame operation is initiated by the use of the Set Asynchronous Balanced Mode (SABM) command. In acknowledged mode, layer 2 can support segmentation of the layer 3 messages. If the layer 2 information field is not able to carry the entire layer 3 message, then the message will be broken down into blocks which can be re-assembled at the receiving entity.

Page 47: Adding Support for Authentication and Encryption to Openbts

39 OpenBTS

1.6.2.3 Data Link Connection Identifier (DLCI) The DLCI consists of two elements: 1. Service Access Point Identifier

The SAPI is carried in the address field of each frame and determines to which and from which Layer 3 entity a message is to be transported by Layer 2. On the air interface only two SAPI values (0 & 3) are currently supported, others may be defined in the future. The SAPI takes a specific value for the following functions on the Dm channel:

SAPI = 0: CS Call Control Signalling (3GPP TS 24.008 ) Mobility Management Signalling (3GPP TS 24.008) Supplementary Services Signalling (3GPP TS 24.010) Radio Resource Management Signalling (3GPP TS 24.008)

SAPI = 3 Short Message Services (3GPP TS 24.011) Priority of SAPIs On SDCCH: Highest priority: SAPI = 0 Lowest priority: SAPI = 3

On SACCH If there is a SAPI 3 frame awaiting transmission, then it will be sent after a SAPI 0 frame even if there are still SAPI 0 messages to be sent. In the downlink direction, any SAPI 3 must always be followed by at least one SAPI 0 message. Allowed SAPI's:

Page 48: Adding Support for Authentication and Encryption to Openbts

40 Introduction to GSM

2. Type of Control Channel:

The type of control channel on which the Data Link Connection is to be established. This information is not carried in frames between Data Link Layer peer entities but is managed locally in each system and is carried in primitives between layers. Procedure for Transmission of Message Unit

1. The Network Layer (Layer 3) will select the appropriate SAP and DLCI.

2. The Network Layer (Layer 3) will indicate to the Data Link Layer which endpoint has been chosen.

Procedure upon Receipt of a Message Unit 1. When the Data Link Layer Receives a frame containing a Layer 3

message unit, it will have also received from the Physical Layer an indication concerning the type of channel on which the message unit was received.

2. This combined information together with the SAPI will enable the Data Link Layer to deliver the Layer 3 message unit to the required Data Link connection endpoint of the indicated SAP.

Page 49: Adding Support for Authentication and Encryption to Openbts

41 OpenBTS

Signaling model showing channels SAPs and SAPIs:

Page 50: Adding Support for Authentication and Encryption to Openbts

42 Introduction to GSM

1.6.2.4 Frame Format Peer-to-Peer Communication:

Format A. Format B. Format Bbis. Format C.

Format A: This format is used on a DCCH for frames where there is no real Layer 3 information to be transmitted. It often occurs that Layer 2 (the receiving entity) does not have a Layer 3 message to send after receiving a frame, which requires acknowledging, from its peer. The Layer 2 entity will simply transmit an empty frame to acknowledge receipt of the last frame, but as yet does not have any information to send in response. The empty frame will contain ll bits, coded with the hexadecimal value 2B or FF.

Figure 1.30: Format A:

Page 51: Adding Support for Authentication and Encryption to Openbts

43 OpenBTS

Format B: This format is used on a DCCH for frames containing an information field.

Figure 1.31: Format B

Format Bbis:

This format is used only on BCCH, PCH and AGCH. Only used in the unacknowledging mode of signaling data transfer.

Figure 1.32: Format Bbits

Page 52: Adding Support for Authentication and Encryption to Openbts

44 Introduction to GSM

Format C: The random access procedure is not LAPDm. Layer 3 is responsible for generating the 8 bit information content of the random access burst and using the primitives will pass this information to the Data Link Layer, the primitives will also contain which type of channel to use.

In the previously mentioned formats there were some fields such as:

• Address Field. • Control Field. • Length Indicator Field. • Information Field.

Address Field: The address field identifies the intended receiver within a command frame, and the transmitter of the response frame.

Figure 1.33: Address Field

EA - Address Extension - set as in LAPDm where a ‗1' indicates that this is the final octet in the address field. If coded as a ‗0', then there is more Address information to come.

C/R - In the downlink, if coded as a ‗1' indicates that this is a command frame. if coded ‗0' then it is a response frame. In the downlink, these values are reversed as in LAPDm. Command/response field bit (C/R): identifies the frame as either a command or response frame.

Service Access Point Identifier (SAPI)

Page 53: Adding Support for Authentication and Encryption to Openbts

45 OpenBTS

The SAPI identifies a point at which data link layer services are provided and consequently the Layer 2/3 boundary. The following SAPI's are defined for use on the A-bis interface. SAPI 0= Call control procedures (normally referred to as the RSL) SAPI 62= Operation and Maintenance procedures (OML) SAPI 63= Layer 2 management procedures (L2ML)

Terminal Endpoint Identifier (TEI) The TEI identifies a unique function or element within the BSS.

Page 54: Adding Support for Authentication and Encryption to Openbts

46 Introduction to GSM

1.6.3 Air Interface-Layer 3: Layer 3 of the air interface is responsible for several signaling functions:

• Connection management (CM) which comprises: Call Control (CC) Short Message Service Support (SMS) Supplementary Services Support (SS)

• Mobility Management (MM) • Radio Resource Management (RR)

A Protocol Discriminator (PD) is used to identify which route the message is to take and for CM messages, a Skip indicator is also specified. The different classes of services provided by the Signaling Layer 3 at the MS side are accessible at the following Service Access Points:

• Registration Services at the MM REG SAP. • CC services for normal and emergency calls including call related Supplementary Services at the MNCC-SAP. • Short Message Services support services at the MN SMS-SAP. • Call Independent Supplementary services, support services at the MNSS-SAP.

The registration services (location - updating IMSI attach/detach) are provided at the service access point MM REG-SAP. These services are provided by and can be directly accessed at the MM sub-layer.

Page 55: Adding Support for Authentication and Encryption to Openbts

47 OpenBTS

1.6.3.1 Radio Resource Management:

Figure 1.34: Radio Resource Management

The Radio Resource sub-layer is responsible for establishing, maintaining and release of dedicated Radio Resource connections. RR responsible for:

• Channel Assignment Procedures Channel Release

• Channel Change and Handover Procedures • Change of:

– Channel Frequencies – Hopping Sequences

• Measurement Reports • Power Control Timing Advance Modification of

Channel Modes (speech and data) • Cipher Mode Setting

The main areas of responsibility are:

• Radio frequency spectrum management • System reactions in response to radio environment changes • Subscriber to PLMN channel maintenance

RR involves:

Primarily the BSC and BTS.

The MSC only when handover is between cells managed by different BSC's.

Page 56: Adding Support for Authentication and Encryption to Openbts

48 Introduction to GSM

1.6.3.2 Mobility Management Sub-layer: The Mobility Management Sub-layer is responsible for functions related to a subscriber but not related to RR functions. Tasks include:

Authentication

Registration

Subscriber Mobility

Checks for subscribed services

Security

Location Update Procedure

Periodic Updating

IMSI Attach Procedure

IMSI Detach Procedure

TMSI Reallocation Procedure

Identification Procedure

Connection Management Sub-layer: • Like MM,CM uses the connection that RR provides for information exchange. • The Connection Management sub-layer is composed of:

– Call Control (CC) – Short Message Service (SMS – Supplementary Service (SS)

Call Control:

– Call establishment procedure for mobile originated calls – Call establishment procedures for mobile terminated calls – Call re-establishment after interruption of a Mobility Management

connection – Dual-Tone Multi-frequency (DTMF) control procedure for DTMF

transmissions Supplementary Services:

– Specific variations of the way the basic service is provided to the user ( call forwarding and multiparty call).

Short Message Services:

– Provision of Point-to-Point Short Message Service

Page 57: Adding Support for Authentication and Encryption to Openbts

49 OpenBTS

1.6.3.3 Layer 3 - Frame Structure:

Page 58: Adding Support for Authentication and Encryption to Openbts

50 Introduction to GSM

The 3 main elements of a standard layer 3 message are:

Protocol Discriminator (PD).

Transaction Identifier (TI), or Skip Indicator.

Message Type.

Protocol Discriminator:

Figure 1.35: Protocol Discriminator

• The Protocol Discriminator identifies the layer 3 protocol that the message belongs to.

• It is made up of the rest 4 bits of octet 1 of the standard layer 3 message. • Bits:

4 3 2 1 0 0 1 1 - Call Control; SS messages (call related) 0 1 0 1 - MM messages 0 1 1 0 - RR management messages 1 0 0 1 - SMS messages 1 0 1 1 - SS messages (non-call related) 1 1 1 1 - Reserved for procedures as per TS GSM 11.10

Skip Indicator: • The second half-octet (bits 5-8) of the layer 3 header octet 1 are used to

distinguish between MM/RR and CC messages. • For MM and RR, they make up the Skip Indicator. If set to ‗0000', the message is

assumed to be either MM or RR. • Any message sent by either MM or RR will set have the Skip Indicator set to

‗0000' by the transmitting entity. • If a message is received with the Skip Indicator any value other than ‗0000', it will

be ignored by MM or RR.

Page 59: Adding Support for Authentication and Encryption to Openbts

51 OpenBTS

Transaction Identifier: • The TI is used to distinguish between possible multiple parallel CM connections

and transactions • The TI is composed of the TI flag and 3 bits for the TI value.

Figure 1.36: Skip Indicator

Message Type (Air Interface)

• Octet 2 of the layer 3 header identifies the message type as per 3GPP TS 24.008.

• The message type defines either MM, RR or CM messages. • If the message is RR, bits 1-7 are coded with the message type.

If the message is either MM or CM, only bits 1-6 are coded with the message type.

Message Sequence Scenarios: • Mobile originating call establishment • Mobile terminating call establishment • Location updating • Call clearing

Page 60: Adding Support for Authentication and Encryption to Openbts

52 Introduction to GSM

1.6.4 Mobile Originating Call A Mobile Originated Call is a call that is initiated by the MS. The following example is a mobile-originated call that terminates outside the PLMN.

1. The MS sends a Channel Request (CHAN_REQ) message on the RACH. 2. The BSS responds with a radio resource assignment (IMM_ASS_CMD) on the AGCH. 3. The MS sends a Service Request (CM_SERV_REQ) message to the BSS on the SDCCH.

Figure 1.37: Mobile Originating Call

Authentication 4. Before the network will provide any services to the MS, the network will require the MS to authenticate itself. The BSS sends an Authentication Request (AUTH_REQ) message to the MS. The RAND serves as the "challenge" for authentication. 5. The MS calculates the proper SRES based on the RAND that was given and sends the SRES to the BSS in an Authentication Response (AUTH_RESP) message. 6. The BSS verifies the SRES. If the SRES is correct then the MS is authenticated and allowed access to the network. The BSS will send a Service Accept (CM_SERV_ACC) message letting the MS know that the service request was received and processed. 7. Once authenticated, the BSS orders the MS to switch to cipher mode with the CIPH_MOD_CMD message.

Page 61: Adding Support for Authentication and Encryption to Openbts

53 OpenBTS

Figure 1.38: Authentication Initial Call Set Up: 8. The MS will immediately switch to cipher mode and send a Cipher Mode Complete (CIPH_MOD_COM) message. 9. The MS then sends a Call Setup (SETUP) message to the BSS. The message includes the address information (MSISDN) of the called party. 10. The BSS assigns a TCH to the MS by sending an Assignment Command (ASS_CMD) message. This message includes which Transceiver (TRX) and which Time Slot (TS) to use. *The BSS does not actually assign a TCH to the MS until the MSC sends a Call Proceeding (CALL_PROC) message to the BSS indicating that the IAM has been sent. 11. The MS immediately switches to the assigned TCH. The MS sends an Assignment Complete (ASS_COM) message back to the BTS on the FACCH. *Remember that a FACCH is not a separate channel, it is simply a stolen time slot from the TCH that is used for signaling data instead of voice traffic.

Page 62: Adding Support for Authentication and Encryption to Openbts

54 Introduction to GSM

Figure 1.39: Initial Call Set Up Call Establishment: 16. Once the MSC receives the ACM, it sends an ALERT message to the MS indicating that the call is going through. The BSS sends the ALERT message on the FACCH. Once the MS receives the ALERT, it will generate the ringing sound in the earpiece. The BSS sends an alerting message the subscriber will hear the line ringing. 17. Once the called party answers the phone, the PSTN will send an Answer message to the MSC. The MSC forwards this to the MS in a Connection (CON) message. 18. Once the MS receives the CON message, it switches over to voice and begins the call. All voice traffic occurs on the assigned TCH.

Figure 1.40: Call Establishment

Page 63: Adding Support for Authentication and Encryption to Openbts

55 OpenBTS

Call Termination: 19. When either the caller or the called party hangs up, the call will be disconnected. Either party can initiate the disconnect. In this example, the MS initiates the disconnect. The MS sends a Disconnect (DISC) message to the BTS on the FACCH. 20. The BSS forwards the DISC to the MSC. Once the MSC receives the DISC message, it sends a Release (REL) message through the GMSC to the PSTN as well as down through the BSS to the MS. 21. The MS responds by sending a Release Complete (REL_COM) message to the BSS on the FACCH. The BSS forwards the REL_COM message up to the MSC. Once the MSC receives the REL_COM message the call is considered ended from the call control perspective. 21. Although the call has ended, the BSS still has a TCH allocated to the MS. The MSC sends a Channel Release (CHAN_REL) message to the BSS. The BSS forwards the CHAN_REL message to the MS. 22. The MS responds with a DISC (LAPDm) message and returns to an idle mode. The BSS deallocates the channel and releases the TRX.

Figure 1.41: Call Termination

Page 64: Adding Support for Authentication and Encryption to Openbts

56 Introduction to GSM

Figure 1.42: Summary for Mobile Originating Call

Page 65: Adding Support for Authentication and Encryption to Openbts

57 OpenBTS

1.6.5 Mobile Terminating Call Call Establishment:

In this example, the call is originating from outside the PLMN. Route Establishment to find the MSC/VLR The calling party dials the MSISDN for the mobile subscriber. The PSTN identifies the network (PLMN) that the dialed MSISDN belongs to and will locate a GMSC for that network. The PSTN sends an Initial Address message to the GMSC. The GMSC forwards the MSISDN to the HLR and requests routing information for it. The HLR looks up the MSISDN and determines the IMSI and the SS7 address for the MSC/VLR that is servicing the MS. The HLR then contacts the servicing MSC/VLR and asks it to assign a Mobile Station Routing Number (MSRN) to the call. The MSC/VLR allocates the MSRN and forwards it to the HLR. Note: It is important to remember that the MSC/VLR assigns a MSRN to the call not to the MS itself. The HLR forwards the MSRN as well as routing information for the servicing MSC/VLR to the GMSC. The GMSC sends an Initial Addressing message to the servicing MSC/VLR and uses the MSRN to route the call to the MSC/VLR. Once the servicing MSC/VLR receives the call, the MSRN can be released and may be made available for reassignment. Paging the Mobile Station The MSC/VLR then orders all of its BSCs and BTSs to page the MS. Since the MSC/VLR does not know exactly which BSC and BTS the MS is monitoring, the page will be sent out across the entire Location Area.

Page 66: Adding Support for Authentication and Encryption to Openbts

58 Introduction to GSM

Initial Setup The MS receives the Page Request (PAG_REQ) on the PCH. The MS recognizes that the page is intended for it, based on a TMSI or an IMSI. The MS sends a Channel Request (CHAN_REQ) message on the RACH. The BSS responds on the AGCH by sending an Immediate Assignment (IMM ASS) message which assigns an SDCCH to the MS. At this point, the network does not know that the MS is the one that it is paging, it only knows that this MS wants access to the network. The MS immediately switches to the assigned SDCCH and sends a Paging Response (PAG_RES) message on the SDCCH. This lets the network know that the MS is responding to its page. Authentication Before the network will provide any services to the MS, the network will require the MS to authenticate itself. The BSS sends an Authentication Request (AUTH_REQ) message to the MS. The RAND serves as the "challenge" for authentication. The MS calculates the proper SRES based on the RAND that was given and sends the SRES to the BSS in an Authentication Response (AUTH_RESP) message. The BSS verifies the SRES. If the SRES is correct then the MS is authenticated and allowed access to the network. Once the MSC/VLR has authenticated the MS, it will order the BSS and MS to switch to cipher mode using the CIPH_MOD_CMD message. Once the MS in encryption mode, the VLR will normally assign a new TMSI to the MS. Establishing a Channel Once the MS is authenticated and in encryption mode, The MSC sends a Setup Message to the BSS, the BSS forwards the SETUP message to the MS on the assigned SDCCH.the assigned SDCCH. The SETUP message may include the Calling Line Identification Presentation (CLIP), which is essentially caller ID. The MS responds by sending a Call Confirmed (CALL_CON) message; which indicates that the MS is able to establish the requested connection. The BSS relays the message up to the MSC. Call Setup The BSS then sends an Assignment Command (ASS_CMD) message to the MS on the assigned SDCCH. The ASS_CMD message assigns a Traffic Channel (TCH) to the MS. The MS immediately switches to the TCH and responds with an Assignment Complete (ASS_COM) message on the FACCH. The MS begins ringing once it has established the TCH. Remember that all signaling that occurs on the traffic channel actually occurs on a FACCH, which is a time slot that is stolen from the TCH and used for signaling. The MS sends an ALERT message to the MSC on the FACCH. The BSS forwards the

Page 67: Adding Support for Authentication and Encryption to Openbts

59 OpenBTS

ALERT message through the PSTN to the calling party and the caller hears the line ringing. Call Establishment Once the user answers the call (by pressing the send button), the MS will send a Connect CON message to the MSC. The Connect message is forwarded back to the caller's switch to activate the call. The MSC sends a Connect Acknowledge CON_ACK message to the MS and the call is established. Call Disconnect Disconnect happens the same way as for any other call. In this example, the calling party initiates the disconnect. When the calling party hangs up, the calling party's switch initiates a Release (REL) message. The message is forwarded to the serving MSC, which is then forwarded to the BSS. The BSS will send a Disconnect (DISC) message to the MS on the FACCH. The MS confirms release of the call by sending a Release (REL) message on the FACCH, which is forwarded to the MSC. The MSC sends e Release Complete (REL_COM) message through the BSS to the MS. As far as call control (CC) is concerned, the connection has been terminated. The MS still has a TCH assigned to it, so the BSS sends a Channel Release (CHAN_REL) message to the MS. This releases the radio resource on the Air Interface. The MS responds be sending a final Disconnect message and returns to idle.

Page 68: Adding Support for Authentication and Encryption to Openbts

60 Introduction to GSM

Figure 1.43: Summary for Mobile Terminating call:

Page 69: Adding Support for Authentication and Encryption to Openbts

61 OpenBTS

1.6.6 Location Update: There are 3 types of location update: 1. Location Updating, Type Normal: The MS listens to the system information, compares the Location Area Identity (LAI) to the one stored in the MS on the SIM card (on BCCH channel if idle or SACCH channel if active) and detects whether it has entered a new location area or is still in the same location area. If the broadcast LAI differs from the one stored on the SIM card, the MS must perform a location update, type normal:

1) The MS sends a channel request message including the reason for the access. Reasons other than location updating can be for example, answering a page or emergency call. 2) The message received by the BTS is forwarded to the BSC. The BSC allocates an SDCCH, if there is one idle, and tells the BTS to activate it. 3) The MS is now told to tune to the SDCCH. 4) The MS sends a location updating request message that contains the identity of the MS, the identity of the old location area and the type of updating. 5) The authentication parameter is sent to the MS. In this case the MS is already registered in this MSC/VLR and the authentication parameter used is stored in the VLR. (If the MS is not already registered in this MSC/VLR the appropriate HLR or the previously used MSC/VLR must be contacted to retrieve MS subscriber data and authentication parameters) 6) MS sends an answer calculated using the received authentication parameter. 7) If the authentication is successful, the VLR is updated. If needed, the HLR and old VLR are also updated. 8) The MS receives an acceptance of the location updating. 9) The BTS is told to release the SDCCH. 10) The MS is told to release the SDCCH and switches to idle mode. In cases where the MS is busy when it changes location area, it receives the information about the new LAI on the SACCH. The location updating takes place after the call is released. The MS must set up a new connection and perform the procedures described in the previous case.

2. Location Updating, Type IMSI attach: IMSI attach is a procedure and is used by the MS to notify the system that it was powered on. The procedure is described below:

1) The MS requests an SDCCH. 2) The system receives the IMSI attach message from the MS. 3) The MSC sends the IMSI attach message to the VLR.The VLR removes the IMSI detached flag and resumes normal call handling for the MS. (Notice that IMSI attach is the complement to the IMSI detach procedure. 4) The VLR returns the IMSI attach acknowledge message to the MSC. 5) The MS also receives an acknowledge message.

Page 70: Adding Support for Authentication and Encryption to Openbts

62 Introduction to GSM

Notice: The procedure is to be used only when the IMSI detach flag is set in the VLR, not in the HLR. If the flag is set in the HLR, switching to active mode requires a normal location updating of the MS. In most GSM system, the detached flag is stored in the VLR and no information is passed to the HLR. 3. Location Updating, Type periodic registration: Periodic registration is a type of location updating procedure that is used to avoid unnecessary paging of the mobile in cases where the MSC never receives the IMSI detach message and also to prevent damage in case of database failure. The procedure is described below:

1) MS listens on the BCCH to specify if Periodic Registration Location Update is used in the cell. If periodic registration is used, the MS is told how often it must register. The time is set by the operator and can have values from 0 to 255 deci-hours (a unit of six minutes). If the parameter is equal to zero, periodic registration is not used in this cell. If the parameter is set to ten, for example, the MS must register every hour. 2) Both the MS and the MSC have the timer which controls the procedure. When the timer in the MS expires, the MS performs a location updating, type periodic registration. After that, the timers in MS and MSC restart. In the MSC there is a time scanning function for the MSs. If the MS does not register within the determined interval plus a guard time, then the scanning function in MSC detects this and the MS is flagged as detached.

Page 71: Adding Support for Authentication and Encryption to Openbts

63 OpenBTS

Figure 1.44: Summary for Location Update:

Page 72: Adding Support for Authentication and Encryption to Openbts

64 Introduction to GSM

1.6.7 Call Clearing: There are 2 types of call clearing:

1. Call Clearing Initiated by the Net

2. Call Clearing Initiated by the Mobile Station

Page 73: Adding Support for Authentication and Encryption to Openbts

65 OpenBTS

References:

[1] http://www.tutorialspoint.com

[2] http://students.ee.sun.ac.za/~gshmaritz/gsmfordummies/arch.shtml

[3] http://www.telecomspace.com/gsm.html

[4] GSM by Siemens

[5] http://www.dummies.com/how-to/content/getting-to-know-the-osi-model-for-the-ccna-

exam.html#ixzz1RYd53mnu

[6] http://www.buzzle.com/articles/osi-model-explained.html

[7] SYS01: GSM Interfaces and Protocols © 2006 Motorola

[8] http://www.gsmfordummies.com/gsmevents/mobile_originated.shtml

Page 74: Adding Support for Authentication and Encryption to Openbts

66 About OpenBTS

Chapter 2: About OpenBTS

2.1 Introduction The OpenBTS Project is an effort to construct an open-source Unix application that uses the Universal Software Radio Peripheral (USRP) to present a GSM air interface (―Um‖) to standard GSM handset and uses the Asterisk VoIP PBX to connect calls. This is in fact very different from a conventional GSM BTS, which is a dumb device that is managed externally by a base station controller (BSC) and connects calls in a remote mobile switching center (MSC). Because of this important architectural difference, the end product of this project is better referred to as an access point, even though the project is called ―OpenBTS‖. According to David Burgess, founder of OpenBTS, in an interview in the emerging communications conference (eComm): ―We know, from public records and interviews with former employees of cellular carriers in Africa, we know the actual cost of service in Africa is something on the order of $5 or $6 per month, per subscriber. We believe in those same environments, the type of network we're talking about [openBTS] can be operated at an order of magnitude lower cost. You could have profitable operations at around $1 per subscriber.‖ OpenBTS also serves as an excellent internal communication tool for field engineers & technicians using mobilephones, as an alternative to walkie-talkie and other classic systems, inwork fields of limited area.

2.2 What‟s OpenBTS? OpenBTS stands for Open Base Transceiver Station. It is an open-source UNIX application that uses the Universal Software-Radio Peripheral (USRP) to present a GSM air interface ("Um") to standard GSM handsets and uses the Asterisk® software PBX to connect calls. [1] As shown in Fig 2.1, the OpenBTS uses the USRP hardware to receive and transmit the GSM signaling. This is done by using the GNU Radio framework. Asterisk is used to interface the GSM calls between the cellular phones under the OpenBTS network. Any other device that can be connected to Asterisk can be also used. Generally speaking, OpenBTS consists of a USRP board connected on a USB port of a Linux machine running Asterisk, GnuRadio and OpenBTS. [2]

2.3 Main Components & Their Functions a. Hardware I. Computer We have done several testing on a laptop powered by Intel dual-core 1.7 GHz and 2 GBs of RAM and it worked totally fine. Some other implementations were done on ARM test-boards, Android phones

Page 75: Adding Support for Authentication and Encryption to Openbts

Secure OpenBTS 67

II. USRP The USRP is a hardware designed by Ettus Research to allow general purpose computers to function as high bandwidth software radios. In essence, it serves as a digital baseband and IF section of a radio communication system. [3] The USRP used for our implementation was USRP ver 1, having the following specifications:[4]

8 MHz of instantaneous RF bandwidth

Lowest cost solution

USB connectivity

MIMO with a single USRP device the motherboard has two daughterboard slots

FPGA: Altera Cyclone

ADCs: 12-bits 64 MS/s

DACs: 14-bits 128 MS/s

III. Daughterboards Daughterboards turn a USRP or USRP2 motherboard into a complete RF transceiver system. Just add an antenna, and you are ready for two-way, high bandwidth communications in many popular frequency bands. [5] There are several daughterboards that can be used with the USRP covering from DC to 5.9 GHz. For OpenBTS, we can use the RFX900, to cover the GSM 850 and 900 bands, or the RFX1800, to cover the GSM 1800 and 1900 bands. [3] Normally, OpenBTS needs two daughterboards, however there‘s a patch[2] that can be used to allow OpenBTS to work using a single daughterboard. IV. Antenna(s) At least two VERT900 are needed. One for TX and another for RX. VERT900 is a 9-inch. 824-960 MHz, 1710-1990 MHz Quad-band Cellular/PCS and ISM Band vertical antenna having 3dBi Gain and it‘s ideal for both RFX900 and RFX1800. [3] Due to the strong on-board RF gain, our tests proved that OpenBTS can work with reduced signal strength and coverage with no antennas at all, however this is not recommended. V. Mobile Station Any unlocked cellular phone can be used. Nokia DCT-3 series phones are most preferred as they include the field-test mode, known as ―Netmonitor‖. Netmonitor can be used to force the mobile station to limit its network search to a certain ARFCN. It can also be used for many other monitoring and troubleshooting purposes. To learn how to enable Netmonitor on Nokia DCT-3 phones, you may check Due to some problems with the stock clock shipped with the USRP, some phones don‘t succeed in finding or registering to OpenBTS. Netmonitor is mainly used to force phones to camp to a certain ARFCN regardless of clock frequency errors. Most phones (especially smartphones) that were manufactured in 2011 were discovered to work

Page 76: Adding Support for Authentication and Encryption to Openbts

68 About OpenBTS

on OpenBTS with no problems. [6] VI. Sim Card(s) OpenBTS should work using any SIM card from any operator, as long as the phone is manually set to register to OpenBTS rather than any other existing network(s). However, for certain applications (like the one this book is based on), programmable SIM cards are used. Of course, in case of using programmable SIM Cards, SIM Card reader/writer will be needed. b. Software[3] I. UNIX or UNIX-like OS Preferably Ubuntu Linux. OpenBTS should also work on Mac OS X. II. OpenBTS Mainly as a GSM stack. III. GNURadio To interface with the USRP on the software-level. IV. Asterisk (or FreeSwitch) Asterisk is an open-source VoIP PBX server that OpenBTS uses by default to connect local and external calls. Other PBX servers like FreeSwitch can also be used. [8] V. C++ Boost libraries Used in some parts of the OpenBTS source-code. 2.4 Clock Modification According to [7], In most GSM implementations, the symbol clock is derived from a 13 MHz ―stratum 3‖ OCXO with a frequency accuracy on the order of 20 ppb. (A VCTCXO in the handset is slaved to the OXCO in the BTS via the FCCH.) The standard USRP clock is a low-cost 64 MHz crystal oscillator. This poses two problems for OpenBTS: 1. The USRP standard clock is not well-matched to the GSM symbol rate. In the current OpenBTS implementation, the software radio includes a resampler for rate-matching, but this is an additional computational cost that should be eliminated. 2. The USRP standard clock is not stable enough for use in multi-BTS networks. The drift of the crystal oscillator may even be outside the frequency search range of some GSM phones. To solve the second problem, the USRP main board should be modified to use a more accurate external clock source according to 2.5 Installation of OpenBTS on Linux (Ubuntu) (Copied from [3] after making few edits) 2.5.1 GNU Radio Installation

a. Installing the dependencies: sudo apt-get update

sudo apt-get -y install swig g++ automake1.9 libtool python-dev

Page 77: Adding Support for Authentication and Encryption to Openbts

Secure OpenBTS 69

sudo apt-get -y install libcppunit-dev sdcc libusb-dev libasound2-dev

libsdl1.2-dev

sudo apt-get -y install python-wxgtk2.8 subversion guile-1.8-dev

libqt4-dev

sudo apt-get -y install ccache python-opengl libgsl0-dev python-

cheetah python-lxml

sudo apt-get -y install libqwt5-qt4-dev libqwtplot3d-qt4-dev qt4-dev-

tools

sudo apt-get -y install fftw3-dev doxygen python-numpy-ext

b. Getting and installing boost libraries: wget

http://kent.dl.sourceforge.net/sourceforge/boost/boost_1_37_0.tar.gz

tar xvzf boost_1_37_0.tar.gz

cd boost_1_37_0

BOOST_PREFIX=/opt/boost_1_37_0

./configure --prefix=$BOOST_PREFIX --with-

libraries=thread,date_time,program_options

make

sudo make install

c. Getting and installing GNURadio: cd ~

wget ftp://ftp.gnu.org/gnu/gnuradio/gnuradio-3.3.0.tar.gz

tar -zxf gnuradio-3.3.0.tar.gz

cd gnuradio-3.3.0

./configure --with-boost-include-dir=$BOOST_PREFIX/include/boost-1_37/

make

make check

sudo make install

sudo mv ~/gnuradio-3.3.0 /usr/local/share

Note:

GnuRadio is also available for download through the GUI front-end for aptitude, Synaptic Package Manager, found in the ―System‖ menu under ―Administration‖.

It's preferred to use the latest version of GnuRadio.If a newer version than the one presented here is found, please download it from http://gnuradio.org/releases/gnuradio or ftp://ftp.gnu.org/gnu/gnuradio. To install it on your PC, extract it run INSTALL.

Removing an old GnuRadio installation on Ubuntu or other Debian-based Linux systems can be done either by referring to the ―Synaptics Package Manager‖, selecting gnuradio and choosing ―Mark for Complete Removal‖ then clicking ―Apply‖, or by simply running ―sudo apt-get remove gnuradio‖

Page 78: Adding Support for Authentication and Encryption to Openbts

70 About OpenBTS

2.5.2 OpenBTS installation

a. Installing the dependencies: sudo apt-get install asterisk libosip2-dev libortp7-*

b. Getting the source code: download the last version available online from [1] and save it in your home directory or any other preferred working directory.

c. Installing: tar -zxf openbts-2.6.0Mamou.tar.gz

mv openbts-2.6.0Mamou openbts-2.6.0

cd openbts-2.6.0

export LIBS=-lpthread

./configure

make

sudo make install

2.5.3 Adding user permissions to work with the USRP: sudo addgroup usrp

sudo addgroup <YOUR_USER> usrp

echo 'ACTION=="add", BUS=="usb", SYSFS{idVendor}=="fffe",

SYSFS{idProduct}=="0002", GROUP:="usrp", MODE:="0660"' > tmpfile

sudo chown root.root tmpfile

sudo mv tmpfile /etc/udev/rules.d/10-usrp.rules

Alternatively, this step can also be done using GUI by referring to ―Users & Groups‖ available in the Ubuntu ―Administration‖ menu, then adding a group called ―usrp‖ (if not there already). Make sure that the ―usrp‖ group has the current user of the machine marked as a user of this group, in the ―Properties‖ window.

2.5.4 Testing the USRP:

Restart the computer (it should work without it, but even restarting the udev service, the USRP worked with user privileges only by restarting the machine): sudo reboot

Connect the USRP to the USB port cd /usr/local/share/gnuradio-3.3.0/gnuradio-examples/python/usrp

./usrp_benchmark_usb.py

Page 79: Adding Support for Authentication and Encryption to Openbts

Secure OpenBTS 71

The output should be similar to this: Check if the maximum throughput between USB and USRP is 32MB/sec.

Testing 2MB/sec... usb_throughput = 2M

ntotal = 1000000

nright = 998435

runlength = 998435

delta = 1565

OK

Testing 4MB/sec... usb_throughput = 4M

ntotal = 2000000

nright = 1998041

runlength = 1998041

delta = 1959

OK

Testing 8MB/sec... usb_throughput = 8M

ntotal = 4000000

nright = 3999272

runlength = 3999272

delta = 728

OK

Testing 16MB/sec... usb_throughput = 16M

ntotal = 8000000

nright = 7992153

runlength = 7992153

delta = 7847

OK

Testing 32MB/sec... usb_throughput = 32M

ntotal = 16000000

nright = 15986239

runlength = 15986239

delta = 13761

OK

Max USB/USRP throughput = 32MB/sec

Page 80: Adding Support for Authentication and Encryption to Openbts

72 About OpenBTS

2.6 Finding an Unused Frequency Band

Luckily, GnuRadio is shipped with a built-in ―Spectrum Analyzer‖ script. The script file name is

usrp_spectrum_sense.py and can be found in the examples/usrp directory inside the gnuradio

root directory. usrp_spectrum_sense.py can be used to find out the available frequencies.

Practically speaking, usrp_fft.py script (fig. 2) should be used instead [3] as it includes a user-

friendly GUI. To run , you have to type the following command in terminal: $ usrp_fft.py -f 1.7838G & where 1.7838 GHz is the centre frequency used.

Kalibrate may also be used to determine vacant frequency bands in a certain area by using the

―GSM Base Station Scan‖ mode for scanning the whole GSM spectrum in this area for BCCH

signals of any nearby BTS and avoiding using the used frequencies by those BTSs.

For example, to use Kalibrate for scanning the GSM-850 band:

$ src/kal -s 850

The output should be similar to:

kal: Scanning for GSM-850 base stations.

GSM-850:

chan: 128 (869.2MHz - 13Hz) power: 9400.80

chan: 131 (869.8MHz + 7Hz) power: 4081.75

chan: 139 (871.4MHz + 10Hz) power: 2936.20

chan: 145 (872.6MHz - 7Hz) power: 33605.48

2.7 Configuring OpenBTS

To configure OpenBTS to run for the first time, it‘s required to open the

apps/OpenBTS.config.example with the most preferred editor then save the file as

OpenBTS.config after making the following modifications.

● The GSM.MCC (Mobile Country Code) should be set according to your country. In our case it is 602(Egypt). To avoid any problems with the current operators, it‘s highly recommended to use 001 as it‘s reserved for testing purposes.

● The GSM.MNC (Mobile Network Code). A good way to check it is by scanning the network with the phone and checks the operator‘s code. Normally it‘ll be showed in the MCC-MNC format (e.g. 602 07). This means that the country is Egypt and network code is 07.

Page 81: Adding Support for Authentication and Encryption to Openbts

Secure OpenBTS 73

To avoid any problems with the current operators, it‘s highly recommended to use 01 as it‘s reserved for testing purposes.

● The GSM.Band defines the frequency band that the OpenBTS will operate on. The best is to use a band not allocated in your region, but sometimes this is not possible. If it‘s your case, you‘ll need to check using a Spectrum Analyzer as shown previously, what is the band has a free space. You can use USRP as Spectrum Analyzer for low cost. Now we can set the GSM.ARFCN (Absolute RF Channel) as the ARFCN for the band we are willing to use.

Legal Notice: It‘s highly recommended to refer to the telecom laws and regulations in your country before running OpenBTS, to avoid any legal complications.

The OpenBTS.config file should like this: (Modifications are bolded) # Sample OpenBTS configuration file.

# Formatting rules:

# Configuration values are defined with line of the form

<key><space><value>

# The key name can contain no spaces.

# Everything between the first space and the end of the line becomes

the value.

# Numeric values can be preceded with "0x" for hex.

# Blank lines are OK.

# Lines starting with "#" are comments.

# By default, configuration values can be changed but not removed

after initialization.

# Lines starting with "$" are directives that define other properties

of config values:

# "static" -- configuration value cannot be changed or removed after

initialization.

# "optional" -- configuration value may be removed after

initialization.

# As a gerenal rule, non-valid configuration values will crash

OpenBTS.

# So be cafeful.

#

# Logging and reporting parameters

#

# The initial global logging level: ERROR, WARN, NOTICE, INFO, DEBUG,

DEEPDEBUG

Log.Level INFO

# Logging levels can also be defined for individual source files.

# This example set shows normal operations in the control layer (L3).

Log.Level.MobilityManagement.cpp INFO

$optional Log.Level.MobilityManagement.cpp

Log.Level.CallControl.cpp INFO

$optional Log.Level.CallControl.cpp

Log.Level.RadioResource.cpp INFO

$optional Log.Level.RadioResource.cpp

# The log file path. If not set, logging goes to stdout.

Page 82: Adding Support for Authentication and Encryption to Openbts

74 About OpenBTS

Log.FileName test.out

#$static Log.FileName

# LOG(ALARM) is printed and also sent as udp to this address.

Log.Alarms.TargetIP 192.168.10.200

$optional Log.Alarms.TargetIP

Log.Alarms.TargetPort 10101

# Number of alarms saved in internal queue

Log.Alarms.Max 10

# Wireshark support

# OpenBTS writes L2 GSMTAP messages to this port.

# If GSMTAP.TargetIP is not defined, this output is disabled.

GSMTAP.TargetIP 127.0.0.1

$optional GSMTAP.TargetIP

# The standard IANA for GSMTAP is 4729. This can be used to override

that.

#GSMTAP.TargetPort 4729

# Indications port

# Some interal operations produce status reports sent to this port.

# This can be the same as the Alarm target.

Indications.TargetIP 127.0.0.1

Indications.TargetPort 10202

# Port number for test calls.

# This is where an external program can interact with a handset via

UDP.

TestCall.Port 28670

#

# Transceiver parameters

#

# Transceiver interface

# This TRX.IP is not really adjustable.

Just leave it as 127.0.0.1.

TRX.IP 127.0.0.1

$static TRX.IP

# This value is hard-coded in the transcevier.

TRX.Port 5700

$static TRX.Port

Just leave it alone.

# Path to transceiver binary

# If this is not defined, you will need to start the transceiver by

hand.

# YOU MUST HAVE A MATCHING libusrp AS WELL!!

TRX.Path ../Transceiver/transceiver

#TRX.Path ../Transceiver52M/transceiver

#$static TRX.Path

Page 83: Adding Support for Authentication and Encryption to Openbts

Secure OpenBTS 75

# TRX logging.

# Logging level.

# IF TRX.Path IS DEFINED, THIS MUST ALSO BE DEFINED.

TRX.LogLevel ERROR

#$static TRX.LogLevel

# Logging file. If not defined, logs to stdout.

# TRX.LogFileName test.out

#$static TRX.LogFileName

#

# SIP, RTP, servers

#

# Asterisk PBX

Asterisk.IP 127.0.0.1

Asterisk.Port 5060

$static Asterisk.IP

$static Asterisk.Port

# Messaging server

Smqueue.IP 127.0.0.1

Smqueue.Port 5063

$static Smqueue.IP

$static Smqueue.Port

# Local SIP/RTP ports

# OpenBTS binds to these ports.

SIP.Port 5062

$static SIP.Port

RTP.Start 16484

RTP.Range 98

$static RTP.Start

$static RTP.Range

# If Asterisk is 127.0.0.1, this is also 127.0.0.1.

# Otherwise, this should be the local IP address of the interface

used to contact asterisk.

# In other words, this is the IP address at which Asterisk will see

OpenBTS.

SIP.IP 127.0.0.1

#

# Special extensions.

#

# Routing extension for emergency calls.

# This must be defined, even if you are not supporting emergency

calls.

# PBX.Emergency 2101

#

# SIP parameters

Page 84: Adding Support for Authentication and Encryption to Openbts

76 About OpenBTS

#

# SIP registration period in seconds.

# Ideally, this should be slightly longer than GSM.T3212.

SIP.RegistrationPeriod 7200

#

# SIP Internal Timers. All timer values are given in millseconds.

# These are from RFC-3261 Table A.

#

# SIP Timer A, the INVITE retry period, RFC-3261 Section 17.1.1.2

# in milliseconds

# For fast SMS interactions, keep this at 2000 or more.

SIP.Timer.A 2000

#

# SMS parameters

#

# ISDN address of source SMSC when we fake out a source SMSC.

SMS.FakeSrcSMSC 0000

# ISDN address of destination SMSC when a fake value is needed.

SMS.DefaultDestSMSC 0000

# The SMS HTTP gateway.

# Comment out if you don't have one or if you want to use smqueue.

# SMS.HTTP.Gateway api.clickatell.com

# IF SMS.HTTP.Gateway IS DEFINED, SMS.HTTP.AccessString MUST ALSO BE

DEFINED.

# SMS.HTTP.AccessString sendmsg?user=xxxx&password=xxxx&api_id=xxxx

# Things to query during registration updates.

#Control.LUR.QueryIMEI

$optional Control.LUR.QueryIMEI

#Control.LUR.QueryClassmark

$optional Control.LUR.QueryClassmark

# Does everyone get a TMSI, registered or not?

Control.LUR.TMSIsAll

$optional Control.LUR.TMSIsAll

# TMSI table controls

# Maximum number of TMSIs to track

Control.TMSITable.MaxSize 10000

# Maximum allowed ages of a TMSI, in hours.

Control.TMSITable.MaxAge 72

# Want persistent TMSIs?

Control.TMSITable.SavePath TMSITable.txt

$optional Control.TMSISavePath

# Open Registration and Self-Provisioning

# If this is defined, the network accepts LUR from unprovisioned

handsets.

# This is required to support SMS-based auto-provisioning.

Page 85: Adding Support for Authentication and Encryption to Openbts

Secure OpenBTS 77

# This is a boolean -- either defined or not.

Control.OpenRegistration

$optional Control.OpenRegistration

#

#

#

#

#

#

"Welcome" messages sent during IMSI attach attempts.

ANY WELCOME MESSAGE MUST BE LESS THAN 138 CHARACTERS.

ANY DEFINED WELCOME MESSAGE MUST ALSO HAVE A DEFINED SHORT CODE.

Comment out any message you don't want to use.

# The message sent upon full successful registration, all the way

through the Asterisk server.

# THIS MESSAGE IS NORMALLY REQUIRED FOR COMPLIANCE WITH AGPLv3.

Control.NormalRegistrationWelcomeMessage Welcome to OpenBTS! AGPLv3

openbts.sf.net. Your IMSI is

Control.NormalRegistrationWelcomeShortCode 0000

# Then message sent to accpeted open registrations.

# IF OPEN REGISTRATION IS ENABLED, THIS MUST ALSO BE DEFINED.

# THIS MESSAGE IS NORMALLY REQUIRED FOR COMPLIANCE WITH AGPLv3.

Control.OpenRegistrationWelcomeMessage Welcome to OpenBTS! AGPLv3

openbts.sf.net. Your IMSI is

# If you use SMS auto-provisioning, use that short code as the return

address here.

Control.OpenRegistrationWelcomeShortCode 101

# Then message send to failed registrations.

#Control.FailedRegistrationWelcomeMessage Your handset is not

provisioned for this network.

$optional Control.FailedRegistrationWelcomeMessage

Control.FailedRegistrationWelcomeShortCode 1000

#

# GSM

#

# Network and cell identity.

# Network Color Code, 0-7

# Also set GSM.NCCsPermitted later in this file.

GSM.NCC 0

# Basesation Color Code, 0-7

GSM.BCC 2

# Mobile Country Code, 3 digits.

# MCC MUST BE 3 DIGITS. Prefix with 0s if needed.

# Test code is 001.

GSM.MCC 001

# Mobile Network Code, 2 or 3 digits.

# Test code is 01.

GSM.MNC 07

# Location Area Code, 0-65535

GSM.LAC 1000

# Cell ID, 0-65535

GSM.CI 10

Page 86: Adding Support for Authentication and Encryption to Openbts

78 About OpenBTS

# Network "short name" to display on the handset.

# This is optional, but must be defined if you also want to

# send current time-of-day to the phine.

GSM.ShortName OpenBTS

$optional GSM.ShortName

# A boolean telling whether or not to show country initials with the

name.

GSM.ShowCountry

$optional GMS.ShowCountry

# Assignment type for call setup.

# The default is early assignment.

# If defined, this will cause us to use very early assignment

instead.

#GSM.VEA

$optional GSM.VEA

# Band and Frequency

# Valid band values are 850, 900, 1800, 1900.

GSM.Band 900

$static GSM.Band

# Valid ARFCN range depends on the band.

GSM.ARFCN 80

# GSM.ARFCN 7 works on some phones in el center elli odam el forn

# GSM.ARFCN 7

# ARCN 975 is inside the US ISM-900 band and also in the GSM900 band.

#GSM.ARFCN 975

# ARFCN 207 was what we ran at BM2008, I think, in the GSM850 band.

#GSM.ARFCN 207

$static GSM.ARFCN

2.8 Installing & Configuring smqueue To compile you first have to install g++-4.3: sudo apt-get install g++-4.3 Then, in OpenBTS/smqueue/Makefile.standalone: Modify g++ -o smqueue $(CPPFLAGS) $(INCLUDES) smqueue.cpp smnet.cpp smcomm... to become g++-4.3 -o smqueue $(CPPFLAGS) $(INCLUDES) smqueue.cpp smnet.cpp smcomm... (In this step we’re instructing gcc to use g++-4.3 instead of g++ for compiling the file) Finally, we will compile smqueue by issuing the following command: sudo make -f Makefile.standalone Note:

By default, OpenBTS is configured to accept only 7 - 12 digit phone numbers on auto-provisioning. This can easily be modified by setting the values of SC.Register.Digits.Max and SC.Register.Digits.Min at openbts/smqueue/smqueue.config.

Page 87: Adding Support for Authentication and Encryption to Openbts

Secure OpenBTS 79

2.9 Asterisk Configuration

a. Backup the /etc/extensions.conf and /etc/sip.conf: cd /etc/asterisk

sudo cp extensions.conf extensions.conf_ori

sudo cp sip.conf sip.conf_ori

b. Copy ~/openbts-2.3/AsteriskConfig/extensions.conf and sip.conf to the /etc/asterisk: sudo cp ~/openbts-2.3/AsteriskConfig/sip.conf .

sudo cp ~/openbts-2.3/AsteriskConfig/extensions.conf .

c. Edit the /etc/asterisk/extension.conf: Add the following to the end of the file: …........ [sip-local]

exten => 2102,1,Macro(dialSIP,IMSI602*)

exten => 2103,1,Macro(dialSIP,IMSI602*)

….......

d. Edit the /etc/asterisk/sip.conf:

…........ ;provisioned Thu Mar 17 05:32:43 2011

[IMSI60203*]

callerid=2102

canreinvite=no

type=friend

context=sip-local

allow=gsm

host=dynamic

dtmfmode=info

;provisioned Thu Mar 17 05:36:13 2011

[IMSI60201*]

callerid=2103

canreinvite=no

type=friend

context=sip-local

allow=gsm

host=dynamic

dtmfmode=info

….........

e. Restart the Asterisk: sudo /etc/init.d/asterisk restart

Page 88: Adding Support for Authentication and Encryption to Openbts

80 About OpenBTS

2.10 Software Architecture of OpenBTS [7] These are the directories:

apps OpenBTS application binaries.

AsteriskConfig Asterisk configuration files for use with OpenBTS. This file contains example Asterisk configuration files for the OpenBTS Asterisk server. This file does not contain REAL configuration files, since those would include real IMSIs.

CLI This is the directory for the OpenBTS command line interface.

CommonLib Common-use libraries, mostly C++ wrappers for basic facilities, most of which are not specific to GSM.

Control

Control-layer functions for the protocols of GSM 04.08 and SIP. Most GSM L3 and VoIP messages terminate here. Everything in this directory should be in the Control namespace. Components: -- RadioResource. -- MobilityManagement. -- CallControl.

doc Project documentation.

GSM The GSM stack.

SIP Components of the SIP state machines ued by the control layer.

smqueue

RFC-3428 store-and-forward server for SMS. Smqueue has different build dependencies than OpenBTS and so it has its own make file outside of the standard openbts autobuild system. This allows smqueue to be built without installing GNU Radio.

SMS The SMS stack.

Transceiver

The software transceiver and specific installation tests.The transceiver consists of three modules: --- transceiver --- radioInterface --- USRPDevice

TRXManager The interface between the GSM stack and the radio.Each TRX Manager UDP socket interface represents a single ARFCN.The per-ARFCN control interface uses a command-reponse protocol.

About apps directory : * OpenBTS.cpp: it contains main function.

* OpenBTS.config.example: Sample OpenBTS configuration file.

About GSM directory : That is directory where most of our work is on. This is a small description for the included files: * GSML1FEC.h & GSML1FEC.cpp: L1, ―PHYSICAL LAYER‖, the radio modem, time-division multipexing, and error-correcting coding, GSM 04.04 and GSM 05.xx series.

Page 89: Adding Support for Authentication and Encryption to Openbts

Secure OpenBTS 81

* GSML2LAPDm.h & GSML2LAPDm.cpp: L2, ―DATA LINK LAYER‖, link layer addressing, segmentation and retransmission , GSM 04.05 and 04.06, ITU-T Q.921.

* GSML3Message.h & GSML3Message.cpp: Description of standard L3 messages, GSM 04.07

* GSML3CommonElements.h & GSML3CommonElements.cpp: Common information elements, GSM 04.08 Sec. 10.5.1.

* GSML3CCMessages.h & GSML3CCMessages.cpp: Messages for circuit-switched call control, GSM 04.08 Sec.9.3, ITU-T Q.931.

* GSML3CCElements.h & GSML3CCElements.cpp:Call control information elements, GSM 04.08 Sec. 10.5.4.

* GSML3MMMessages.h & GSML3MMMessages.cpp: Messages for mobility management, 04.08 Sec. 9.2.

* GSML3MMElements.h & GSML3MMElements.cpp: Mobility management information elements, GSM 04.08 Sec. 10.5.3.

* GSML3RRMessages.h & GSML3RRMessages.cpp: Messages for Radio Resources management, GSM 04.08 Sec. 9.1.

* GSML3RRElements.h & GSML3RRElements.cpp: Radio Resource management information elements, GSM 04.08 Sec. 10.5.2.

* GSMLogicalChannel.cpp & GSMLogicalChannel.cpp: A complete logical channel. Includes processors for L1, L2, L3, as needed. The layered structure of GSM is defined in GSM 04.01. The concept of the logical channel and the channel types are defined in GSM 04.03.

* GSMEncryption.h: contatain A3A8 algorithm and A5/1 algorithm.

* GSMTransfer.h & GSMTransfer.cpp: Data transfer objects for the GSM core.

* GSMTDMA.h & GSMTDMA.cpp: A description of a channel's multiplexing pattern From GSM 05.02 Clause 7.

Classes for GSM directory:

Classes for GSML1FEC: * GSM::L1Encoder

Abstract class for L1 encoders. In most subclasses, writeHighSide() drives the processing. Definition at line 81 of file GSML1FEC.h. Inheritance from L1Encoder classes GeneratorL1Encoder [FCCHL1Encoder, SCHL1Encoder], XCCHL1Encoder [CCCHL1Encoder, NDCCHL1Encoder (BCCHL1Encoder), SACCHL1Encoder, TCHFACCHL1Encoder]

Page 90: Adding Support for Authentication and Encryption to Openbts

82 About OpenBTS

* GSM::L1Decoder An abstract class for L1 decoders. writeLowSide() drives the processing. Definition at line 200 of file GSML1FEC.h. Inheritance from L1Decode classes RACHL1Decode, XCCHL1Decoder [ SDCCHL1Dencoder, SACCHL1Decoder, TCHFACCHL1Decoder]

* GSM::L1FEC The L1FEC encapsulates an encoder and decoder. Definition at line 327 of file GSML1FEC.h. Inheritance from L1FEC classes CCCHL1FEC, LoopbackL1FEC, NDCCHL1FEC [ BCCHL1FEC, FCCHL1FEC, RACHL1FEC, SCHL1FEC], SACCHL1FEC, SDCCHL1FEC, TCHFACCHL1FEC, TestL1FEC.

Classes for GSML2LAPDm: * GSM::L2DL

Skeleton for data link layer (L2) entities. This is a base class from which the various channel classes are derived. Many derived classes are "thin" and do not implement full LAPDm. This is especially true of the downlink-only classes which do not have equivalents in Q.921 and HDLC. Definition at line 63 of file GSML2LAPDm.h. Inheritance from L2DL classes CCCHL2, L2LAPDm [FACCHL2, SACCHL2, SDCCHL2]

Classes for GSMLogicalChannel: * GSM::LogicalChannel

Definition at line 65 of file GSMLogicalChannel.h. Inheritance from LogicalChannel classes L3LoopbackLogicalChannel, NDCCHLogicalChannel [CCCHLogicalChannel], SACCHLogicalChannel, SDCCHLogicalChannel [SDCCHLogicalChannel_LB], TCHFACCHLogicalChannel [TCHFACCHLogicalChannel_UPLINK]

Classes for GSML3Messages: * GSM::L3Messages

This is virtual base class for the messages of GSM's L3 signalling layer. It defines almost nothing, but is the origination of other classes. Definition at line 59 of file GSML3Message.h. Inheritance from L3MMMessages classes L3MMMessages, L3RRMessages, L3CCMessages.

* GSM::L3ProtocolElement Abstract class used for GSM L3 information elements. See GSM 04.07 Sec.11.2.1.1.4 for a description of TLV element formatting. Definition at line 175 of file GSML3Message.h.

Classes for GSML3MMMessages: * GSM::L3MMMessage

This a virtual class for L3 messages in the Mobility Management protocol. These messages are defined in GSM 04.08 Sec. 9.2 Definition at line 49 of file GSML3MMMessages.h. Inheritance from L3MMMessages classes L3CMReestablishmentRequest, L3CMServiceAccept,L3CMServiceReject, L3CMServiceAbort, L3CMServiceRequest, L3IdentityRequest, L3IdentityResponse, L3IMSIDetachIndication, L3LocationUpdatingAccept, L3LocationUpdatingReject,

Page 91: Adding Support for Authentication and Encryption to Openbts

Secure OpenBTS 83

L3LocationUpdatingRequest, L3AuthenticationReject, L3AuthenticationRequest, L3AuthenticationResponse, L3MMInformation, L3MMStatus.

Classes for GSML3RRMessages: * GSM::L3RRMessage

This a virtual class for L3 messages in the Radio Resource protocol. These messages are defined in GSM Sec. 04.08 9.1. Definition at line 47 of file GSML3RRMessages.h. Inheritance from L3RRMessages classes L3ApplicationInformation, L3AssignmentCommand, L3AssignmentComplete, L3AssignmentFailure, L3ChannelModeModify, L3ChannelModeModifyAcknowledge, L3ChannelRelease, L3ChannelRequest, L3ClassmarkChange, L3ClassmarkEnquiry, L3GPRSSuspensionRequest, L3ImmediateAssignment, L3ImmediateAssignmentReject, L3MeasurementReport, L3PagingRequestType1, L3PagingResponse, L3CipheringModeCommand, L3CipheringModeComplete, L3RRStatus, L3SystemInformationType1, L3SystemInformationType2, L3SystemInformationType3, L3SystemInformationType4, L3SystemInformationType5, L3SystemInformationType6.

Classes for GSML3CCMessages: * GSM::L3CCMessage

This a virtual class for L3 messages in the Call Control protocol. These messages are defined in GSM 04.08 Sec. 9.3. GSM call control is based on and nearly identical to ISDN call control. ISDN call control is defined in ITU-T Q.931. Definition at line 49 of file GSML3CCMessages.h. Inheritance from L3CCMessages classec L3classesAlerting, L3CallConfirmed, L3CallProceeding, L3CCStatus, L3Connect, L3ConnectAcknowledge, L3Disconnect, L3EmergencySetup, L3Hold, L3HoldReject, L3Progress, L3Release, L3ReleaseComplete, L3Setup, L3StartDTMF, L3StartDTMFAcknowledge, L3StartDTMFReject, L3StopDTMF, L3StopDTMFAcknowledge.

Anther classes: * GSM::L3RejectCause

RejectCause, GSM 04.08 Sec. 10.5.3.6 Definition at line 86 of file GSML3MMElements.h.

* GSM::L3RRCause RRCause, GSM 04.08 Sec. 10.5.2.31. Definition at line 514 of file GSML3RRElements.h.

* GSM::L3MobileIdentity Mobile Identity, GSM 04.08 Sec. 10.5.1.4. Definition at line 106 of file GSML3CommonElements.h.

* GSM::L3LocationAreaIdentify LAI, GSM 04.08 Sec. 10.5.1.3. Definition at line 67 of file GSML3CommonElements.h.

Page 92: Adding Support for Authentication and Encryption to Openbts

84 About OpenBTS

* GSM::L3Cause Cause, GSM 04.08 10.5.4.11 Read the spec closely: we only have to support coding standard 3 (GSM), and that format doesn't carry the "recommendation" field. Definition at line 186 of file GSML3CCElements.h.

* GSM::GSMError A base class for GSM exceptions. Definition at line 57 of file GSMCommon.h. Inheritance from GSMError classes L2ReadError, L2WriteError,L3ReadError, L3WriteError, RRLPReadError, SMSReadError.

Common Function for Messages: * int MTI() const { return (int)LocationUpdatingRequest; }

Return the messag type indicator

* size_t bodyLength() const; Return the expected message body length in bytes, not including L3 header.

* void parseBody( const L3Frame &src, size_t &rp ); The method starts processing at the first byte following the message type octet in the L3 message, which the caller indicates with the readPosition argument. If not defined, this will assert at runtime.

* void text(std::ostream&) const; Generate a human-readable representation of a message.

* void writeBody( L3Frame &dest, size_t &wp ) const;

The method defined in some subclasses. If not defined, this will assert at runtime.

About Control directory:

* CallControl.cpp: Functions for CC (mobile originated, mobile terminated)

* MobilityManagement.cpp: Functions for MM procedures (CM service, location updating)

* RadioResource.cpp: Functions for RR procedures (paging, access grant) and in it we can determine the channel type needed.

* SMSControl.cpp: Controller for SMS MOSMS (Mobile Originated Short Message Service): The MS "submits" a message that OpenBTS then "sends" to the network, and MTSMS (Mobile Terminated Short Message Service): OpenBTS "receives" a message from the network that it then "delivers" to the MS.

* DCCHDispatch.cpp: Dispatch the appropriate controller for a Mobility Management message and for a Radio Resource message.

Functions for MobilityManagement.cpp: * void Control::CMServiceResponder(const L3CMServiceRequest* cmsrq, LogicalChannel* DCCH)

Controller for CM Service requests, dispatches out to multiple possible transaction controllers. Definition at line 54.

Page 93: Adding Support for Authentication and Encryption to Openbts

Secure OpenBTS 85

* void Control::IMSIDetachController(const L3IMSIDetachIndication* idi, LogicalChannel* DCCH)

Controller for the IMSI Detach transaction, GSM 04.08 Sec. 4.3.4. Definition at line 83.

*bool sendWelcomeMessage(const char* messageName, const char* shortCodeName, const char *IMSI, SDCCHLogicalChannel* SDCCH)

Send a given welcome message from a given short code. Returns: true if it was sent. Definition at line 115.

* void Control::LocationUpdatingController(const L3LocationUpdatingRequest* lur, SDCCHLogicalChannel* SDCCH)

Controller for the Location Updating transaction, GSM 04.08 Sec. 4.4.4. Definition at line 115.

Functions for RadioResource.cpp: * void Control::AccessGrantResponder( unsigned RA, const GSM::Time& when, float RSSI, float timingError)

Decode RACH bits and send an immediate assignment.Definition at line 119.

* void Control::PagingResponseHandler(const L3PagingResponse* resp, LogicalChannel* DCCH)

Find and compelte the in-process transaction associated with a paging repsonse. Definition at line 232.

* void Control::AssignmentCompleteHandler(const L3AssignmentComplete *confirm, TCHFACCHLogicalChannel *TCH)

Find and compelte the in-process transaction associated with a completed assignment. Definition at line 296.

Functions for CallControl.cpp: MOC

* void Control::MOCStarter(const L3CMServiceRequest* req, LogicalChannel *LCH) Run the MOC to the point of alerting, doing early assignment if needed. This function starts MOC on the SDCCH to the point of TCH assignment. Definition at line 567.

* void Control::MOCController(TransactionEntry& transaction, TCHFACCHLogicalChannel* TCH)

Complete the MOC connection.Continue MOC process on the TCH. Definition at line 797.

MTC

* void Control::MTCStarter(TransactionEntry& transaction, LogicalChannel *LCH, L3MobileIdentity mobID)

Run the MTC to the point of alerting, doing early assignment if needed. Definition at line

918.

* void Control::MTCController(TransactionEntry& transaction, TCHFACCHLogicalChannel* TCH).

Page 94: Adding Support for Authentication and Encryption to Openbts

86 About OpenBTS

Complete the MTC connection.Definition at line 1083.

Note in Coding:

When describing layers (L1, L2, L3) we will refer to the ―low‖ side of the layer as the side the interfaces closer to the hardware and the ―high‖ side as the side that interfaces to higher-level functions. In a BTS, the the low-to-high direction is ―uplink‖ and the high-to-low direction is ―downlink‖. In the MS, those labels are reversed.

To enforce good testing practices, we recommend the following:

• Use assert() calls liberally to insure internal consistency. Do not continue once an unresolvable error condition is identified. • Build unit test fixtures for every component in the system. Do not check in code that does not pass the unit tests. It would be especially nice if someone could automate this testing process. • If you know there‘s a potential problem in a piece of code, use a ―FIXME‖ comment. If you leave something undone, use a ―TODO‖ comment. • Use the bug tracking system. That‘s why it‘s there.

2.11 Using OpenBTS The main OpenBTS binary can be run by simply going to the apps directory and executing: $ ./OpenBTS To enable SMS support, the built-in SMS queuing server should also be executing by going to the smqueue directory and running: $ ./smqueue

When the phone is registered on a network it gets a TMSI (Temporary Mobile Subscriber Identity). TMSI is randomly assigned by the VLR to every mobile in the area. It‘s good to clear the TMSI to get the first registration on the OpenBTS. A way to do it is to turn off the phone and take off the battery.

Put your mobile phones on and force the phone to use the OpenBTS network. To do so:

1. Nokia: Go to tools → Settings → Phone → Network. Select GSM only (not dual mode, nor 3G) and select operator manually (not automatically). OR Settings → Phone →Operator selection → Manual. 2. Wait for a while, while the phone is scanning available networks. You should see the OpenBTS network 602-07. Select it. 3. Wait again, the OpenBTS network should send you a welcome SMS. The exact message depends on the configuration of OpenBTS (openbts.config)

When you choose the OpenBTS network from the networks list on your phone, your phone connects to the network, but it doesn't register it's IMSI and it doesn't reserve a phone number. To do this, you have to send an SMS to 101 from your phone including the number you wish to have. For example, if I want my number on OpenBTS to be 2102, I'll just type 2102 on my

Page 95: Adding Support for Authentication and Encryption to Openbts

Secure OpenBTS 87

phone as SMS and send it to 101. So I did it and in less than a minute, It a confirmation SMS saying that my phone number is now registered as 2102.

You are ready to use the phones.

Typing ‗help‘ in the same terminal window where OpenBTS is running returns the following menu: alarms calls cellid

chans config configsave

exit findimsi help

load noise notices

page power regperiod

rxgain sendrrlp sendsms

setlogfile testcall tmsis

unconfig uptime version

Important commands & their usage:

Command Usage/Function

sendsms sendsms <IMSI> <src> -- send SMS to <IMSI>, addressed from <src>, after prompting.

testcall testcall <IMSI> <time> -- initiate a test call to a given IMSI with a given paging time

uptime uptime -- show BTS uptime and BTS frame number.

findimsi findimsi [IMSIPrefix] -- prints all imsi's that are prefixed by IMSIPrefix

calls calls -- print the transaction table

tmsis tmsis ["clear"] or ["dump" filename] -- print/clear the TMSI table or dump it to a file.

version version -- show current OpenBTS version.

Page 96: Adding Support for Authentication and Encryption to Openbts

88 About OpenBTS

2.12 Community Support

Due to the open-source nature of OpenBTS, community support is highly available in different

forms. For OpenBTS users & developers, its highly recommended to follow and use the

OpenBTS mailing-list [9] hosted on sourceforge.net

Very rich wiki-based documentation is also hosted on the GnuRadio website, as well as three

other guides written by OpenBTS developers. [3][2][7]

Page 97: Adding Support for Authentication and Encryption to Openbts

Secure OpenBTS 89

Bibliography : [1] OpenBTS Official Website on Sourceforge - http://openbts.sourceforge.net/ (accessed July 13 2011). [2] Apvrille, Axelle. 2010. “OpenBTS for Dummies ver 0.2” [3] Loula, Alexsander. 2009. “OpenBTS Installation & Configuration Guide” [4] “Frequently Asked Questions”. Ettus Research. http://www.ettus.com/faq (accessed July 13, 2011) [5] “Transceiver Daughterboards For the USRP Software Radio System”. Ettus Research. www.ettus.com/downloads/ettus_ds_transceiver_dbrds_v6c.pdf (accessed July 13, 2011). [6] “[Openbts-discuss] Which new 2011 mobiles work with OpenBTS?”.

http://sourceforge.net/mailarchive/forum.php?thread_name=BANLkTi%3DzOXRSxA94F8bVXt0K5rF3Sc

kEog%40mail.gmail.com&forum_name=openbts-discuss. (accessed July 9, 2011) [7] David A. Burgess, Harvind S. Samra. “The OpenBTS Project”. Kestrel Signal Processing, Inc. [8] “GNU Radio - OpenBTSSettingUpFreeSWITCH”.

http://gnuradio.org/redmine/projects/gnuradio/wiki/OpenBTSSettingUpFreeSWITCH. (accessed July 11,

2011) [9] OpenBTS Mailing-list (openbts-discuss). https://lists.sourceforge.net/lists/listinfo/openbts-discuss

(accessed July 12, 2011)

Page 98: Adding Support for Authentication and Encryption to Openbts

90 Network Security in OpenBTS

Chapter 3: GSM Mobile Network Security 3.1 Importance of Security in GSM Mobile Networks: Cellular Communication has become an important part of our daily lives, so it‘s important that the channels are secure in order to ensure subscriber confidentiality, call confidentiality (prevent eavesdropping), as well preventing unauthorized use of the service (authorized network usage). GSM systems aim to achieve a security level equal to that of the public switched telephone network. The weakest part of the GSM system is the radio link path, as it can be easily intercepted. Since the radio medium can be accessed by anyone, authentication of users to prove that they are who they claim to be is a very important element of a mobile network. Encryption algorithms are used to protect data from intruders and makes sure that only the intended recipient can decode and read the information.

3.2 Security in OpenBTS: In spite of all of the advantages of OpenBTS that were discussed in Chapter 2, OpenBTS has some hidden weaknesses when concerned with the security issues. Most of the data transmitted over the OpenBTS network is sent in clear text making it easy for unwanted persons to capture and read sensitive information. All of the authentication and ciphering messages (shown in the Call procedures in chapter 1) are skipped in the OpenBTS codes. The solution falls in the authentication and encryption algorithms that protect data from intruders and makes sure that only the intended recipient can decode and read the information.

Authentication and encryption are two intertwined technologies that help to insure that the data remains secure. Authentication is the process of insuring that both ends of the connection are in fact who they say they are.

Encryption helps to insure that the information within a session is not compromised. This includes not only reading the information within a data

stream, but altering it, as well.

While authentication and encryption each has its own responsibilities in securing a communication session, maximum protection can only be achieved when the

two are combined. For this reason, many security protocols contain both authentication and encryption specifications.

Page 99: Adding Support for Authentication and Encryption to Openbts

91 OpenBTS

3.3 Cryptography Encryption is based on the science of cryptography; the science of secret writing, that is used to hide information from unwanted readers/receivers. Why do we use cryptography in mobile communications?

Authentication: The process of proving one's identity Privacy/confidentiality: Ensuring that no one can read the message except the

intended receiver Integrity: Assuring the receiver that the received message has not been altered in

any way from the original A mechanism to prove that the sender really sent this message

There are many techniques that can hide messages from the casual readers, such as: invisible writing. However, cryptography only applies to translating messages into codes. In cryptography, a cipher is an algorithm used to encrypt or decrypt — ciphers maybe be considered as a procedure or a sequence of steps that are applied on the message. When using a cipher the original information/message is known as plaintext, and the encrypted form as ciphertext. The ciphertext message contains all the information of the plaintext message, only in a form that is not readable without the proper mechanism/procedure to decrypt it. The cipher procedure depends on a key or a cryptovariable, and the procedure is varied depending on the key. The greater the number of bits in the key, the more possible key combinations and the longer it would take to break the code. So, it‘s fair to say that the number of bits in the key represents the cipher strength. The security of a cryptosystem relies on the secrecy of the keys not the secrecy of the algorithm. A strong cryptosystem has a large range of possible keys (greater number of bits) so that it is not possible to try all possible keys.

Data is encrypted, by combining the bits in the key mathematically with the data bits.

Figure 3.1 Encryption

process

Page 100: Adding Support for Authentication and Encryption to Openbts

92 Network Security in OpenBTS

At the receiving end, the key is used to decrypt the code and restore the original data. Without knowledge of the key, it should be extremely difficult to decrypt the resulting ciphertext into readable plaintext.

--------------------------------------------------------------------------------------------------------------------- Here's an example of a typical cipher, it includes letters and their corresponding numbers:

1 2 3 4 5

1 A B C D E

2 F G H I/J K

3 L M N O P

4 Q R S T U

5 V W X Y Z

Plaintext: OpenBTS Ciphertext: 43 53 51 33 21 44 34 As long as both the receiver and sender have the same cipher, the receiver should be able to decode the message correctly. Of course this is a very simple cipher! ---------------------------------------------------------------------------------------------------------------- Most cryptosystems rely on computers because human-based systems are easy to crack. Ciphers are known as algorithms, which are the guides for encryption.

Figure 3.2 Encrypted and Decrypted

process

Page 101: Adding Support for Authentication and Encryption to Openbts

93 OpenBTS

3.4 GSM Security Mechanism: The security mechanisms of GSM are implemented in three different system elements; the Subscriber Identity Module (SIM), the GSM handset or MS, and the GSM network.

1. The SIM contains the IMSI, the individual subscriber authentication key (Ki), the ciphering key generating algorithm (A8), the authentication algorithm (A3), as well as a Personal Identification Number (PIN).

2. The GSM handset contains the ciphering algorithm (A5). 3. The GSM network contains the encryption algorithms (A3, A5, A8). The

Authentication Center (AUC), part of the Operation and Maintenance Subsystem (OMS) of the GSM network, consists of a database of identification and authentication information for subscribers. This information consists of the IMSI, the TMSI, the Location Area Identity (LAI), and the individual subscriber authentication key (Ki) for each user.

In order for the authentication and security mechanisms to function, all three elements (SIM, handset, and GSM network) are required. In GSM, encryption refers to the process of creating authentication and ciphering cryptovariables using a special key and encryption algorithms. Whenever a MS (Mobile Station) requests access to a network, the network must authenticate the MS. Authentication verifies the identity and validity of the SIM card to the network and ensures that the subscriber is authorized access to the network. The Ciphering refers to the process of changing plaintext data into encrypted data using a special key and a special encryption algorithm. Transmissions between the MS and the BTS on the Um link are enciphered.

Page 102: Adding Support for Authentication and Encryption to Openbts

94 Network Security in OpenBTS

3.5 Ciphering

Symmetric methods (private key) are less secure because the same key is used for ciphering and deciphering.

Stream Ciphers Vs Block Ciphers: Most modern ciphers can be categorized by whether they work on blocks of symbols usually of a fixed size or on a continuous stream of symbols. It‘s divided into:-

Block ciphers, Encrypt plaintext in chunks, fixed size blocks. Common block sizes are 64 and 128 bits.

Ciphering

Symmetric

Block Ciphers

Stream Ciphers

Asymmetric

Figure 3.3 Ciphering type

Figure 3.4 Symmetric methods

Page 103: Adding Support for Authentication and Encryption to Openbts

95 OpenBTS

Stream ciphers, which encrypt continuous streams of data, one byte or one bit at a time. A stream cipher can be thought of as a block cipher with a really small block size.

3.5.1 Stream Ciphers: A stream cipher is a type of symmetric encryption algorithm. Stream ciphers can be designed to be exceptionally fast, much faster than any block cipher. While block ciphers operate on large blocks of data, stream ciphers typically operate on smaller units of plaintext, usually bits. The encryption of any particular plaintext with a block cipher will result in the same ciphertext when the same key is used. With a stream cipher, the transformation of these smaller plaintext units will vary, depending on when they are encountered during the encryption process. Advantages of Stream Ciphers: Stream ciphers represent a different approach to symmetric encryption from block ciphers. Block ciphers operate on large blocks of digits with a fixed, unvarying transformation. This distinction is not always clear-cut: in some modes of operation, a block cipher primitive is used in such a way that it acts effectively as a stream cipher. Stream ciphers typically execute at a higher speed than block ciphers and have lower hardware complexity. However, stream ciphers can be susceptible to serious security problems if used incorrectly Procedure: A stream cipher generates what is called a keystream (a sequence of bits used as a key). Encryption is accomplished by combining the keystream with the plaintext, usually with the bitwise XOR operation. The generation of the keystream can be independent of the plaintext and ciphertext, yielding what is termed a synchronous stream cipher, or it can depend on the data and its encryption, in which case the stream cipher is said to be self-synchronizing. Most stream cipher designs are for synchronous stream ciphers. Diagram:

Figure 3.5 Stream cipher

Page 104: Adding Support for Authentication and Encryption to Openbts

96 Network Security in OpenBTS

Asymmetric methods use one encryption key (public key) and another decryption key (private key). It is not possible to calculate the decryption key only by knowing the encryption key. The method is based on the principle of big prime numbers: It is relatively easy to detect two prime numbers x and y with 1000 and more digits. However, even today it is not possible to calculate the factors of the product ―x * y‖ in reasonable time.

Figure 3.6 Asymmetric method

Page 105: Adding Support for Authentication and Encryption to Openbts

97 OpenBTS

3.6 GSM Encryption Algorithms:

1. A3: Authentication Algorithm computes a 32-bit Signed Response (SRES). The Ki and RAND are inputted into the A3 algorithm and the result is the 32-bit SRES. The A3 algorithm resides on the SIM card and at the AuC.

2. A5: Ciphering Algorithm is used to encipher and decipher the data that is being transmitted on the Um interface. The Kc and the plaintext data are inputted into the A5 algorithm and the output is enciphered data. The A5 algorithm is a function of the Mobile Equipment (ME) and not a function of the SIM card. The BTS also makes use of the A5 algorithm.

There are three versions of the A5 algorithm:

1) A5/1 - The current standard for U.S. and European networks. A5/1 is a stream cipher. 2) A5/2 - The deliberately weakened version of A5/1 that is intended for export to non-western countries. A5/2 is a stream cipher. 3) A5/3 - A newly developed algorithm not yet in full use. A5/3 is a block cipher.

3. A8: Ciphering Key Generating Algorithm computes a 64-bit ciphering key (Kc). The Ki and the RAND are inputted into the A8 algorithm and the result is the 64-bit Kc. The A8 algorithm resides on the SIM card and at the AuC.

Figure 3.7 A3

Figure 3.8

A5

Figure 3.9 A8

Page 106: Adding Support for Authentication and Encryption to Openbts

98 Network Security in OpenBTS

Notes:

1. In practice, A3 and A8 are generally implemented together and are known as A3/A8.

2. The RAND, SRES, and Kc together are known as the Triplets. The AuC will send these three cryptovariables to Network so it can authenticate and encipher.

Page 107: Adding Support for Authentication and Encryption to Openbts

99 OpenBTS

3.6.1 Frame number (FN)

Frame number (FN) is the internal clock of a BTS, to which every MS has to

synchronize before the MS can start communicating with the BTS. For that purpose, the

BTS broadcasts the current frame number five times for every 51-multiframe over the

synchronization channel. The FN can take on values between 0 and 2,715,647, where

each FN identifies exactly one TDMA frame within a hyperframe.

The possible number of frames:

Therefore the possible number of frames = (26 × 51 × 2048) – 1 = 2,715,647

Note:

1. The - 1 is necessary, since the count starts with zero.

2. 1 Hyperframe = 2,048 Superframes

1 Superframe = 26 Multiframes

51 TDMA frames or 51 multiframes with 26 TDMA frames

What is transmitted?

What is transmitted is not the absolute value of the FN, but the relative position of an FN

in the frame hierarchy, consisting of 51-multiframe, superframe, and hyperframe. This

method of addressing the FN is similar to the way two people tell the time of day.

Compare, for example, ―The time is 54.900 seconds,‖ and ―The time is 3.15 p.m.‖

In practice, the FN is sent as a combination of the parameters T1, T2, and T3, what

could be brought in the analogy the example: hours (T1), minutes (T2), and seconds

(T3‘) of a clock. T1, T2 and T3‘ make up the current frame number.

Figure 3.10 Possible numbers of

frames

Page 108: Adding Support for Authentication and Encryption to Openbts

100 Network Security in OpenBTS

T1, T2 and T3‘ are calculated as follows:

1. T1 (11 bit): Number of the current superframe in the hyperframe

T1 = FN div (26 x 51), with a range 0 to 2047

2. T2 (5 bit): Number of the current 51-multiframe in the superframe

T2 = FN mod 26, with a range 0 to 25

3. T3 = FN mod 51, with a range 0 to 50

For T3, the only value sent is the value of the decade T3‘, since the

synchronization channel is sent exactly five times per 51- multiframe, in

fact, always in the position FN = 1, 11, 21, 31, 41.

T3‘ (3 bit) = (T3 - 1) div 10, with a range 0 to 4

T3: (6 bit): Number of the TDMA frame in the 51-multiframe

T3‘ along with T1 and T2, forms a part of Reduced Frame Number (RFN)

of 19bits

Therefore the single digit value, therefore, is redundant and there is no need for its

transmission. The value of T3‘ tells the MS exactly which FN in a 51-multiframe is

meant and can easily calculate the FN of a 26-multiframe or the absolute value of FN.

Note: This rule only applies to the transmission of FN on the synchronization channel

Take a look at this example:

A decimal FN will be converted to 19-bit binary format as T1,T2 and T3' which are then transmitted over the air.

By following the above reference, if FN = 25, then we will have T1 = 25 div (26*51) = 0; T2 = 25 mod 26 = 25; T3 = 25 mod 51 = 25; T3' = (T3-1) div 10 = 2; (integer division!)

At the receiving end:

Assume T1,T2 and T3' are received with no error, then we have

T3 = (10*T3')+1 = 10*2 + 1 = 21;

FN = 51*[(T3-T2)mod(26)]+T3+51*26*T1 =

51*((21-25)mod(26))+21+0=51*22+21+0 = 1143!

As you can see, the received frame number is not correct .

What's wrong with the conversion?!!

Nothing is wrong with the conversion however; the formula is valid only "when the synch

burst is received".

Page 109: Adding Support for Authentication and Encryption to Openbts

101 OpenBTS

For example SCH in frame number FN=11:

T1 = 0

T2 = 11 mod 26 = 11

T3 = 11 mod 51 = 11

T3'= (11-1) div = 1

After receiving T1, T2 and T3'

T3 = (10*T3')+1 = 10*1+1 = 11

FN = 11

We conclude from this that FN takes certain values only:

FN = 1, 11, 21, 31, 41 …etc

Page 110: Adding Support for Authentication and Encryption to Openbts

102 Network Security in OpenBTS

3.6.2 Encryption Overview:

The RAND is a pseudorandom 128-bit number that

is generated by the Auc when the network requests

to authenticate a subscriber. The RAND is used to

generate the Signed Response (SRES) and Kc

cryptovariables.

The Ki is the individual subscriber

authentication key. It is a 128-bit number

that is paired with an IMSI when the SIM

card is created. The Ki is only stored on the

SIM card and at the Authentication Center

(AuC). The Ki should never be transmitted

across the network on any link.

The SRES is a 32-bit cryptovariable used in the

authentication process. The MS is challenged by being

given the RAND by the network, the SRES is the

expected correct response. The SRES is never passed

on the Um (Air) interface. It is kept at the MSC/VLR,

which performs the authentication check.

The Kc is the 64-bit ciphering key that is used in

the A5 encryption algorithm to encipher and

decipher the data that is being transmitted on

the Um interface.

Figure 3.11 Encryption over view

Page 111: Adding Support for Authentication and Encryption to Openbts

103 OpenBTS

3.6.3 Authentication (A3 -- Authentication Algorithm)

So, in a nutshell the GSM network authenticates the identity of the subscriber through

the use of a challenge-response mechanism. A 128-bit random number (RAND) is sent

to the MS. The MS computes the 32-bit signed response (SRES) based on the

encryption of the random number (RAND) with the authentication algorithm (A3) using

the individual subscriber authentication key (Ki). Upon receiving the signed response

(SRES) from the subscriber, the GSM network repeats the calculation to verify the

identity of the subscriber. If the received SRES agrees with the calculated value, the MS

has been successfully authenticated and may continue. If the values do not match, the

connection is terminated and an authentication failure indicated to the MS.

3.6.4 Signaling and Data Confidentiality (A8 -- Ciphering Key

Generating Algorithm)

The SIM contains the ciphering key generating algorithm (A8) which is used to produce

the 64-bit ciphering key (Kc). The ciphering key is computed by applying the same

random number (RAND) used in the authentication process to the ciphering key

generating algorithm (A8) with the individual subscriber authentication key (Ki). An

additional level of security is provided by having the means to change the ciphering key,

making the system more resistant to eavesdropping. The ciphering key may be

changed at regular intervals as required by network design and security considerations.

Figure 3.12

Page 112: Adding Support for Authentication and Encryption to Openbts

104 Network Security in OpenBTS

3.6.5 COMP 128 COMP128 is a secret algorithm which is used in GSM Networks for authentication purpose; it is used for both the A3 and A8 algorithms. COMP128 is a keyed hash function, the hash function takes 256 bits as an input and computes a hash value of 128 bits, and it works as a compression function. It takes a 16 byte (128 bits) key (Ki), and 16 byte (128 bits) of data (Rand), to output a 12 byte (96 bits) hash. Note: The individual subscriber authentication key (Ki) is never transmitted over the radio channel. It is present in the subscriber's SIM, as well as the Networks’ database.

Generally, one-way hash functions produce a fixed-length output given an arbitrary input. Secure one-way hash functions are designed such that it is computationally unfeasible to determine the input given the hash value, or to determine two unique inputs that hash to the same value. A key-dependent one-way hash function requires a key to compute and verify the hash value. This is useful for authentication purposes, where a sender and receiver may use a key-dependent hash function in a challenge-response scheme. A key-dependent one-way hash function may be implemented by simply appending the key to the message and computing the hash value. The A3 and A8 algorithms of GSM are key- dependent one-way hash functions. The COMP128 generates both the SRES response and the session key (Kc), the first 32 bits of the hash are used as a response to the Rand challenge and sent back to the base station. The remaining 64 bits are used as a session key for voice encryption using the A5 algorithm.

The last 54 bits of the COMP128 output represent the session key, note that the key length at this point is 54 bits instead of 64 bits! Ten zero-bits are appended to the key generated by the COMP128 algorithm. Thus, we have a key of 64 bits with the last ten bits zeroed out. This effectively reduces the keyspace from 64 bits to 54 bits. This is done in all A8 implementations, including those that do not use COMP128 for key generation, and seems to be a deliberate feature of the A8 algorithm implementations.

Figure 3.13 Com128

Figure 3.14

Page 113: Adding Support for Authentication and Encryption to Openbts

105 OpenBTS

Both the A3 and A8 algorithms are stored in the SIM in order to prevent people from tampering with them. This means that the operator can decide which algorithms to use independently from hardware manufacturers and other network operators. GSM security and COMP128: When a GSM phone call is being set up the network sends the RAND, a freshly generated 128 bit random number, via the network and the GSM handset to the SIM. The SIM combines RAND and K using a hash function called A3, which gives a 32 bit ―signed response‖ SRES. The SIM sends SRES back to the network via the handset and the network. The network then compares the SRES to the value which it computed using its own copy of RAND and K. If they are equal, the network believes that the SIM is authentic and the call is allowed to proceed. The speech exchanged between the GSM handset and the network is encrypted using an algorithm called A5 which has a 64 bit session key (Kc). For each new call the required A5 session key is generated using a hash function called A8. This takes the same 128 bit challenge and 128 bit key K and produces the 64 bit session key, so no further exchange of data is required for this step. Comp128 Algorithm Let Ki be the secret key of the target SIM card, and R the challenge sent to the card by the base station. Ki and R are each 16 bytes long. Let X [0...15] = Ki and X [16...31] = R be the 32 byte input to the hash function. Let T0[0..511], T1[0..255], T2[0..127], T3[0..63] and T4[0..31] be the five secret tables.

The algorithm first loads K and R in a 32–byte vector []. Then, eight iterative loops are applied on X []. Each iteration starts with a butterfly–structure like compression. The compression consists of five levels of table lookups using T0 [512], T1 [256], T2 [128], T3 [64] and T4 [32] respectively. In all iterations except the last, a permutation follows the compression. Each Ti contains only (8-i)–bit values. Thus, compression results in 32 4–bit values that are then assembled into 16 bytes before the permutation is applied. These 16 bytes are stored into X [16...31] and K is loaded into X [0...15] before a new iteration begins. The resulting 128 bits after the eight iterations are further compressed to 12 bytes, which form the output of the algorithm. Compress 16-byte result to 12-bytes, store in simoutput [ 0 . . 1 1 ] and return. simoutput [ 0 . . 3 ] is SRES, and simoutput [ 4 . . 1 1 ] is Kc (the A5 session key).

Page 114: Adding Support for Authentication and Encryption to Openbts

106 Network Security in OpenBTS

(Each round R is a so-called ―butterfly‖ network, P is a permutation and F is a permutation/selection)

The size of the elements in the tables decreases from one table to the next. Starting from 8 bit outputs for table T0, and 7 bit outputs for table T1, we get down to 4 bit outputs in table T4. Actually, the 32 output bytes only have 4 significant bits each. Therefore these 32 bytes '4-bit' are reorganized into 16 bytes '8-bit'. For level i, Ti table contains 29−i elements & (8-i)-bit values. For example, table0 has 512 entries, each an 8 bit value, and table4 has 32 entries, each a 4 bit value.

T0 [512] → 8-bit T1 [256] → 7-bit T2 [128] → 6-bit T3 [64] → 5-bit T4 [32] → 4-bit

In each level, two input bytes are used to calculate the index for the table and the result is the output byte.

Figure 3.15

Figure 3.16

Page 115: Adding Support for Authentication and Encryption to Openbts

107 OpenBTS

For each level, the compression works on pairs of equal sized sections of X []. In level 0, (j =0),X [] is split into two sections X [0..15] and X [16..31]. The value of each right element,X [i+16], (i = 0..15) is combined with that of the left element,X [i], to compute y =(X [i]+2*X [i+16])mod 512. Similarly, the value of the left element,X [i] is combined with the corresponding right element to compute z =(2*X [i] +X [i+16])mod (512). X [i] and X [i+16] are then replaced by T0[y] and T0[z] before the next level starts. On every new level, a section gets divided into a pair of sections in which the same scheme is applied. Note that the size of the table decreases in succeeding levels. Accordingly, level 1 computes y =(X [i] + 2*X [i+8])mod 256 and z =(2*X [i]+X [i+8])mod 256 for i=0..7, 16..23. In level 2,y =(X [i] + 2*X [i+4]) mod 128 and z =(2*X [i]+X [i+4])mod 128 for i=0..3, 8..11, 16..19, 24..27 and so on.

The permutation after each round of COMP128, except the last one, the permutation is performed as follows:

• The low order nibbles in the array x[ ] are to be interpreted as a bit-array bit (after the reduction, the four MSBs are 0) • The new position of every bit is then defined in this way:

bit[i] = bit[(17 · i)(mod128)] • After that the bit-array is used to reinitialize the highest 4 byte of the input x[ ]. Thereby the bits bit[i] to bit[i + 7] are used as the byte x[i], but in reverse order. So bit[i] is the MSB of byte[i].

Figure 3.17

Page 116: Adding Support for Authentication and Encryption to Openbts

108 Network Security in OpenBTS

Figure 3.18

Page 117: Adding Support for Authentication and Encryption to Openbts

109 OpenBTS

COMP128 pseudocode:

Input: 16 byte secret key, 16 byte RAND Output: 4 byte SRES, 8 byte session key(Kc) → (simoutput[12]) Load RAND into x[16…31] Perform the following 8 times

Load secret key into x[0…15] Compression (Butterfly-structure) Bits to Bytes Permutation (only on first 7 rounds)

Compress 16 bytes to 12 bytes (simoutput) Return simoutput[ ]

Lookup table: In computer science, a lookup table is a data structure, usually an array or associative array, often used to replace a runtime computation with a simpler array indexing operation. The savings in terms of processing time can be significant, since retrieving a value from memory is often faster than undergoing an 'expensive' computation or input/output operation. The tables may be precalculated and stored in static program storage or calculated (or "pre-fetched") as part of a programs initialization phase (memoization). Lookup tables are also used extensively to validate input values by matching against a list of valid (or invalid) items in an array and, in some programming languages, may include pointer functions (or offsets to labels) to process the matching input.

COMP128-1 & COMP28-2 & COMP128-3 GSM network operators are slowly migrating from COMP128 (also known as COMP128-1) to COMP28-2 or COMP128-3. Because the A3 and A8 algorithms are stored in the Subscriber Identity Module, this requires changing the GSM subscribers SIM cards. The COMP128-2 and COMP128-3 algorithms have been developed to address the security issues of COMP128-1. COMP128-2 and COMP128-3 are secret algorithms which have not been subject to cryptanalysis. COMP128-3 fixes the issue where 10 bits of the Session Key (Kc) were set to zero. The A8 algorithm takes a 64-bit key, but ten key bits were set to zero. The attack on the A8 algorithm demonstrated by Goldberg and Wagner takes just 2^19 queries to the GSM SIM *Subscriber Identity Module), which takes roughly 8 hours. Use a special SIM Card with COMP128 v2. This SIM COMP128 v2 is special because I can change the Ki. Put in this (special) card the Ki of one of COMP128 v1. and the card connected without problems (yes... yes... with the IMSI and Ki of one card of COMP128 v1).

Page 118: Adding Support for Authentication and Encryption to Openbts

110 Network Security in OpenBTS

3.6.6 A5 – Ciphering algorithm:

The over-the-air privacy of GSM telephone conversations is protected by the A5 stream cipher.

A5/0 utilizes no encryption ―NO Cipher‖

A5/1 is the original A5 algorithm used in Europe ―Stream Cipher‖

A5/2 is a weaker encryption algorithm created for export and used in the United States ―Stream Cipher‖

A5/3 is a strong encryption algorithm, but more complex created as part of the 3rd Generation Partnership Project (3GPP) ―Block Cipher‖

We are interested in A5/1 as it stronger than a5/2 & it easier than a5/3. Stream Cipher Structure:

Figure 3.19 stream cipher

Page 119: Adding Support for Authentication and Encryption to Openbts

111 OpenBTS

Functionally of ciphering data

Functionally of deciphering data

Figure 3.20 Ciphered data

Figure 3.21 Deciphered data

Page 120: Adding Support for Authentication and Encryption to Openbts

112 Network Security in OpenBTS

A5 /1 Description:- A5/1 is built from three short linear feedback shift registers (LFSR)

R1 of length from 0-19 bits & it‘s taps 13,16,17,18

R2 of length from 0-22 bits& it‘s taps 20,21

R3 of length from 0-22 bits& it‘s taps 7,20,21,22

How the three register clocked??

They are clocked in a stop/go fashion using the following majority rule

Each register has a single "clocking" tap (Bit 8 for R1, bit 10 for R2, and bit 10 for for R3)

Each clock cycle, the majority function of the clocking taps is calculated and only those registers whose clocking taps agree with the majority bit is actually clocked.

Each registers move with probability 3/4 and stops with probability ¼.

How A5/1 work?? FIRST:- initial state of the frame “Ignoring the stop/go clock control”

The three registers are zeroed, and then clocked for 64 cycles (ignoring the stop/go clock control). During this period each bit of K (from lsb to msb) is XOR'ed in parallel into the lsb's of the three registers.

The three registers are clocked for 22 additional cycles (ignoring the stop/go clock control). During this period the successive bits of FN (from lsb to msb) are again XOR'ed in parallel into the lsb's of the three registers.

SECOND: - ―Using the stop/go clock control”

The three registers are clocked for 100 additional clock cycles with the stop/go clock control but without producing any outputs.

Figure 3.22 A5/1

Page 121: Adding Support for Authentication and Encryption to Openbts

113 OpenBTS

The three registers are clocked for 228 additional clock cycles with the stop/go clock control in order to produce the 228 output bits. At each clock cycle, one output bit is produced as the XOR of the msb's of the three registers

3.7 Authentication and Encryption summary: To sum up, GSM security is addressed in two aspects: authentication and encryption. Authentication avoids fraudulent access of a cloned MS. Encryption avoids unauthorized listening. A secret key Ki is used to achieve authentication and, is stored in the AuC and the SIM. The Ki value is used to initiate the authentication process, the home system of the MS

generates a 128-bit random number called RAND. The RAND is sent to the MS. Using

the A3 Algorithm, both the network and the MS (SIM) use Ki and RAND to produce a

signed result (SRES). The SRES generated by the MS is sent to the home system and

Figure 3.23

Page 122: Adding Support for Authentication and Encryption to Openbts

114 Network Security in OpenBTS

is compared with the SRES generated by the AuC in the Network.

References: [1] Cellular Mobile Systems and Services (TCOM1010)

[2] http://www.suedmeyer.ne t/inhalte/pdf/comp128_thesis.pdf

[3] http://www.stuartwray.n et/comp128-a-birthday-surprise-rev.pdf

[4] http://www.garykessler.net

Page 123: Adding Support for Authentication and Encryption to Openbts

115 OpenBTS

Chapter 4: Code Implementation of Encryption

4.1 Authentication

Authentication is used to identify the user (or holder of a Smart Card) to the network operator. It uses a technique that can be described as a "Challenge and Response", based on encryption. Authentication is performed by a challenge and response mechanism. A random challenge is issued to the mobile, the mobile encrypts the challenge using the authentication algorithm (A3) and the key assigned to the mobile, and sends a response back. The operator can check that, given the key of the mobile, that the response to the challenge is correct.

Eavesdropping the radio channel reveals no useful information, as the next time a new random challenge will be used. Authentication can be provided using this process. A random number is generated by the network and sent to the mobile. The mobile use the Random number R as the input (Plaintext) to the encryption, and, using a secret key unique to the mobile Ki, transforms this into a response Signed Response (SRES) (Cipher text) which is sent back to the network. The network can check that the mobile really has the secret key by performing the same SRES process and comparing the responses with what it receives from the mobile.

4.2 User Data and Signaling Protection

The response is then passed through an algorithm A8 by both the mobile and the network to derive the key Kc used for encrypting the signaling and messages to provide privacy (A5 series algorithms).

Figure 4.1

Page 124: Adding Support for Authentication and Encryption to Openbts

116 Code Implementations of Encryption

4.3 Individual Subscriber Authentication Key (Ki):

Ki is the 128-bit Individual Subscriber Authentication Key utilized as a secret key shared between the Mobile Station and the Home Location Register of the subscriber‘s home network.

It is not a something we can‘t extract from the SIM by default ways, so we have to add it in a separate database which will be added in a text file named KiTable .This file will be included in the apps folder.

4.3.1 Ki codes implementations:

Reference of Classes:

KiRecord: this class is the interface with the text file

KiTable: this class is responsible for searching for the Ki in the KiTable.txt using the load method in the KiRecord.

Reference of Functions:

unsigned load(FILE*): this method is to load a line from the KiTable.txt and return

it to the mKI and mIMSI variables.it is a member function from the KiRecord Class.

void KiTable::loadAndFindKI(const char* IMSI): this function is used to

search for a certain KI using an IMSI.it is a member function from the KiTable Class

unsigned char* getKi():This function is used to return the Ki into a variable. it is

a member function from the KiTable Class.

Edits in the File: OpenBTS.config line: 205

We needed to add this block of code to make the file name of the KiTable editable in the code.

# KiTable Database table. Control.KiTable.SavePath KiTable.txt

Page 125: Adding Support for Authentication and Encryption to Openbts

117 OpenBTS

Edits in the File: OpenBTS.cpp

In this file, a global Variable was created named gKiTable and whenever you want to

call the KI just call this line

gKiTable.loadAndFindKI(imsi);

then return the Ki into variable:

ki=gKiTable.getKi();

Code Implementation in File : ControlCommon.h

class KiRecord {

private:

std::string mIMSI;

std::string mKi;

public:

const char* Ki() const { return mKi.c_str(); }

unsigned load(FILE*);};

class KiTable {

private:

mutable Mutex mLock;

unsigned char Ki[16];

public:

KiTable(){};

unsigned char* getKi(){return Ki;};

void loadAndFindKI(const char* IMSI);

int hextoint(char x);

};

Code Implementation in File: ControlCommon.cpp

KiTable gKiTable;

unsigned KiRecord::load(FILE* fp) {

unsigned KI=0; //dummy variable

char IMSI[16],IMSI2[16];

char Ki[32];

fscanf(fp, "%16s %32s %15s\n",IMSI, Ki, IMSI2);

//IMSI is another dummy variable just in order to get

things right

LOG(DEBUG) << "IMSIRead" << IMSI2;

LOG(DEBUG) << "KiRead" << Ki;

Page 126: Adding Support for Authentication and Encryption to Openbts

118 Code Implementations of Encryption

mIMSI = IMSI2;

mKi = Ki;

return KI;

}

//this function returns the numerical value of the hex character

//ex: input character f the output numerical value 15

int KiTable::hextoint(char x) {

x = toupper(x);

if (x >= 'A' && x <= 'F')

return x - 'A' + 10;

else if (x >= '0' && x <= '9')

return x - '0';

exit(1);

}

void KiTable::loadAndFindKI(const char* IMSI) {

//Getting the file name from the configuration file

const char* filename =

gConfig.getStr("Control.KiTable.SavePath");

FILE* fp = fopen(filename, "r");

const char *KiSigned;

LOG(INFO) << "loading Ki table from " << filename;

mLock.lock();

//Searching for the KI begans here

while (!feof(fp)) {

KiRecord val;

unsigned key = val.load(fp);

if (!strcmp(val.IMSI(), IMSI)) {

KiSigned = val.Ki();

for (int i = 0; i < 16; i++){

Ki[i] = (hextoint(KiSigned[2 * i]) << 4) |

hextoint(KiSigned[2 * i + 1]);

LOG(DEBUG) << "Converting Ki to unsigned ... " << Ki[i];

}

break;

}

Page 127: Adding Support for Authentication and Encryption to Openbts

119 OpenBTS

if (!key) break;

}

mLock.unlock();

fclose(fp);

LOG(INFO) << "Ki= " << Ki;

}

Ki is an input argument to A3A8 algorithm so, whenever we need to call the A3/A8

Algorithm we should include the ControlCommon.h to the file and add the following lines

of code:

const char* imsi;

imsi=mobID.digits();

gKiTable.loadAndFindKI(imsi);

a3a8.A3A8(mRand.getRandToA3A8(),gKiTable.getKi());

4.4 Random challenge (Rand):

The random number generator generates 128 bit variable ―RAND‖ using a specified seed to produce two concatenated 64-bit pseudo-random numbers. The RAND is used to generate the Signed Response (SRES) and Kc cryptovariables. 4.4.1 Challenges introduced in this scope: There is no variable that can store this size (contain this large number of bits), so we will divide the RAND into two parts; Rand High ―mRandHigh‖ and Rand Low ‖mRandLow‖,) each of 64 bits and of type uint64_t.

mRandHigh and mRandLow are generated in the ControlCommon.h file of type uint64_t Rand then passed to Encryption.h file which contains the A3A8 function. A3A8 takes input ―Rand & Ki― then generates output ―Simoutput‖ which contains SRES and Kc. But the Rand in the A3A8 function is of type unsigned char ―Byte‖ and of size 8 bytes (64 bit) and in order to be able to pass the rand between both functions we had to change the type and decrease the size.

1. Changing the type from uint64_t to char:

These following commands were convert from uint64_t to char. char mRandCharLow[sizeof(uint64_t)];

char mRandCharHigh[sizeof(uint64_t)];

for (unsigned int i = 0; i < sizeof(uint64_t); ++i)

mRandCharLow[i] =(mRANDLow >> (8 * i)) & 0xFF;

for (unsigned int i = 0; i < sizeof(uint64_t); ++i)

mRandCharHigh[i] = ( mRANDHigh>> (8 * i)) & 0xFF;

Page 128: Adding Support for Authentication and Encryption to Openbts

120 Code Implementations of Encryption

2. Changing the size from 128 bits to 64 bits: The idea of changing the size was based on the face that each character is represented by its ASCII code written in Hex format. So if we have two characters; the First character is ―A‖ and is equivalent to ―41‖ hex and the second character is ―B‖ and is equivalent to ―42‖ Hex. These two numbers are combined into one variable ―4241 hex‖ which is equivalent to ―BA‖, b y using this algorithm we decrease the size to the half as the ASCII equivalent of two characters are combined into one variable. This is done by putting the mRandCharLow in the low byte of the rand and putting mRandCharHigh in the high byte of the rand. for (int i=0; i<8; i++)

{

rand[i] = mRandCharLow[i];

rand[i+8] = mRandCharHigh[i];

}

for (int i=15; i>=0; --i)

rand[15-i]=newRand[i];

3. Randomness The random number generated ―RAND‖ isn‘t completely random as it is generated from the noise generated by the system. The RAND is generated using ―/dev/rand command which generates real random numbers of variable size. Because we need to generate a random number of a large size, the noise generated finishes causing the random bits to equal zero. In order to overcome the zeroing that occurs we had to use a pseudo random number generator instead. mRANDLow = random() % 0xFFFFFFFFFFFFFFFFLLU + 1;

mRANDHigh = random() % 0xFFFFFFFFFFFFFFFFLLU + 1;

4.5 A3A8 Algorithm:

An A3/A8 algorithm is an encryption algorithms implemented in Subscriber Identity Module (SIM) cards and in GSM network Authentication Centers. It is used to authenticate the customer and generate a key for encrypting voice and data traffic, as defined in 3GPP TS 43.020 (03.20 before Rel-4). Development of A3 and A8 algorithms is considered a matter for individual GSM network operators.

A3 Algorithm - The A3 algorithm computes a 32-bit Signed Response (SRES). The Ki and RAND are inputted into the A3 algorithm and the result is the 32-bit SRES. The A3 algorithm resides on the SIM card and at the AuC. A8 Algorithm - The A8 algorithm computes a 64-bit ciphering key (Kc). The Ki and the RAND are inputted into the A8 algorithm and the result is the 64-bit Kc. The A8 algorithm resides on the SIM card and at the AuC.

Page 129: Adding Support for Authentication and Encryption to Openbts

121 OpenBTS

4.5.1 Functionality: COMP128 is used for both the A3 and A8 algorithms in most GSM networks.

Figure 4.2

1. Input: 16 byte secret key (Ki), 16 byte RAND 2. Output: 4 byte SRES, 8 byte session key(Kc) → (simoutput[12]) 3. Load RAND into x[16...31] 4. Perform the following steps 8 times:

I. Load secret key into x[0...15] II. Compression (Butterfly_structure)

III. Bits to Bytes IV. Permutation (for the first 7 rounds)

Compress 16 bytes to 12 bytes (simoutput) Return simoutput[ ]

The SRES is compared with XRES which is generated at the Mobile Station side if they are equal then this Mobile is authenticated and then the Ciphering operation will start to encrypt the data. The SIM contains the ciphering key generating algorithm (A8) which is used to produce the 64-bit ciphering key (Kc). The ciphering key which is 8 bytes is computed by applying the same random number (RAND) used in the authentication process to the ciphering key generating algorithm (A8) with the individual subscriber authentication key. 4.5.2 A3A8 Implementation: The A3A8 is implemented as class in the code which contains the following member functions:

void A3A8(unsigned char* rand, unisgned char* ki):This is the main function which uses comp128 to generate the simoutput.

uint64_t getKC() :This function is used to extract the Kc from simoutput ―the output of the A3A8 function‖.

unsigned int getSRES(): This function is used to extract the Signed Response (SRES) from the simoutput ―the output of the A3A8 function‖.

Page 130: Adding Support for Authentication and Encryption to Openbts

122 Code Implementations of Encryption

So, whenever we need to call one of these functions just create an object of this class

and then u can have access on them.

Code Implementation in File : GSMEncryption.h typedef unsigned char Byte;

// This class implements the A3A8 Encryption Algorithm according

to OpenBTS convension names

class A3A8Class {

public:

Byte simoutput[12];

void A3A8(/* in */ Byte* rand, /* in */ Byte* ki) {

/*Let table_0[0..511],

table_1[0..255],

table_2[0..127],

table_3[0..63] and

table_4[0..31] be the five secret tables.

These five secret tables have been recovered by reverse

engineering */

static const Byte table_0[512] = {

102,177,186,162, 2,156,112, 75, 55, 25, 8,

12,251,193,246,188,

109,213,151, 53, 42,

79,191,115,233,242,164,223,209,148,108,161,

252, 37,244, 47, 64,211, 6,237,185,160,139,113,

76,138, 59, 70,

67, 26, 13,157, 63,179,221, 30,214, 36,166,

69,152,124,207,116,

247,194, 41, 84, 71, 1, 49, 14, 95, 35,169, 21, 96,

78,215,225,

182,243, 28, 92,201,118, 4, 74,248,128, 17,

11,146,132,245, 48,

149, 90,120, 39, 87,230,106,232,175,

19,126,190,202,141,137,176,

250, 27,101, 40,219,227, 58, 20, 51,178, 98,216,140,

22, 32,121,

61,103,203, 72, 29,110, 85,212,180,204,150,183, 15,

66,172,196,

56,197,158, 0,100, 45,153, 7,144,222,163,167,

Page 131: Adding Support for Authentication and Encryption to Openbts

123 OpenBTS

60,135,210,231,

174,165, 38,249,224, 34,220,229,217,208,241,

68,206,189,125,255,

239, 54,168, 89,123,122, 73,145,117,234,143,

99,129,200,192, 82,

104,170,136,235, 93, 81,205,173,236, 94,105, 52,

46,228,198, 5,

57,254, 97,155,142,133,199,171,187, 50,

65,181,127,107,147,226,

184,218,131, 33, 77, 86, 31, 44, 88, 62,238, 18, 24,

43,154, 23,

80,159,134,111, 9,114, 3, 91, 16,130, 83,

10,195,240,253,119,

177,102,162,186,156, 2, 75,112, 25, 55, 12,

8,193,251,188,246,

213,109, 53,151, 79,

42,115,191,242,233,223,164,148,209,161,108,

37,252, 47,244,211, 64,237, 6,160,185,113,139,138,

76, 70, 59,

26, 67,157, 13,179, 63, 30,221, 36,214,

69,166,124,152,116,207,

194,247, 84, 41, 1, 71, 14, 49, 35, 95, 21,169, 78,

96,225,215,

243,182, 92, 28,118,201, 74, 4,128,248, 11,

17,132,146, 48,245,

90,149, 39,120,230, 87,232,106,

19,175,190,126,141,202,176,137,

27,250, 40,101,227,219, 20, 58,178, 51,216, 98,

22,140,121, 32,

103, 61, 72,203,110, 29,212, 85,204,180,183,150, 66,

15,196,172,

197, 56, 0,158, 45,100, 7,153,222,144,167,163,135,

60,231,210,

165,174,249, 38, 34,224,229,220,208,217,

68,241,189,206,255,125,

54,239, 89,168,122,123,145, 73,234,117,

99,143,200,129, 82,192,

170,104,235,136, 81, 93,173,205, 94,236, 52,105,228,

46, 5,198,

254, 57,155, 97,133,142,171,199, 50,187,181,

65,107,127,226,147,

218,184, 33,131, 86, 77, 44, 31, 62, 88, 18,238, 43,

24, 23,154,

159, 80,111,134,114, 9, 91, 3,130, 16, 10,

83,240,195,119,253

},

Page 132: Adding Support for Authentication and Encryption to Openbts

124 Code Implementations of Encryption

table_1[256] = {

19, 11, 80,114, 43, 1, 69, 94, 39, 18,127,117, 97,

3, 85, 43,

27,124, 70, 83, 47, 71, 63, 10, 47, 89, 79, 4, 14,

59, 11, 5,

35,107,103, 68, 21, 86, 36, 91, 85,126, 32, 50,109,

94,120, 6,

53, 79, 28, 45, 99, 95, 41, 34, 88, 68, 93,

55,110,125,105, 20,

90, 80, 76, 96, 23, 60, 89, 64,121, 56, 14, 74,101,

8, 19, 78,

76, 66,104, 46,111, 50, 32, 3, 39, 0, 58, 25, 92,

22, 18, 51,

57, 65,119,116, 22,109, 7, 86, 59, 93, 62,110, 78,

99, 77, 67,

12,113, 87, 98,102, 5, 88, 33, 38, 56, 23, 8, 75,

45, 13, 75,

95, 63, 28, 49,123,120, 20,112, 44, 30, 15, 98,106,

2,103, 29,

82,107, 42,124, 24, 30, 41, 16,108,100,117, 40, 73,

40, 7,114,

82,115, 36,112, 12,102,100, 84, 92, 48, 72, 97, 9,

54, 55, 74,

113,123, 17, 26, 53, 58, 4, 9, 69,122, 21,118, 42,

60, 27, 73,

118,125, 34, 15, 65,115, 84, 64, 62, 81, 70, 1,

24,111,121, 83,

104, 81, 49,127, 48,105, 31, 10, 6, 91, 87, 37, 16,

54,116,126,

31, 38, 13, 0, 72,106, 77, 61, 26, 67, 46, 29, 96,

37, 61, 52,

101, 17, 44,108, 71, 52, 66, 57, 33, 51, 25, 90,

2,119,122, 35

}, table_2[128] = {

52, 50, 44, 6, 21, 49, 41, 59, 39, 51, 25, 32, 51,

47, 52, 43,

37, 4, 40, 34, 61, 12, 28, 4, 58, 23, 8, 15, 12,

22, 9, 18,

55, 10, 33, 35, 50, 1, 43, 3, 57, 13, 62, 14, 7,

42, 44, 59,

62, 57, 27, 6, 8, 31, 26, 54, 41, 22, 45, 20, 39,

3, 16, 56,

48, 2, 21, 28, 36, 42, 60, 33, 34, 18, 0, 11, 24,

10, 17, 61,

29, 14, 45, 26, 55, 46, 11, 17, 54, 46, 9, 24, 30,

60, 32, 0,

20, 38, 2, 30, 58, 35, 1, 16, 56, 40, 23, 48, 13,

Page 133: Adding Support for Authentication and Encryption to Openbts

125 OpenBTS

19, 19, 27,

31, 53, 47, 38, 63, 15, 49, 5, 37, 53, 25, 36, 63,

29, 5, 7

}, table_3[64] = {

1, 5, 29, 6, 25, 1, 18, 23, 17, 19, 0, 9, 24,

25, 6, 31,

28, 20, 24, 30, 4, 27, 3, 13, 15, 16, 14, 18, 4,

3, 8, 9,

20, 0, 12, 26, 21, 8, 28, 2, 29, 2, 15, 7, 11,

22, 14, 10,

17, 21, 12, 30, 26, 27, 16, 31, 11, 7, 13, 23, 10,

5, 22, 19

}, table_4[32] = {

15, 12, 10, 4, 1, 14, 11, 7, 5, 0, 14, 7, 1,

2, 13, 8,

10, 3, 4, 9, 6, 0, 3, 2, 5, 6, 8, 9, 11,

13, 15, 12

}, *table[5] = { table_0, table_1, table_2, table_3,

table_4 };

Byte x[32], bit[128];

int i, j, k, l, m, n, y, z, next_bit;

/* ( Load RAND into last 16 bytes of input ) */

for (i = 16; i < 32; i++)

x[i] = rand[i - 16];

/* ( Loop eight times ) */

for (i = 1; i < 9; i++) {

/* ( Load key into first 16 bytes of input ) */

for (j = 0; j < 16; j++)

x[j] = ki[j];

/* ( Perform substitutions ) */

for (j = 0; j < 5; j++)

for (k = 0; k < (1 << j); k++)

for (l = 0; l < (1 << (4 - j)); l++) {

m = l + k * (1 << (5 - j));

n = m + (1 << (4 - j));

y = (x[m] + 2 * x[n]) % (1 << (9 - j));

z = (2 * x[m] + x[n]) % (1 << (9 - j));

x[m] = table[j][y];

x[n] = table[j][z];

}

/* ( Form bits from bytes ) */

for (j = 0; j < 32; j++)

for (k = 0; k < 4; k++)

bit[4 * j + k] = (x[j] >> (3 - k)) & 1;

/* ( Permutation but not on the last loop ) */

if (i < 8)

for (j = 0; j < 16; j++) {

Page 134: Adding Support for Authentication and Encryption to Openbts

126 Code Implementations of Encryption

x[j + 16] = 0;

for (k = 0; k < 8; k++) {

next_bit = ((8 * j + k)*17) % 128;

x[j + 16] |= bit[next_bit] << (7 - k);

}

}

}

/*

* ( At this stage the vector x[] consists of 32 nibbles.

* The first 8 of these are taken as the output SRES. )

*/

/* The remainder of the code is not given explicitly in

the

* standard, but was derived by reverse-engineering.

*/

for (i = 0; i < 4; i++)

simoutput[i] = (x[2 * i] << 4) | x[2 * i + 1];

for (i = 0; i < 6; i++)

simoutput[4 + i] = (x[2 * i + 18] << 6) | (x[2 * i +

18 + 1] << 2)

| (x[2 * i + 18 + 2] >> 2);

simoutput[4 + 6] = (x[2 * 6 + 18] << 6) | (x[2 * 6 + 18 +

1] << 2);

simoutput[4 + 7] = 0;

LOG(DEBUG) << "simoutput = " << simoutput;

};

/* Preparing the KC part of the simoutput to fit the OpenBTS

code*/

uint64_t getKC() {

Byte Kc[8];

uint64_t KCuint_64=0;

int k=0;

int i;

for (i = 0; i < 8; i++) {

Kc[i] = simoutput[i + 4];

}

for (i = 7;i>=0 ; i--){

for(int j=7; j>=0 ; j--){

KCuint_64 = KCuint_64 + ( (Kc[i] >> (7-j) ) &

1)*pow(2,k);

Page 135: Adding Support for Authentication and Encryption to Openbts

127 OpenBTS

k++;

}

}

return KCuint_64;

};

/* Preparing the SRES part of the simoutput to fit the

OpenBTS code*/

unsigned int getSRES(){

Byte SRES[4];

unsigned int SRESint=0;

int k=0;

int i;

for (i = 0; i < 4; i++) {

SRES[i] = simoutput[i];

}

for (i = 3;i>=0 ; i--){

for(int j=7; j>=0 ; j--){

SRESint = SRESint + ( (SRES[i] >> (7-j) ) &

1)*pow(2,k);

k++;

}

}

return SRESint;

}

A3A8Class() {

};

};

Page 136: Adding Support for Authentication and Encryption to Openbts

128 Code Implementations of Encryption

Whenever you need to call the functions, you need to include the GSMEncryption.h file. In our case, A3A8 algorithm was used whenever the user needed to be authenticated. Therefore we had to include the GSMEncryption.h in the following files:

1. Control/MobilityMangment.cpp

void Control::LocationUpdatingController(const

L3LocationUpdatingRequest* lur, SDCCHLogicalChannel* SDCCH)

2. Control/CallControl.cpp

void Control::MOCStarter(const L3CMServiceRequest* req,

LogicalChannel *LCH) void

Control::MTCStarter(TransactionEntry& transaction,

LogicalChannel *LCH)

Page 137: Adding Support for Authentication and Encryption to Openbts

129 OpenBTS

After calling the A3A8 algorithm you can get the SRES using the following code: const char* imsi;

imsi=mobID.digits();//If this code was added to the

CallControl.cpp you should replace mobID with

mobileIdentity.

if (gConfig.defines("Control.KiTable.SavePath")) {

LOG(INFO) << "IMSI = " << imsi;

gKiTable.loadAndFindKI(imsi);

LOG(INFO) << "Ki = " << gKiTable.getKi();

A3A8Class a3a8;

GSM::L3AuthenticationParameterRAND mRand;

for (int i=0;i<16;i++)

LOG(INFO) << "RAND = " <<

int(mRand.getRandToA3A8()[i]);

a3a8.A3A8(mRand.getRandToA3A8(),gKiTable.getKi());

uint64_t Kc;

Kc=a3a8.getKC();

mobID.setKC(Kc);

unsigned int SRES;

SRES=a3a8.getSRES();

}

4.6 Frame number (FN):

The Frame Number was already implemented in: File: GSMCommon.h, line: 343.

int FN() const { return mFN; } // It’s a member of the

class named Time

Frame number. The implementation is

based on the values of the T1, T2 and

T3’ .This is the binary

representation of the frame numbers. Thay are also

defined as a member function of Class Time

in GSMCommon.h.

/** GSM 05.02 3.3.2.2.1 */

unsigned T1() const { return SFN() % 2048; }

/** GSM 05.02 3.3.2.2.1 */

unsigned T2() const { return mFN % 26; }

/** GSM 05.02 3.3.2.2.1 */

unsigned T3() const { return mFN % 51; }

/** GSM 05.02 3.3.2.2.1. */

unsigned T3p() const { return (T3()-1)/10; }

Page 138: Adding Support for Authentication and Encryption to Openbts

130 Code Implementations of Encryption

The frame number is generated from T1, T2 and T3'. But the Count, which is used in the A5/1 algorithm is generated from T1, T2 and T3, forming a 22-bit value. 4.6.1 Our modifications in this scope: The following lines should be added to the file where the A5/1 algorithm will be called to make sure that you have the correct count based on T1, T2 and T3. GSM::Time mCount;//creating an object to access the member functions of this class mCount(gBTS.time().FN(),wTN)//this is a constructor So in order to call the A5/1 algorithm, we have to use this function:

void keysetup( kc, (mCount.T1()<<11)|(mCount.T3()<<5)|mCount.T2)

4.7 A5/1 Algorithm:

The A5 encryption algorithm is used to encipher and decipher the data that is being transmitted on the Um interface. The Kc and the plaintext data are inputted into the A5 algorithm and the output is enciphered data. The A5 algorithm is a function of the Mobile Equipment (ME) and not a function of the SIM card. The BTS also makes use of the A5 algorithm.

The A5 algorithm is built up of three short linear feedback shift registers (LFSR)

I. R1 of length from 0-19 bits & its taps 13,16,17,18 II. R2 of length from 0-22 bits& its taps 20, 21

III. R3 of length from 0-22 bits& its taps 7,20,21,22 Each register has a single "clocking" tap (Bit 8 for R1, bit 10 for R2, and bit 10 for R3) 4.7.1 Functionality:

A5: Uses the cipher key (KC) and the 22-bit TDMA frame number (FN) as the input parameters in order to cipher/decipher the data/digitized voice. 1. Input: Frame number (Fn), Ciphering key (Kc) Fn: 22-bit, generated as an initialization vector (IV) and is used to seed A5. Kc: 64 bit, generated both in mobile and in SIM card (GSM), used as a session key to encipher and decipher the data that is being transmitted on the Um interface. 2. Output: 228 bits Keystream (114 to encrypt or decrypt uplink and 114 for the downlink). 3. The LFSR are clocked in a stop/go fashion using the majority rule.

Page 139: Adding Support for Authentication and Encryption to Openbts

131 OpenBTS

4.7.2 A5/1 Implementation:

The A5/1 is implemented as a Class in the code which contains the following member functions:

a. static int parity32 (uint32_t x)

b. static int majority (uint32_t R1, uint32_t R2, uint32_t R3)

This function is used to calculate the value of the majority bit which will be used to make clocking of the registers.

c. static int getbit (uint32_t R1, uint32_t R2, uint32_t R3)

This function XORs the most significant bits of each of the three registers to get the output bit which is one of the bits that forms the Keystream which will be used in encrypting the data.

d. static uint32_t clockone(uint32_t reg, uint32_t mask, uint32_t taps)

This function is used in clocking only the registers that follow the majority bit.

e. void keysetup(uint64_t kc,uint32_t frameno)

This function is the main function whose inputs are Kc generated before in the A3A8 Algorithm and the frame number,it‘s used to load their values in the 3 Linear feedback shift registers.

f. int generate_keystream_bit() This function is used to generate the key stream which is used in the XORing process to get the uplink and downlink for the encryption process.

So, whenever you need to perform the A5/1 algorithm all you need to do is just create

an object from this class and call the keysetup function and the

generate_keystream_bit.

Code Implementation in File : GSMEncryption.h class A51 {

Page 140: Adding Support for Authentication and Encryption to Openbts

132 Code Implementations of Encryption

static const uint32_t R1MASK = 0x07FFFF; /* 19 bits, numbered

0..18 */

static const uint32_t R2MASK = 0x3FFFFF; /* 22 bits, numbered

0..21 */

static const uint32_t R3MASK = 0x7FFFFF; /* 23 bits, numbered

0..22 */

// majority bit

/* Middle bit of each of the three shift registers, for clock

control */

static const uint32_t R1MID = 8; /* bit 8 */

static const uint32_t R2MID = 10; /* bit 10 */

static const uint32_t R3MID = 10; /* bit 10 */

/* Feedback taps, for clocking the shift registers. */

static const uint32_t R1TAPS = 0x072000; /* bits 18,17,16,13

*/

static const uint32_t R2TAPS = 0x300000; /* bits 21,20 */

static const uint32_t R3TAPS = 0x700080; /* bits 22,21,20,7

*/

/* Output taps, for output generation */

static const uint32_t R1OUT = 18; /* bit 18 (the high bit) */

static const uint32_t R2OUT = 21; /* bit 21 (the high bit) */

static const uint32_t R3OUT = 22; /* bit 22 (the high bit) */

// xor the taps and return the LSB as it contains the result

of xoring

static int parity32(uint32_t x) {

x ^= x >> 16;

x ^= x >> 8;

x ^= x >> 4;

x ^= x >> 2;

x ^= x >> 1;

return x & 1;

};

static int majority(uint32_t R1, uint32_t R2, uint32_t R3) {

int sum;

sum = (R1 >> R1MID & 1) + (R2 >> R2MID & 1) + (R3 >>

R3MID & 1);

if (sum >= 2)

return 1;

else

return 0;

};

Page 141: Adding Support for Authentication and Encryption to Openbts

133 OpenBTS

static int getbit(uint32_t R1, uint32_t R2, uint32_t R3) {

return (R1 >> R1OUT ^ R2 >> R2OUT ^ R3 >> R3OUT) & 1;

};

static uint32_t clockone(uint32_t reg, uint32_t mask,

uint32_t taps) {

uint32_t t = reg & taps; // select tap bits only

reg = (reg << 1) & mask;

reg |= parity32(t);

return reg;

};

uint32_t R1, R2, R3;

public:

void keysetup(uint64_t kc,uint32_t frameno) {

R1 = R2 = R3 = 0; //initialization

for (int i = 0; i < 64; ++i) {

R1 = clockone(R1, R1MASK, R1TAPS) ^ ((kc >> i) & 1);

// return register after clocking

R2 = clockone(R2, R2MASK, R2TAPS) ^ kc >> i & 1;

R3 = clockone(R3, R3MASK, R3TAPS) ^ kc >> i & 1;

}

for (int i = 0; i < 22; ++i) {

R1 = clockone(R1, R1MASK, R1TAPS) ^ frameno >> i & 1;

R2 = clockone(R2, R2MASK, R2TAPS) ^ frameno >> i & 1;

R3 = clockone(R3, R3MASK, R3TAPS) ^ frameno >> i & 1;

}

for (int i = 0; i < 100; ++i) {

int maj = majority(R1, R2, R3);

if ((R1 >> R1MID & 1) == maj)

R1 = clockone(R1, R1MASK, R1TAPS);

if ((R2 >> R2MID & 1) == maj)

R2 = clockone(R2, R2MASK, R2TAPS);

if ((R3 >> R3MID & 1) == maj)

R3 = clockone(R3, R3MASK, R3TAPS);

}

};

int generate_keystream_bit() {

int maj = majority(R1, R2, R3);

if ((R1 >> R1MID & 1) == maj)

R1 = clockone(R1, R1MASK, R1TAPS);

Page 142: Adding Support for Authentication and Encryption to Openbts

134 Code Implementations of Encryption

if ((R2 >> R2MID & 1) == maj)

R2 = clockone(R2, R2MASK, R2TAPS);

if ((R3 >> R3MID & 1) == maj)

R3 = clockone(R3, R3MASK, R3TAPS);

int res = getbit(R1, R2, R3);

return res;

};

};

Whenever you need to call the functions of this algorithm ,you must include the GSMEncryption.h file in any code you are willing to use it.A5/1 is used in the following files:

1. GSM/GSML1FEC.cpp

4.8 XORing stage – conversion from plain text to cipher text:

Algorithm A5 is implemented into both the MS and the BSS. The A5 algorithm is implemented for the physical channels (TCH or DCCH). The ciphering takes place before modulation and after interleaving; the deciphering takes place after demodulation symmetrically. The bottom layer of GSM (layer 1) which is known as the physical layer is used to convert speech into radio waves and vice verse. So, we will to take a closer look onto this layer to be able to imagine the whole sequence.

4.8.1 Forward error correction and Radio Modem in L1:

Figure 4.3 The sequence of operation consists of mainly six important stages:

1. The GSM Speech Coding: The full rate speech codec in GSM is described as Regular Pulse Excitation with Long

Page 143: Adding Support for Authentication and Encryption to Openbts

135 OpenBTS

Term Prediction GSM 06.10 RPE-LTP. Basically, the encoder divides the speech into short-term predictable parts, long-term predictable part and the remaining residual pulse. Then, it encodes that pulse and parameters for the two predictors. The decoder reconstructs the speech by passing the residual pulse first through the long-term prediction filter, and then through the short-term predictor.

Figure 4.4

Page 144: Adding Support for Authentication and Encryption to Openbts

136 Code Implementations of Encryption

OpenBTS will initially support the ―full rate‖ vocoder of GSM 06.10, relying on Asterisk

to run the transcoders for us. Half rate traffic channels are ignored as they are not a

priority in

a first release.

2 .The GSM Channel Coding:

Channel coding introduces redundancy into the data flow in order to allow the detection

or even the correction of bit errors introduced during the transmission. The speech

coding algorithm produces a speech block of 260 bits every 20 ms i.e. bit rate 13 Kbits.

In the decoder, these speech blocks are decoded and converted to 13 bit uniformly

coded speech samples. The 260 bits of the speech block are classified into two groups.

The 78 Class II bits are considered of less importance and are unprotected.

The 182 Class I bits are split into 50 Class Ia bits and 132 Class Ib bits .Class Ia bits are

first protected by 3 parity bits for error detection. Class Ib bits are then added together

with 4 tail bits before applying the convolution code with rate r = 1 and constraint length

K = 5. The resulting 378 bits are then added to the 78 unprotected Class II bits resulting

in a complete coded speech frame of 456 bits.

Figure 4.5

Page 145: Adding Support for Authentication and Encryption to Openbts

137 OpenBTS

Figure 4.6

The GSM standard uses a 3-bit error redundancy code to enable assessment of the correctness of the bits which are more sensitive to errors in the speech frame the category IA 50-bits. If one of these bits is wrong, this may create a loud noise instead of the 20 ms speech slice. Detecting such errors allows the corrupted block to be replaced by something less disturbing such as an extrapolation of the preceding block.

The polynomial representing the detection code for category Ia bits is GX = X 3 + X + 1.At the receiving side, the same operation is done and if the remainder differs, an error is detected and the audio frame is eventually discarded. The GSM convolutional code consists in adding 4 bits set to 0" to the initial 185 bit sequence and then applying two different convolutions: polynomials are respectively G1 X = X 4 + X 3 + 1 and G2X = X 4 + X 3 + X + 1. The final result is composed of twice 189 bits sequences.

Convolutional decoding can be performed using a Viterbi algorithm. A Viterbi decoder logically explores in parallel every possible user data in sequence. It encodes and compares each one against the received sequence and picks up the closest match: it is a maximum likelihood decoder. To reduce the complexity the number of possible data sequence double with each additional data bit, the decoder recognizes at each point that certain sequences cannot belong to the maximum likelihood path and it discards them. The encoder memory is limited to K bits; a Viterbi decoder in steady-state operation keeps only 2K, 1 paths. Its complexity increases exponentially with the constraint length K.

In OpenBTS, all GSM channels use some type of block code. Some channels use simple CRC-type parity check codes. Most channels use a Fire code that can also be used for burst-error correction, described in GSM 05.03 Section 4.1.2.Also Most GSM channels use a rate-1/2 convolutional encoder described in GSM 05.03 Section 4.1.3.

Page 146: Adding Support for Authentication and Encryption to Openbts

138 Code Implementations of Encryption

Code Implementation in File: GSML1FEC.cpp, line: 808

void XCCHL1Encoder::encode()

{

// Perform the FEC encoding of GSM 05.03 4.1.2 and 4.1.3

// GSM 05.03 4.1.2

// Generate the parity bits.

mBlockCoder.writeParityWord(mD,mP);

OBJLOG(DEEPDEBUG) << "XCCHL1Encoder u[]=" << mU;

// GSM 05.03 4.1.3

// Apply the convolutional encoder.

mU.encode(mVCoder,mC);

OBJLOG(DEEPDEBUG) << "XCCHL1Encoder c[]=" << mC;

}

3 .Interleaving/ De-interleaving:

Interleaving is meant to decorrelate the relative positions of the bits respectively in the

code words and in the modulated radio bursts. The aim of the interleaving algorithm is

to avoid the risk of losing consecutive data bits. GSM blocks of full rate speech are

interleaved on 8 bursts: the 456 bits of one block are split into 8 bursts in sub-blocks of

57 bits each. A sub-block is defined as either the odd- or the even-numbered bits of the

coded data within one burst. Each sub-blocks of 57 bit is carried by a di erent burst and

in a different TDMA frame. So, a burst contains the contribution of two successive

speech blocks A and B. In order to destroy the proximity relations between successive

bits, bits of block A use the even positions inside the burst and bits of block B, the odd

positions. De-interleaving consists in performing the reverse operation.

The major drawback of interleaving is the corresponding delay: transmission time from

the first burst to the last one in a block is equal to 8 TDMA frames i.e. about 37 ms.

In most GSM channels, a higher-layer data frame is spread over 4 radio bursts with an

interleaving pattern according to the rules of GSM 05.03 Sections 4.1.4 and

4.1.5.Interleaving. Some channels (TCH/FACCH) use 8-burst diagonal interleaving as

per GSM 05.03 Sections 3.1.3 and 3.1.4.

In some channels (RACH, RACCH and SCH) each protocol element maps to a single

radio burst and there is no interleaving.

Code Implementation in File :GSML1FEC.cpp, line: 842

void XCCHL1Encoder::interleave()

{

for (int k=0; k<456; k++) {

int B = k%4;

Page 147: Adding Support for Authentication and Encryption to Openbts

139 OpenBTS

int j = 2*((49*k) % 57) + ((k%8)/4);

mI[B][j] = mC[k];

}

}

4 .Ciphering/ Deciphering: A protection has been introduced in GSM by means of transmission ciphering. The ciphering method does not depend on the type of data to be transmitted speech, user data or signaling but is only applied to normal bursts. Ciphering is achieved by performing an exclusive or" operation between a pseudo-random bit sequence and 114 useful bits of a normal burst i.e. all information bits except the 2 stealing flags. The pseudo-random sequence is derived from the burst number and a key session established previously through signaling means. Deciphering follows exactly the same operation.

Figure 4.7 the open source OpenBTS version didn't support encryption but in our project we succeed to integrate this feature which will be discussed later. 5 .Modulation /Demodulation: GSM uses the Gaussian Modulation Shift Keying GMSK with modulation index h =0:5, BT (filter bandwidth times bit period) equal to 0.3 and a modulation rate of 271 (270 5/6 kbauds). The GMSK modulation has been chosen as a compromise between, a fairly high spectrum efficiency of the order of 1 bit Hz and a reasonable demodulation complexity. The constant envelope allows the use of simple power amplifiers and the low out-of-band radiation minimizes the effect of

Page 148: Adding Support for Authentication and Encryption to Openbts

140 Code Implementations of Encryption

adjacent channel interference. GMSK differs from Minimum Shift Keying MSK in that a pre-modulation Gaussian filter is used.

Figure 4.8 Code Implementation in File :sigProcLib.cpp., line: 521 signalVector *modulateBurst(const BitVector &wBurst,const

signalVector &gsmPulse,int guardPeriodLength, int

samplesPerSymbol)

as the ciphering is applied on the normal bursts so we need also to focus on the construction of Normal bursts 4.8.2 Normal burst: As an indication, due to the TDMA techniques used in the system, the useful data (also called the plain text in the sequel) are organized into blocks of 114 bits. Then, each block is incorporated into a normal burst and transmitted during a time slot.

Table 4.1

Page 149: Adding Support for Authentication and Encryption to Openbts

141 OpenBTS

-where the "tail bits" are defined as modulating bits with states as follows:

(BN0, BN1, BN2) = (0, 0, 0) and

(BN145, BN146, BN147)= (0, 0, 0)

Code Implementation in File :GSML1FEC.cpp, line: 742

mU.zero();

-where the "training sequence bits" are defined as modulating bits with states as given

in the following table. For broadcast and common control channels, the TSC must be

equal to the BCC. In networks supporting E-OTD Location services (see GSM 03.71

Annex C), the TSC shall be equal to the BCC for all normal bursts on BCCH

frequencies.

Code Implementation in File :GSML1FEC.cpp, line:739

gTrainingSequence[mTSC].copyToSegment(mBurst,61);

Code Implementation in File :GSMCommon.cpp, line:44

const BitVector GSM::gTrainingSequence[] = {

BitVector("00100101110000100010010111"),

BitVector("00101101110111100010110111"),

BitVector("01000011101110100100001110"),

BitVector("01000111101101000100011110"),

BitVector("00011010111001000001101011"),

BitVector("01001110101100000100111010"),

BitVector("10100111110110001010011111"),

BitVector("11101111000100101110111100"),

};

So according to GSM 05.03, the useful information bits into a block are numbered e0 to

e56 and e59 to e115 (the flag bits e57 and e58 are ignored .

4.8.3 SDCCH channel mapping:

Control Channels are composed of 51 TDMA frames. On a time slot Within the

multiframe, the 51 TDMA frames are divided up and allocated to the various logical

channels. There are several channel combinations allowed in GSM but we are only

concerned with two channels the SDCCH and the TCH as they are the channels where

the ciphering will be applied.

SDCCH/8(0 .7) + SACCH/C8 (0.7)

Page 150: Adding Support for Authentication and Encryption to Openbts

142 Code Implementations of Encryption

Figure 4.9 Uplink

Figure 4.10 Downlink

The downlink and uplink multiframes do not align with each other. This is done so that if the BTS sends an information request to the MS, it does not have to wait an entire multiframe to receive the needed information. The uplink is transmitted 15 TDMA frames behind the downlink. For example, the BTS might send an authentication request to the MS on SDCCH0 (downlink) which corresponds to TDMA frames 22-25. The MS then has enough time to process the request and reply on SDCCH0 (uplink) which immediately follows it on TDMA frames 37-40.

The 228-bit Keystream is supposed to be generated from the Frame Number and the Kc . According to this and the channel mapping,this shouldn't cause any problems in the TCH as the Frame Number is the same for both the Uplink and the Downlink, the 228 bits are split into 2*114 bits for the same frame number.but for SDCCH the UL and DL are in different frames,so we would only use one of the pair of 114 bits .

4.8.4 The ciphering process:

For ciphering, Algorithm A5 produces, each 4.615 ms, a sequence of 114

encipher/decipher bits (here called BLOCK) which is combined by a bit-wise

modulo 2 addition with the 114-bit plain text block. The first encipher/decipher bit

produced by A5 is added to e0, the second to e1 and so on. As an indication, the

resulting 114-bit block is then applied to the burst builder (see GSM 05.01).

For each slot, deciphering is performed on the MS side with the first block

(BLOCK1) of 114 bits produced by A5, and enciphering is performed with the

second block (BLOCK2). As a consequence, on the network side BLOCK1 is

used for enciphering and BLOCK2 for deciphering. Therefore Algorithm A5 must

produce two blocks of 114 bits (i.e. BLOCK1 and BLOCK2) each 4.615 ms.

Page 151: Adding Support for Authentication and Encryption to Openbts

143 OpenBTS

4.8.5 Ciphering/deciphering Codes Part:

We have two channels that we should encrypt and decrypt in order to make

correct ciphering procedures which are the Traffic Channel (TCH) and Stand

alone dedicated channel (SDCCH)

Reference of Functions:

copyToSegment: void Vector< T >::copyToSegment (Vector< T > & other, size_t start, size_t span ) : Copy part of this Vector to a segment of another Vector.

void encrypt(): performs the Xoring Stage between the 114 bits downlink with the interleaved bit void decrypt(): performs the Xoring Stage between the 114 bits uplink with the Received bits virtual void sendFrame(const L2Frame&):sends a single L2 frame.It makes sure there's a downstream data there to take this uncoded bits and start the encoding process. void transmit():Formats i[] into timeslots and send them down for transmission. Set stealing flags assuming a control channel. Also updates mWriteTime. const SoftVector data1():Return a SoftVector alias to the first data field. const SoftVector data2():Return a SoftVector alias to the second data field. Important Definitions: BitVector: Construct from a string of "0" and "1". SoftVector: The SoftVector class is used to represent a soft-decision signal. Values 0..1 represent probabilities that a bit is "true". ChannelType: Describes the Type of the Channel L1FEC: this class is concerned with the encapsulation of the encoder and the decoder.The L1FEC member functions are over-ridden for different channel types.

Naming Conventions: "k" and "j" for numbering of bits in data blocks and bursts; "n" is used for numbering of delivered data blocks "N" marks a certain data block; "B" is used for numbering of bursts or blocks

Page 152: Adding Support for Authentication and Encryption to Openbts

144 Code Implementations of Encryption

Interleaved data bits: i(B,k) for k = 0,1,...,Ki-1 B = B0, B0+1,.... Interleaved data symbols: I(B,k) for k = 0,1,...,KI-1 Bits in one burst :e(B,k) for k = 0,1,...,114,115

4.9 Xoring Full Description with Codes: The encryption after the interleaving stage is done by Xoring the 114 bits keystream with the plaintext in order to produce a cipher text, those bits are the first 114 bits generated from the 228 output bits from the A51 Algorithm which takes Frame number and the Kc of the mobile as an input parameters, the same thing happens for the Uplink when we need to decipher the Text in order to get the plain text again by Xoring the second 114 bits with the cipher text. 1. Traffic Channel (TCH): In class TCHFACCHL1Encoder: the changes that we made in GSML1FEC.h concerning this channel was : 1-defining a new variable which contains the encrypted bits in one burst this variable will be a private member for the class TCHFACCHL1Encoder which is inherited from the class XCCHL1Encoder where Private members can be accessed only within methods of the class itself. Code Implementation in File :GSML1FEC.h, line:746 BitVector mE[8]; and this variable will be initialized GSML1FEC.cpp inside the constructor of TCHFACCHL1Encoder Code Implementation in File :GSML1FEC.cpp, line:1439 for(int k = 0; k<8; k++) {

mE[k] = BitVector(114);

mI[k] = BitVector(114);

// Fill with zeros just to make Valgrind happy.

mI[k].fill(0);

mE[k].fill(0);

}

2-adding a new function to the class TCHFACCHL1Encoder .this is the function where Xoring takes place .

Page 153: Adding Support for Authentication and Encryption to Openbts

145 OpenBTS

Code Implementation in File :GSML1FEC.h, line:780 virtual void encrypt();//function prototype

Code Implementation in File :GSML1FEC.cpp, line:1611 void TCHFACCHL1Encoder::encrypt()//function definition

{

for (int B=0; B<8; B++) // the loop till 8 cause the number of

blocks in the TCH are 8

{

mE[B]=mI[B]^keyStreamDL;

LOG(INFO) <<"TCHFACCHL1Encoder encrypt";

}

}

and this function will be called after the interleaving and before the coping into segment and transmission. Code Implementation in File :GSML1FEC.cpp, line:1575 LOG(INFO)<<"TCH START INTERLEAVE";

interleave(mOffset);

LOG(INFO)<<"TCH START ENCRYPT";

encrypt();

LOG(INFO)<<"TCH START ENCRYPTed";

and instead of filling the segment with interleaved bits it will

be filled with encrypted

mE[B].segment(0,57).copyToSegment(mBurst,3);

mE[B].segment(57,57).copyToSegment(mBurst,88);

In class TCHFACCHL1Decoder: The changes that we made in GSML1FEC.h concerning this channel were : 1-Defining a new variable which contains the encrypted bits in one burst this variable will be a protected member for the class TCHFACCHL1Decoder which is inherited from the class XCCHL1Decoder where Protected is the middle point between the private and public .this variable can be accessed by the class itself , Functions/classes marked as friend and Objects that inherit from that class. Code Implementation in File :GSML1FEC.h, line:811

SoftVector mE[8]; ///< decrypting history, 8 blocks instead of 4

and this variable will be initialized GSML1FEC.cpp inside the constructor of TCHFACCHL1Decoder Code Implementation in File :GSML1FEC.cpp, line:1186 for (int i=0; i<8; i++) {

Page 154: Adding Support for Authentication and Encryption to Openbts

146 Code Implementations of Encryption

mE[i] = SoftVector(114);

mI[i] = SoftVector(114);

// Fill with zeros just to make Valgrind happy.

mI[i].fill(.0);

mE[i].fill(.0);

}

2-Adding a new function to the class TCHFACCHL1Decoder .this is the function where XORing takes place but here we are doing this on the upstream data. Code Implementation in File :GSML1FEC.h, line:846 void decrypt();//function prototype

Code Implementation in File :GSML1FEC.CPP, line:1296 void TCHFACCHL1Decoder::decrypt()

{

for (int B=0; B<8; B++)

{

mI[B]=mE[B]^keyStreamUL;

LOG(INFO) <<"TCHFACCHL1Decoder decrypt";

}

}

This function will be called before the de-interleaving and after copying the received data into the segment.

decrypt(); if (B==3)

{

LOG(INFO) <<"TCH PROCESS BURST ";

LOG(INFO) <<"TCH PROCESS BURST DECRYPTED";

deinterleave(4);

LOG(INFO) <<"TCH PROCESS BURST INTERLEAVED";

}

else

{

LOG(INFO) <<"TCH PROCESS BURST 1";

deinterleave(0);

LOG(INFO) <<"TCH PROCESS BURST 2";

}

2.Stand alone dedicated control channel (SDCCH) : In class SDCCHL1Encoder: we have to implement a new class because we need to encrypt the SDCCH only not the whole channels so the new function will be a member of this class.

Page 155: Adding Support for Authentication and Encryption to Openbts

147 OpenBTS

Code Implementation in File :GSML1FEC.h, line:681 class SDCCHL1Encoder : public XCCHL1Encoder {

private:

/**@name FEC signal processing state. */

//@{

BitVector mE[4]; ///< e[][], as per GSM 05.03 2.2

//@}

public:

SDCCHL1Encoder(

unsigned wTN,

const TDMAMapping& wMapping,

L1FEC* wParent);

void encrypt();

protected:

/** Send a single L2 frame. */

virtual void sendFrame(const L2Frame&); void

transmit();

/** Will start the dispatch thread. */

// void start();

};

the changes that we made in GSML1FEC.h concerning this channel was : 1-defining a new variable which contains the encrypted bits in one burst this variable will be a private member for the class SDCCHL1Encoder which is inherited from the class XCCHL1Encoder where Private members can be accessed only within methods of the class itself. Code Implementation in File :GSML1FEC.h, line:687 BitVector mE[4];

and this variable will be initialized GSML1FEC.cpp inside

the constructor of SDCCHL1Encoder

Code Implementation in File :GSML1FEC.cpp, line:926 for(int k = 0; k<4; k++) {

mE[k] = BitVector(114);

mI[k] = BitVector(114);

// Fill with zeros just to make Valgrind happy.

mI[k].fill(0);

mE[k].fill(0);

}

2-Adding a new function to the class XCCHL1Encoder ( XORing class)

Page 156: Adding Support for Authentication and Encryption to Openbts

148 Code Implementations of Encryption

Code Implementation in File :GSML1FEC.h, line:699 void encrypt();;//function prototype

Code Implementation in File :GSML1FEC.cpp, line:966 void SDCCHL1Encoder::encrypt()

{

LOG(INFO)<< "SDCCH ENCRYPT frmae number" <<

((mCount.T1()<<11)|(mCount.T3()<<5)|mCount.T2());

for (int B=0; B<4; B++)

{

mE[B]=mI[B]^keyStreamDl;

LOG(INFO) <<"SDCCHL1Encoder ENCRYPT";

}

}

And this function will be called after the interleaving and before transmission. Code Implementation in File :GSML1FEC.cpp, line:997

interleave(); // Interleave c[] to i[][], GSM 05.03

4.1.4.

LOG(INFO) << "SDCCHL1ENCODER INTERLEAVED";

encrypt(); // Encrypt i[][] to e[].

LOG(INFO) << "SDCCHL1ENCODER ENCRYPTED";

transmit(); // Send the bursts to the radio,

GSM 05.03 4.1.5.

LOG(INFO) << "SDCCHL1ENCODER TRANSMITTED";and instead of

filling the segment with interleaved bits it will be filled

with encrypted

To activate this new class ,we have to chane the definition

of the class SDCCHL1FEC which is implemented in GSML1FEC

line 1082 to be

class SDCCHL1FEC : public L1FEC {

public:

SDCCHL1FEC(

unsigned wTN,

const MappingPair& wMapping)

:L1FEC()

{

mEncoder = new

SDCCHL1Encoder(wTN,wMapping.downlink(),this);

mDecoder = new

SDCCHL1Decoder(wTN,wMapping.uplink(),this);

}

};

Page 157: Adding Support for Authentication and Encryption to Openbts

149 OpenBTS

In class SDCCHL1Decoder: the changes that we made in GSML1FEC.h concerning this channel was : 1-defining a new variable which contains the encrypted bits in one burst this variable will be a protected member for the class XCCHL1Decoder which is inherited from the class L1Decoder where Protected is the middle point between the private and puplic .this variable can be accessed by the class itself , Functions/classes marked as friend and Objects that inherit from that class. Code Implementation in File :GSML1FEC.h, line:465

SoftVector mE[4]; ///< decrypting history

and this variable will be initialized GSML1FEC.cpp inside the constructor of XCCHL1Decoder Code Implementation in File :GSML1FEC.cpp, line:1186 for (int K=0; K<4; i++) {

mE[K] = BitVector(114);

mI[K] = BitVector(114);

// Fill with zeros just to make Valgrind happy.

mI[K].fill(0);

mE[K].fill(0);

}

2-Adding a new function to the class XCCHL1Decoder (XORing place) - upstream data. Code Implementation in File :GSML1FEC.h, line:505 virtual void decrypt();//function prototype

Code Implementation in File :GSML1FEC.CPP, line:1307 void XCCHL1Decoder::decrypt()

{

for (int B=0; B<4; B++)

{

if(channelType()==SDCCHType)

{

mI[B]=mE[B]^keyStreamUL;

LOG(INFO) <<"XCCHL1Decoder Decrypt";

}

else

{

mI[B]=mE[B];

LOG(INFO) <<"XCCHL1Decoder ELSE";

}

}

Page 158: Adding Support for Authentication and Encryption to Openbts

150 Code Implementations of Encryption

}

and this function will be called before the deinterleaving Code Implementation in File :GSML1FEC.cpp, line:559 if (!processBurst(inBurst)) return;

decrypt();

deinterleave();

if (decode()) {

countGoodFrame();

mD.LSB8MSB();

handleGoodFrame();

} else {

countBadFrame();

}

Page 159: Adding Support for Authentication and Encryption to Openbts

151 OpenBTS

References:

[1] GSM 05.03 version 8.5.1 Release 1999

[2]GSM 05.10 version 8.4.0 Release 1999

[3]A brief Overview of the GSM Radio Interface .Thierry Turletti Telemedia ,Networks

and Systems Group .

[4] The Open BTS Project .David A. Burgess, Harvind S. Samra .August 3, 2008.

Page 160: Adding Support for Authentication and Encryption to Openbts

152 Authentication and Ciphering Messages

Chapter 5: Authentication and Ciphering Messages 5.1 Authentication: The purpose of authentication is to validate the identity provided by the mobile station. It is initiated by the network. The authentication procedure also provides the mobile station with information from which a new ciphering key can be derived, the network decides whether or not to use authentication, this may depend on the context.

The authentication procedure exchange between the fixed subsystem and the MS: ● The fixed subsystem transmits a number RAND to the MS. ● The MS computes the signature of RAND, say SRES, using algorithm A3 and some secret

information: the Individual Subscriber Authentication Key, denoted below by Ki. ● The MS transmits the signature SRES to the fixed subsystem. ● The fixed subsystem tests SRES for validity.

Page 161: Adding Support for Authentication and Encryption to Openbts

153 OpenBTS

General authentication procedure

Mobile Station (MS) The mobile station permanently stores:

- Authentication algorithm A3; - Encryption algorithm A5; - ciphering key generating algorithm A8; - Individual subscriber authentication key Ki; - ciphering key Kc; - ciphering key sequence number; - TMSI.

The mobile station generates and stores: - ciphering key Kc.

The mobile station receives and stores: - ciphering key sequence number; - TMSI; - LAI.

Page 162: Adding Support for Authentication and Encryption to Openbts

154 Authentication and Ciphering Messages

5.1.1 Authentication applies for: ● A change of subscriber-related information element in the VLR or HLR (including some

or all of: location updating involving change of VLR, registration or erasure of a supplementary service)

● An access to a service (including some or all of: set-up of mobile originating or terminated calls, activation or deactivation of a supplementary service)

● First network access after restart of MSC/VLR ● The event of cipher key sequence number mismatch.

5.1.2 Authentication during a malfunction of the network ● If an MS is registered and has been successfully authenticated, whether active or not

active on a call, calls are permitted (including continuation and hand-over). ● If an MS has already been registered (and therefore been already authenticated) and

cannot be successfully reauthenticated due to the network malfunction (e.g. the HPLMN was not able to provide authentication pairs RAND, SRES), calls are permitted.

● If an MS attempts to register and cannot be successfully authenticated due to the network malfunction, calls are not permitted.

● If the MS is not registered, or ceases to be registered, a new registration needs to be performed, and the preceding cases apply.

Page 163: Adding Support for Authentication and Encryption to Openbts

155 OpenBTS

5.2 Ciphering in GSM: Ciphering is used in GSM to encrypt data in the Air- interface between the mobile station and the BTS. Encryption applies only to the Air-Interface Ciphering refers to the process of changing plaintext data into encrypted data using a special key and a special encryption algorithm. Transmissions between the MS and the BTS on the Um link are enciphered. The ciphering takes place before modulation and after interleaving; the deciphering takes place after demodulation symmetrically. Both enciphering and deciphering need Algorithm A5 and start at different times. Algorithm A5 realizes the protection of both user data and signaling information elements at the physical layer on the dedicated channels (TCH or DCCH). As an indication due to the TDMA techniques used in the system, the useful data (also called the plain text in the sequel) are organized into blocks of 114 bits. Then, each block is incorporated into a normal burst and transmitted during a time slot. The useful information bits into a block are numbered e0 to e56 and e59 to e115 (the flag bits e57 and e58 are ignored). Successive slots for a given physical channel are separated at least by a frame duration, approximately 4.615 ms. Synchronization of both the enciphering and deciphering (especially at hand-over) must be guaranteed. Synchronization is guaranteed by driving Algorithm A5 by an explicit time variable, COUNT, derived from the TDMA frame number. COUNT is expressed in 22 bits as the concatenation of the binary representation of T1, T3 and T2. It is an input parameter of Algorithm A5.

Page 164: Adding Support for Authentication and Encryption to Openbts

156 Authentication and Ciphering Messages

The coding of COUNT is shown in figure summarizes the implementation indications listed above, with only one enciphering/deciphering procedure represented.

5.2.1 Ciphering mode setting

Ciphering mode setting is initiated by the network. Its purpose is to instruct the mobile station whether or not to use ciphering and which algorithm to use. Where ciphering is used, this procedure synchronizes the start of ciphering at the mobile station and in the network.

Page 165: Adding Support for Authentication and Encryption to Openbts

157 OpenBTS

5.3 Authentication and Ciphering Codes Before diving into the code we are going to explain some of the common and popular functions, the functions that we used frequently while implementing the authentication and ciphering codes. We will also briefly map all of the classes that we used in our codes.

5.3.1 Important Definitions:

Assert: If the argument expression of this macro with functional form compares equal to zero (i.e., the expression is false), a message is written to the standard error device and abort is called, terminating the program execution. dest: destination L3 frame that will be filled with the proper elements where each frame is filled according to the standards GSM 04.08. wp: the write position acts like a pointer which indicates the position where the bits will be written and it may be incremented to skip some parts of the frame as we will see in the case of spare half octet or the ciphering key sequence number. src: source L3 frame which is received and decoded. According to the output of this received frame, actions will be taken for example LOCATION UPDATING REQUEST requests update of mobile station location file or IMSI attach. rp: the read position it acts like a pointer which indicates the position where the bits will be read and it may be incremented to skip some parts of the frame as we will see in the case of spare half octet or the ciphering key sequence number.

5.3.2 Reference of Functions: size_t bodyLength() const:

Returns the expected message body length in bytes, not including L3 header. If the bodyLength has return value between the braces i.e: bodyLength(){return 4}, then the length of the frame is fixed to a frame size and not edited according to the change of the size of the frame elements.

size_t lengthV() const:

Returns the length of the value part of the element in bytes. This is the core length method, referenced by all other length methods. Return zero for 1/2 octet fields (type 1 elements). void writeBody( L3Frame &dest, size_t &wp ) const:

Writes the L3 message body, a method defined in some subclasses. If not defined, this will assert at runtime. void writeV( L3Frame& dest, size_t &wp ) const;

Page 166: Adding Support for Authentication and Encryption to Openbts

158 Authentication and Ciphering Messages

Writes the V format. This is the core write method for writable elements and all other write methods use it. N.B: check the Standards for (V, LV and TV) void text(std::ostream&) const:

Generates a human-readable representation of a message. void parseBody( const L3Frame &src, size_t &rp ):

The parseBody() method starts processing at the first byte following the message type octet in the L3 message, which the caller indicates with the read Position(rp) argument. If not defined, this will assert at runtime. void parseV(const L3Frame&, size_t&)

The parseV method decodes L3 message bits from fixed-length value parts. This is the core parse method for fixed-length parsable elements and all other parse methods use it.

Page 167: Adding Support for Authentication and Encryption to Openbts

159 OpenBTS

5.3.3 Information Elements: Description of standards of L3 messages This sub-clause describes a generic description method for standard L3 messages, the tabular description. Protocol specification may follow other methods. A standard L3 message is described by a table listing the header elements and the standard IEs in the message. For each element is given

1. If applicable the IEI, in hexadecimal representation (one digit followed by and hyphen for TV formatted type 1, and two digits for the other cases).

2. The name of the IE. 3. The name of the type of the information element (which indicates the coding of the value

part of the IE). 4. The presence requirement indication (M, C, or O) for the IE. 5. The format of the information element (T, V, TV, LV, TLV). 6. The length, or the range of lengths, of the whole standard IE, including when applicable

the T and L parts.

5.3.3.1 Presence requirements of information elements The relevant protocol specification may define three different presence requirements (M, C, or O) for a standard IE within a given standard L3 message: ● M ("Mandatory") means that the IE shall be included by the sending side, and that the

receiver diagnoses a "missing mandatory IE" error when detecting that the IE is not present. An IE belonging to the imperative part of a message has presence requirement M. An IE belonging to the non-imperative part of a message may have presence requirement M.

● C ("Conditional") means that inclusion of the IE by the sender depends on conditions specified in the relevant protocol specification.Only IEs belonging to the non-imperative part of a message may have presence requirement C.

● O ("Optional") means that the receiver shall never diagnose a "missing mandatory IE" error, a "missing conditional IE" error, or an "unexpected conditional IE" error because it detects that the IE is present or that the IE is not present. Only IEs belonging to the non-imperative part of a message may have presence requirement O.

5.3.3.2 Information Elements Format T - Type only V - Value Only TV - Type and Value LV - Length and Value TLV - Type, Length and Value Four categories of standard information elements are defined:

● information elements of format V or TV with value part consisting of 1/2 octet (type 1); ● information elements of format T with value part consisting of 0 octets (type 2);

Page 168: Adding Support for Authentication and Encryption to Openbts

160 Authentication and Ciphering Messages

● information elements of format V or TV with value part that has fixed length of at least one octet (type 3);

● information elements of format TLV or LV with value part consisting of zero, one or more octets (type 4);

5.3.3.3 Common Information Elements: 1) Protocol Discriminator Bits 1 to 4 of the first octet of a standard L3 message contain the protocol discriminator (PD) information element. The correspondence between L3 protocols and PDs is one-to-one. The PD can take the following values:

0 0 0 0 group call control 0 0 0 1 broadcast call control 0 0 1 1 call control; call related SS messages 0 1 0 1 mobility management messages 0 1 1 0 radio resources management messages 1 0 0 1 SMS messages

Code Implementation in file: GSMCommon.h enum L3PD {

L3MobilityManagementPD=0x05,

L3RadioResourcePD=0x06,

};

Code Implementation in File: GSML3MMMessages.h (Authentication Messages) class L3MMMessage : public L3Message {

public:

L3MMMessage():L3Message() {}

/** Return the L3 protocol discriptor. */

L3PD PD() const { return L3MobilityManagementPD; }

}

Page 169: Adding Support for Authentication and Encryption to Openbts

161 OpenBTS

Code Implementation in File : GSML3RRMessages.h (Ciphering Messages) class L3RRMessage : public L3Message {

public:

L3RRMessage():L3Message() { }

/** Return the L3 protocol discriptor. */

L3PD PD() const { return L3RadioResourcePD; }

}

2) Skip indicator or Transaction Identifier (TI) It is bits from 5 to 8 of the first octet of every Radio Resource management message and Mobility Management message. The TI is used to distinguish between possible multiple parallel CM connections and transactions. The TI is composed of the TI flag and 3 bits for the TI value. The TI value is allocated by the entity initiating the transaction. This then identifies all messages relevant to that transaction. Once the transaction is complete, the TI value is released for re-use. If two opposite entities originate different transactions but also assign the same TI value to each, the TI flag avoids ambiguity because it is set to ‘0' by the entity allocating the TI value. Thus, Bit 8 is set to:

'0' if the message is sent from the side that originates the TI '1' if the message is sent to the side that originates the TI

The TI value can be set to: Bit 7 6 5 TI Value

000 0 001 1 010 2 011 3 100 4 101 5 110 6 111 Reserved for future use

A message received with skip indicator different from 0000 shall be ignored. A message received with skip indicator encoded as 0000 shall not be ignored (unless it is ignored for other reasons). A protocol entity sending a Radio Resource management message or a Mobility Management message shall encode the skip indicator as 0000.

Definition at line 260 of GSMCommon.h, where the protocol discriminator takes values that start with zero to indicate the skip indicator.

5.3.4 Authentication Messages and Codes 5.3.4.1 Authentication Request:

Page 170: Adding Support for Authentication and Encryption to Openbts

162 Authentication and Ciphering Messages

This message is sent by the network to the mobile station to initiate authentication of the mobile station identity. Message type: AUTHENTICATION REQUEST Significance: dual Direction: network to mobile station

According to the standards the entire message has to be written for the Protocol Discriminator and the Skip indicator, and it is common as described above in the Common Information Elements. Code Implementation in file : GSML3MMMessages.h, line: 204 class L3AuthenticationRequest : public L3MMMessage

{

L3AuthenticationParameterRAND mRAND;

//L3CKSN mCKSN;

public:

L3AuthenticationRequest()

:L3MMMessage()

{}

int MTI() const { return (int)AuthenticationRequest; }

size_t bodyLength() const;

void writeBody( L3Frame &dest, size_t &wp ) const;

void text(std::ostream&) const;

};

Code Implementation in File : GSML3MMMessages.cpp, line: 321 void L3AuthenticationRequest::writeBody(L3Frame& dest, size_t

&wp) const

{

dest.writeField(wp,0,4); // spare half octet

Page 171: Adding Support for Authentication and Encryption to Openbts

163 OpenBTS

dest.writeField(wp,0,4); //Skip CKSN

“mCKSN.writeV(dest,wp);” mRAND.writeV(dest,wp);

}

void L3AuthenticationRequest::text(ostream& os) const

{

L3MMMessage::text(os);

os << "RAND = ("<< mRAND<<")";

//os << " CKSN = ("<<mCKSN<<")";

}

size_t L3AuthenticationRequest::bodyLength() const

{

size_t len = 1;

len += mRAND.lengthV();

return len;

}

a) Message types: 0 x 0 1 - - - - Security messages: 0 0 1 0 --> AUTHENTICATION REQUEST

Code Implementation in file: GSML3MMMessages.h class L3MMMessage : public L3Message {

public:

enum MessageType {

AuthenticationRequest=0x12,

}

b) Ciphering Key Sequence Number The purpose of the Ciphering Key Sequence Number information element is to make it possible for the network to identify the ciphering key Kc which is stored in the mobile station without invoking the authentication procedure. The ciphering key sequence number is allocated by the network and sent with the AUTHENTICATION REQUEST message to the mobile station where it is stored together with the calculated ciphering key Kc. The security parameters for authentication and ciphering are tied together in sets, i.e. from a challenge parameter RAND both the authentication response SRES and the ciphering key can be computed given the secret key associated to the IMSI. In order to allow start of ciphering on a RR connection without authentication, the ciphering key sequence numbers are introduced. The mobile station stores this number with the key, and indicates to the network in the first message (LOCATION UPDATING REQUEST, CM SERVICE

Page 172: Adding Support for Authentication and Encryption to Openbts

164 Authentication and Ciphering Messages

REQUEST, PAGING RESPONSE, and CM RE-ESTABLISHMENT REQUEST) which sequence number the stored key has. The ciphering key sequence number is a type 1 information element.

Key sequence (octet 1) _ 0 0 0 through 1 1 0 Possible values for the ciphering key sequence number _ 1 1 1 No key is available (MS to network); Reserved (network to MS) In the Codes part we have skipped this information element as it is not implemented in the whole codes not the authentication and ciphering only. c) Spare Half Octet This element is used in the description of messages when an odd number of half octet type 1 information elements are used. This element is filled with spare bits set to zero and is placed in bits 5 to 8 of the octet unless otherwise specified. Code Implementation in file: GSML3MMMessages.cpp, line: 323 dest.writeField(wp,0,4); // spare half octet d) Authentication parameter RAND The purpose of the Authentication Parameter RAND information element is to provide the mobile station with a no predictable number to be used to calculate the authentication response signature SRES and the ciphering key Kc. The Authentication Parameter RAND is a type 3 information element with 17 octets length.

RAND value (octet 2, 3,... and 17) The RAND value consists of 128 bits. Bit 8 of octet_2 is the most significant bit while bit 1 of octet_17 is the least significant bit. Code Implementation in file: GSML3MMElements.h, line: 188 class L3AuthenticationParameterRAND : public L3ProtocolElement {

Page 173: Adding Support for Authentication and Encryption to Openbts

165 OpenBTS

private:

uint64_t mRANDLow;

uint64_t mRANDHigh;

unsigned char rand[16];

// since we can’t have one 128 bit long Rand then we will

split it into two 64 bits RandLow and RandHigh

public: // This is declared as public

L3AuthenticationParameterRAND()

:L3ProtocolElement() // Constructor

{

mRANDLow = 0x3b9af1449deefd90LLU;

mRANDHigh = 0x11d1c55568e89960LLU;

}

size_t lengthV() const { return 16; }

void writeV( L3Frame& dest, size_t &wp ) const;

void parseV(const L3Frame&, size_t&) { assert(0); }

void parseV(const L3Frame&, size_t& , size_t) { assert(0);

}

void text(std::ostream&) const;

};

Page 174: Adding Support for Authentication and Encryption to Openbts

166 Authentication and Ciphering Messages

Code Implementation in file: GSML3MMElements.cpp, line: 217 void L3AuthenticationParameterRAND::writeV( L3Frame& dest,

size_t &wp ) const

{

dest.writeField(wp, mRANDHigh, 64);

dest.writeField(wp, mRANDLow, 64);

}

void L3AuthenticationParameterRAND::text(ostream& os) const

{

os << "RAND = 0x"<< hex << mRANDHigh << hex << mRANDLow;

}

Page 175: Adding Support for Authentication and Encryption to Openbts

167 OpenBTS

Log file ouput: 05 12 00 11 d1 c5 55 68 e8 99 60 3b 9a f1 44 9d ee fd 90 05 ⇒ 0------- Direction From : originating site ⇒ -000---- TransactionID :0 ⇒ ----0101 Protocol Discrim. :Mobile Management Message (non GPRS) 12 ⇒ 00------ SendSequenceNumber : 0 ⇒ --010010 Message Type :Authentication Request 00 ⇒ 0000---- Spare ⇒ ----0--- Spare ⇒ -----000 Cipher Key Sequence Number: 0 11 ⇒ 00010001 Auth. Param. RAND : 17 d1 ⇒ 11010001 Auth. Param. RAND : 209 c5 ⇒ 11000101 Auth. Param. RAND : 197 55 ⇒ 01010101 Auth. Param. RAND : 85 68 ⇒ 01101000 Auth. Param. RAND : 104 e8 ⇒ 11101000 Auth. Param. RAND : 232 99 ⇒ 10011001 Auth. Param. RAND : 153 60 ⇒ 01100000 Auth. Param. RAND : 96 3b ⇒ 00111011 Auth. Param. RAND : 59 9a ⇒ 10011010 Auth. Param. RAND : 154 f1 ⇒ 11110001 Auth. Param. RAND : 241 44 ⇒ 01000100 Auth. Param. RAND : 68 9d ⇒ 10011101 Auth. Param. RAND : 157 ee ⇒ 11101110 Auth. Param. RAND : 238 fd ⇒ 11111101 Auth. Param. RAND : 253 90 ⇒ 10010000 Auth. Param. RAND : 144

Page 176: Adding Support for Authentication and Encryption to Openbts

168 Authentication and Ciphering Messages

5.2.4.2 Authentication Response: This message is sent by the mobile station to the network to deliver a calculated response to the network. Message type: AUTHENTICATION RESPONSE Significance: dual Direction: mobile station to network

According to the Standards all those Messages have to be Written in the codes For the Protocol Discriminator and the Skip indicator it is common as described above in the Common Information Elements

Code Implementation in file: GSML3MMMessage.h, line: 248 class L3AuthenticationResponse : public L3MMMessage

{

L3AuthenticationParameterSRES mSRES; //this part of

the code is used to define the include information elements

public:

L3AuthenticationResponse():L3MMMessage() {}

int MTI() const { return (int)AuthenticationResponse; }

size_t bodyLength() const{ return 4; }

void parseBody( const L3Frame &src, size_t &rp );

void text(std::ostream&) const;

};

Code Implementation in file: GSML3MMMessage.cpp, line: 336 void L3AuthenticationResponse::parseBody(const L3Frame &src,

size_t &rp )

{

mSRES.parseV(src,rp);

}

void L3AuthenticationResponse::text(ostream& os) const

{

L3MMMessage::text(os);

Page 177: Adding Support for Authentication and Encryption to Openbts

169 OpenBTS

os << "L3SRES=("<<mSRES<<")";

}

a) Message types: 0 x 0 1 - - - - Security messages:

0 1 0 0 --> AUTHENTICATION RESPONSE

Code Implementation in File : GSML3MMMessages.h class L3MMMessage : public L3Message {

public:

enum MessageType {

AuthenticationResponse=0x14,

}

b) Authentication parameter SRES: The purpose of the authentication parameter SRES information element is to provide the network with the authentication response signature calculated in the mobile station. The Authentication Parameter SRES is a type 3 information element with 5 octets length.

SRES value (octet 2, 3, 4 and 5) The SRES value consists of 32 bits. Bit 8 of octet_2 is the most significant bit while bit 1 of octet_5 is the least significant bit.

Page 178: Adding Support for Authentication and Encryption to Openbts

170 Authentication and Ciphering Messages

Code Implementation in file: GSML3MMElements.h, line: 212 class L3AuthenticationParameterSRES : public L3ProtocolElement

{

private:

int mSRES;

public:

L3AuthenticationParameterSRES()

:L3ProtocolElement() {}

//empty constructor used to initialize the variables contained

//within the object to certain values, or you want to do

//something every time an object is created, so it'll be useless

//to find a constructor with no definition. The only case I've

//seen a constructor with no definition was the case of the

//L3LocationUpdatingAccept() constructor and this is OK because

//the input arguments of the constructors were used to call

//other constructors/functions or initialize other objects using

//the initializer list.

size_t lengthV() const { return 4; }//the SRES value in 4

octets

void writeV(L3Frame&, size_t&) const { assert(0); }

//authentication request //message is uplink so we don’t

need to write it .

void parseV(const L3Frame &src, size_t &rp);

void parseV(const L3Frame&, size_t&, size_t) { assert(0); }

void text(std::ostream&) const;

};

Code Implementation in file: GSML3MMElements.cpp, line: 229 void L3AuthenticationParameterSRES::parseV(const L3Frame &src,

size_t &rp)

{

mSRES=src.readField(rp,32);

}

void L3AuthenticationParameterSRES::text(ostream& os) const

{

os <<"0x"<< hex << mSRES;

}

Log file output: 01 20 19 05 54 b2 ee 1b 9a 01 ⇒0------- Spare : 0 ⇒ -00----- Link Protocol Discriminator : 0 GSM (not Cell Broadcasting)

Page 179: Adding Support for Authentication and Encryption to Openbts

171 OpenBTS

⇒ ---000-- SAPI : RR, MM and CC ⇒ ------0- C/RFlag : Response, MS side to BS Side ⇒ -------1 Extended Address : 1 octet long 20 ⇒ 001----- N(R), Retransmission counter: 1 ⇒ ---0---- P : 0 ⇒ ----000- N(S), Sequence counter : 0 ⇒ -------0 Information Frame 19 ⇒ 000110-- Length : 6 ⇒ ------0- M, segmentation : (0) N ⇒ -------1 EL, Extended Length : (1) y 05 ⇒ 0------- Direction From : originating site ⇒ -000---- TransactionID : 0 ⇒ ----0101 Protocol Discrim. : Mobile Management Message (non GPRS) 54 ⇒ 01------ SendSequenceNumber : 1 ⇒ --010100 Message Type : Authentication Response b2 ⇒ 10110010 Auth. Param. SRES : 178 ee ⇒ 10110010 Auth. Param. SRES : 238 1b ⇒ 10110010 Auth. Param. SRES : 27 9a ⇒ 10110010 Auth. Param. SRES : 154 5.3.4.3 Authentication Reject: This message is sent by the network to the mobile station to indicate that authentication has failed (and that the receiving mobile station shall abort all activities). Message type: AUTHENTICATION REJECT Significance: dual Direction: network to mobile station

Page 180: Adding Support for Authentication and Encryption to Openbts

172 Authentication and Ciphering Messages

According to the Standards all those Messages have to be Implemented in the codes For the Protocol Discriminator and the Skip indicator it is common as described above in the Common Information Elements Code Implementation in File : GSML3MMMessage.h, line: 231 class L3AuthenticationReject : public L3MMMessage

{

public:

L3AuthenticationReject():L3MMMessage() {}

int MTI() const { return (int)AuthenticationReject; }

size_t bodyLength() const{ return 0;}

void writeBody( L3Frame& dest, size_t &wp ) const {};

void text(std::ostream&) const;

};

Code Implementation in File : GSML3MMMessage.cpp, line: void L3AuthenticationReject::text(ostream& os) const

{

L3MMMessage::text(os);

}

Page 181: Adding Support for Authentication and Encryption to Openbts

173 OpenBTS

a) Message types: 0 x 0 1 - - - - Security messages:

0 0 0 1--> AUTHENTICATION REJECT

Code Implementation in File : GSML3MMMessages.h class L3MMMessage : public L3Message { public: enum MessageType { AuthenticationReject=0x11,

} Log file output: 0511 05 ⇒ 0------- Direction From : originating site ⇒ -000---- TransactionID : 0 ⇒ ----0101 Protocol Discrim. :Mobile Management Message (non GPRS) 11 ⇒ 00------ SendSequenceNumber : 0 ⇒ --010001 Message Type : Authentication Reject

Page 182: Adding Support for Authentication and Encryption to Openbts

174 Authentication and Ciphering Messages

5.3.5 Cipher Messages and Codes:

5.3.5.1 Ciphering mode command This message is sent on the main DCCH from the network to the mobile station to indicate that the network has started deciphering and that enciphering and deciphering shall be started in the mobile station, or to indicate that ciphering will not be performed. Message type: CIPHERING MODE COMMAND Significance: dual Direction: network to mobile station

According to the Standards all those Messages have to be Implemented in the codes For the Protocol Discriminator and the Skip indicator it is common as described above in the Common Information Elements Code Implementation in file: GSML3RRMessages.h, line: 217 class L3CipheringModeCommand : public L3RRMessage {

private:

L3CipheringSettings mSetting;

L3CipheringResponse mResponse;

public:

L3CipheringModeCommand():L3RRMessage() {}

int MTI() const { return CipheringModeCommand; }

size_t bodyLength() const { return 1; }

void writeBody(L3Frame& dest, size_t& wp) const;

void text(std::ostream&) const;

};

Code Implementation in file: GSML3RRMessages.cpp, line: 267 void L3CipheringModeCommand::writeBody(L3Frame& dest, size_t

&wp) const

Page 183: Adding Support for Authentication and Encryption to Openbts

175 OpenBTS

{

mResponse.writeV(dest,wp);

mSetting.writeV(dest,wp);

}

void L3CipheringModeCommand::text(ostream& os) const

{

L3RRMessage::text(os);

os << "Ciphering Settings=(" << mSetting << ")";

os << " Ciphering Response=(" << mResponse << ")";

}

a) Message types: 0 0 1 1 0 - - - Ciphering messages:

1 0 1 - CIPHERING MODE COMMAND Code Implementation in File : GSML3RRMessages.h class L3RRMessage : public L3Message { public: enum MessageType {

CipheringModeCommand=0x35, } b) Ciphering Mode Setting The purpose of the Cipher Mode Setting information element is to indicate whether stream ciphering shall be started or not and if it is to be started, which algorithm to use. The Cipher Mode Setting information element is coded as shown in figure. The Cipher Mode Setting is a type 1 information element.

Page 184: Adding Support for Authentication and Encryption to Openbts

176 Authentication and Ciphering Messages

Code Implementation in file: GSML3RRElements.h, line: 139 class L3CipheringSettings : public L3ProtocolElement {

private:

unsigned mSC;

unsigned mAlgorithmIdentifier;

public:

L3CipheringSettings():L3ProtocolElement()

{

mSC=0; // Start

Ciphering

mAlgorithmIdentifier=0; // A5/1 Algorithm

}

size_t lengthV() const { return 0; }

void writeV(L3Frame& dest, size_t &wp) const;

void parseV(const L3Frame&, size_t&) { assert(0); }

void parseV(const L3Frame&, size_t& , size_t) { assert(0);

}

void text(std::ostream&) const;

};

Code Implementation in file: GSML3RRElements.cpp, line: 102 void L3CipheringSettings::writeV(L3Frame& dest, size_t &wp)

const

{

dest.writeField(wp,mAlgorithmIdentifier,3);

dest.writeField(wp,mSC,1);

Page 185: Adding Support for Authentication and Encryption to Openbts

177 OpenBTS

}

void L3CipheringSettings::text(ostream& os) const

{

os << "AlgorithmIdentifier=" << mAlgorithmIdentifier;

os << "SC=" << mSC;

}

c) Cipher Mode Response The Cipher Response information element is used by the network to indicate to the mobile station which information the mobile station has to include in the CIPHERING MODE COMPLETE message. The Cipher Response information element is coded as shown in figure.The Cipher Response is a type 1 information element.

Code Implementation in file: GSML3RRElements.h, line: 165 class L3CipheringResponse : public L3ProtocolElement {

private:

unsigned mCR;

public:

L3CipheringResponse():L3ProtocolElement() { mCR=1; }

/* Send Cipher Mode Complete with IMEISV */

size_t lengthV() const { return 0; }

void writeV(L3Frame& dest, size_t &wp) const;

void parseV(const L3Frame&, size_t&) { assert(0); }

void parseV(const L3Frame&, size_t& , size_t) { assert(0);

}

void text(std::ostream&) const;

};

Code Implementation in File : GSML3RRElements.cpp, line: 116 void L3CipheringResponse::writeV(L3Frame& dest, size_t &wp)

const

{

Page 186: Adding Support for Authentication and Encryption to Openbts

178 Authentication and Ciphering Messages

dest.writeField(wp,0,3);

// Spare Bits 0 0 0

dest.writeField(wp,mCR,1);

}

void L3CipheringResponse::text(ostream& os) const

{

os << "CR=" << mCR;

}

Log file output: 06 35 10 06 ⇒ 0------- Direction From : originating site ⇒ -000---- TransactionID : 0 ⇒ ----0110 Protocal Discrim. : Radio Resource Management 35 ⇒ 00110101 RR Cipher Mode Command 10 ⇒ 000----- Spare : 0 ⇒ ---1---- Cipher Response : IMEISV shall be included ⇒ ----000- Cipher : A5/1 ⇒ -------0 Don't Start ciphering

5.3.5.2 Ciphering mode complete This message is sent on the main DCCH from the mobile station to the network to indicate that enciphering and deciphering has been started in the MS. Message type: CIPHERING MODE COMPLETE Significance: dual Direction: mobile station to network

According to the Standards all those Messages have to be Written

Page 187: Adding Support for Authentication and Encryption to Openbts

179 OpenBTS

For the Protocol Discriminator and the Skip indicator it is common as described above in the Common Information Elements Code Implementation in File : GSML3RRMessages.h, line: 217 class L3CipheringModeComplete : public L3RRMessage {

protected:

bool mHaveMobileID;

L3MobileIdentity mMobileID;

public:

L3CipheringModeComplete():L3RRMessage() {}

const L3MobileIdentity& mobileIdentity() const { return

mMobileID; }

int MTI() const { return CipheringModeComplete; }

size_t bodyLength() const;

void parseBody(const L3Frame& src, size_t &rp);

void text(std::ostream&) const;

};

Code Implementation in File : GSML3RRMessages.cpp, line: 284 size_t L3CipheringModeComplete::bodyLength() const

{

size_t sum = 0;

/*

if (mHaveMobileID) sum += mMobileID.lengthTLV() ;

*/

return sum;

}

void L3CipheringModeComplete::parseBody(const L3Frame& src,

size_t &rp)

{

mHaveMobileID = mMobileID.parseTLV(0x17,src,rp);

}

void L3CipheringModeComplete::text(ostream& os) const

{

L3RRMessage::text(os);

if (mHaveMobileID)

os << "mobileID=(" << mHaveMobileID << ")";

}

Page 188: Adding Support for Authentication and Encryption to Openbts

180 Authentication and Ciphering Messages

a) Message types: 0 0 1 1 0 - - - Ciphering messages:

0 1 0 - CIPHERING MODE COMPLETE Code Implementation in file: GSML3RRMessages.h class L3RRMessage : public L3Message {

public:

enum MessageType {

CipheringModeComplete=0x32,

}

b) Mobile Identity: The purpose of the Mobile Identity information element is to provide either the international mobile subscriber identity, IMSI, the temporary mobile subscriber identity, TMSI/P-TMSI, the international mobile equipment identity, IMEI or the international mobile equipment identity together with the software version number, IMEISV. The IMSI shall not exceed 15 digits, the TMSI/P-TMSI is 4 octets long, and the IMEI is composed of 15 digits, the IMEISV is 16 digits. In the identification procedure and in the GMM identification procedure the mobile station shall select the mobile identity type which was requested by the network. In the ciphering mode setting procedure and in the GMM authentication and ciphering procedure the mobile shall select the IMEISV. The Mobile Identity information element is coded as shown in figure . The Mobile Identity is a type 4 information element with a minimum length of 3 octet and 11 octets length maximal. Further restriction on the length may be applied, e.g. number plans.

Page 189: Adding Support for Authentication and Encryption to Openbts

181 OpenBTS

Log file output: 06 32 17 09 33 35 49 05 01 05 54 46 f3 06 ⇒ 0------- Direction From : originating site ⇒ -000---- TransactionID : 0 ⇒ ----0110 Protocal Discrim. : Radio Resource Management 32 ⇒ 00110010 RR Cipher Mode Complete 17 ⇒ 00010111 Imformation Element : Mobile Identity 09 ⇒ 00001001 length of Mob. ident. 33 ⇒ ----0--- No.of digits : even ⇒ -----011 Type of identity : IMEISV ⇒ 0011---- Identity Digit 1 : 3 35 ⇒ ----0101 Identity Digit 2 : 5 ⇒ 0011---- Identity Digit 3 : 3

Page 190: Adding Support for Authentication and Encryption to Openbts

182 Authentication and Ciphering Messages

49 ⇒ ----1001 Identity Digit 4 : 9 ⇒ 0100---- Identity Digit 5 : 4 05 ⇒ ----0101 Identity Digit 6 : 5 ⇒ 0000---- Identity Digit 7 : 0 01 ⇒ ----0001 Identity Digit 8 : 1 ⇒ 0000---- Identity Digit 9 : 0 05 ⇒ ----0101 Identity Digit 10 : 5 ⇒ 0000---- Identity Digit 11 : 0 54 ⇒ ----0100 Identity Digit 12 : 4 ⇒ 0101---- Identity Digit 13 : 5 46 ⇒ ----0110 Identity Digit 14 : 6 ⇒ 0100---- Identity Digit 15 : 4 f3 ⇒ ----0011 Identity Digit 16 : 3 ⇒ 1111---- Identity Digit 17 : 15

5.3.6. Places of Authentication and Cipher implementations 5.3.6.1 Location Updating: Location updating procedures:

1 Location updating request (L3MMMessages 9.2.15), uplink. this message triggers a registration attempt with Asterisk.

2 Location updating accept (L3MMMessages 9.2.13), downlink. this message is returned upon successful registration with Asterisk.

3 Location updating reject (L3MMMessages 9.2.14), downlink. this message is returned upon registration failure with Asterisk.

Page 191: Adding Support for Authentication and Encryption to Openbts

183 OpenBTS

Page 192: Adding Support for Authentication and Encryption to Openbts

184 Authentication and Ciphering Messages

5.3.6.2 Mobile originating call establishment: The example in the Figure 7.10a of GSM 04.08 shows call establishment with authentication. In the OpenBTS open source version, the authentication steps were skipped; they simply dived into responding to the CM Service Request with a CM Service Accept or Reject. – CM Service Request (L3MMMessages, 9.2.9), uplink. This message indicates to the BTS that the phone will require ISDN-style (connection-oriented) services. – CM Service Accept (L3MMMessages, 9.2.5), downlink. This message allows us to bypass authentication and proceed directly to ISDN-style/Q.931call control. – CM Service Reject (L3MMMessages, 9.2.6), downlink. This message is sent to reject service if the call setup cannot be performed for some reason, such as an lack of available traffic channels. – Setup (L3CCMessages, 9.3.23), uplink. Simply skip unsupported elements based on T and L fields when parsing. This message triggers an INVITE message to the Asterisk server that starts the hybrid Q.931/SIP call setup procedure. – Call Proceeding (L3CCMessages, 9.3.3), downlink. – Assignment Command (L3RRMessages, 9.1.2), downlink. This message moves the transaction from the SDCCH to the TCH/FACCH. – Assignment Complete (L3RRMessages, 9.1.3), uplink. This is the first message sent from the phone on the newly assigned TCH/FACCH. – Alerting (L3CCMessages 9.3.1), downlink. This message corresponds to the SIP 180 Ringing message. – Progress (L3CCMessages 9.3.17), downlink. This message is needed to keep the connection alive when Asterisk delays are large. It is similar in purpose to the SIP 100 Trying message. – Connect (L3CCMessages, 9.3.5), downlink. This message corresponds to the SIP 200 OK message. – Connect Acknowledge (L3CCMessages, 9.3.6), uplink. This message corresponds to the SIP ACK message. After implementing authentication and ciphering messages according the procedures mentioned in the standards, the CM service accept message became useless so we ended up removing it from our version of the code the code.

Page 193: Adding Support for Authentication and Encryption to Openbts

185 OpenBTS

5.3.6.3 Mobile terminating call establishment: The example in the Figure 7.11a of GSM 04.08 shows call establishment with authentication. In the open source version, the authentication steps were skipped by sending a CM Service Accept or Reject after receiving the Paging Response.

Page 194: Adding Support for Authentication and Encryption to Openbts

186 Authentication and Ciphering Messages

– Paging Request Type 1 (L3RRMessages, 9.1.22), downlink. This message is sent whenever a SIP INVITE message arrives from Asterisk. Because we are not yet supporting TMSIs, we have no use for the other Paging Request formats. – Paging Response (L3RRMessages, 9.1.25), uplink. – Setup (L3CCMessages, 9.3.23), downlink. This message carries the content of the SIP INVITE message to the phone. – Call Confirmed (L3CCMessages,, 9.3.2), uplink. – Assignment Command (L3RRMessages, 9.1.2), downlink. – Assignment Complete (L3RRMessages, 9.1.3), uplink. – Alerting (L3CCMessages, 9.3.1), uplink. – Progress (L3CCMessages, 9.3.17), downlink. – Connect (L3CCMessages 9.3.5), uplink. – Connect Acknowledge (L3CCMessages, 9.3.6), downlink.

Page 195: Adding Support for Authentication and Encryption to Openbts

187 OpenBTS

Page 196: Adding Support for Authentication and Encryption to Openbts

188 Authentication and Ciphering Messages

5.3.7 Authentication and Ciphering Procedures: 5.3.7.1 The purpose of the authentication and ciphering procedure is threefold:

1 To permit the network to check whether the identity provided by the MS is acceptable or not.

2 To let the network set the ciphering mode (ciphering/no ciphering) and algorithm. 3 The authentication and ciphering procedure can be used for either:

- Authentication only. - Setting of the ciphering mode and the ciphering algorithm only. - Authentication and the setting of the ciphering mode and the ciphering algorithm.

5.3.7.2 Important Definitions: SDCCH: Stand-alone Dedicated Control Channels which is used in the GSM system to provide a

reliable connection for signalling and Short Message Service (SMS) messages. dynamic_cast: Can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class. void operator delete[] (void* ptr) throw (): Deallocate the memory block pointed by ptr (if not-null), releasing the storage space previously allocated to it by a call to operator new[] and making that pointer location invalid. LOG: This writes to the log file and we have levels of debugging: Notice, Error, Info, Debug, Deep Debug 5.3.7.3 Reference of Functions: virtual void send(const L3Frame& frame, unsigned SAPI=0)

Send an L3Frame on downlink. This method will block until the message is transferred to the transceiver where frame refers to The L3Frame to be sent and SAPI stands for The service access point indicator. L3Message* Control::getMessage(LogicalChannel *LCH, unsigned

SAPI)

Get a message from a LogicalChannel. Close the channel with abnormal release on timeout. Caller must delete the returned pointer. Throws ChannelReadTimeout, UnexpecedPrimitive or UnsupportedMessage on timeout where LCH refers to The channel to receive on and SAPI stands for The service access point . virtual L3Frame * recv(unsigned timeout_ms = 15000, unsigned

SAPI=0)

Page 197: Adding Support for Authentication and Encryption to Openbts

189 OpenBTS

Read an L3Frame from SAP0 uplink, blocking, with timeout. The caller is responsible for deleting the returned pointer. The default 15 second timeout works for most L3 operations where timeout_msA is a read timeout in milliseconds and SAPI is The service access point indicator from which to read. L3ChannelRelease(const L3RRCause& cause = L3RRCause(0x0))

This message is sent on the main DCCH from the network to the mobile station to initiate deactivation of the dedicated channel used.The default cause is 0x0, "normal event". L3CMServiceReject(const L3RejectCause& wCause)

This message is sent by the network to the mobile station to indicate that the requested service cannot be provided. 5.3.7.4 Authentication Procedures full description with codes: 5.3.7.4.1 Authentication procedures: The authentication procedure will be used to set the ciphering key. Therefore, it is performed after the subscriber identity (TMSI/IMSI) is known by the network and before the channel is encrypted. The authentication procedure is always initiated and controlled by the network.

1) Authentication request by the network The network initiates the authentication procedure by transferring an AUTHENTICATION REQUEST message across the radio interface and starts the timer T3260. The AUTHENTICATION REQUEST message contains the parameters necessary to calculate the response parameters. It also contains the ciphering key sequence number allocated to the key which may be computed from the given parameters. Code Implementation in File : MobilityManagement.cpp, line: 229 SDCCH->send(L3AuthenticationRequest());

LOG(INFO) << "Authentication Request Sent";//Authentication

Request sent on the main SDCCH

2) Authentication response by the mobile station The mobile station shall be ready to respond upon an AUTHENTICATION REQUEST message at any time whilst a RR connection exists. It shall process the challenge information and send back

Page 198: Adding Support for Authentication and Encryption to Openbts

190 Authentication and Ciphering Messages

an AUTHENTICATION RESPONSE message to the network. The new ciphering key calculated from the challenge information shall overwrite the previous one and be stored on the SIM before the AUTHENTICATION RESPONSE message is transmitted. The ciphering key stored in the SIM shall be loaded in to the ME when any valid CIPHERING MODE COMMAND is received during an RR. The ciphering key sequence number shall be stored together with the calculated key.

Code Implementation in File : MobilityManagement.cpp, line: 233 L3Message* msg = getMessage(SDCCH);

LOG(INFO) << *msg<< "Authentication Response";

L3AuthenticationResponse *resp =

dynamic_cast<L3AuthenticationResponse*>(msg); //create a

pointer from the type L3AuthenticationResponse

if (!resp) {

if (msg) {

LOG(WARN) << "Unexpected message " << *msg;

delete msg;

}

throw UnexpectedMessage();

} //check if the message type not compatible with

protocol state. if this //happens, it will throw an error which

leads to clearing the transaction history

LOG(INFO) << *resp<< "Response Recieved";

3) Authentication processing in the network Upon receipt of the AUTHENTICATION RESPONSE message, the network stops the timer T3260 and checks the validity of the response. Authentication timer --> The authentication procedure has been started by the network. The timer T3260 is running.

Z100timer → CCITT Z.100 activity timer. All times are in milliseconds. For handling of timers, the procedures and terminology of CCITT Recommendation Z.100 will be used, i.e. set <timer name> means that:

a) If the timer is inactive, the timer becomes active, i.e. a timer value is associated with the timer and it starts running; b) If the timer is active, the timer is first reset, as in c) below and then set as in a) above;

reset <timer name> means that: c) If the timer is active, the timer becomes inactive, i.e. the association with the timer

Page 199: Adding Support for Authentication and Encryption to Openbts

191 OpenBTS

value is lost and it stops running; d) If the timer is inactive, it remains inactive.

If you add a timer to code, remember to add it to the constructor, timer Expired and reset Timers methods. In the Codes part we have skipped this information element as it is not implemented in the whole codes not the authentication and ciphering only. 4) Unsuccessful authentication If authentication fails, i.e. if the response is not valid, the network may distinguish between the two different ways of identification used by the mobile station:

- the TMSI was used. - the IMSI was used.

If the TMSI has been used, the network may decide to initiate the identification procedure. If the IMSI given by the mobile station then differs from the one the network had associated with the TMSI, the authentication should be restarted with the correct parameters. If the IMSI provided by the MS is the expected one (i.e. authentication has really failed), the network should proceed as described below. If the IMSI has been used, or the network decides not to try the identification procedure, an AUTHENTICATION REJECT message should be transferred to the mobile station. After having sent this message, all MM connections in progress (if any) are released and the network should initiate the RR connection release. Upon receipt of an AUTHENTICATION REJECT message, the mobile station shall set the update status in the SIM to U2 ROAMING NOT ALLOWED; delete from the SIM the stored TMSI, LAI and ciphering key sequence number. The SIM shall be considered as invalid until switching off or the SIM is removed. If the AUTHENTICATION REJECT message is received in any other state the mobile station shall abort any MM specific, MM connection establishment or call re- establishment procedure, stop any of the timers T3210 or T3230 (if running), release all MM connections (if any), start timer T3240 and enter the state WAIT FOR NETWORK COMMAND, expecting the release of the RR connection. If the RR connection is not released within a given time controlled by the timer T3240, the mobile station shall abort the RR connection. In both cases, either after a RR connection release triggered from the network side or after a RR connection abort requested by the MS-side, the MS enters state MM IDLE, sub-state NO IMSI.

Page 200: Adding Support for Authentication and Encryption to Openbts

192 Authentication and Ciphering Messages

RR connection release The release of the RR connection can be requested by upper layers. The purpose of this procedure is to deactivate all the dedicated channels in use. When the channels are released, the mobile station returns to the CCCH configuration idle mode. The channel release procedure can be used in a variety of cases, including TCH release after a call release, and DCCH release when a dedicated channel allocated for signaling is released. #6f : Protocol error, unspecified This cause is used to report a protocol error event only when no other cause in the protocol error class applies. MM connection release An established MM connection can be released by the local CM entity. The release of the CM connection will then be done locally in the MM sublayer, i.e. no MM message is sent over the radio interface for this purpose. If no MM connection is active, the network may start the RR connection when the CM SERVICE REJECT message is sent. If a CM SERVICE REJECT message is received by the mobile station, timer T3230 shall be stopped, the requesting CM sublayer entity informed. Then the mobile station shall proceed as follows: - If the cause value is not #4 or #6 the MM sublayer returns to the previous state (the state where the request was received). Other MM connections shall not be affected by the CM SERVICE REJECT message.

Page 201: Adding Support for Authentication and Encryption to Openbts

193 OpenBTS

- If cause value #4 is received, the mobile station aborts any MM connection, deletes any TMSI, LAI and ciphering key sequence number in the SIM, changes the update status to NOT UPDATED (and stores it in the SIM), and enters the MM sublayer state WAIT FOR NETWORK COMMAND. If subsequently the RR connection is released or aborted, this will force the mobile station to initiate a normal location updating. Whether the CM request shall be memorized during the location updating procedure, is a choice of implementation. - If cause value #6 is received, the mobile station aborts any MM connection, deletes any TMSI, LAI and ciphering key sequence number in the SIM, changes the update status to ROAMING NOT ALLOWED (and stores it in the SIM), and enters the MM sublayer state WAIT FOR NETWORK COMMAND. The mobile station shall consider the SIM as invalid until switch-off or the SIM is removed. Cause Value with Hexadecimal representation #4: IMSI unknown in VLR #6: Illegal ME #21: Requested service option not subscribed This cause is sent when the MS requests a service option for which it has no subscription. Code Implementation in File : MobilityManagement.cpp, line: 246 if(1/**resp == SRES*/) // check if the response is valid,it

will start the ciphering //procedures.if not,it will send

authentication reject and release all the channels.

{

/*Ciphering Mode Procedures*/

}

else{

// If the subscriber isn't authorized, send a CM Service Reject

with cause code, 0x41, //"requested service option not

subscribed",followed by a Channel Release with cause //code

0x6f, "unspecified".Otherwise, proceed to the next section of

code.For now, we //are assuming that the phone won't make a call

if it didn't get registered.

SDCCH->send(L3AuthenticationReject());

LOG(INFO) << "Authentication Reject";

SDCCH->send(L3CMServiceReject(0x21));

LOG(INFO) << "CM Service Reject";

SDCCH->send(L3ChannelRelease(0x6f))

LOG(INFO) << "Channel Release";

return;

}

Page 202: Adding Support for Authentication and Encryption to Openbts

194 Authentication and Ciphering Messages

Page 203: Adding Support for Authentication and Encryption to Openbts

195 OpenBTS

5.3.7.4.2 Ciphering Procedures Ciphering procedure:

1) Ciphering mode setting procedure:- In dedicated mode, the ciphering mode setting procedure is used by the network to set the ciphering mode, i.e. whether or not the transmission is ciphered, and if so which algorithm to use. The procedure shall only be used to change from "not ciphered" mode to "ciphered" mode, or vice-versa, or to pass a CIPHERING MODE COMMAND message to the mobile station while remaining in the "not ciphered" mode. The ciphering mode setting procedure is always triggered by the network and it only applies to dedicated resources. The cipher mode setting procedure shall not be applied in group transmit mode. Code Implementation in File : MobilityManagement.cpp, line: 249 SDCCH->send(L3CipheringModeCommand());

LOG(INFO) << "Ciphering Command Sent";

2) Ciphering mode complete Whenever the mobile station receives a valid CIPHERING MODE COMMAND message, it shall, if a SIM is present and considered valid by the ME and the ciphering key sequence number stored on the SIM indicates that a ciphering key is available, load the ciphering key stored on the SIM into the ME. A valid CIPHERING MODE COMMAND message is defined to be one of the following: - one that indicates "start ciphering" and is received by the mobile station in the "not ciphered" mode; - one that indicates "no ciphering" and is received by the MS in the "not ciphered" mode;

Page 204: Adding Support for Authentication and Encryption to Openbts

196 Authentication and Ciphering Messages

- one that indicates "no ciphering" and is received by the mobile station in the "ciphered" mode. Other CIPHERING MODE COMMAND messages shall be regarded as erroneous, an RR STATUS message with cause "Protocol error unspecified" shall be returned, and no further action taken. When the appropriate action on the CIPHERING MODE COMMAND has been taken, the mobile station sends back a CIPHERING MODE COMPLETE message. If the "cipher response" field of the cipher response information element in the CIPHERING MODE COMMAND message specified "IMEI must be included" the mobile station shall include its IMEISV in the CIPHERING MODE COMPLETE message. Upon receipt of the CIPHERING MODE COMPLETE message or any other correct layer 2 frame which was sent in the new mode, the network starts transmission in the new mode. Code Implementation in File : MobilityManagement.cpp, line: 249 L3Frame* resp = SDCCH->recv();

LOG(INFO) << "Received";

if (!resp) {

LOG(NOTICE) << "Ciphering Error";

} else {

LOG(INFO) << *resp ;

}

delete resp;

LOG(INFO) << "Ciphering Completed";

Page 205: Adding Support for Authentication and Encryption to Openbts

197 OpenBTS

References: L3 Messages:

Format of standard information elements...........................GSM 04.07 Sec. 11.2.1.1

Protocol discriminator.........................................................GSM 04.07 Sec. 11.2.3.1.1

Skip indicator......................................................................GSM 04.07 Sec. 11.2.3.1.2

Transaction identifier..........................................................GSM 04.07 Sec. 11.2.3.1.3

Message Type....................................................................GSM 04.08 Sec. 10.4

Presence requirements of information elements................GSM 04.07 Sec. 11.2.5

Description of standard L3 messages................................GSM 04.07 Sec. 11.2.6

Authentication:

Authentication Request …..................................................GSM 04.08 Sec. 9.2.2

Authentication Response....................................................GSM 04.08 Sec. 9.2.3

Authentication Reject..........................................................GSM 04.08 Sec. 9.2.1

Authentication Parameter RAND........................................GSM 04.08 Sec. 10.5.3.1

Authentication Parameter SRES........................................GSM 04.08 Sec. 10.5.3.2

Channel release.................................................................GSM 04.08 Sec. 9.1.7

RR Cause..........................................................................GSM 04.08 Sec. 10.5.2.31

CM service reject................................................................GSM 04.08 Sec. 9.2.6

Reject cause.......................................................................GSM 04.08 Sec. 10.5.3.6

Authentication procedure....................................................GSM 04.08 Sec. 4.3.2

Subscriber identity authentication.......................................GSM 03.20 Sec. 3

Ciphering:

Ciphering Command...........................................................GSM 04.08 Sec. 9.1.9

Ciphering Mode Complete...................................................GSM 04.08 Sec. 9.1.10

Cipher Mode Settings.........................................................GSM 04.08 Sec. 10.5.2.9

Cipher Mode Response......................................................GSM 04.08 Sec. 10.5.2.10

Ciphering procedure...........................................................GSM 04.08 Sec. 3.4.7

Starting of the ciphering and deciphering processes.........GSM 03.20 Sec. 4.5

Page 206: Adding Support for Authentication and Encryption to Openbts

198 Challenges

Chapter 6: Challenges 6.1 Attacking A5/1 The A5/1 cipher used in GSM has been under attack, analysis and critique for a long time because of deficiencies, well documented in many papers. However, few findings have evolved into practical attacks. People declaring A5/1 as broken have never released the tools necessary to perform decryption of GSM traffic, nor have they published proof that confirms their claims. The media in particular should also take some part of the blame, as they do not always get the facts right and create inaccurate or misleading impressions as to whether A5/1 is cracked or not.

In August 2009, Nohl and Krissler announced the A5/1 Security Project. Their aim is to generate rainbow tables as a pre-computation stage to enable a ciphertext-only attack against the A5/1 encryption algorithm. Using the A5/1 Security Project as a basis, this chapter will attempt to create a set of rainbow tables and investigate the feasibility of capturing GSM traffic. The latter will utilize interception software provided by the Air Probe project.

In addition, this chapter will try to perform an active attack where a GSM network is created. For instance, a USRP together with Open BTS and Asterisk can provide a generic GSM infrastructure, from the Base Transceiver Station and upwards.

6.1.1 History A practical attack did not arise until 2003, when Barkan et al. published their findings. They used a passive ciphertext, only time-memory trade-off attack requiring a large amount of pre-computed tables. This was the first real attack not requiring large amounts of known plaintext. It is uncertain whether tables were generated. Regardless, tables were never publicly released. In 2007, two groups headed by Prof. C. Paar (Ruhr University of Bochum) and Prof. M. Schimmler (Christian-Albrechts University Kiel) created a Cost-Optimized Parallel Code Breaker (COPACOBANA), an FPGA-based machine that could be used to create tables employing the same principles as described in Barkan et al. The FPGA solution was made commercially available, but no tables were released. In 2008, the The Hackers Choice (THC), represented by David Hulton and Steve Muller, reiterated the 2003 attack with 68 FPGA boards. This group also had a sister project named Air Probe that developed software to capture and decode GSM signaling traffic. Rainbow tables were claimed to have been computed, but were never released. They made the assumption that the key size used in GSM is only 54 bits. Although this was the case in several countries some years ago, it is not the case as of per today. This means that even if these tables were to exist, they would not be useful in the process of attacking A5/1.

Page 207: Adding Support for Authentication and Encryption to Openbts

199 Secure OpenBTS

6.1.2 Hellman’s Time-Memory Trade-Off There are two naive approaches on how to break a block cipher; exhaustive search and table look-up. The exhaustive search technique is a known-plaintext attack, where the ciphertext gets deciphered with each possible key and then compared with the known plaintext. This gives a time complexity of T = O(N) and a memory requirement of M = 1. The approach taken in a table lookup attack is to encrypt some fixed plaintext with each of the N possible keys in order to produce N distinct ciphertexts. These ciphertexts are then sorted and stored together with their keys in a table of size M = N. The pre-computation cost of such an attack is N operations and the time complexity for doing lookup is T = O(1). The problem with these two methods is that the attack time is either to long, i.e T = O(N) in the case of exhaustive search, or that they require a large amount of memory, i.e M = N in the case of table lookup. As an example, consider the amount of memory needed in order to create a lookup table for a 64-bit key:

A number that leaves such an attack impossible in practice. It is easy to do a comparison with Hellman’s time-memory trade-off, which only needs N^2/3 words of memory. In the same case of a 64-bit key, the memory requirement would be:

Although still a large memory requirement, it is well within the limits of what is practically feasible. Hellman introduced his time-memory trade-off for block ciphers in 1980. Given a fixed plaintext block P0, this can be encrypted with the cipher S. The ciphertext C is thus given by:

C = Sk(P0)

The attack works by creating chains consisting of key-ciphertext pairs. The chain starts with a key value ki. This key is used to encipher P0 in order to get Ci = Ski (P0). The ciphertext Ci can then be converted into a key ki+1 by applying a reduction function4 R on Ci. Chains of alternating keys and ciphertexts can thus be created by successively applying the cipher S and the reduction function R:

Page 208: Adding Support for Authentication and Encryption to Openbts

200 Challenges

R(Sk(P0)) is the sequence of operations that generates a key from a key. It is called f(k) = R(Sk(P0)) and leads to a chain of keys:

As can be seen in the following figure, a table consists of m chains of length t. However, only the first and last element in each chain is stored in order to reduce the memory requirements. Given a ciphertext C, the aim is to find out whether the key used to generate C is in the table. The first step is to apply R to C in order to obtain a key Y1.

This key is compared to the endpoints of the table, and if a match is found it means that the key used to encipher C might be found in the next to last column of the corresponding chain. The chain can then be reconstructed from the start point in order to possibly find this key. If there is no matching endpoint, the function f is applied until a matching endpoint is found, or until it has been applied a maximum of t - 1 times. A match with one of the endpoints in the table does not necessarily mean that the key can be found in that chain. This is due to so-called false alarms.

False alarms are undesirable, since there needs to be computing time spent in searching through a chain looking for a key, only not to find it. Let s be the length of the generated chain at the time when a matching endpoint is found, and let this generated chain be denoted by z:

Figure 6.1

Page 209: Adding Support for Authentication and Encryption to Openbts

201 Secure OpenBTS

Given an endpoint Ej that matches Ys, this chain is then calculated from the startpoint Sj . If Y1 is not found in this chain it was only a false alarm. This is the result of chain z merging with the chain where we found a false alarm, somewhere later than the column where Y1 is.

a false alarm in the case of a Hellman table for hash values. In this example h1 is the given hash value that we’re looking for the corresponding password to, in this case 1. If the reduction function R and the hash function H is applied successively on h1, then the result after a couple of alternations will be the value 9. Since this is also an endpoint in the table, a false alarm will now occur. Note that even if the second row had not been a chain in the table, we would still get a false alarm. In other words, false alarms exist as a result of merges with chains both inside and outside the table.

One of the drawbacks of Hellman’s time-memory trade off is that chains starting at different keys may collide and merge. This is a consequence of the fact that R only provides an arbitrary reduction from the space of ciphertexts into the space of keys. Merges lead to less efficient tables, since there will be keys that are covered by more than one chain. The chance of finding a key by using a table of m rows of t keys is given by

As can be seen, the efficiency of a single table decreases rapidly with its size. In order to obtain a high probability of success it is therefore better to generate multiple tables, where a different reduction function is used for each table. There can be collisions between chains of different tables when using more than one table, but they will not merge since different reduction functions are used in different tables. Using l tables, the probability of success is given by

Figure 6.2

Page 210: Adding Support for Authentication and Encryption to Openbts

202 Challenges

6.1.3 A Cryptanalytic Time/Memory/Data Trade-off for Stream Ciphers There are two major types of symmetric-key cryptosystems; block ciphers and stream ciphers. Block ciphers take a number of bytes and encrypt them as a single unit, whereas stream ciphers encrypts one bit at a time. Furthermore, encryption in block ciphers is carried out by mixing plaintext with the key in an invertible way, whereas stream ciphers use the key to produce a keystream that is XORed with the plaintext.

Hellman and Oechslin’s trade-off’s were both directed towards block ciphers. Since a block cipher takes the plaintext and key as input and produce ciphertext as output, each ciphertext corresponds to a particular plaintext for block ciphers. A pre-computed table for a block cipher can thus only be used for one particular known plaintext. Stream ciphers on the other hand have a very different behavior when it comes to time-memory trade-off attacks. It uses its internal state as input and produces a keystream as output. This means that we have state-keystream pairs that are independent from any particular plaintext, and it is thus possible to create pre-computed tables that can be used independently of the plaintext. The first time-memory trade-off for stream ciphers works as follows They connect each of the N possible states of the generator with the first log2(N) keystream bits produced by the stream cipher from those states. This mapping can be described as:

Where x is the internal states of the stream cipher and y the keystream generated from x. The attack works by picking M random xi states, computing their corresponding keystream, yi, and then store all of the (xi, yi) pairs on a disk sorted on increasing order of yi. OnlyMout of N states are covered, but coverage can be improved by having more known data points D. Since lookup is done on log2(N) bits of keystream, D data points give us a total of D - log2(N) + 1 samples of keystream. Thus, lookup can be done on all D-log2(N)+1 keystream samples in the table. This increases the probability of a hit by 1D-log2(N)+1 . If a match is found, the rest of the plaintext can be derived by running the keystream generator from that point on. A general attack that combines the work of both Hellman, Babbage and Golic was proposed by Biryukov et Al. in the article Cryptanalytic Time/Memory/ Data Tradeoffs for Stream Ciphers. Their idea is to successively apply f(x) = y from 3.4 and a function that maps the keystream into the state space again. This forms the basis for the attack used in the A5/1 Security Project. It is interesting to note that distinguished points fits especially well together with time-memory trade-offs that have more than one data point. This has to do with the fact that a disk access is an extremely expensive operation, and should be avoided if possible. Thus, when looking up more than one keystream sample the profit becomes even more apparent.

Page 211: Adding Support for Authentication and Encryption to Openbts

203 Secure OpenBTS

6.1.4 Clocking back A5/1

In order to decrypt an entire conversation it is important to know either the key or the state of A5/1 just after the key has been mixed in. Both of these are of equal value, since the keystream for every frame in a conversation can be determined directly from both. In the process of obtaining this state, some back-clocking is needed

Clocking back one single register is a trivial task. When clocked forward, all the tapped bits are XORed together and the result used as input to the rightmost bit (lsb). Backward clocking on the other hand, is performed by taking all the tapped bits except the leftmost (msb), and then XORing these together with the rightmost bit. After this, all registers are shifted one step to the right, and the result from the XOR operation is stored in the leftmost bit position. It is when clocking back the entire A5/1 machine that things get more complicated, since majority clocking needs to be taken into account. However, it is also when looking closer at this process that the reason why the A5/1 algorithm only utilizes 16% of the key space gets revealed. By looking at the clockbits of each LFSR, and the bit to the left of it, it becomes apparent that there are in total 2^6 = 64 combinations of the values that these bits can have.

Let S(t) = (S1(t), S2(t), S3(t)) denote the whole internal state of A5/1 at time t 0, where S(0) is the internal state of A5/1 just after the frame number has been mixed in. At the same time, let C(t) denote the clock-control sequence at time t 0, such that if C(t) = {1, 2}, then registers 1 and 2 are to be clocked, if C(t) = {1, 2, 3}, then registers 1,2 and 3 is clocked, and so on. Let (i,j,k) denote a permutation of (1,2,3). Then the following six events can occur

Page 212: Adding Support for Authentication and Encryption to Openbts

204 Challenges

Further on, if an internal state S(t) is randomly chosen according to uniform distribution, then the number of solutions for S(t - 1) is a nonnegative integer random variable Z with the probability distribution :

As can be seen, 24 of 64 states cannot be clocked 1 step back. This means that there is no way that such a state can exist, and it is therefore called an illegal state. A conclusion that follows immediately from this is that the keystream space is reduced to:

1 -

= 0.625 = 62.5%

62.5% of the original key space, an example of such a state can be seen in following figure:

When looking at the bits to the left of the clocking bits, it becomes apparent that the registers clocked in the previous round were registers R1 and R3, since they make up the majority function. By clocking R1 and R3 one step back the result is the state seen in the following figure:

Figure 6.3

Page 213: Adding Support for Authentication and Encryption to Openbts

205 Secure OpenBTS

It is easy to see that this state is not a valid one, since R2 now suddenly is a part of the majority clocking function, a contradiction to the back-clocking step that was just performed. One would therefore end up with a different state if an attempt to clock it forward from S(t - 1) to S(t) was made. The fact that 24 of 64 states cannot be clocked back 1 step was pointed out by Golic in the paper Cryptanalysis of Alleged A5 Stream Cipher, but strangely enough Golic fails to see the correlation between this and the reduction in keystream space that follows from this.

6.1.5 Our Contribution

COMP128 is used for both the A3 and A8 algorithms in most GSM networks. It takes a 16 byte (128bits) key (Ki), and 16 byte (128 bits) of data (Rand), to output a 12 byte (96 bits) hash. The key (Ki), is unique to each subscriber and is stored in the SIM card. The Ki is the individual subscriber authentication key. It is a 128-bit number that is paired with an IMSI when the SIM card is created. The Ki is only stored on the SIM card and at the Authentication Center (AuC). The Ki should never be transmitted across the network. However, we need the Ki at the network side. How will OpenBTS get hold of the Ki.. … Reverse engineering COMP128 algorithm seemed like a good solution According to algorithm of COMP128 we make butterfly 8 times and permutation 7 times. The Output for butterfly every time is input for permutation and output for permutation for every time is input for butterfly. In the Last time for the butterfly output we will select some bits from it to get output of COMP128.

Figure 6.4

Page 214: Adding Support for Authentication and Encryption to Openbts

206 Challenges

For example: if we input to algorithm Ki=11d1c55568e899603b9af1449deefd90 and Rand= 23553cbe9637a89d218ae64dae47bf35 then the output of the algorithm is 84CFE9274049A23BD44EE000 and the output of the last time for butterfly is 08040C0F0E0902070A0F0303080607040F0C010001020608080E0F0501030B08

● We will select the first 8 bytes “08040C0F0E090207” ⇒ select LSB of every byte will give 32 bits that is “SRES = 84CFE927”

● We will select last 13 byte “010001020608080E0F0501030B08” ⇒ select LSB of every byte and delete first 2 bits and add ten bits zeros that is “Kc = 4049A23BD44EE000”

So the main problem is that we have lost bits “0A0F0303080607040F0C” so reversing the algorithm will be somehow impossible if we walked in the direct way which is going back with the Butterfly algorithm in order to obtain the Ki and Rand from the knowledge of the Kc and the Sres.

6.2 Lack of information Security is an important issue, especially in today’s technologically advanced society. GSM is a world-wide standard for digital wireless mobile telephones, currently used by 4.4 billion people. People all over the world use their phones to store, transmit and receive voice and data communications. Unlike a fixed telephone, which offers some level of physical security, a wireless link enables anyone with a receiver to passively intercept the traffic. Because of this, it is highly important that security measures are taken to ensure the confidentiality of users’ phone calls and SMS messages. OpenBTS is considered a new project that still open for development. GSM uses a very complex signaling mechanism in order to increase the security; however this also made our job harder. We were working on the implementation of authentication and ciphering, as this is a security related issue and is a very critical matter, not a lot of information was found. Of course information on security related issue should be minimal in order to prevent misuse of the information by hackers or unwanted people.

6.2.1 Extracting KI from the SIM: We had to add the secret keys of the users to the table which includes their IMSIs and TMSIs. However we couldn’t find any useful information about how to extract the KI from the SIM, all we found were some forums that all appeared to conflict with each other. After trying various types of SIM readers we came to discover that our SIM cards use comp128-v2, meaning that we wouldn’t be able to extract the Ki at all. That was when we decided to move to plan B, which was buying Programmable SIMs.

6.2.2 Encrypted Frame

Page 215: Adding Support for Authentication and Encryption to Openbts

207 Secure OpenBTS

For each normal-burst timeslot in the TDMA frame, you need to add (xor) the keystream to the 114bit long block .GSM standard 05.03 indicates only the data blocks given to the encryption unit which includes the specification of encoding, reordering, interleaving and the stealing flag within the digital cellular telecommunications system. All that we know is that the useful information bits into the block are numbered (according to GSM 05.03) from e0 to e56 and from e59 to e115, where flag bits are skipped over (namely e57 and e58). And that A5 is implemented for the physical channels, TCH or DCCH and that ciphering takes place (see GSM 05.01) right before the modulation and after the interleaving (symmetrically for deciphering, after the demodulation and before de-interleaving). However there was no clear information regarding the difference between ciphering process in TCH and DCCH.

6.2.3 Comp128 and A5/1 Algorithms Our codes deal with the secret algorithms COMP128 and A5/1 which are both used in GSM Networks for authentication purposes. We got hold of these algorithms from some websites where people had secretly reverse engineered the outputs with the aid of some secret standards. The COMP128 algorithm is still not available to the public but it has been reverse engineered by Marc Briceno, Ian Goldberg, and David Wagner in 1998. COMP128 uses five secret tables (substitution table) T0[0..511], T1[0..255], T2[0..127], T3[0..63] and T4[0..31]. We were supposed to guess the content of secret key and substitution table; however we used the secret tables that are available on the Internet.

6.3 Error in the GSM Standards In the codes B = ( k + blockOffset ) % 8; [ GSML1FEC.cpp. line: 1136 in the original code However what the standard said was different: B = B0 + 4n + (k mod 8) - 4 [GSM 05.03 version8.5.1, (3.9.3.2)] The block-offset was inside the brackets not outside it, however after trial and error we came to realize that the OpenBTS codes were right and that the standards were incorrect.

Page 216: Adding Support for Authentication and Encryption to Openbts

208 Challenges

Page 217: Adding Support for Authentication and Encryption to Openbts

209 Secure OpenBTS

References:- [1] Decoding GSM by: Magnus Glendrange - Kristian Hove - Espen Hvideberg

Page 218: Adding Support for Authentication and Encryption to Openbts

210 Future Work

Chapter 7: Future Work After our implementation of encryption and authentication, OpenBTS provides some security features to ensure protection for both the operator and the customers. However, over the lifetime of a system threat and technology change, this means that the security must be reconsidered and changed every now and then. We also implemented the A3/A8 authentication and A5/1 Encryption which form a security system that has many security flaws. We will discuss some of these flaws and the proposed enhancements to address these security flaws.

7.1 Flaws of the A3/A8 and A5/1 Security System in OpenBTS:

7.1.1 Flaws in A5/1: The A5/1 output is based on the modulo-2 summed output of 3 LFSRs whose clock inputs are controlled by a majority function of certain bits in each LFSR. However, Alex Biryukov, Adi Shamir and David Wagner demonstrated in a paper that A5/1 could be cracked in under 1 second on a typical PC.

Proposed Solutions: A5/3 Ciphering We implemented A5/1 ciphering; in the next couple of pages we will discuss the A5/2 algorithm and the A5/3 algorithm.

7.1.2 A5/2: This algorithm is simpler than A5/1 and was developed by ETSI (European Telecommunications Standards Institute) for use in Eastern European states that had restrictions to certain Western technologies. Description: A5/2 is built from four LFSRs of lengths 19, 22, 23, 17 bits denoted by R1, R2, R3 and R4 respectively, each register is updated by its own primitive feedback polynomial. The feedback functions, The A5/1 Stream Cipher R1, R2 and R3 of A5/2 are the same as those of R1, R2 and R3 of A5/1. Clocking of R1, R2 and R3 is controlled by R4 and R4 is regularly clocked in each clock cycle. Majority of the bits, R4(3), R4(7) and R4(10), is calculated and a binary result according to majority rule is obtained. If the result is the same as R4(3), then R2 is clocked, if the result is the same as R4(7), then R3 is clocked and if the result is the same as R4(10) then R1 is clocked. After the clocking of R1, R2 and R3, R4 are clocked. It is obvious that, the clock control mechanism of both A5/1 and A5/2 depends on majority rule. However inputs to clocking control mechanism are given from R4 in case of A5/2, while in A5/1 inputs are from R1, R2 and R3. The output bit is generated as follows: in each register majority of two bits and complementary of a third bit is calculated; the results of all the majorities and the right most bit from each register are XOR‘d to form the output bit.

Page 219: Adding Support for Authentication and Encryption to Openbts

211 OpenBTS

A5/2 is built from four short linear feedback shift registers (LFSR):-

R1 of length from 0-19 bits & it‘s taps 13,16,17,18.

R2 of length from 0-22 bits & it‘s taps 20,21.

R3 of length from 0-22 bits & it‘s taps 7,20,21,22.

R4 of length from 0-16 bits & it‘s taps 11,16.

How are the four registers clocked?

R4 controls the clocking of R1, R2 and R3.

When clocking of R1, R2, and R3 is to be performed, bits R4[3], R4[7], and R4[10] are the input of the clocking unit.

The clocking unit performs a majority function on the bits.

R1 is clocked if and only if R4[10] agrees with the majority.

R2 is clocked if and only if R4[3] agrees with the majority.

R3 is clocked if and only if R4[7] agrees with the majority.

After these clocking, R4 is clocked.

Page 220: Adding Support for Authentication and Encryption to Openbts

212 Future Work

How does A5/2 work?

Initialize the internal state with Kc and frame number.

Force the bits R1[15], R2[16], R3[18], R4[10] to be 1.

Run A5/2 for 99 clocks and ignore the output.

Run A5/2 for 228 clocks and use the output as keystream.

How to initialize the internal state with Kc and frame number??

- Set all LFSRs to 0 (R1 = R2 = R3 = R4 = 0) - For i =0 to 63 do 1- Clock all 4 LFSRs 2- R1[0] R1[0] Kc[i] 3- R2[0] R2[0] Kc[i] 4- R3[0] R3[0] Kc[i] 5- R4[0] R4[0] Kc[i] - For i =0 to 21 do 1- Clock all 4 LFSRs 2- R1[0] R1[0] f[i] 3- R2[0] R2[0] f[i] 4- R3[0] R3[0] f[i] 5- R4[0] R4[0] f[i]

Page 221: Adding Support for Authentication and Encryption to Openbts

213 OpenBTS

7.1.3 A5/3

KASUMI, also termed A5/3, is a block cipher used in the confidentiality(f8)

and integrity algorithms (f9) for 3GPP mobile communications. KASUMI was designed

by the Security Algorithms Group of Experts (SAGE), part of the European standards

body ETSI. Rather than invent a cipher from scratch, an existing algorithm, MISTY1,

was selected by SAGE and slightly optimized for implementation in hardware. Hence,

both MISTY1 and KASUMI are very similar — KASUMI (霞) is the Japanese word

for "misty" — and the cryptanalysis of one is likely to be readily adaptable to the other.

KASUMI has a block size of 64 bits and a key size of 128 bits. It is a Feistel cipher with

eight rounds, and it has a recursive structure, with subcomponents also having a

Feistel-like form.

Use of the algorithm:

The algorithm is used to encrypt user and signaling data over the air interface.

The algorithm will be used for EDGE, enhanced data in GSM.

The algorithm will be used for GPRS packet radio service in GSM. Type and parameters of algorithm:

The algorithm is a binary key stream generator.

The inputs are the Key Kc and a time variant parameter COUNT.

The outputs of the ciphering algorithm are two binary blocks BLOCK1 and BLOCK2.

Relation of the input and output parameters is illustrated in figure below:

Page 222: Adding Support for Authentication and Encryption to Openbts

214 Future Work

The parameters of the algorithms are to be as follows:

Kc 64-128 bits

COUNT 22 bits or 32 bits for GPRS

BLOCK1 64 bits for GPRS, 114 bits for GSM or 348 bits for EDGE

BLOCK2 64 bits for GPRS, 114 bits for GSM or 348 bits for EDGE

7.1.4 Conclusion The encryption algorithms that are implemented in GSM are members of a family of algorithms called A5.

A5/0 is no encryption A5/1 is the "standard" encryption algorithm A5/2 is the "export" (weakened) algorithm A5/3 is a new algorithm based on the Kasumi Core. Phones that are compatible with A5/2 are especially vulnerable, as A5/2 can easily be decrypted in as little as 6 seconds, and a compatible phone can be tricked into using A5/2 by a fake base station even if the network is using A5/1 or A5/3. While one of the attacks manages to "walk around" A5/3, there is no attack against it directly. However, with the release of the A5/1 cipher tables, and the relationship between A5/1 and A5/3, it is only a matter of time before hackers are intercepting GSM calls using A5/3 encryption, because 5/1 is already attacked. The GSM will need a new encryption standard by the end of it all, as A5/3 will be the next target in line.

7.2 Flaws due to errors in the OpenBTS codes (fix me‟s):

7.2.1- Ciphering key sequence number (CKSN): The security parameters for authentication and ciphering are tied together in sets, i.e. from a challenge parameter RAND both the authentication response SRES and the ciphering key can be computed, given the secret key associated to the IMSI. In order to allow start of ciphering on an RR connection without authentication, the ciphering key sequence numbers are introduced. The sequence number is managed by the network in the way that the AUTHENTICATION REQUEST message contains the sequence number allocated to the key which may be computed from the RAND parameter carried in that message. The mobile station stores this number with the key, and indicates to the network in the first message (LOCATION UPDATING REQUEST, CM SERVICE REQUEST, PAGING RESPONSE, CM RE-ESTABLISHMENT REQUEST) which sequence number the stored key has. When the deletion of the sequence number is described this also means that the associated key shall be considered as invalid.

Page 223: Adding Support for Authentication and Encryption to Openbts

215 OpenBTS

The network may choose to start ciphering with the stored key if, the stored sequence number and the one given from the mobile station are equal. This is done in order to reduce the overhead of authentication and key generation process, GSM takes a middle road. This process is required only once per MS attachment; when the MSC sends the RAND value to the MS for authentication, the MSC also passes ciphering key sequence number (CKSN). This is a serial number given to the ‗triple‘ by the MSC and stored in VLR along with the MS‘s data. Some uplink messages such as: LOCATION UPDATING REQUEST, CM SERVICE REQUEST, PAGING RESPONSE and CM RE-ESTABLISHMENT REQUEST need the ciphering key sequence number in their information elements according to the GSM standards. However, the CKSN is skipped in the entire OpenBTS code. In the original OpenBTS codes: GSML3MMMessages.cpp, line: 128 void L3LocationUpdatingRequest::parseBody( const L3Frame &src, size_t &rp ) { // skip ciphering key sequence number rp += 4; //moving the read pointer four bits to avoid parsing ciphering key sequence number } In the modified OpenBTS code (including Encryption and Authentication): The authentication request is sent on a downlink channel, this means that network should send the ciphering key sequence number to the mobile station. As the CKSN was skipped in the original code, we also skipped it in the Authentication request message that we generated. GSML3MMMessages.h, line: 204 class L3AuthenticationRequest : public L3MMMessage { L3AuthenticationParameterRAND mRAND;//contains only the authentication parameter RAND information element } 7.2.2 RAND: The RAND is a 128-bit number that is generated by the AUC when the network requests to authenticate the subscriber. The RAND is used to generate the signed response (SRES) and Kc crypto-variables. RAND must take a "random" value, in a given range, or more generally with a specific statistical distribution. Such cases interest only the Mobile Station. the probability that a new value of RAND is the same as any one particular previously generated value of RAND should not be significantly greater than 2^(-128) in order to avoid repetition of the

Page 224: Adding Support for Authentication and Encryption to Openbts

216 Future Work

generated RAND. In the original codes: The function used to fill in (write) the information element in the frame, has a maximum of 64-bit variables Bitvector.cpp, line: 142 void BitVector::writeField(size_t& writeIndex, uint64_t value, unsigned length) In the modified OpenBTS code (including Encryption and Authentication) : In our case, we need to generate a 128-bit variable (RAND). So, we divided the RAND into RANDlow and RANDhigh; where each one is a 64-bit variable. This caused the probability of repetition to become 2^(-64), leading to decreased security. GSML3MMElements.cpp, line: 217 void L3AuthenticationParameterRAND::writeV( L3Frame& dest, size_t &wp ) const { dest.writeField(wp, mRANDHigh, 64); dest.writeField(wp, mRANDLow, 64); }

Page 225: Adding Support for Authentication and Encryption to Openbts

217 OpenBTS

7.2.3 Timers: Timers are considered as one of the most important system parameters. GSM uses timers to indicate the elapsed time for each operation. The network and the mobile station start specific timers at the beginning of each operation. If the timer expires and no response is received, all of the MM and RR connections are released and this channel release may be done optionally. Timers can be classified to: 1-Timers and counters for radio resource management, 2-Timers of mobility management. 3-Timers of circuit-switched call control. T3260 Authentication response timer: It represents the time duration between the network sending the AUTHENTICATION REQUEST and receiving the AUTHENTICATION RESPONSE. This occurs before aborting the procedure and releasing the Radio Resource connection. For example:

Page 226: Adding Support for Authentication and Encryption to Openbts

218 Future Work

In the original codes: Most of the radio resource timers are already implemented and used, while mobility management timers were not implemented. const unsigned T3101ms = 4000; //This timer is started when a channel is allocated with an IMMEDIATE ASSIGNMENT message. const unsigned T3107ms = 3000; //This timer is started when a channel is allocated with an IMMEDIATE ASSIGNMENT message. const unsigned T3109ms = 30000; //This timer is started when a channel is allocated with an IMMEDIATE ASSIGNMENT message. const unsigned T3111ms = 2*T200ms; // This timer is used to delay the channel deactivation after disconnection of the main signaling link. const unsigned T3260ms = 12000; //authentication timer implemented but not used

In the modified OpenBTS code (including Encryption and Authentication) : We used the function recv which has a default timeout, to decrease the chances of any errors. GSMLogicalChannel.h line: 129 virtual L3Frame * recv(unsigned timeout_ms = 15000, unsigned SAPI=0) This function reads an L3Frame from SAP0 uplink, blocking, with timeout. The caller is responsible for deleting the returned pointer. The default 15 second timeout works for most L3 operations. Parameters:

timeout_ms A read timeout in milliseconds.

SAPI The service access point indicator from which to read.

Page 227: Adding Support for Authentication and Encryption to Openbts

219 OpenBTS

References:

http://cryptodox.com/A5/2

http://eprint.iacr.org/2000/052.pdf

http://cryptome.org/gsm-crack-bbk.pdf

http://www.3gpp.org/ftp/tsg_sa/wg3_security/TSGS3_13_Yokohama/Docs/PDF/S3-000362.pdf