<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by IOTEROP on Medium]]></title>
        <description><![CDATA[Stories by IOTEROP on Medium]]></description>
        <link>https://medium.com/@IoTerop?source=rss-c76b7550a85a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PSAbwhUEv79DqFpV8fQkTw.png</url>
            <title>Stories by IOTEROP on Medium</title>
            <link>https://medium.com/@IoTerop?source=rss-c76b7550a85a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:33:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@IoTerop/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The LwM2M Gateway: Making All Devices LwM2M Compatible]]></title>
            <link>https://medium.com/@IoTerop/the-lwm2m-gateway-making-all-devices-lwm2m-compatible-01cafe0c45e0?source=rss-c76b7550a85a------2</link>
            <guid isPermaLink="false">https://medium.com/p/01cafe0c45e0</guid>
            <category><![CDATA[gateway]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[device-management]]></category>
            <category><![CDATA[interoperability]]></category>
            <dc:creator><![CDATA[IOTEROP]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 07:01:43 GMT</pubDate>
            <atom:updated>2024-09-10T07:01:43.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gjLI_rRJYIYmXtaUMgs7YQ.png" /></figure><p><em>By David Navarro, IoTerop co-founder and OMA SpecWorks Board Member</em></p><h3>Introduction</h3><p>The Lightweight Machine-to-Machine protocol (LwM2M) from OMA SpecWorks is now the prominent standard in the Internet of Things (IoT) landscape for data reporting, monitoring, and control of devices.</p><p>Several factors explain this. But the main one is that LwM2M effectively addresses the needs of an IoT system during the whole lifecycle of a device, from the factory provisioning to the final decommissioning, with security key management, firmware updates, device handovers, connectivity management, data reporting, remote configuration, actualization, and much more.</p><p>Due to its versatility and adaptability, LwM2M is present in a wide range of IoT devices, from industrial equipment that is always connected and always powered on to embedded mobile sensors on high latency, low bandwidth networks with long standby periods.</p><p>However, there are cases where LwM2M cannot be implemented. Some systems may rely on legacy devices whose firmware cannot be updated. Or the infrastructure may require protocols like BACnet, DLMS, Zigbee, or Bluetooth.</p><p>For such cases, OMA SpecWorks designed a new extension to the protocol: the LwM2M Gateway.</p><h3>The LwM2M Protocol</h3><p>Without going into too many details, LwM2M follows the REST design principles. LwM2M devices expose a set of resources with well-known URIs. Through a LwM2M Server, the manager of the devices performs simple operations on these resources: Read, Write, Execute, Create, Delete, and Observe.</p><p>In the LwM2M data model, the resources are grouped in LwM2M Objects. A LwM2M Object is defined by its list of resources, their semantic, their data type, and their list of allowed operations. Each LwM2M Object possesses a unique numerical identifier, which is the same for all LwM2M devices.</p><p>For instance, the LwM2M Object 3311 is the Light Control Object. When a device presents this Object, the manager knows that the device can control a light. The Light Control Object is composed of several resources, among which:</p><ul><li>A boolean resource with ID 5850 indicating the status of the light. The manager can also write this resource to switch the light on or off.</li><li>An integer resource with ID 5851 to monitor and control the dimming of the light.</li><li>A resource with ID 5852 indicating the time the light has been on.</li></ul><p>So for any LwM2M device featuring a light, the LwM2M Server can get the status of the light by performing a Read operation on the URI /3311/0/5850. The second identifier in this URI matches the Object Instance as a device may feature several lights.</p><h3>The LwM2M Gateway</h3><p>In a nutshell, a LwM2M Gateway is a device presenting LwM2M Objects on the behalf of other IoT devices.</p><p>The LwM2M gateway device is typically deployed on the same local network as the IoT devices. And the LwM2M Gateway device is usually the only device capable of connecting to the LwM2M Server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aPF4KBKrEWaAv3N4cB_u1w.png" /></figure><p>On the local network, the LwM2M Gateway device communicates with the IoT devices to retrieve their measurements and interact with them. Depending on each IoT device’s capabilities, the LwM2M Gateway device instantiates the matching LwM2M Objects. The LwM2M Server can then interact with these IoT devices as if they were LwM2M devices.</p><p>Note that it is important for the LwM2M Server to be aware of the IoT devices and their respective capabilities. It is not enough for the LwM2M Gateway device to list only instances of LwM2M Objects without context. The answer to this need is in two parts:</p><p>First, the URI of the LwM2M Objects for each IoT device is prepended with a dedicated prefix. For instance, if there are three smart light bulbs on the local network, instead of presenting three instances of the LwM2M Light Control Object under the URIs /3311/0, /3311/1, and /3311/2, the LwM2M Gateway device uses a URI prefix. And the LwM2M Light Control Object instances URIs could be: /Ceiling_Fan/3311/0, /Desk_Lamp/3311/0, and /Floor_Lamp/3311/0. All the LwM2M Objects of the same IoT device are presented under the same prefix.</p><p>The LwM2M Gateway device also presents to the LwM2M Server a list of the IoT devices to which it is connected. This list is presented as a specific LwM2M Object: The LwM2M Gateway Object (ID: 25). There is one instance of this Object per IoT device. This Object has three resources:</p><ul><li>An identifier of the IoT device. This identifier must allow the LwM2M Server to identify the IoT device uniquely. It is, for instance, the Bluetooth device address (BD_ADDR).</li><li>The URI prefix under which the LwM2M Objects relevant to this IoT device are present.</li><li>The list of LwM2M Objects exposed by the LwM2M Gateway on behalf of the IoT device.</li></ul><h3>The LwM2M Server Point of View</h3><p>When a LwM2M device connects to a LwM2M Server, it sends the list of LwM2M Objects it features. This list allows the LwM2M Server to determine the capabilities of the LwM2M device.</p><p>In the case of a LwM2M Gateway device, this list contains only the LwM2M Objects of the LwM2M Gateway device (and not the LwM2M Objects matching the IoT device capabilities). The presence of the LwM2M Gateway Object in this list informs the LwM2M Server that the device is a LwM2M Gateway device and that IoT devices are connected to it.</p><p>By inspecting the LwM2M Gateway Object instances, the LwM2M Server can retrieve a list of the connected IoT devices and their respective capabilities. The LwM2M Server can then rely on the provided prefix to interact with an IoT device through the LwM2M Gateway device.</p><p>For instance if the LwM2M gateway presents an instance of the LwM2M Gateway Object with the following content:</p><ul><li>Device ID: BT:11:22:33:44:55:66</li><li>Prefix: /Desk_Lamp</li><li>IoT Device Objects: &lt;/5/0&gt;,&lt;/3303/0&gt;,&lt;/3311/0&gt;</li></ul><p>The LwM2M Server determines that the IoT device features a light control (through the presence of Object with ID 3311), a temperature sensor (through the presence of the Object with ID 3303), and that its firmware can be updated (through the presence of the Object with ID 5).</p><p>To retrieve the status of the light, the LwM2M Server performs a Read operation on the URI /Desk_Lamp/3311/0/5850.</p><h3>Alternate Usage</h3><p>As stated before, the LwM2M data model is in the form Object/Instance/Resource. This can lead to confusion in complex devices with a lot of features. Take, for instance, a car. It contains several temperature sensors: the coolant temperature, the inside temperature, the outdoor temperature, the A/C requested temperature. And it contains even more lights.</p><p>With the LwM2M Gateway, the car can be presented as a collection of “sub-devices” like the engine, the A/C, or the IVI system. With this approach, the user of the LwM2M Server no longer needs outside information on the layout of the car to identify the right LwM2M Object instance for a particular sensor. Additionally, the LwM2M server can match the different sensors belonging to the same part of the vehicle, making it easier to manage interactions.</p><p>Join us on GitHub and let’s discuss: <a href="https://github.com/ioterop">https://github.com/ioterop</a></p><p><a href="http://www.ioterop.com/">www.ioterop.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01cafe0c45e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stateless to StateFul Filtering]]></title>
            <link>https://medium.com/@IoTerop/stateless-to-stateful-filtering-68d096b5efbe?source=rss-c76b7550a85a------2</link>
            <guid isPermaLink="false">https://medium.com/p/68d096b5efbe</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[cloud-services]]></category>
            <category><![CDATA[stateful]]></category>
            <category><![CDATA[filtering]]></category>
            <dc:creator><![CDATA[IOTEROP]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 07:31:36 GMT</pubDate>
            <atom:updated>2024-07-23T07:31:36.581Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*KRLTthR9o8V0ES7ESq3QaA.png" /></figure><p>The Team behind Angular provides many ways to transmit data between components. What if we used something everyone uses on the web: Uri?</p><h3>What is a URI?</h3><p>From the Oxford Dictionary: a string of characters used to identify a resource on a computer network, of which the best-known type is the web address or URL.</p><p>An example of uri:</p><p><a href="https://example.com/list?name=scala&amp;type=10">https://example.com/list?name=scala&amp;type=10</a></p><p>Everything after the ‘?’ is called a queryParams.</p><p>We can retrieve them in Angular using ActivatedRoute.queryParams (an Observable). The application is notified whenever a user changes one of the queryParams.</p><h3>Our use-case</h3><p>At IoTerop, we present information as a list of items. Our API allows our users to filter data based on parameters.</p><p>We have used several ways to keep the filter state when filtering data, but none of them were stateful.</p><p>We wanted to filter data and keep the filters when a user refreshes their page.</p><h3>The stateless way of filtering</h3><h4>Input/Output</h4><p>Two components can communicate with each other using the @Input() and @Output() keywords provided by Angular.</p><p>If you are not familiar with Angular, my advice would be to read the documentation, of course: <a href="https://angular.dev/">https://angular.dev/</a></p><p>Since the new version, Angular¹⁸, the doc has been revised and is in its prime.</p><p>Here are two images to explain the concept.</p><p>Input allows a parent to transfer data to a child, who will mount with custom data. It’s the most common way for the Child to be “dumb” and render the correct data.</p><p>Input could allow reusability by decoupling the dumb component and its DTO.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQTGxO2u81y_WsdBlxS4OA.png" /></figure><p>Output is the opposite of Input. It allows the Child to say, ‘Hey Dad, could you please do something?’ The Child outputs an event, and the parent does all the work.</p><p>When we were babies, being hungry was an output, and our parents listened to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zfew3_YnoriicUWMcGkMdg.png" /></figure><p>Of course, everything is fine until we add more components, and our Parents must communicate with the last one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mn3846jJly8CL5TRV-sOUA.png" /></figure><p>Cons:</p><p>The state is created while the user is modifying the component. We don’t keep track of the filter chosen on page refresh: it is stateless.</p><p>Input/Output is okay if we don’t want to initialize the filter with data.</p><p>We could do ListRender &lt;-&gt; FilterContainer directly.</p><h4>Dependency Injection</h4><p>Angular gives us a second way of passing data. Technically, the concept doesn’t come from Angular, but it’s used and effective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5mPdOFGYTujciTRZM0ggEA.png" /></figure><p>It is fine to add a service inside a dumb component. Services are also easier and faster to test.</p><p>Cons:</p><p>It’s still stateless.</p><h3>The Uri-way (stateful)</h3><p>Since the beginning of the Internet, users have navigated using URIs. Javascript has already implemented methods to retrieve information from the URI.</p><p>The Angular Team built a Router service that makes using those methods easy.</p><p>The router has many tools, but we won’t use it directly. Instead, we will use the ActivatedRoute to get the queryParams of our route.</p><p>Using a custom service or a directive, we can use this observable to retrieve filters from URI and update that URI when a filter changes.</p><pre><br>@Directive()<br>export class FilterDirective&lt;TFilter extends Record&lt;string, any&gt;&gt;<br>  implements OnInit<br>{<br>  @Output()<br>  public filterData = new EventEmitter&lt;TFilter&gt;();<br>  protected formGroup!: FormGroup;<br>  private readonly activatedRoute = inject(ActivatedRoute);<br>  protected readonly destroyRef = inject(DestroyRef);<br><br>  public ngOnInit() {<br>    this.activatedRoute.queryParams<br>      .pipe(<br>        takeUntilDestroyed(this.destroyRef),<br>        tap((data) =&gt; {<br>          if (Object.keys(data).length &gt; 0) {<br>            this.formGroup.patchValue(data);<br>            this.filterData.emit(data as TFilter);<br>          } else {<br>            this.formGroup.reset();<br>            this.filterData.emit();<br>          }<br>        })<br>      )<br>      .subscribe();<br>  }<br>}</pre><p>You can then extend the FilterDirective in your FilterContainer.</p><p>Since the directive is generic, it is reusable, now everything depends on how you will update query:</p><p>From FormGroup:</p><pre>form.valueChanges(value =&gt; {<br>this.router.navigate([], {queryParamsHandling: ‘merge’, queryParams:value})</pre><p>When you submit on a formControl:</p><pre>OnSubmit() {<br>              let queryParams = {};<br>//if value is undefined, queryParams is removed by Angular service <br>              queryParams[controlName] = control.value;  <br>              this. Router.navigate([], {queryParamsHandling:’merge’, queryParams})<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQ10u8IhmufqDV_rsX0xdA.png" /></figure><h3>Elevate your taste with stateful filtering</h3><p>At IoTerop, we only update our filters when the user clicks a submit button.</p><p>Listening to every change on a form could lead to useless API calls.</p><p>We implemented the URI way to use state in Angular, allowing users to bookmark their favorite filters and share them between team members.</p><p>In terms of user experience, it makes sense to store the filters somewhere.</p><p>It could be localstorage, if you want to hydrate a previous state even if the URI doesn’t have queryParams or from URI, as in this article.</p><p>The next step is up to you.</p><p>Stackblitz’s link: <br><a href="https://stackblitz.com/edit/stackblitz-starters-uvsfwg?file=src%2Ffilter-container.component.ts">https://stackblitz.com/edit/stackblitz-starters-uvsfwg?file=src%2Ffilter-container.component.ts</a> <br>In order to see the queryParams, do not hesitate to click on ‘Open Preview in new tab’</p><p>Join us on GitHub and let’s discuss: <a href="https://github.com/ioterop">https://github.com/ioterop</a></p><p><a href="http://www.ioterop.com/">www.ioterop.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68d096b5efbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Transactions in a Microservices Architecture]]></title>
            <link>https://medium.com/@IoTerop/distributed-transactions-in-a-microservices-architecture-b969c54f51a4?source=rss-c76b7550a85a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b969c54f51a4</guid>
            <category><![CDATA[saga-pattern]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[iot-platform]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[IOTEROP]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 07:17:16 GMT</pubDate>
            <atom:updated>2024-06-25T07:17:16.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ebXeXXkU0lDZGNg9_3FoQA.png" /></figure><p><em>By Axel Czarniak, IoTerop Junior Software Architect</em></p><h3>Introduction</h3><p>The microservices architecture is an approach where an application is divided into several small independent services. Each service implements a specific business functionality and manages its data source autonomously, promoting strong decoupling and enhanced modularity. This approach allows the selection of the most suitable storage technology for each service’s requirements, enhancing overall system resilience and facilitating service deployment and updates without disrupting the entire application.</p><p>While this approach offers numerous benefits, it also presents many challenges. The microservices architecture must efficiently and reliably manage service interactions while ensuring synchronization. The principle of distributed transactions comes into play within this context.</p><p>A distributed transaction is an operation that spans across multiple distinct services, requiring coordination to ensure that all involved parts either succeed or fail together, thereby maintaining data consistency across the entire system.</p><p>In this article, we will explore several types of distributed transactions.</p><h3>Two-Phase Commit (2PC)</h3><p>The Two-Phase Commit is an atomic commitment protocol used in distributed systems to ensure that a distributed transaction either commits on all involved nodes or rolls back entirely. It is primarily used in environments where transactions span across multiple databases or services, and maintaining a consistent state across these systems is critical.</p><p>This protocol introduces two core components:</p><ul><li>Coordinator: The node responsible for managing the transaction and coordinating interactions among participants.</li><li>Participants: Nodes that execute the transaction and report their status to the coordinator.</li></ul><p>The protocol operates in two distinct phases:</p><h4>Prepare Phase or Voting Phase:</h4><p>The coordinator node sends a prepare request to all participants. Each participant executes the transaction up to the pre-commit phase and records its intent in a local log, ensuring it can finalize the transaction if required. Participants then respond to the coordinator with either a vote-commit or vote-abort, indicating their readiness to commit or abort the transaction.</p><h4>Commit Phase:</h4><p>If the coordinator receives vote-commit from all participants, it sends a commit message to all participants, instructing them to commit the transaction.</p><p>If any participant votes to abort, or fails to respond within a specified timeout, the coordinator sends an abort message, instructing all participants to roll back the transaction.</p><p>Participants acknowledge the instructions and complete the transaction accordingly.</p><p>Here at IoTerop, customers must provision all the devices they intend to use on our server to utilize our IoT Platform. Because these are primarily secure, customers must also furnish credentials to grant access to them. Initially, we implemented the Two-Phase Commit protocol for the provisioning phase.</p><p>When a customer inserts a device (1), the coordinator initiates two requests: one to verify and reserve the credentials in the security service (2) and another to insert the device into the tenant’s inventory (3). Once the coordinator receives responses from both participants (4, 5), it decides whether to commit or abort the transaction (6, 7). Based on this decision, the customer receives a response indicating whether its provisioning was successful (8).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ybBZZUCUz1SjAuVjm2HBkg.png" /></figure><p>In the diagram above, if either participant responds with a vote-abort, the coordinator will send an abort message to all participants and then respond to the customer with an error.</p><h4>Pros and cons</h4><p>The Two-Phase Commit (2PC) protocol offers several advantages:</p><ul><li>Atomicity: Ensures that a transaction is atomic across all participants, meaning it either fully completes or fails.</li><li>Consistency: By coordinating the process, the coordinator helps maintain a consistent state across the system.</li><li>Fault Tolerance: Storing a temporary state for handling the transaction helps participants recover in case of a failure.</li></ul><p>However, it also has limitations:</p><ul><li>Blocking: The coordinator is a single point of failure. If it fails at any stage of the process, participants can remain in a locked state, unable to commit or abort until the coordinator recovers.</li><li>Latency: The protocol involves multiple rounds of communication, which can reduce the system’s overall performance.</li><li>Scalability: Work well when the number of participants is small.</li></ul><p>While it has its limitations, its ability to ensure consistency and atomicity makes it a critical tool in various applications and a foundational technique in distributed systems. Understanding its mechanics, the contexts in which it excels, and its limitations is essential for designing robust and reliable distributed systems.</p><p>In our situation, as our system expanded and the number of participants during provisioning grew, using Two-Phase Commit for our provisioning became increasingly complex, making it challenging to maintain consistency across all our services. Moreover, when provisioning in bulk, we aimed to enable operations to proceed with a best-effort approach rather than rolling back the entire process. This led us to transition to using the Saga pattern.</p><h3>Saga</h3><p>A saga consists of multiple local transactions, each executed within its own service’s context. Each transaction updates its data and publishes an event or message to initiate the next step of the saga. If any transaction fails, compensatory actions is triggered to undo the preceding transactions and restore the initial state.</p><p>Sagas rely on two primary coordination models: choreographed sagas and orchestrated sagas.</p><h4>Choreographed Saga</h4><p>In this type of saga, each participating service knows and communicates directly with the other involved services. Therefore, coordination is distributed and implicit.</p><p>This system is often used for simple tasks with few participants and no need for coordination logic. However, it has several drawbacks: adding steps to an existing saga is challenging due to the absence of a central point for tracking steps, and there is a risk of cyclic dependencies between participants.</p><h4>Orchestrated Saga</h4><p>In orchestrated sagas, an orchestrator manages the saga by coordinating local transactions and overseeing the overall transaction status. It sends commands to participating services, waits for their responses before proceeding to the next step, and handles compensating actions in case of errors.</p><p>In contrast to a choreographed saga, this approach is well-suited for complex workflows, facilitates the seamless addition of steps, mitigates cyclic dependency risks, and streamlines business logic for participants. However, it does introduce added design complexity for the orchestrator implementation.</p><p>Let’s return to our example:</p><p>In this scenario, we will replace the coordinator with the provisioning service. Its scope remains the same: this service provides the API, validates the payload, and orchestrates the saga. And For this use case, we will use Kafka for event streaming instead of HTTP calls between services for more resilience.</p><p>When a customer inserts a device (1), the provisioning service creates a task for the saga and immediately responds to the customer with the taskId (2) to enable them to track the request’s progress. The saga begins by reserving the credentials in the security service (3). Upon receiving confirmation from the security service (4), the provisioning service creates an order to insert the device into the tenant’s inventory (5). Based on the response from the final involved service (6), the orchestrator updates the saga’s state, allowing the customer to see whether the provisioning was successful or not (7).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63S1HcVclTaiAdeB-EbZug.png" /></figure><h4>Pros and cons</h4><p>The saga pattern addresses many issues with the Two-Phase Commit protocol and offers numerous advantages:</p><ul><li>Eventual consistency: It ensures eventual consistency rather than strict consistency, which is often sufficient for many distributed applications.</li><li>Resilience and reliability: Avoiding global transactions reduces the risk of blocking and enhances system resilience against failures.</li><li>Scalability: It enables better scalability by distributing local transactions across independent services.</li><li>Flexibility: Compensating actions provide a flexible method to undo the effects of failed transactions, which is more adaptable than traditional rollback mechanisms in ACID transactions.</li><li>Long-Running Transactions: Sagas supports long-running transactions across multiple services, a challenge for traditional ACID transactions.</li></ul><p>However, this pattern also has its drawbacks:</p><ul><li>Complexity: Implementing and managing sagas can be complex, especially when compensating actions and ensuring transactional consistency across distributed services.</li><li>Increased development overhead: Developers must meticulously design and implement each saga and its compensating actions, which increases development time and complexity.</li><li>Consistency guarantees: Sagas do not offer strong consistency guarantees like traditional ACID transactions. Instead, they rely on compensating actions to revert changes, which can be more error-prone and challenging to manage.</li></ul><p>While the saga pattern provides significant benefits for distributed systems, its adoption requires careful consideration of the trade-offs involved in managing complexity and ensuring consistency.</p><h3>Conclusion</h3><p>In summary, while both 2PC and sagas have advantages and limitations, the choice between them depends on the system’s specific needs and the trade-offs that can be managed. Understanding these patterns and their implications is crucial for designing robust and reliable systems using a microservices architecture.</p><p>Join us on GitHub and let’s discuss: <a href="https://github.com/ioterop">https://github.com/ioterop</a></p><p><a href="http://www.ioterop.com/">www.ioterop.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b969c54f51a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining multi-region infrastructure with Terraform and GitLab CI]]></title>
            <link>https://medium.com/@IoTerop/streamlining-multi-region-infrastructure-with-terraform-and-gitlab-ci-6009618e40d3?source=rss-c76b7550a85a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6009618e40d3</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[IOTEROP]]></dc:creator>
            <pubDate>Tue, 21 May 2024 07:02:25 GMT</pubDate>
            <atom:updated>2024-05-21T07:02:25.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sTonSKxja9Iof9GB320AoQ.png" /></figure><p><em>By Thomas Gouveia, IoTerop Lead Site Reliability Engineer</em></p><p><strong>At </strong><a href="https://ioterop.com/"><strong>IoTerop</strong></a><strong>, we’re building Alaska, a highly scalable device management platform designed to accommodate millions of IoT devices. To ensure global operations, optimize customer accessibility, and adhere to legal regulations, we built Alaska on Amazon Web Services.</strong></p><p>As the Lead Site Reliability Engineer, one of my key roles is to ensure that our infrastructure evolves continuously without compromising our strict service level agreements (SLAs).</p><p>In this article, I’ll detail our journey toward achieving streamlined multi-region infrastructure deployment using <a href="https://terraform.io/">Terraform</a> and <a href="https://docs.gitlab.com/ee/ci/">GitLab CI</a>. By sharing our experiences, I aim to instill confidence that additional tools/wrappers like <a href="https://terragrunt.gruntwork.io/">Terragrunt</a> or <a href="https://terraspace.cloud/">Terraspace</a> may not be necessary to simplify your workflow.</p><p><strong>A little bit of context</strong></p><p>Alaska’s infrastructure is built solely on various AWS services, including EKS, S3, CloudFront, Route 53, etc.</p><p>All our infrastructure is deployed via Infrastructure as Code (IaC), to improve consistency, scalability, and reproducibility in a disaster recovery scenario. Initially, the platform was deployed only in a European region, and the SRE and some developers performed deployments (infrastructure and application) manually.</p><p>To manage the infrastructure efficiently, we utilized Terraform and Terragrunt, leveraging the <strong>Don’t Repeat Yourself (DRY) principle</strong>. We developed reusable modules and extensively utilized Terragrunt features, such as g<a href="https://terragrunt.gruntwork.io/docs/reference/config-blocks-and-attributes/#generate">enerat</a>ing and <a href="https://terragrunt.gruntwork.io/docs/reference/config-blocks-and-attributes/#include">includ</a>ing blocks, to structure our configurations with a minimal duplication rate.</p><blockquote>Application deployment within the Kubernetes clusters is also managed through Terraform, utilizing the <a href="https://registry.terraform.io/providers/hashicorp/helm/latest/docs">Helm provider</a> and others following the same model as the one explained below.</blockquote><p>Terraform modules were stored in their dedicated Git repository, while the deployment configurations were stored in another. Below is an illustration (simplified) of how the latter was structured:</p><pre>.<br>├── common<br>│   ├── base<br>│   │   ├── app<br>│   │   └── infrastructure<br>│   └── providers<br>│       ├── aws.hcl<br>│       └── kubernetes.hcl<br>├── production<br>│   └── aws<br>│       └── eu-north-1<br>│           ├── app<br>│           ├── environment.hcl<br>│           └── infrastructure<br>├── staging<br>│   └── aws<br>│       └── eu-west-1<br>│           ├── app<br>│           ├── environment.hcl<br>│           └── infrastructure<br>└── terragrunt.hcl</pre><ul><li>common: holds shared files (such as providers <a href="https://terragrunt.gruntwork.io/docs/reference/config-blocks-and-attributes/#generate">generate</a> blocks) and default configurations (Helm, Terragrunt) for all modules.</li><li>production / staging: holds the configuration for the respective environment.</li><li>terragrunt.hcl: holds state block for Terraform, common to all environments thanks to the Terragrunt function path_relative_to_include() that allows us to compute the correct key in the state bucket automatically.</li></ul><p>Let’s take an example infrastructure module. When properly configured, the repository structure looks like:</p><pre>.<br>├── common<br>│   └── base<br>│       └── infrastructure<br>|           └── example.hcl # NEW<br>├── production<br>│   └── aws<br>│       └── eu-north-1<br>│           └── infrastructure<br>|               └── example<br>|                   └── terragrunt.hcl # NEW<br>├── staging<br>│   └── aws<br>│       └── eu-west-1<br>│           └── infrastructure<br>|               └── example<br>|                   └── terragrunt.hcl # NEW<br>└── terragrunt.hcl</pre><ul><li>common/base/infrastructure/example.hcl: defines default Terragrunt configuration for this module, with the default target as production.</li><li>production/aws/eu-north-1/infrastructure/example/terragrunt.hcl: defines the Terragrunt configuration that will be applied for the production environment in the region eu-north-1. (same for staging).</li></ul><p>Finally, here is the content of the moduleterragrunt.hcl file:</p><pre># file: production/aws/eu-north-1/infrastructure/example/terragrunt.hcl</pre><pre>include &quot;root&quot; {<br>  path = find_in_parent_folders() # includes terragrunt.hcl at the root of the repo<br>}</pre><pre>include &quot;environment&quot; {<br>  path           = find_in_parent_folders(&quot;environment.hcl&quot;) # includes production/aws/eu-north-1/environment.hcl<br>  merge_strategy = &quot;deep&quot;<br>}</pre><pre>include &quot;base&quot; {<br>  path           = &quot;${get_repo_root()}/common/base/infrastructure/example.hcl&quot;<br>  merge_strategy = &quot;deep&quot;<br>}</pre><pre>include &quot;aws_provider&quot; {<br>  path = &quot;${get_repo_root()}/common/providers/aws.hcl&quot;<br>}</pre><pre>inputs = {}</pre><p>As demonstrated, Terragrunt is a great tool that provides powerful features such as inclusion, allowing users to compose a configuration with files from different sources to achieve DRY architecture.</p><p>Last year, in response to increasing demand from our Oceanian customers, <strong>we introduced a new region in Australia</strong>. Adding a new environment/region is as simple as duplicating a directory, renaming it, and editing the configurations inside. But, this led to some issues.</p><h4>Issues with the repository architecture</h4><p>Our platform consists of global and regional services, which means certain services are exclusively available in specific instances, such as our European deployment, and vice versa. Although we strive to maintain consistency across regions, there are instances where configurations may differ temporarily or permanently.</p><p>Adapting our architecture to accommodate these requirements was manageable, even if it increased the complexity of the repository. This complexity arose from the introduction of override files at specific levels within the hierarchy. Consequently, <strong>it became challenging to identify the source of truth </strong>of what had been deployed in the different environments, mainly due to the several inclusions done by Terragrunt, for example, even if Terraform was outputting the plan for the changes it’ll perform.</p><p>From a DevOps perspective, we’ve also transitioned to the “<strong>You Build It, You Run It</strong>” principle, empowering feature teams to oversee their applications’ development and production lifecycle. Consequently, team members increasingly assumed responsibility for updating their application configurations in the repository. As mentioned earlier, manual deployment posed challenges in <strong>tracking deployed updates, their origins, and timing</strong>.</p><h3>Rethinking our repository</h3><p>Considering the issues outlined above, we reassessed our repository organization and functionality. We aimed to ensure its utility and optimize workflows for developers and SREs. Below are the elements we focused on to build our new repository model:</p><ul><li><strong>GitOps</strong>: We should apply the same Git flow used by developers to build software (e.g. Merge Requests, Code Review, CI/CD Pipelines, etc), but for building infrastructure. <strong>The repository must be our source of truth</strong> about what is currently deployed, when the deployment was done, and by whom.</li><li><strong>Simple hierarchy</strong>: The structure of the repository must not be too complex or have too many nested levels. From within an environment folder, we must be able to identify all the files used by Terraform.</li><li><strong>Scalability</strong>: We should be able to deploy/destroy environments easily.</li><li><strong>Automation:</strong> CI/CD pipelines must be developed to facilitate the review of changes and deliver them to production automatically.</li><li><strong>Easy migration:</strong> The old repository model could be easily migrated to the new one, without any service disruption.</li></ul><p>As stated previously, we wanted to design the new repository model with something simple to understand and navigate. We were convinced that our previous structure was sufficient for our needs, so we reused it for the new model. Each <strong>final</strong> Terraform configuration must be placed under an <strong>environment</strong> and a <strong>region. </strong>Let’s say we have a production environment deployed into the region eu-west-3; the Terraform files must be put into production/eu-west-3.</p><blockquote>A<strong> final</strong> Terraform configuration is simply the directory for executing Terraform commands.</blockquote><p>Now that we’ve settled on the repository folder structure, we were asking ourselves the following question: “<strong>Should we keep Terragrunt? Is it really useful for our use case?</strong>”</p><p>The introduction mentions that Terragrunt is a powerful tool for achieving a Don’t Repeat Yourself (DRY) architecture. However, depending on its usage, it can increase your project’s complexity. Therefore, we have decided to discontinue using Terragrunt in favor of native Terraform. So, how can we achieve a minimal DRY architecture with Terraform only?</p><p>Terraform offers a built-in feature called <a href="https://developer.hashicorp.com/terraform/language/state/workspaces">workspaces</a>, enabling users to manage multiple states for the same Terraform configuration. Each workspace maintains its state, allowing for isolated environments within a single configuration. However, this approach aligns differently with our requirements, as the <a href="https://developer.hashicorp.com/terraform/cli/workspaces#when-not-to-use-multiple-workspaces">documentation</a> advises against using workspaces when each configuration has a separate configuration and backend. Remember, we want separate Terraform configurations depending on the environment, the region, etc.</p><p>The concept here involves utilizing <strong>symbolic links</strong>, which are universally supported across operating systems and Git. With symlinks, sharing files between directories becomes straightforward, and it seamlessly integrates with our goal of accessing all the files Terraform uses within its folder structure as each file must be linked directly in the final Terraform configuration to be used.</p><blockquote>Remember about the Keep It Simple Stupid (KISS) principle.</blockquote><p>For example, let’s say we have two production environments, one in eu-west-3, and another in eu-west-1. Both environments share the same variables. Without symlinks, you will need to create a file variables.tf in one environment and duplicate it in the other:</p><pre>production<br>├── eu-west-3<br>│   └── variables.tf<br>└── eu-west-1<br>    └── variables.tf</pre><p>What if you need to add a new variable? You’ll need to edit all the environment variables.tf files. And if you have plenty of environment, it is complex to maintain. With symlinks, we can simply extract all the common variables for production into a production/prod-variables.tf file (the name is arbitrary), and make a symlink in each region:</p><pre>production<br>├── eu-west-3<br>│   └── prod-variables.tf -&gt; symlink ../prod-variables.tf<br>├── eu-west-1<br>|   └── prod-variables.tf -&gt; symlink ../prod-variables.tf<br>└── prod-variables.tf</pre><p>And now, if you update the production/prod-variables.tf to add a new variable, all your environments will inherit from the changes thanks to the symlink.</p><p><strong>What about Terraform modules?</strong> Remember, in the previous architecture, they were stored in their own dedicated Git repository, but it could be painful to maintain (especially when they’re designed to not be re-used by other projects).</p><p>To improve the maintainability, we decided to introduce a modules folder at the root of the new repository model designated for storing global and regional Terraform modules utilized in this repository. If you have a module that could be reused across multiple projects, I recommend placing it in a separate repository. This allows you to utilize it across projects using <a href="https://developer.hashicorp.com/terraform/language/modules/sources#generic-git-repository">Terraform’s Git module source</a>. Additionally, if necessary, you can reference modules from this repository in other projects using <a href="https://developer.hashicorp.com/terraform/language/modules/sources#modules-in-package-sub-directories">sub-directories</a>.</p><p>Below is a recapitulation schema of the new repository model, with symlinks represented in blue:</p><figure><img alt="New file structure of the Git repository schema. Blue files are symlinks." src="https://cdn-images-1.medium.com/max/1024/1*2bSrjBwEbP3u94f9V1ZY9Q.png" /><figcaption>The new repository model. Blue files are symlinks.</figcaption></figure><p>Our new repository model is ready and fits with the several requirements we’ve established previously, except <strong>automation</strong>.</p><blockquote>The article does not cover the migration process from the old repository to the new one. However, since both repository models utilize Terraform for deploying resources, transitioning or reimporting states is straightforward with Terraform commands such as <em>import</em> and/or <em>state</em>.</blockquote><p>What tasks do we want to automate for a such repository? Generally, when discussing Terraform automation, automatic planning and applying are key elements. We want to define our automation with the following rules:</p><p><strong>Merge requests:</strong></p><ul><li>Each change to a module located in modules triggers a Terraform plan on all environments.</li><li>Each change to a specific environment triggers a plan for this environment.</li></ul><p>The goal here is to facilitate the code review by putting forward to the reviewer the changes that will be performed against the live infrastructure.</p><p><strong>Main branch:</strong></p><ul><li>Each change to a module located in modules triggers a Terraform plan on all environments and creates the associated Terraform apply job (one per environment).</li><li>Each change to a specific environment triggers a plan for this environment and creates the associated apply job.</li></ul><p>The goal here is to facilitate the delivery of infrastructure changes by concurrently running Terraform apply commands to the update environments when changes have been approved in merge requests.</p><p>Lastly, we’ve opted not to pursue continuous deployment for our infrastructure, particularly in production. Instead, we prefer a continuous delivery model, requiring manual intervention to trigger Terraform apply jobs. In the next section, we’ll explore how we can implement such an approval process.</p><p>Below is a summary schema representing the overall architecture of the new repository model:</p><figure><img alt="Schema representing the overall architecture of the new repository model with automation." src="https://cdn-images-1.medium.com/max/1024/1*l9gM4Ll-2v9JF-t2tE-7YA.png" /><figcaption>The overall architecture of the new repository model, with automation.</figcaption></figure><h3>Key points</h3><p>Migrating our repositories from our old model to the new one is straightforward and primarily involves classic Terraform development. Below, I’ll outline the various challenges we encountered during the migration and how we addressed them.</p><h4>Authentication &amp; IAM permissions</h4><p>Terraform providers typically require authentication with the system they manage. In our scenario, we needed to authenticate the various <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs">AWS providers</a> we utilize to enable the deployment of Terraform resources across the cloud platform.</p><p>At IoTerop, we maintain a fleet of GitLab runners deployed into one of our Kubernetes clusters, managed through AWS EKS. Using EKS here allows us to use the <a href="https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html">IAM Role for Service Account</a> feature, also called <strong>IRSA</strong>. This feature allows us to map AWS IAM roles to a dedicated service account (e.g. the runner’s ones), so that we can perform actions over the AWS API, without the need to store static AWS credentials in our cluster.</p><p>We developed a dedicated role for each repository with restricted permissions on the AWS API. This repository role is then included in the list of roles that the runner’s role can assume. With this setup, assuming we have the following providers.tf file in one of our environments:</p><pre>provider &quot;aws&quot; {<br>  region = &quot;eu-west-3&quot;<br>  assume_role {<br>    role_arn     = &quot;arn:aws:iam::123456789:role/my-repository-role&quot;<br>    session_name = &quot;terraform&quot;<br>  }<br>}</pre><p>The pod executing the Terraform job will automatically assume the role specified in the role_arn attribute.</p><p>One of the primary advantages of using a classic assume_role rather than the assume_role_with_web_identity (<a href="https://docs.gitlab.com/ee/ci/cloud_services/aws/">supported by GitLab</a>) is that we can easily assume the role through our IAM users locally without the need to update anything in our Terraform codebase. Since provider configuration can&#39;t be dynamic, this approach can be extremely useful in case of emergencies when manual intervention is required.</p><blockquote>I recommend using a highly usefull tool like <a href="https://github.com/iann0036/iamlive">iamlive</a> to retrieve IAM actions required by a Terraform configuration.</blockquote><h4>State Key</h4><p>With the old repository model using Terragrunt, we utilized the built-in function path_relative_to_include() to dynamically compute the key in the S3 bucket for storing Terraform states. However, with the removal of Terragrunt in the new model, we no longer have access to this function. Consequently, we needed an alternative method to easily declare the key in the bucket for a given configuration.</p><p>Due to the critical nature of state management and the necessity for a clear definition, we encountered challenges in finding a solution that would consistently generate the state key across both CI environments and local machines. Given the importance of being able to intervene in emergencies from our local machines, ensuring the ability to execute Terraform init commands was paramount. We included a file named backend.tfvars in each of our final Terraform configurations. This file contains a single variable, key which configures the S3 backend of Terraform:</p><pre>key = &quot;path/to/state/in/bucket/tfstate.json&quot;</pre><p>The remaining backend configuration is abstracted into a shared backend.tf file located at the root of the repository. This file is then symlinked to each of our final configurations for seamless integration.</p><h4>GitLab CI</h4><p>To avoid creating a separate .gitlab-ci.yml file for each environment, we leverage the GitLab CI <a href="https://docs.gitlab.com/ee/ci/yaml/#parallelmatrix">parallel:matrix</a> keyword to generate the jobs dynamically. But how do we use it with our repository model?</p><blockquote>The different elements showcased below don’t represent an entire and valid <em>.gitlab-ci.yml</em> file. Feel free to use them to build your file.</blockquote><p>In our matrices, we want to have two variables:</p><ul><li>ENVIRONMENT: The name of the environment.</li><li>REGION: A list of regions within this environment.</li></ul><p>To illustrate this, let’s say we have the following repository hierarchy:</p><pre>.<br>├── production<br>│   ├── eu-west-2<br>│   └── eu-west-3<br>└── staging<br>    └── eu-west-1</pre><p>In our .gitlab-ci.yml, we can declare the following matrices. YAML anchors are utilized to reuse these matrices in different jobs without duplication:</p><pre>.production: &amp;production<br>  ENVIRONMENT: production<br>  REGION:<br>    - eu-west-2<br>    - eu-west-3</pre><pre>.staging: &amp;staging<br>  ENVIRONMENT: staging<br>  REGION:<br>    - eu-west-1</pre><p>Adding or removing a region simply requires editing the corresponding anchor within the .gitlab-ci.yml file. Now, we can use those anchors in our terraform plan job:</p><pre>terraform plan:<br>  # Custom template job, defines caching, aliases, image etc...<br>  extends: .terraform<br>  stage: plan<br>  script:<br>    - cd $ENVIRONMENT/$REGION<br>    - terraform init -backend-config=backend.tfvars<br>    - terraform plan<br>    # Integration with GitLab merge requests<br>    # See: https://docs.gitlab.com/ee/user/infrastructure/iac/mr_integration.html<br>    - terraform show --json $TF_PLAN | convert_report &gt; $TF_PLAN_JSON<br>  # Use the GitLab environment to track deployment<br>  # See: https://docs.gitlab.com/ee/ci/environments/<br>  environment:<br>    name: $ENVIRONMENT/$REGION<br>    action: prepare<br>  parallel:<br>    matrix:<br>      - *staging<br>      - *production<br>  rules:<br>    - changes:<br>        - $ENVIRONMENT/$REGION/*.{tf,tfvars}<br>        - $ENVIRONMENT/*.{tf,tfvars}<br>        - modules/**/*.tf<br>  artifacts:<br>    name: $ENVIRONMENT/$REGION<br>    reports:<br>      terraform: $ENVIRONMENT/$REGION/$TF_PLAN_JSON<br>    paths:<br>      - $ENVIRONMENT/$REGION/$TF_PLAN</pre><p>With such a job, our pipeline can generate a terraform plan job for all our Terraform configurations, depending on changes made by users in their commit (keyword rules).</p><p>We applied the same principle to our terraform apply jobs, with a little difference. <strong>Remember, we want manual approval to “validate” deployments before they are automatically executed</strong>. We achieved this using an intermediary stage hold between your plan and apply stages. Below is an example of a production hold job:</p><pre>production/hold:<br>  image: public.ecr.aws/docker/library/alpine:3.18.3<br>  stage: hold<br>  script:<br>    - echo &quot;Hold triggered&quot;<br>  rules:<br>    - if: $CI_COMMIT_BRANCH == &quot;main&quot;<br>      when: manual<br>      changes:<br>        - production/**/*.{tf,tfvars}<br>        - modules/**/*.tf</pre><p>And finally, here is a terraform apply job manifest:</p><pre>production/terraform apply:<br>  extends: .terraform<br>  stage: apply<br>  dependencies:<br>    - terraform plan<br>  script:<br>    - cd $ENVIRONMENT/$REGION<br>    - terraform init -backend-config=backend.tfvars<br>    - terraform apply $TF_PLAN<br>  environment:<br>    name: $ENVIRONMENT/$REGION<br>  parallel:<br>    matrix:<br>      - *production<br>  needs:<br>    - job: production/wait-for-approval<br>    - job: terraform plan<br>      # We need to define this job as optional as we may only perform<br>      # changes to a single region, and without making it optional here, <br>      # it will expect to have a terraform plan job for all region of <br>      # the production matrix.<br>      optional: true<br>      parallel:<br>        matrix:<br>          - *production<br>  rules:<br>    - if: $CI_COMMIT_BRANCH == &quot;main&quot;<br>      changes:<br>        - $ENVIRONMENT/$REGION/*.{tf,tfvars}<br>        - $ENVIRONMENT/*.{tf,tfvars}<br>        - modules/**/*.tf</pre><p>We use nearly the same job for our staging deployments. Below is an example of a complete pipeline:</p><figure><img alt="Example of a pipeline generated using elements outlined previously." src="https://cdn-images-1.medium.com/max/1024/1*ZxB9lt5-QOvEoh3g0CJNPw.png" /><figcaption>Example of a pipeline generated using elements outlined previously.</figcaption></figure><h3>Closing remarks</h3><p>That’s it! The new repository model has been successfully implemented across all our infrastructure projects, and we’ve established a template repository for the easy creation of new repositories in the future. As I demonstrated through this article, additional tools such as Terragrunt could be very powerful but can also considerably increase the complexity and the maintainability of your projects.</p><p>Since its adoption, we’ve experienced faster and safer development, review, and deployment processes in our environments. Adding a new region is now a straightforward task that can be automated through a simple script.</p><p>On the application side, we’re supporting our feature teams to become increasingly independent in maintaining their service configurations across different platform environments by promoting the adoption of our new repository model and giving them the tools they need. There’s potential to migrate application repositories to more reliable and Kubernetes-native solutions, enabling robust GitOps practices and deployments, such as <a href="https://argo-cd.readthedocs.io/en/stable/">ArgoCD</a> or <a href="https://fluxcd.io/">Flux</a>. Maybe we’ll discuss this more in a future article!</p><p>Join us on GitHub and let’s discuss: <a href="https://github.com/ioterop">https://github.com/ioterop</a></p><p><a href="http://www.ioterop.com/">www.ioterop.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6009618e40d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OSCORE, the End-to-End Security Protocol for IoT]]></title>
            <link>https://medium.com/@IoTerop/oscore-the-end-to-end-security-protocol-for-iot-4498cf3aa50a?source=rss-c76b7550a85a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4498cf3aa50a</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[lwm2m]]></category>
            <category><![CDATA[oscore]]></category>
            <category><![CDATA[device-management]]></category>
            <dc:creator><![CDATA[IOTEROP]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 07:32:50 GMT</pubDate>
            <atom:updated>2024-04-29T14:20:49.476Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*3TRXZsuLKvhSSKC5ULIB8w.png" /></figure><p><em>By Loïc Dalmasso, PhD, Cybersecurity Software Engineer</em></p><h3>1. IoT at a glance</h3><p>The International Telecommunication Union (ITU) defined the Internet of Things (IoT) as “a global infrastructure for the information society, enabling advanced services by interconnecting objects (physical and virtual) using existing or evolving interoperable information and communication technologies”. In other words, the IoT operates the information gathering, processing, action, and communication capabilities of autonomous entities with the aim of creating new services and applications. Many industries benefit from IoT capabilities, including metering (e.g., electrical, gas, water), smart city, automotive, healthcare, and environmental, to name just a few. It is straightforward to imagine an IoT use case: the interconnection of several temperature, humidity, and pressure sensors spread over a geographical area (e.g., region, country, etc.) to create a weather service. More recently, the Tesla Model X’s owner can control the car with its smartphone to lock/unlock the vehicle, control heating or air conditioning, collect the car’s information, etc. By connecting anything to the global network, the scientific community also extends the concept of IoT to the Internet of Everything (IoE). Even if the IoT/IoE services create important economies of scale disrupting existing processes, they bring huge security and privacy challenges.</p><h3>2. Security must be a requirement for IoT</h3><p>As the name suggests, objects are the main element in an IoT ecosystem. They are physical elements, integrating one or more sensors and/or actuators with data processing and communication capacities. By definition, IoT devices are deployed everywhere, and they are subject to various constraints in terms of size, memory, computing power, and energy consumption. In addition, because of the sensitive nature of data (e.g., healthcare, bank information …), IoT devices are key targets for hackers. Indeed, in 2020, a COSIC (Computer Security and Industrial Cryptography Group) team showed how to exploit vulnerabilities in the Tesla Model X’s entry system to steal the vehicle: the team was able to rewrite the firmware of the Tesla key fob from Bluetooth connection to get an unlock code and then enter in the vehicle, in just a matter of minutes. We can then look ahead and imagine that such an attack could go even further, for example, by re-programming the Tesla’s firmware for malicious purposes. This is a perfect example of IoT vulnerabilities: use a weak point in the ecosystem to get access to the most sensitive system. With the emergence of cyber-attacks, devices must embed security mechanisms ensuring both confidentiality and integrity of exchanges, as well as communication authentication, while taking into account their resource constraints.</p><h3>3. Secure the communication</h3><p>One of the most important features of an IoT device is its ability to communicate (inbound and outbound). In the Tesla scenario, the two critical vulnerabilities are the lack of authentication and authentication during the firmware update of the key fob and during the paring between the fob and the Tesla. Nevertheless, standard solutions already exist: TLS protocol (Transport Layer Security) [3] to secure exchange over TCP (Transmission Control Protocol), and DTLS [4] to secure exchange over UDP (User Datagram Protocol). Have a look at our previous articles [5–6] on TCP/UDP and TLS/DTLS for complementary information. TLS/DTLS protocols ensure host-to-host authentication, confidentiality, and communication integrity between two entities, also known as `hop-by-hop` security.</p><p>Ensuring security in an IoT ecosystem is a real challenge because of its high heterogeneity and dynamic nature. As we explained before, any kind of devices are deployed in the environment, and they are in a perpetual state of flux (i.e., connected/disconnected), mainly for energetic reasons. To collect data from the device to the server/cloud, there may be many intermediaries (e.g., proxy, gateway, other device …), introducing many security issues. Therefore, it is decisive to set up a mechanism that provides security from the device to the server/cloud. This is the so-called `end-to-end` security.</p><h3>4. The End-to-End Problem</h3><p>The notion of `end-to-end` refers to the ability of the protocol to secure communication from the very beginning of the transmission (i.e., the sender) to its termination (i.e., the receiver).</p><p>Let’s simplify the following scenario to highlight the main difference between `hop-by-hop` and `end-to-end` security: You want to send a letter to a friend to make an appointment at a specific time and location.</p><p>If you don’t care about security, you simply write your letter, indicate your friend’s address, and mail it off. The postman will pick up the letter and get your friend’s address, but he can also read the contents of your letter, a.k.a. the appointment time and location (cf. Figure 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Sr8claqElu6VfwJGQWtJA.png" /><figcaption>Figure 1</figcaption></figure><p>Now you don’t want anyone to be able to read your letter. So you write your letter, indicate your friend’s address, put it in a blank envelope, and mail it off. At this stage, everyone can see your envelope but no one can read what’s inside without opening it. However, for your letter to reach its destination, the postman will have to open it to retrieve your friend’s address. He, in turn, can put your letter back in its blank envelope and send it to your friend. Once again, no one will be able to read the contents of the letter while it’s in transit to your friend. However, you have no guarantee that the postman has not read the contents of your letter (the appointment time and location) before sending it to your friend (cf. Figure 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1uX4D_l99hCJD2vlc7Zmfw.png" /><figcaption>Figure 2</figcaption></figure><p>To fully ensure confidentiality of the appointment time and location, you decide to write your letter, put it in an envelope, write on it your friend’s address and then seal the envelope with a wax seal. Once again, everyone can see your envelope but now no one can neither read what’s inside nor open it, even the postman. In addition, the latter doesn’t even have to open it, because your friend’s address is printed on the envelope. He just needs to forward your letter to the right destination. In this configuration, only you and your friend know the appointment time and location. Congratulations, you’ve just set up your first end-to-end security system! (cf. Figure 3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWiWUR3fZ4Dlj5sA5qpZyw.png" /><figcaption>Figure 3</figcaption></figure><h3>5. TLS/DTLS for the End-to-End Security</h3><p>As explained above, TLS/DTLS protocols work at the Transport Layer in a `hop-by-hop` scheme: communication between two entities is secured, as shown in Figure 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxYK-COAzc5cCoOX49O20Q.png" /><figcaption>Figure 4</figcaption></figure><p>In this specific configuration, TLS/DTLS performs the `end-to-end` security: the device-to-server communication is secured. No one except the device and the server can access the data.</p><p>Now let’s take a basic IoT scenario: the device has a limited communication range (e.g., Bluetooth), and it has to send its data to the server. An intermediary node (e.g., proxy) has to be placed between the device and server; both collect device data and send it to the server (cf. Figure 5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCDWJPAnayZ2i6a8hYezoA.png" /><figcaption>Figure 5</figcaption></figure><p>In such a scenario, TLS/DTLS secure communications through two distinct TLS/DTLS channels, device-to-proxy and proxy-to-server. This leads to a double encryption process: the client encrypts and sends data to the proxy. Then, the proxy decrypts the data, re-encrypts it, and sends it to the server. So here, the device-to-server communication is NOT secured; TLS/DTLS does not ensure end-to-end security since the proxy has access to all data (in the clear). This is a security point of failure.</p><p>Another security protocol must be used to ensure the `end-to-end` security from device to server/cloud.</p><h3>6. OSCORE, the End-to-End security protocol dedicated to IoT</h3><p>OSCORE [7] (Object Security for Constrained RESTful Environments) is an application layer security protocol protecting CoAP [8] (Constrained Application Protocol), a web transfer protocol designed for constrained nodes and networks. OSCORE is also designed for constrained nodes and networks, providing end-to-end security (i.e., confidentiality, integrity, and message authenticity) thanks to the AEAD encryption (Authenticated Encryption with Associated Data) and its several protection modes, depending on the criticality of each part of a message: while confidentiality and integrity are applied to the payload (most sensitive data), some options can be integrity protected only, and non-sensitive data are kept visible (e.g. CoAP Token, CoAP URI-Host, etc.). Due to these capabilities, OSCORE prevents alterations/access of any message field by intermediary nodes, such as proxies, while allowing them to perform operations (e.g., forwarding and scheduling CoAP requests/responses, translation between protocols).</p><p>In addition, it is important to note that since OSCORE operates at the application layer, it can be used with any transport layer security, such as TLS/DTLS protocols. In such a configuration, the application data are secured by OSCORE, while TLS/DTLS secures the whole data exchange (e.g., CoAP headers and options). When the intermediate node receives the OSCORE-TLS/DTLS message, it can only access the TLS/DLS-secured message part but not the OSCORE-secured message part (a.k.a application data). Only the recipient can access this part.</p><p>Also, OSCORE is compatible with any transport layer protocol such as TCP, UDP, or non-IP transports.</p><h4>6.1. OSCORE Message</h4><p>OSCORE transforms a CoAP message into an OSCORE message before sending, and vice versa after receiving (cf. Figure 6).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HeU0he4a622SutXxvS8B_w.png" /><figcaption>Figure 6</figcaption></figure><p>The CoAP message is divided into three classes:</p><p>- Class U: unprotected part (most of the CoAP header fields and some options)</p><p>- Class I: integrity protected only (currently no header/option field)</p><p>- Class E: encrypted and integrity protected (the CoAP code, some options, and the payload)</p><p>The header/options fields of the OSCORE message include Class U elements. They are not protected and are visible by intermediary nodes, facilitating proxy operations, and they are directly mapped to the header and option fields of the OSCORE message.</p><p>Figure 7 shows the introduced “OSCORE option” has to be formatted, as shown in Figure 18. This option indicates that the CoAP message is in OSCORE form and provides the necessary elements to the receiver to correctly handle the message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRnJMT2b02u8qGUDYc9SOQ.png" /><figcaption>Figure 7</figcaption></figure><p>Opposite class U and class I, class E (payload, CoAP Code, and some options) is encrypted by the AEAD algorithm before being included in the OSCORE message. Future options could be integrity-protected only as additional data of the AEAD algorithm.</p><h4>6.2.OSCORE Security Context</h4><p>To enable secured communication with OSCORE, the client and server have to set up a shared configuration, a.k.a OSCORE context, which is the set of information elements necessary to carry out the cryptographic operations. The security context of OSCORE is composed of 3 contexts, detailed in Figure 8 and Table 1:</p><p>- Common Context: shared configuration</p><p>- Sender Context: used to protect messages to send</p><ul><li>Recipient Context: used to verify received messages</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5Ba0RmoOvJ976XcuUdwEw.png" /><figcaption>Figure 8</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KWF7Oi9TSVCupQDoiilmZg.png" /><figcaption>Table 1</figcaption></figure><p>Each endpoint has to embed the three contexts. Since OSCORE uses symmetric cryptography only, the Sender Context (used to send a message) and the Recipient Context (used to verify the message) of two endpoints are mirrored, as shown in Figure 9: the Sender Context of the client is linked to the Recipient Context of server, and vice versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QmqrgrjF_7UY9VYWR56Cw.png" /><figcaption>Figure 9</figcaption></figure><h4>6.3.Security Requirements</h4><p>The OSCORE context configuration requires setting the Master Secret, the Sender ID, and the Recipient ID. Other elements, such as Master Salt, ID Context, and algorithms, are optional. If they are not set, the OSCORE RFC defines the default values.</p><p>The Sender Key et Recipient Key are always derived from the current OSCORE configuration (i.e., Master Secret, Master Salt, ID Context, Sender/Recipient ID), as shown in Figures 10 &amp; 11.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rt61NpL2MZDjndtiCDIQIg.png" /><figcaption>Figure 10</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9KUtUB2zrKXiHC4BuVePYw.png" /><figcaption>Figure 11</figcaption></figure><p>Since OSCORE relies on symmetric-key cryptography only, the most important requirement is to ensure Sender Key uniqueness for each endpoint. Indeed, if several endpoints use the same sender key, OSCORE cannot ensure the confidentiality, integrity, or message authenticity. To ensure this unicity, the quartet (Master Secret, Master Salt, ID Context, and Sender ID) has to be unique, as shown in Figure 12.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FkzdGX1jAMyyO4_MMxhcnw.png" /><figcaption>Figure 12</figcaption></figure><p>However, OSCORE allows clients and servers to share the same Master Secret and Master Salt. Consequently, to ensure the Sender Key’s uniqueness, the couple ID Context — Sender ID has to be unique. Note that this requirement does not prohibit using the same Sender ID with multiple ID Context and vice-versa. For example, (ID Context A — Sender ID 1), (ID Context A — Sender ID 2), (ID Context B — Sender ID 3), and (ID Context C — Sender ID 3) are all unique couples. Finally, it is also possible to share Master Secret, Master Salt, and ID Context between all endpoints. In this case, the uniqueness of the Sender Key relies on the uniqueness of the Sender ID.</p><p>Note that the Sender ID’s uniqueness implicitly sets up the Receiver ID and Receiver Key’s uniqueness on the receiver side. As a reminder, the Sender ID/Key on the sender endpoint corresponds to the Receiver ID/Key on the receiver endpoint.</p><p>Another critical security requirement is related to the AEAD algorithm. The latter requires a unique key–nonce pair, meaning that a nonce has not to be used more than once for the same key. To handle this property, OSCORE uses the Sender Sequence Number to construct the nonce: The most straightforward implementation is a counter incremented before each message is sent. OSCORE provides rules to handle the unexpected Sender Sequence Number loss (e.g., reboot) by storing the latter in non-volatile memory</p><h3>7. TLS/DTLS vs OSCORE</h3><p>TLS, DTLS, and OSCORE rely on the same cryptography algorithms (e.g., AES-CCM), depending on the used cipher suites. Therefore, they intrinsically provide the same security requirements, such as confidentiality, integrity, and authenticity. However, they differ in their securing approach. TLS and DTLS encrypt the entire CoAP message, while OSCORE encrypts only some parts (e.g., payload). This implies a higher cryptography overhead of TLS/DTLS since it requires more encryption processes than OSCORE to encrypt the whole application message.</p><p>Also, since all fields are encrypted, TLS and DTLS are not optimized for proxy operation. Therefore, each intermediary has to decrypt-then-encrypt the received message before forwarding it to the next node, potentially exposing sensitive data at the proxy. This is the so-called Hop-by-Hop security scheme. In contrast, OSCORE leaves some parts of the CoAP message unencrypted, facilitating proxy operations while keeping sensitive data protected all the way to the recipient (i.e., End-to-End security scheme).</p><p>Another advantage of OSCORE is its higher compatibility compared to TLS/DTLS. TLS is used only over the TCP transport layer, while DTLS can be used over specific transport layers such as UDP or SMS. In contrast, OSCORE is an application-layer security protocol, meaning that it can be used over any transport layer and even in conjunction with TLS or DTLS.</p><p>[9] provides a fair comparison between TLS, DTLS, and OSCORE in terms of message size overhead for a plaintext of 6 bytes (and the sequence number ‘05’), shown in Table 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cY49puL32ZE9yKOzpnVmcg.png" /><figcaption>Table 2</figcaption></figure><p>Results highlight that DTLS 1.2 and TLS 1.2 have the largest overhead. Using the Generic Header Compression (6LoWPAN-GHC) allows to reduce the overhead, but their 1.3 version remains smaller. The lightweight options are DTLS 1.3 and OSCORE. It is interesting to note that even if DTLS 1.3 is smaller (only 2 bytes) than OSCORE when the Connection/Sender ID is empty, thanks to the OSCORE structure, the response overhead is fixed independently of the sequence number or Sender ID. As a consequence, OSCORE overhead becomes more profitable than DTLS 1.3 with increasing Connection/Sender ID. In a realistic scenario, these ids are seldom empty. Indeed, for DTLS, as discussed in our previous blog [5], the Connection ID is composed of, at most, a 32-byte value, and the DTLS Server generates it. Regarding OSCORE, the Sender ID is at most 7 bytes.</p><p>Also, Gunnarsson et al. [10] emphasize the lower execution overheads of OSCORE against DTLS 1.2 in terms of message size (-45% of request-response exchange), transmission time (-29%), CPU computation time (-50%), memory utilization (-15% RAM; -15% ROM) and energy consumption (-30%).</p><p>Even if previous elements show OSCORE as a lightweight alternative to TLS and DTLS. However, OSCORE is a new protocol and does not benefit from a large user community like TLS/DTLS. Today, many IoT devices contain embedded TLS libraries, facilitating implementation, whereas OSCORE must be added. The most significant limitation of OSCORE is its lack of a handshake mechanism to facilitate key exchanges and endpoint authentication: before any application data exchange, two endpoints have to authenticate each other and reach an agreement on the cryptographic algorithms used in the following communication channel.</p><p>Because OSCORE has no such procedure to set up the keying materials, both endpoints must agree on all cryptographic elements and and identities. Otherwise, no application data exchange will be possible (e.g., impossible to decrypt the message if endpoints do not use the same algorithm, same secret, etc.). One possibility is to use the TLS/DTLS handshake protocol to set up an OSCORE key exchange. However, this approach requires the implementation of TLS/DTLS handshake and OSCORE side-by-side. Also, as mentioned above, TLS and DTLS were not designed for constrained devices. Recently, efforts have paid off since the release of RFC 9528 Ephemeral Diffie-Hellman Over COSE (EDHOC) [11]. This approach, based on Diffie-Hellman, is a very compact and lightweight key exchange mechanism providing mutual authentication and perfect forward secrecy. This makes up for the lack of handshake protocol for OSCORE.</p><p>Another in-progress effort is the “OSCORE Profile of the Authentication and Authorization for Constrained Environments Framework” [12]. The principle is to generate a client’s token via an authorization server, bind the client’s cryptographic key and establish client access rights to resource server resources/data. The latter uses the token to authenticate the client, and finally, both the client and resource server use the OSCORE protocol to derive a new security context. Mutual authentication is only achieved at the end of the derivation context.</p><h3>8. Conclusion</h3><p>One of the main characteristics of an IoT device is its ability to communicate with its counterparts and servers to exchange data and for management purposes. Since communications can transport sensitive information or can be used to manage devices, security is paramount but must be addressed in a way that addresses device resource constraints (e.g., computing power, memory, energy). To this end, some dedicated communication protocols have been created, such as CoAP. For security, the well-known TLS and DTLS (for its datagram equivalent) are used. However, TLS/DTLS were not designed for IoT devices. OSCORE, is an interesting approach to provide a dedicated security protocol for constrained devices, using CoAP. This article provides an overview and comparison between TLS, DTLS, and OSCORE protocols (summarized in Table 3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyuCFHNwDHV5hVBuimAqAg.png" /><figcaption>Table 3</figcaption></figure><p>OSCORE is more performant than TLS/DTLS in terms of message size, computing, and memory overhead, leading to corresponding energy-efficiency gains. Additionally, OSCORE provides end-to-end security, optimizing proxy operations, incompatible with the hop-by-hop scheme of TLS/DTLS. In addition, thanks to its application-layer approach, OSCORE is compatible with any transport layer and transport layer security, including TLS/DTLS. The main drawback of OSCORE was its lack of handshake protocol, but the release of EDHOC RFC in March 2024 fills the gap and should increase the OSCORE spread out. EDHOC will be the subject of a future article.</p><p>Join us on GitHub and let’s discuss: <a href="https://github.com/ioterop">https://github.com/ioterop</a></p><p><a href="http://www.ioterop.com/">www.ioterop.com</a></p><h4>References</h4><p><em>[1] International Telecommunication Union (ITU), “Termes et définitions applicables à l’Internet des objets,” Jul. 2012.</em></p><p><em>[2] This Bluetooth Attack Can Steal a Tesla Model X in Minutes (https://www.wired.com/story/tesla-model-x-hack-bluetooth/)</em></p><p><em>[3] T. Dierks and E. Rescorla, “TLS 1.2 — RFC 5246.” 2008 (https://datatracker.ietf.org/doc/html/rfc5246)</em></p><p><em>[4] E. Rescorla and N. Modadugu, “DTLS 1.2 — RFC 6347.” 2012 (https://datatracker.ietf.org/doc/html/rfc6347)</em></p><p><em>[5] IoTerop Blog: Connection-less Transport Management for Long Run Sessions (https://medium.com/@IoTerop/connection-less-transport-management-for-long-run-sessions-12be69594533)</em></p><p><em>[6] IoTerop Blog: Building a LwM2M Client with a Focus on Energy Conservation (https://medium.com/@IoTerop/building-a-lwm2m-client-with-a-focus-on-energy-conservation-d5d871061ff0)</em></p><p><em>[7] Object Security for Constrained RESTful Environments, RFC 8613 (https://datatracker.ietf.org/doc/html/rfc8613)</em></p><p><em>[8] Z. Shelby, K. Hartke, and C. Bormann, “The Constrained Application Protocol (CoAP),” RFC Editor,</em></p><p><em>RFC7252, Jun. 2014. doi: 10.17487/rfc7252. (https://datatracker.ietf.org/doc/html/rfc7252)</em></p><p><em>[9] J. Mattsson, “Message Size Overhead of CoAP Security Protocols.” 2017, [Online]. Available: </em><a href="https://tools.ietf.org/id/draft-mattsson-core-security-overhead-02.html."><em>https://tools.ietf.org/id/draft-mattsson-core-security-overhead-02.html.</em></a></p><p><em>[10] Gunnarsson, Martin &amp; Brorsson, Joakim &amp; Palombini, Francesca &amp; Seitz, Ludwig &amp; Tiloca, Marco. (2021). Evaluating the performance of the OSCORE security protocol in constrained IoT environments. Internet of Things. 13. 100333. 10.1016/j.iot.2020.100333.</em></p><p><em>[11] G. Selander, J. Mattsson, F. Palombini, “RFC 9528 — Ephemeral Diffie-Hellman Over COSE (EDHOC)”, [Online]. Available: </em><a href="https://datatracker.ietf.org/doc/rfc9528/"><em>https://datatracker.ietf.org/doc/rfc9528/</em></a></p><p><em>[12] F. Palombini, L. Seitz, G. Selander, M. Gunnarsson, “OSCORE Profile of the Authentication and Authorization for Constrained Environments Framework — draft-ietf-ace-oscore-profile-19” [Online]. Available: </em><a href="https://www.ietf.org/archive/id/draft-ietf-ace-oscore-profile-19.html"><em>https://www.ietf.org/archive/id/draft-ietf-ace-oscore-profile-19.html</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4498cf3aa50a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using LwM2M for Remote SIM Provisioning on IoT devices]]></title>
            <link>https://medium.com/@IoTerop/using-lwm2m-for-remote-sim-provisioning-on-iot-devices-3b476074455b?source=rss-c76b7550a85a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b476074455b</guid>
            <category><![CDATA[esim]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[connectivity]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[cellular]]></category>
            <dc:creator><![CDATA[IOTEROP]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 11:00:03 GMT</pubDate>
            <atom:updated>2024-04-29T14:22:09.445Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*iIX9w6O8urh-FYN-epC4TA.png" /></figure><p><em>By Stephane Quetglas Mobile Connectivity Solutions Marketing Director at Thales, Loïc Bonvarlet, Senior Vice President Product Marketing at Kigen and Christophe Serrano, Head of Product at IoTerop</em></p><p><strong>Low power Cellular IoT is the preferred LPWAN for massive IoT. But vendor lock-in and the requirement for multiple MNOs for multinational deployments make SIM provisioning challenging for enterprises. LwM2M device management promises an efficient, standardized solution.</strong></p><p>Low Power Cellular IoT is gaining traction as the <a href="https://ioterop.com/blog/iot-industry-converges-on-cellular-as-the-wireless-platform-of-the-future">preferred low power wireless area network</a> (LPWAN) technology for <a href="https://ioterop.com/white-papers/managing-massive-iot">massive IoT</a> — a network supporting applications that require a huge volume and density of devices to provide wide coverage for applications such as smart meters, <a href="https://ioterop.com/customer-case-studies/managing-smart-street-lights">smart streetlights</a>, and <a href="https://ioterop.com/case-studies/shipping-container-tracking">cargo asset trackers</a>.</p><p>Cellular IoT leverages the same network all smartphones use every day to connect massive IoT devices to the cloud. The technology can connect over kilometers, supports a high density of IoT devices, and can operate from modest power sources. Other key advantages include Internet Protocol (IP) interoperability which enables a bidirectional link between end-devices and the cloud without the need for expensive and complex routers or gateways. Further advantages include future proofing, scalability, security, and high quality of service (QoS).</p><p>Narrow band (NB)-IoT and LTE category M1 (LTE-M) are the two underlying technologies supporting low power cellular IoT. They are different technologies, although some commercial low power cellular IoT modems can support both simultaneously. The selection between NB-IoT and LTE-M is largely determined by region, as well as the data throughput and latency requirements of each use case.</p><p>However, despite its clear advantages there’s a major challenge threatening to stall cellular-based massive IoT rollouts. Connectivity of cellular IoT devices to the network requires the use of a Subscriber Identity Module (SIM) — a combination of secure software and hardware that identifies and authenticates devices that wish to access the network. Initially the provisioning of connectivity profiles in eSIM has been created for machine-to-machine use cases such as managing connectivity in cars and designed to provide a high level of control to mobile network operators (MNOs). But this arrangement is ill-suited to enterprises wishing to connect millions of (potentially resource-constrained) devices to a cellular network for massive IoT applications.</p><p>“Enterprises tells us that although things have improved, there are still limitations when using the MNO-oriented SIM for the low power cellular IoT provisioning processes. Worse still, the current process lacks compatibility with NB-IoT,” explains Stephane Quetglas, Mobile Connectivity Solutions Marketing Director with Thales, a global technology provider. “But now a solution is near. A new eSIM for IoT standard is nearing adoption and is far more enterprise oriented, compatible with NB-IoT, and destined to increase business agility.”</p><p>The solution Quetglas cites comprises: eSIMs/integrated-SIMs (iSIMs); Remote SIM Provisioning (RSP); a new eSIM standard (SGP.32) architecture that moves SIM provisioning away from “push” (machine-to-machine (M2M)) to adapt to a “pull” (consumer) model for IoT devices; and Lightweight M2M (LwM2M), an interoperable industry standard for massive IoT device management. This technical article explains how this will work.</p><p><strong>From SIMs to eSIMs and iSIMs</strong></p><p>Cellular networks use regulated spectrum allocations. This brings robust, reliable service, security, and global coverage. But it also brings a degree of complexity because connection to the network is only granted to individually identified and authenticated wireless devices. As mobile telephony took off, the industry adopted SIMs for identification and authentication. The SIM was carried on a Universal Integrated Circuit Card (UICC), a compact plastic smart card that plugged into the mobile handset. The SIM contained information such as a unique serial number, international mobile subscriber identity (IMSI) number, security authentication and ciphering information, a list of the services the user has access to, passwords, and other information.</p><p>With the handset activated, the cellular network interrogates the SIM and once satisfied with its identity and authentication, it grants access to the network. Removing the SIM from the handset and plugging it into another device repeats the process and allows that device access to the network while disconnecting the original handset.</p><p>SIM technology has rapidly developed. Advances have gradually shrunk the device and transformed it from a removable UICC to a component that is forever soldered directly to the electronic assembly of the cellular device — an eSIM or “eUICC”. An even later development has resulted in the iSIM, a dedicated System-on-Chip (SoC) secure enclave and an eUICC OS that forms part of the mobile device’s CPU. (Figure 1.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*oQg8fZWtDZdyytp6Jzug9g.png" /><figcaption><em>Figure 1: SIMs have migrated from a UICC to a soldered component (eSIM) and now to an integrated part of the mobile device’s silicon (iSIM). (Image courtesy: Thales.)</em></figcaption></figure><p>“eSIMs and iSIMs are becoming popular for IoT devices because they eliminate the need to plug in a discrete UICC into each end-device. That’s impractical when you are connecting millions of products to the cellular network,” says Waseem Haider, Principal Analyst, IoT, Enterprise Research with TechInsights, a semiconductor intelligence firm. “It also makes the manufacturing process easier. The supplier can just add a component on to the board or CPU rather than having to manually put SIM cards into slots. Moreover, there is no need to change a SIM card when switching connectivity providers.”</p><p>Haider says that of the two billion cellular IoT connections made in 2022, 600 million were performed by eSIM or iSIM. That number is set to boom as massive IoT rolls out.</p><p>There’s a major difference between the process of connecting a smartphone to a cellular network and an IoT end-product. In the first instance, the smartphone will be in the hands of a user, and the process is controlled by them “pulling” the instructions for provisioning, often using a QR code or an alternative internet link. (The process is detailed in the GSMA SGP .21/.22 standard.) Such a method is not efficient for a fleet of IoT devices and requires end-user intervention. In the case of an M2M or IoT device, an end-user will rarely be present, so the provisioning is “pushed” from the MNO to the remote device (GSMA SGP .01/.02 standard) using RSP.</p><p>“More than 300 million devices of the 2 billion Cellular IoT connections were Remote SIM Provisioning (RSP) capable in 2022, meaning that these devices are using the RSP capability to change MNO profile actively,” says Haider. “The relevant GSMA standard facilitates provisioning using over-the-air commands.”</p><p>Although the M2M RSP overcomes the need for a human operator when joining a cellular network, it is currently not ideal for massive IoT. For one, the standard is really designed for the convenience of MNOs rather than massive IoT service providers. And second, and perhaps even more crucial, the process is not compatible with NB-IoT, one of the leading low power cellular IoT technologies.</p><p>The GSMA is addressing this problem with the introduction of GSMA SGP.31/.32. The standard is specifically designed to overcome the challenges of network provisioning for massive IoT: it is well suited to the provisioning of resource-constrained devices; it is fully compatible with NB-IoT and LTE-M; and it makes it much easier for enterprises to control the process.</p><p>GSMA SGP.31/.32 includes some functionality from SGP .21/.22 including: IoT Profile Assistant (IPA) — which provides functionality such as profile download, discovery service, and notification handling; a rollback fallback mechanism; remote IoT device network profile triggering; and simpler integration and reduced costs for massive IoT deployments. The IPA can be implemented directly in the eSIM to further simplify the adoption of cellular for enterprises, removing the need for additional integration and testing work.</p><p>“SGP.31/.32 is an evolution rather that a revolution and encompasses the best parts of the original consumer and M2M standards, while learning from the shortcomings of those standards when attempting to apply them to LPWANs,” says Loic Bonvarlet, SVP Product and Marketing with Kigen, a supplier of secure SIM technology.</p><p>The tests and compliance specifications for GSMA SGP .31/.32 are expected to be finished by 2024 with commercial solutions expected to be launched some time in 2025. (Figure 2.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*YFT8NffbUdW02loWQE2s6w.png" /><figcaption><em>Figure 2: The GSMA SGP.31/.32 IoT SIM standard builds on the success of consumer and M2M models but adds LPWAN support and is more convenient for massive IoT enterprises. (Image courtesy: GSMA (Architecture) &amp; TechInsights’ Telecoms Strategies Group.)</em></figcaption></figure><p>“With the implementation of GSMA SGP .31/.32 we expect that there will be 36% RSP-capable connections by 2030 from 6.6 billion of total Cellular IoT Installed Base”,” says TechInsights’ Waseem Haider. (Figure 3.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*CWcn7-zlkn5ysh9VIHPWrQ.png" /><figcaption><em>Figure 3: Cellular IoT installed base forecast with percentage of RSP-capable connections, 2022 to 2030. (Image courtesy: Techinsights’ Telecoms Strategies Group.)</em></figcaption></figure><p><strong>Why LwM2M is the best solution for RSP</strong></p><p>The introduction of GSMA SGP .31/.32 hands back control of cellular device provisioning to enterprises, but they still require a simple and reliable mechanism to trigger the process, especially when those devices are remotely situated.</p><p>“When you consider it closely, it’s clear that eSIMs and iSIMs are now integral parts of the IoT device rather than a separate plug-in entity. It therefore seems a natural step to consider provisioning of the SIM as part of the overall device management software task,” says Christophe Serrano, Head of Product at IoTerop. “That simplifies the task for the enterprise as the workflow is abstracted by the device management software provider, a service they control, rather than the MNO, one they don’t. It also helps the enterprise avoid MNO lock-in contracts.</p><p>“And soon, things will get even better with a ‘rule engine’ that will allow device management software to mix an eSIM remote manager (eIM) with device management capabilities,” adds Serrano. “We will then be able to define criteria to dynamically allocate profiles — depending on geography, coverage, signal strength, and the preference for a given MNO.”</p><p>An ideal candidate for SIM provisioning as part of an overall device management service is LwM2M. The protocol is an <a href="https://ioterop.com/blog/why-interoperability-is-more-than-just-a-buzzword">interoperable</a> industry standard ideally suited to the <a href="https://ioterop.com/blog/why-do-we-need-massive-iot-device-management">management of resource-constrained IoT devices</a> as well as more powerful and complex IoT devices including routers and gateways. It was created by the Open Mobile Alliance (OMA) to bring together existing standards — that each contributed to a full solution for device management — into a single, cohesive common service layer. The result is a solution that reduces IoT device management complexity and boosts security while supporting the scalability and security demanded by massive IoT.</p><p>IoTerop has developed a highly optimized commercial implementation of a LwM2M stack called <a href="https://ioterop.com/iowa">IOWA</a>. IOWA is fully compliant with the LwM2M specifications, has passed LwM2M MNO certification (for example, the certification programs of AT&amp;T and Verizon), and features a full implementation of LwM2M Version 1.0, 1.1, and 1.2 within its streamlined stack. IOWA is the perfect complement to <a href="https://ioterop.com/alaska">ALASKA</a>, IoTerop’s device management platform that enables data collection, remote configuration, security updates, firmware updates, and device monitoring. (Figure 4.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*59r1KNQ-1x7XFaHNnNCbAg.png" /><figcaption><em>Figure 4: ALASKA and IOWA use LwM2M for comprehensive device management. Shown here is an example of remote management of a water meter. (Image courtesy: IoTerop.)</em></figcaption></figure><p>In addition to the other device management task it handles with ease, LwM2M is particularly suited to eSIM and iSIM profile management. LwM2M transports the messages required to perform RSP back and forth. That allows for flexibility in RSP implementations; for example, using IoTerop’s IOWA and ALASKA, it would be possible to pause and resume an RSP process if the network is poor, avoiding having to restart the operation from scratch. This mirrors what happens when LwM2M is used for over-the-air updates.</p><p>Process interoperability is ensured through pre-defined RSP and other SIM operations. The protocol’s remote provisioning capability is a critical feature that allows devices to seamlessly switch between various operators or networks and perform configurations over-the-air. This flexibility is essential, not only when considering the device’s location, but also for specific application requirements, such as the features offered by the cellular network at each location.</p><p>It is the Subscription Manager Data Preparation + (SMDP+) that stores network profiles and makes them available for download. ALASKA and IOWA handle the profile management by facilitating protocol interactions between the SMDP+ and the eSIM/iSIM. Better yet, OMA SpecWorks already issued a LwM2M Object (representing a collection of device properties, organized in a logical fashion to share a unified data model between devices and managing platforms; in this case Object ID 3443) to handle IoT RSP. (Figure 5.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t9Oh5_HgwTAHmxPX2aJL2w.png" /><figcaption><em>Figure 5: ALASKA and IOWA are well suited to cellular IoT remote SIM provisioning by facilitating protocol interactions between the SMDP+ and the eSIM/iSIM. (Image courtesy: IoTerop.)</em></figcaption></figure><p><strong>Key benefits of LwM2M for RSP</strong></p><p>Beyond its other device management capabilities, LwM2M includes many other features that make it ideally suited to RSP. Key benefits include:</p><ul><li><strong>Unified management interface</strong>: LwM2M provides a unified management interface for application, device, communication, and SIM management, ensuring consistent user experience and reducing integration challenges.</li><li><strong>Scalability</strong>: LwM2M is scalable, catering to both small and large IoT deployments. By utilizing it for RSP, enterprises can ensure that as their IoT deployments rapidly grow, eSIM/iSIM management won’t stall rollout.</li><li><strong>Reduced complexity</strong>: By centralizing eSIM/iSIM operations within the LwM2M framework, organizations can reduce the complexity associated with handling multiple systems or protocols. They can also leverage an existing communication channel rather than having to build a new one.</li><li><strong>Improved Security</strong>: LwM2M has inherent protection features that can be extended to eSIM/iSIM management. This ensures that operations such as profile switching are carried out securely.</li><li><strong>Cost efficiency</strong>: By using LwM2M for RSP, enterprises can avoid additional capital and operational costs from data usage, power consumption, and the investment in separate systems for RSP. Note that SMDP+, eIM, and IPA will still be required.</li><li><strong>Streamlined troubleshooting</strong>: With a unified system for RSP, diagnosing and resolving issues becomes more efficient. Service providers can pinpoint problems faster and apply solutions consistently across devices and SIM profiles.</li><li><strong>Future proofing</strong>: By integrating eSIM/iSIM management with LwM2M, it ensures that the system remains relevant and adaptable to future changes as the IoT rapidly expands.</li></ul><p><strong>What’s next?</strong></p><p>LwM2M is already a proven commercial solution for device management of utility applications such as smart meters and smart streetlights. That makes it the prime candidate for general massive IoT device management. And now cellular IoT, eSIMs and iSIMs, SGP.31/.32 are joining the protocol to offer an efficient, simple, and secure way to orchestrate connectivity for millions of IoT devices. The technologies will hand control of the SIM provisioning operation from MNO to enterprise. That enhances flexibility and convenience, and lowers costs.</p><p>But there is still some work to do. The tests and compliance specifications for GSMA SGP .31/.32 won’t be finished until next year and commercial solutions won’t hit the market until 2025. And it’s important to think of the best way to implement these new technologies before they hit the mainstream. For example, Kigen’s Bonvarlet, says: “It’s important to anticipate as much as possible and set things up at the point of device manufacturing because even with RSP, field management will still be bandwidth and energy costly for cost sensitive and single charge battery operated IoT devices.”</p><p>Key players in the RSP segment — companies like IoTerop, Kigen, and Thales — are working together today to ensure that the inevitable engineering wrinkles are ironed out before LwM2M-based RSP’s widespread adoption. In doing so, they are ensuring that massive IoT will fulfill its potential much faster than it might otherwise have done.</p><p>Join us on GitHub and let’s discuss: <a href="https://github.com/ioterop">https://github.com/ioterop</a></p><p><a href="http://www.ioterop.com/">www.ioterop.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b476074455b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a LwM2M Client with a Focus on Energy Conservation]]></title>
            <link>https://medium.com/@IoTerop/building-a-lwm2m-client-with-a-focus-on-energy-conservation-d5d871061ff0?source=rss-c76b7550a85a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5d871061ff0</guid>
            <category><![CDATA[device-management]]></category>
            <category><![CDATA[energy-efficiency]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[nb-iot]]></category>
            <category><![CDATA[lwm2m]]></category>
            <dc:creator><![CDATA[IOTEROP]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 11:00:53 GMT</pubDate>
            <atom:updated>2024-04-29T14:23:05.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*OUqAuQsVIjY9rA9jXRe-PA.png" /></figure><p><em>By Patrick Porlan, IoTerop Senior Software Engineer</em></p><p>Designing a radio connected device operating on battery power means balancing several aspects that often conflict. Frequent data reporting, real time event notifications, and a rich feature set are convenient features to include, but they can be difficult to reconcile with years of operation on a small battery.</p><p>A central design decision involves the protocol used to report data and remotely control the device. One good option is Lightweight Machine to Machine (LwM2M), built on CoAP. For an embedded system designer building a low-cost LwM2M client, a complete system including the battery, processor, modem, communication stacks, and application need to be independently efficient and thoughtfully integrated for optimal battery life.</p><h4>Threading</h4><p>One of the first architecture choices to settle is whether to use a RTOS, or multiple execution threads. Threads are useful to lower the complexity of large applications, and to distribute CPU resources among concurrent tasks, but they may not be worth including in the context of a closed-off system controlling a small set of sensors. Using threads increases memory consumption (a 1 KB processor stack per thread is typical), and adds concurrency issues.</p><p>Nevertheless, the alternative finite state automaton model also has drawbacks, as it can be fragile and difficult to maintain. In all cases, the overall code execution schedule should be clear from the design stage. LwM2M itself does not mandate the use of a rich TCP/IP stack and can usually rely on a single thread and a single modem-provided socket for all its needs (data upload, device management, firmware update, etc.), so it does not require a RTOS.</p><h4>Spotty communication</h4><p>The key to reducing power usage lies in reducing and condensing the times when a device is actively communicating. It is best to set the device to sleep when its awake periods are unneeded, and only talk to a management server a few times a day.</p><p>While it is possible to build such a system using TCP, this streaming protocol bears several aspects that impact a device’s power budget:</p><ul><li>Establishing a TCP connection, especially if secured using TLS, is relatively costly</li><li>Maintaining the connection requires sending keep-alive messages periodically, as well as being to reply to server-initiated keep alive probes</li><li>It can incur significant memory usage due to its dynamic aspect</li></ul><p>UDP is usually more desirable since:</p><ul><li>It requires no connection</li><li>It does not require periodic transmissions (keep alive probes)</li></ul><p>UDP datagrams can reach their destination in a different order than they were sent, or even be dropped. Another downside is that network UDP routes are dropped quicker than TCP routes. Once this happens, the server is unable to reach the device until the device itself sends data again.</p><p>These downsides are also known to CoAP, which associate tokens to requests and supports confirmation and retransmission, as well as LwM2M, which handles unreachable devices through the queue mode mechanism. The UDP routing problem is aligned with NB-IoT power saving mechanisms, which will turn off the radio quickly after transmission, rendering the device offline anyway.</p><h4>PSM</h4><p>NB-IoT supports a Power Saving Mode that is basically a sleep mode during which the device is still attached to a cell tower, but is offline. Data sent through the radio network to the device won’t reach it. As soon as the device wakes up, either periodically due to the timers negotiated while registering to the tower or because it needs to communicate, a new “connected” period starts. While connected, the device is available for incoming traffic reception. The duration of this window is negotiated with the cell tower and is best kept at a few seconds.</p><p>Power consumed while in idle mode is thousands less than while transmitting, and a small fraction of the current needed while connected, even without sending or receiving data. The connected window itself can be partitioned so the device is only reachable during small intervals, to save power: this is the DRX mechanism, which stands for Discontinuous Reception. Data sent to the device is delivered with a predictable delay, but not discarded by the network.</p><p>Such a cycle starts immediately after the device stops transmitting. A well-designed application can align its transmissions with the programmed radio timers, or restrict its radio activity itself to the connected periods boundaries, which are reported by the modem to the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RprhulZWtc8BLXgva7gG4g.png" /></figure><h4>Latency</h4><p>NB-IoT latencies can easily reach ~10s and its throughput is in the order of kilobytes per second, even under ideal conditions. This needs to be considered when selecting the CoAP timeouts and PSM parameters values, and accounted for in the applications built on top of LwM2M / NB-IoT.</p><p>This also means that the power budget imposes a cap on the total amount of data that can be exchanged between device and server!</p><p>LwM2M offers several mechanisms to reduce the number of frames exchanged.</p><h4>Bulk transfer</h4><p>Coalescing several updates and sending them as a large packet rather than one by one reduces total latency and improves throughput. This can be done using the LwM2M 1.1 data push operation (a composite operation in nature) or by temporarily locking the transmission of notifications if the application permits. It should be noted that heavy usage of the modem, with several large frames transmitted over a short time span, needs to be supported by the underlying battery.</p><h4>Peak power consumption</h4><p>Batteries with low self-discharge are limited in the amount of power they can provide at once. They won’t be able to sustain prolonged radio usage as used by a firmware update session, and either need to be coupled to a capacitor, or their characteristics taken into account by all elements of the firmware stack to limit peak power usage. Testing should cover good as well as bad network conditions: NB-IoT power usage can increase markedly under degraded conditions (long distance, interference), without even taking packet loss and retransmissions into account.</p><h4>The “turn on modem, transmit, then turn off” method</h4><p>Instead of dealing with all these questions, it is easier to simply turn off the modem when not needed. While conceptually simple, this technique usually yields higher average power consumption than PSM, due to complexity of reattaching to the network. The typical power draw in PSM idle is a few μA, which allows for years of operation on a small battery.</p><h4>RX path</h4><p>Particular attention should be devoted to the handling of the radio reception window. CAT-NB1 and its newer NB2 (3GPP rel 14, higher bandwidth) iteration are half duplex. The modem can be seen as generally alternating between transmission, reception, paging (checking if the communication tower holds incoming data), and idle mode.</p><p>Several parameters are negotiated when the modem attaches to the tower. The Tracking Area Update timer controls the interval between the connected/idle cycle. The active cycle contains several paging windows, whose duration can be configured. The active time timer controls the number of seconds during which the RX path remains open after a transmission. The tower has the ultimate say on the values that get used. The modem communicates them to the application using the CEREG notification.</p><p>Having the shortest possible RX windows is a good way to save power. It works well with LwM2M provided a) the device requests queue mode when registering to the LwM2M server, b) the application itself is tolerant of this scheme and c) NB-IoT latencies, which easily go to 10 seconds under poor radio coverage, are supported.</p><h4>Queue mode</h4><p>LwM2M servers will buffer any outgoing traffic for clients registering with the Q mode indication, and send everything that has been stored once the client performs a registration update. The delay between registration updates is therefore an important consideration for the application designer. It’s also possible for the client to buffer outgoing notifications until the next outgoing traffic time slot, as an optimization.</p><h4>RAI</h4><p>NB-IoT also supports unilateral shutdown of the RX path through the Release Assistance Indication mechanism, which may help save additional milliwatts. This means there is no need for paging after a non-confirmable data push, so the application can tell the modem that it does not expect any incoming traffic for the foreseeable future. This should be used with care, though, as it may interfere with reception of ACK for confirmable CoAP messages, queued LwM2M commands following a registration update, a DTLS handshake, or a firmware update session, for example.</p><h4>Encryption options</h4><p>Using DTLS, it is possible to cryptographically secure the link between the device and the server. However, this may not be the best choice energy-wise. Support for the connection ID extension ought to be used to guarantee that the link can be used for a long time after the initial (relatively costly) handshake completes, even in the case of a change of IP address. Likewise, using the Pre-Shared Key mechanism is going to be less energy-intensive than using certificates. Using CoAP level authentication and encryption (OSCORE) is a better choice, as it leads to smaller frames on average.</p><h4>Error management</h4><p>Transitory problems (such as a power outage affecting the radio network) can happen. It’s important to react to them thoughtfully, in a way that won’t deplete the battery. This needs to be considered in the design phase of the product, even if it is difficult to test. It’s worth having a fallback mechanism, such as reverting to the LwM2M bootstrap phase or factory settings after a while.</p><h3>Conclusion</h3><p>Besides a careful selection of the technologies on board, getting an embedded device to run for years on battery requires a holistic understanding of the entire hardware and software, as well as painstaking attention to detail. Understanding precisely what the system does and when is key.</p><p>Join us on GitHub and let’s discuss: <a href="https://github.com/ioterop">https://github.com/ioterop</a></p><p><a href="http://www.ioterop.com/">www.ioterop.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5d871061ff0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connection-less Transport Management for Long Run Sessions]]></title>
            <link>https://medium.com/@IoTerop/connection-less-transport-management-for-long-run-sessions-12be69594533?source=rss-c76b7550a85a------2</link>
            <guid isPermaLink="false">https://medium.com/p/12be69594533</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[device-management]]></category>
            <category><![CDATA[coap]]></category>
            <category><![CDATA[lwm2m]]></category>
            <dc:creator><![CDATA[IOTEROP]]></dc:creator>
            <pubDate>Mon, 19 Feb 2024 16:07:56 GMT</pubDate>
            <atom:updated>2024-04-29T14:27:12.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-K6vgo4dqexJDcjfviL_A.png" /></figure><p><em>By Jeremy Audiger, IoTerop Principal Software Engineer</em></p><p>Have you ever wondered why the connection between your device and your server seems intermittently disrupted? This can be frustrating at times, as lost connections reduce overall solution efficiency such as battery lifespan and cloud connection costs and can have multiple causes. However, this behavior is often perfectly normal, and it is due to the way Network Address Translation (NAT) works. NAT typically maintains an internal table (called a “NAT table”) to map your device’s internal IP to the external IP address of your router. The NAT table is used to route the response from one side to the other.</p><p>Like all systems in the world, devices are built on physical hardware, and hardware has its limitations. NAT tables can’t be infinite, and can therefore struggle to maintain the mappings over a long period of time. A timeout exists to clean the mappings stored to help NAT effectively manage their RAM/CPU consumption. Referring to the [<a href="https://www.rfc-editor.org/rfc/rfc4787.html#page-12">RFC 4787 (chapter 4.3. Mapping Refresh)</a>], this timeout is typically set to 2 minutes and can vary depending on the NAT implementation.</p><blockquote>NAT mapping timeout implementations vary, but include the timer’s value and the way the mapping timer is refreshed to keep the mapping alive.</blockquote><blockquote>The mapping timer is defined as the time a mapping will stay active without packets traversing the NAT. There is great variation in the values used by different NATs.</blockquote><blockquote>REQ-5: A NAT UDP mapping timer MUST NOT expire in less than two minutes, unless REQ-5a applies.</blockquote><p>If your device or server fails to send any packet during the timeout period, its corresponding entry in the NAT table will be marked for cleaning. This is why the link can be broken over time or after a long period of inactivity.</p><h3><strong>Solutions</strong></h3><p>Now that the problem has been identified, how can we solve it? Let’s go over a few options in detail in the following section.</p><h4><strong>Raw UDP</strong></h4><p>User Datagram Protocol (UDP) is a connection-less protocol, meaning that peers using this protocol do not maintain a continuous connection. In this sense, UDP can be considered a stateless protocol. On the other hand, Transmission Control Protocol (TCP) is a connection-oriented protocol. Peers using this protocol maintain a connection between each other through various messages.</p><p>By default, UDP does not provide a mechanism to maintain the connection. However, several simple to complex mechanisms do exist. If we take raw UDP (meaning sending packets without doing anything on top of it), the only way to maintain the connection is to send packets periodically in the time-frame of the NAT table timeout (more or less, 2 minutes). This mechanism is called “keep-alive,” and can be seen as a ping-pong between the different protagonists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*eazCeMWFuzLYZ161pLvuaQ.png" /></figure><p>The drawback of this method is the consumption of the bandwidth. If you send a packet every 2 minutes, it means that you will consume 30 packets per hour, 720 packets per day, 21,600 packets per month, and so on. The number of packets sent can grow very quickly and can be a problem for an application running on constrained networks.</p><p>Let’s take a real-world example from the Internet of Things: IoT devices are constrained, and rely on less-than-perfect networks. The latencies can be high while the throughput is often low. Due to the nature of UDP, the packets could be lost, or simply take time to be delivered to the other side. If you send a packet every 2 minutes, and one of the packets is dropped by the network, the connection could end up being closed by the NAT table. This happens frequently on constrained networks such as LoRaWAN, Sigfox, NB-IoT, and so on.</p><p>Now, let’s see how this problem is handled by a well-known IoT protocol: the Lightweight Machine to Machine (LwM2M) protocol.</p><p>LwM2M provides a registration mechanism to maintain a shared context on a LwM2M Client and a LwM2M Server. The registration is based on the concept of lifetime, expressed in seconds. The lifetime is a value sent by the LwM2M Client to the LwM2M Server, and represents the time that the registration context is valid. To maintain this context, the LwM2M Client needs to send a registration message to the LwM2M Server before the end of the lifetime. If the LwM2M Client does not send a registration message before the end of the lifetime, the LwM2M Server will consider the LwM2M Client as deregistered. Each time the LwM2M Server receives a registration update message, it will reset the timer of the lifetime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*kUlgFsTGfc-wPA4MuJTOIw.png" /></figure><p>To prevent the problem seen with UDP without any other mechanism, the lifetime is usually set to a value that is lower than the NAT table timeout. However, this is not acceptable for reasons explained above.</p><p>Let’s take an example with real messages exchanged between a LwM2M Client and a LwM2M Server:</p><p>1. The LwM2M Client sends a registration message to the LwM2M Server:</p><ul><li><em>POST /rd?ep=urn:imei:1234567890&amp;lt=120&amp;lwm2m=1.1&amp;b=U</em></li><li>Object lists: <em>&lt;/1/0&gt;;ver=1.1,&lt;/3/0&gt;;ver=1.1,&lt;/5/0&gt;,&lt;/3303/0&gt;</em></li></ul><p>2. The LwM2M Server sends an acknowledgement message to the LwM2M Client:</p><ul><li><em>2.01 Created</em></li><li>Location-Path: <em>&lt;/rd/1234&gt;</em></li></ul><p>3. The LwM2M Client sends a registration update message to the LwM2M Server:</p><ul><li><em>PUT /rd/1234</em></li></ul><p>4. The LwM2M Server sends an acknowledgement message to the LwM2M Client:</p><ul><li><em>2.04 Changed</em></li></ul><p>We won’t go deep into the details of the messages sequence, but we will focus on the exchange cost in terms of bandwidth: if a LwM2M Client sends a registration update message every 2 minutes, and the LwM2M Server acknowledges the message, it means in this example that we’ll have 13 bytes sent by the LwM2M Client, and 5 bytes sent by the LwM2M Server. The total is 18 bytes. The first exchange is intentionally omitted, since it could be considered as a sort of “upfront cost” and does not contribute to the maintenance of the connection in the long run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*w557v79KL3YeU0iKfgA9-A.png" /></figure><p>But what happens if the LwM2M Client does not send a registration update before the mapping on the NAT table expires? If the lifetime is set, for example, to 1 hour, the LwM2M Client does not send a registration update every 2 minutes. The only real impact in this scenario is that the LwM2M Server will not be able to send any messages to the LwM2M Client after the expiration of the NAT table mapping. The LwM2M Client will first need to send a registration message to the LwM2M Server to let the server associate the correct UDP peer with its LwM2M registration context. From there, the server will have a time-frame of 2 minutes to send messages. Apart from that, the LwM2M Client will not notice that much of impact. The only requirement to resume the communication with the server is to send a registration message after the expiration of the NAT table mapping.</p><h4><strong>UDP + DTLS</strong></h4><p>Datagram Transport Layer Security (DTLS) is a protocol that is based on UDP. It provides the same security guarantees as TLS. The protocol is defined in the [<a href="https://www.rfc-editor.org/rfc/rfc6347.html">RFC 6347</a>].</p><p>When a peer wants to establish an encrypted connection with another peer, they need to perform a handshake to negotiate the security parameters. The handshake is composed of the following messages (not exhaustive, since it can depend on the security parameters negotiated):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*-3o66bJaCpYnTiMuT_j9cg.png" /></figure><p>Once a DTLS session is established, the peers can send encrypted messages to each other. A session is closed when one of the peers sends a close notify message.</p><p>The DTLS server associates a DTLS client through its IP address and port. It maintains a DTLS session per DTLS client, meaning the client needs to always use the same IP address and port to communicate with the server. If the IP address or port changes, the DTLS server will not be able to associate the DTLS client with its DTLS session. When the server receives a message from an unknown DTLS client, it works on the assumption that this message is a client “hello” message. If this is not the case, the server will either drop the message silently, or emit an alert message before closing the session.</p><p>One of the mechanisms to resume a security session is called <strong>session resumption</strong>, which allows a client and server to establish a new secure session by reusing the security parameters from a previous session. This can significantly reduce the overhead of establishing a new session, as it avoids the need for a full handshake. Instead, the client sends a session ID to the server, and if the server recognizes the session ID and is willing to reuse the session parameters, it can resume the session:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*8VU9SVUiachUOUh2Vx6CkA.png" /></figure><p>Compared to the previous handshake, the client does not send a client key exchange message, and the server does not send a server “hello done” message.</p><p>It is recommended that the DTLS Client be the one initiating the session resumption mechanism after a long period of inactivity (meaning no communication between the peers). Such mechanisms can’t be triggered by the DTLS Server. The latter can only accept or reject the incoming session resumption requests. It’s only then that the DTLS Client can re-establish the session.</p><p>Finally, this mechanism must be used by the DTLS client to inform the DTLS server that the IP address and/or port has changed. It’s the only way to associate the correct IP address and port couple to the DTLS session for the server.</p><p>By reusing the previous example from <strong>Raw UDP</strong>, nothing much has changed for the LwM2M Client. Instead of just sending a registration update message, the client first needs to initiate a session resumption mechanism before sending its registration update message. If no messages are sent and the NAT table mapping is cleaned, the server will not be able to send outbound messages to the client, and will therefore have the same consequences as before. The only difference is that instead of “only” sending 18 bytes (i.e. the registration update message and the acknowledgement of the message), the Client will need to send:</p><ul><li>Client Hello with Session ID (132 bytes)</li><li>Client Hello with Session ID + Cookie (164 bytes): optional step</li><li>Change Cipher Spec (14 bytes)</li><li>Encrypted Handshake Message (53 bytes)</li><li>Registration Update Message (13 bytes without encryption overhead)</li></ul><p>=&gt; Total of 363 bytes</p><p>And the Server:</p><ul><li>Hello Verify Request (60 bytes): optional step</li><li>Server Hello (111 bytes)</li><li>Change Cipher Spec (14 bytes)</li><li>Encrypted Handshake Message (53 bytes)</li><li>Registration Update Message Acknowledgement (5 bytes without encryption overhead)</li></ul><p>=&gt; Total of 238 bytes</p><p>The total is 619 (363 + 238 + 18) bytes, which is approximately 34 times more than the previous example. Please note that we don’t count the encryption overhead of the messages exchanged by both applications to simplify the example. In the end, there will be even more bytes sent over the network. This is the cost to obtain a secure connection between entities over the time. The overhead is huge and can be a major problem for constrained networks.</p><p>Note: The example above is based on Pre-Shared Key (PSK) cipher suite with the ciphersuite: TLS_PSK_WITH_AES_128_CCM_8.</p><h4><strong>UDP + DTLS + Connection Identifier</strong></h4><p>What can the DTLS protocol offer to reduce the overhead of the session resumption mechanism? The answer is the Connection Identifier (CID), which is the topic of this section.</p><p>The Connection Identifier has been proposed in the <a href="https://www.rfc-editor.org/rfc/rfc9146.html">[RFC 9146]</a> as an extension to DTLS 1.2 protocol before being fully integrated in DTLS 1.3 protocol. The Connection Identifier is composed of at most a 32 bytes value that is used to identify a DTLS session. The value is generated by the DTLS Server, and is sent to the DTLS Client during the handshake. The DTLS server will then use this value to associate the DTLS session. The Connection Identifier is sent clear, not encrypted, and is part of the DTLS record layer. Basically, the DTLS Client needs to attach this value to each encrypted message sent. Extract from the RFC 9146:</p><pre>struct {<br>ContentType outer_type = tls12_cid;<br>ProtocolVersion version;<br>uint16 epoch;<br>uint48 sequence_number;<br>opaque cid[cid_length]; // New field<br>uint16 length; // New field<br>opaque enc_content[DTLSCiphertext.length];<br>} DTLSCiphertext;</pre><p>The extension is negotiated during the handshake and is first exposed by the DTLS Client in the Client Hello message. If the DTLS Server supports the extension, it will reply with the same extension in the Server Hello message + the Connection Identifier value. If one of the parties does not support the extension, the DTLS session will be established without the Connection Identifier.</p><p>The Connection Identifier eliminates the need for session resumption mechanisms since it allows the DTLS session to be decoupled from the IP address and port. The DTLS Client can change its IP address and port, and the DTLS Server will still be able to associate the DTLS session with the DTLS Client. It reduces the overhead of the costly session resumption mechanism.</p><p>To state it briefly, the DTLS Client needs to simply attach this identifier to each encrypted message so long as the DTLS session is not interrupted by a Close Notify message.</p><p>Let’s return to our first example to see what the impact of a session resumption would be in this case. We can now mimic the same behavior as <strong>Raw UDP</strong>, but without the cost of a session resumption mechanism. Of course, we still have the overhead of DTLS, but it could be considered acceptable since we need to encrypt the messages exchanged. Sending messages without any encryption on the wire is not acceptable for the major IoT use cases due to cybersecurity considerations.</p><p>The only downside in this scenario is the addition of the Connection Identifier to each message sent by the DTLS Client to the DTLS Server. Compared to “regular” DTLS, the encrypted messages are a bit bigger, but it’s not a big deal if we take a common IoT use case of an IoT Device that is sleeping most of the time and wakes up periodically to send data to the server. Comparing between “regular” DTLS and DTLS with a Connection Identifier, we eliminate a lot of messages exchanged and bytes sent on the wire.</p><p>Please note that in this scenario, only the DTLS Client needs to attach the Connection Identifier to the messages. The DTLS Server does not need to do it, and thus, we do not have any additional overhead on the server side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*Td09W73mg2MOAZL19x039w.png" /></figure><h4><strong>UDP + OSCORE</strong></h4><p>A good way to sum up the challenge of connecting IoT devices to the cloud as a programmer is we are trying to bridge two opposed worlds: IoT with constraints and intermittent connectivity to the limitless, always connected IP-centric approach of the cloud.</p><p>Previously, we outlined different technical approaches dealing with the connection challenges, but could we achieve better than DTLS + CID? The answer may be “yes.” A new security mode has been proposed for the CoAP protocol called Object Security for Constrained RESTful Environments (or “OSCORE”). It is defined in [<a href="https://www.rfc-editor.org/rfc/rfc8613.html">RFC 8613</a>]. The protocol is based on the CBOR Object Signing and Encryption (COSE) protocol, and is defined in the [<a href="https://www.rfc-editor.org/rfc/rfc8152.html">RFC 8152</a>].</p><p>But before going into further details, it is worth mentioning that this solution is specific to the CoAP protocol, and can’t be used for other protocols. This is not a replacement of DTLS, but a new security mode that can be used on top of DTLS if necessary. Of course, it can also be used without DTLS. That’s why here we’ll demonstrate the usage of OSCORE with UDP only.</p><p>We won’t go into the details of the protocol, as these details will be part of another article. But one of the main advantages of the protocol is that it enables partial encryption for messages sent by the Client to the Server. In turn, this reduces the overall overhead of the encryption and helps to save bandwidth.</p><p>Let’s now discuss how the protocol can help us to solve the NAT table timeout problem. The OSCORE protocol can be seen as a mixture between “regular” DTLS and the Connection Identifier extensions. Each security session is identified through a Key ID Context. This key ID is used by the Server to associate its internal security context with the Client. This mechanism can be seen as the Connection Identifier extension.</p><p>But comparing with DTLS, the OSCORE protocol does not need to perform a handshake similar to the DTLS handshake. A handshake does exist, but it’s much shorter. And if we take into consideration the fact that the messages exchanged between the Client and the Server are partially encrypted, the overhead is much lower than the DTLS handshake.</p><p>To take a concrete example and compare it with the <strong>UDP + DTLS + Connection Identifier</strong> solution, let’s take the same example as before.</p><p>To initiate a secure connection using OSCORE, the LwM2M Client needs to send its registration message during the negotiation of the OSCORE context with the LwM2M Server. The LwM2M Server will then reply with both the registration acknowledgement message and the end of the negotiation of the OSCORE context. It helps to remove the usual handshake messages since they are directly part of the first application messages exchanged between the Client and the Server. In addition to this scenario, the negotiation of the OSCORE context can be derived multiple times through the Appendix B.2 of the RFC 8613.</p><p>In total, to establish a secure connection:</p><ul><li>DTLS (with ciphersuite: TLS_PSK_WITH_AES_128_CCM_8) + Connection Identifier (with a length of 9 bytes): 988 bytes<br>- DTLS handshake: 746 bytes<br><em>Client Hello (137 bytes)<br>Hello Verify Request (60 bytes): optional step<br>Client Hello + Cookie (169 bytes): optional step<br>Server Hello (124 bytes)<br>Server Hello Done (25 bytes)<br>Client Key Exchange (41 bytes)<br>Change Cipher Spec (14 bytes)<br>Encrypted Handshake Message (69 bytes)<br>Change Cipher Spec (14 bytes)<br>Encrypted Handshake Message (93 bytes)</em><br>- LwM2M registration message: 242 bytes<br><em>Registration (165 bytes)<br>Acknowledgement (77 bytes)</em></li><li>OSCORE: 359 bytes<br>- OSCORE context negotiation with LwM2M registration message: 359 bytes<br><em>Registration (147 bytes)<br>Response with Appendix B.2 (28 bytes)<br>Registration with Appendix B.2 (157 bytes)<br>Acknowledgement (27 bytes)</em></li></ul><p>Then, to maintain the connection (by looking at only the Registration Update message with its acknowledgement):</p><ul><li>DTLS + Connection Identifier: 130 bytes<br>- LwM2M registration update message: 130 bytes<br><em>Registration Update (53 bytes)<br>Acknowledgement (77 bytes)</em></li><li>OSCORE: 65 bytes<br>- LwM2M registration update message: 65 bytes<br><em>Registration Update (48 bytes)<br>Acknowledgement (17 bytes)</em></li></ul><h3><strong>Conclusion</strong></h3><p>As highlighted above, the problem of NAT table timeout is not a simple problem to solve. But fortunately, there are good solutions to overcome this problem. It depends on your use case and the constraints that you have. If you can’t use OSCORE security, you may be interested in using DTLS with Connection ID. But if one of the DTLS peers does not support a Connection ID, you would then use the usual mechanisms that are costly in terms of bandwidth.</p><p>The best solution would of course be to rely on the most recent solution (OSCORE security), but due to the lack of support for this security mode, this solution has not been widely adopted yet. More and more devices are using DTLS with a Connection ID. Unfortunately, some issues came up during the early days of this solution’s adoption: a few existing implementations were written while the RFC wasn’t finished yet, which made them incompatible with each other. The situation has greatly improved since the final version of the RFC. However, it did cause a lot of confusion, and some implementations even support the old version of the RFC with all its variations.</p><p>Today, the most used solution is still the session resumption mechanism of DTLS.</p><p>Join us on GitHub and let’s discuss: <a href="https://github.com/ioterop">https://github.com/ioterop</a></p><p><a href="http://www.ioterop.com/">www.ioterop.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12be69594533" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>