Hermann  Frami

Hermann Frami

1679923020

Flipperzero-firmware: Flipper Zero Firmware Source Code

Flipper Zero Firmware


Cloning source code

Make sure you have enough space and clone the source code:

git clone --recursive https://github.com/flipperdevices/flipperzero-firmware.git

Building

Build firmware using Flipper Build Tool:

./fbt

Flashing firmware using an in-circuit debugger

Connect your in-circuit debugger to your Flipper and flash firmware using Flipper Build Tool:

./fbt flash

Flashing firmware using USB

Make sure your Flipper is on, and your firmware is functioning. Connect your Flipper with a USB cable and flash firmware using Flipper Build Tool:

./fbt flash_usb

Documentation

Project structure

  • applications - applications and services used in firmware
  • assets - assets used by applications and services
  • furi - Furi Core: OS-level primitives and helpers
  • debug - debug tool: GDB plugins, an SVD file, etc.
  • documentation - documentation generation system configs and input files
  • firmware - firmware source code
  • lib - our and 3rd party libraries, drivers, etc.
  • scripts - supplementary scripts and python libraries home

Also, see ReadMe.md files inside those directories for further details.


Contributing

Our main goal is to build a healthy and sustainable community around Flipper, so we're open to any new ideas and contributions. We also have some rules and taboos here, so please read this page and our Code of Conduct carefully.

I need help

The best place to search for answers is our User Documentation. If you can't find the answer there, check our Discord Server or our Forum.

I want to report an issue

If you've found an issue and want to report it, please check our Issues page. Make sure the description contains information about the firmware version you're using, your platform, and a clear explanation of the steps to reproduce the issue.

I want to contribute code

Before opening a PR, please confirm that your changes must be contained in the firmware. Many ideas can easily be implemented as external applications and published in the Flipper Application Catalog (coming soon). If you are unsure, reach out to us on the Discord Server or the Issues page, and we'll help you find the right place for your code.

Also, please read our Contribution Guide and our Coding Style, and make sure your code is compatible with our Project License.

Finally, open a Pull Request and make sure that CI/CD statuses are all green.

Development

Flipper Zero Firmware is written in C, with some bits and pieces written in C++ and armv7m assembly languages. An intermediate level of C knowledge is recommended for comfortable programming. C, C++, and armv7m assembly languages are supported for Flipper applications.

Requirements

Supported development platforms:

  • Windows 10+ with PowerShell and Git (x86_64)
  • macOS 12+ with Command Line tools (x86_64, arm64)
  • Ubuntu 20.04+ with build-essential and Git (x86_64)

Supported in-circuit debuggers (optional but highly recommended):

Flipper Build System will take care of all the other dependencies.


Links


Download Details:

Author: Flipperdevices
Source Code: https://github.com/flipperdevices/flipperzero-firmware 
License: GPL-3.0 license

#flipper #firmware #nfc #c 

Flipperzero-firmware: Flipper Zero Firmware Source Code
Annie  Emard

Annie Emard

1652374500

Binbloom: Raw Binary Firmware Analysis Software

About

The purpose of this project is to analyse a raw binary firmware and determine automatically some of its features. This tool is compatible with all architectures as basically, it just does simple statistics on it.

In order to compute the loading address, you will need the help of an external reverse engineering tool to extract a list of potential functions, before using binbloom.

Main features:

  • Loading address: binbloom can parse a raw binary firmware and determine its loading address.
  • Endianness: binbloom can use heuristics to determine the endianness of a firmware.
  • UDS Database: binbloom can parse a raw binary firmware and check if it contains an array containing UDS command IDs.

Download / Install

First, clone the git repository:

git clone https://github.com/quarkslab/binbloom.git
cd binbloom

To build the latest version:

mkdir build
cd build 
cmake ..
make

To install the latest version (linux only):

make install

Getting started

Determine the endianness

binbloom -f firmware.bin -e

This command should give an output like this:

Loaded firmware.bin, size:624128, bit:fff00000, 000fffff, nb_segments:4096, shift:20
End address:00098600
Determining the endianness
Computing heuristics in big endian order:
Base: 00000000: unique pointers:1839, number of array elements:217900
Base: 01000000: unique pointers:1343, number of array elements:13085
Base: 02000000: unique pointers:621, number of array elements:5735
Base: 03000000: unique pointers:566, number of array elements:3823
Base: 05000000: unique pointers:575, number of array elements:6139
Base: 80000000: unique pointers:642, number of array elements:528
247210
Computing score in little endian order:
Base: 00000000: unique pointers:8309, number of array elements:515404
515404
This firmware seems to be LITTLE ENDIAN

In this output, the last line is the most important one as it gives the result of the analysis. The other lines are information about the number of unique pointers and number of array elements binbloom has been able to find in the firmware, both in big endian and in little endian mode. These lines can provide useful information to corroborate the heuristic used to determine the endianness.

Determine the loading address

First, you have to provide a file containing a list of potential functions addresses, in hexadecimal (one per line), like this:

00000010
00000054
000005f0
00000a50
00000a54
00000ac0
00000b40
00000b6c
00000b74
00000bc0

This file should be named after the firmware itself, followed with the ".fun" extension.

This file can be generated with the tag_code() function of the provided tag_code.py python script, using IDA Pro:

  • Load the firmware in IDA Pro at address 0 (select the correct architecture/endianness)
  • From the File menu, choose Script File and select tag_code.py
  • In the console at the bottom of IDA Pro, use tag_code(). The functions file is automatically generated.

If you prefer to use another tool to generate the functions file, you can do it as long as you load the firmware at address 0 (i.e. the hex values in the functions file correspond to offsets in the firmware).

You can then ask binbloom to compute a (list of) potential loading address(es) by computing a correlation score between the potential functions and the arrays of functions pointers that can be found in the firmware:

binbloom -f firmware.bin -b

This command should give an output like this:

Loaded firmware.bin, size:2668912, bit:ffc00000, 003fffff, nb_segments:1024, shift:22
End address:0028b970
loaded 14903 functions

Highest score for base address: 1545, for base address 80010000
For information, here are the best scores:
For base address 80010000, found 1545 functions
Saving function pointers for this base address...
Done.

In this output, we can see that on the 14903 provided potential functions, 1545 were found in function pointers arrays when the program takes the assumption that the loading address is 0x80010000.

If there are several sections in the binary firmware, binbloom lists the different sections with the corresponding guess for the loading address:

Highest score for base address: 93, for base address 00000000
For information, here are the best scores:
For base address 00000000, found 93 functions
For base address 00040000, found 93 functions

Here we have a section of code at address 0x00000000, and another one at 0x00040000.

Binbloom generates 2 output files:

  • firmware.fad : this file contains the addresses of identified functions
  • firmware.fpt : this file contains the addresses of the pointers to the identified functions

You can now start IDA Pro again (or any reverse engineering software), load the firmware at the specified address and import the addresses of the 1545 identified functions:

  • Load the firmware in IDA Pro at the specified address (in this example 0x80010000)
  • From the File menu, choose Script File and select import_entry_points.py
  • Select the .fad file
  • Select the .fpt file

Note:

binbloom will start by determining the endianness, as this information is needed to look for the arrays of functions pointers. If the automatic analysis of the endianness is wrong, you can override its result with the following option:

-E b: force big endian mode

-E l: force little endian mode

Find the UDS database (for an ECU's firmware)

binbloom can try to search an array containing UDS/KWP2000 IDs, with the -u option:

binbloom -f firmware.bin -u

This command should give an output like this:

Loaded firmware.bin, size:1540096, bit:ffe00000, 001fffff, nb_segments:2048, shift:21
End address:00178000
UDS DB position: 1234 with a score of 12 and a stride of 12:
10 00 31 00 26 27 00 80 00 00 00 00 
11 00 31 00 24 3d 01 80 00 00 00 00 
22 00 10 00 2c 42 01 80 00 00 00 00 
27 00 10 00 1c 41 01 80 60 a8 01 80 
28 00 31 00 36 7f 01 80 00 00 00 00 
2e 00 10 00 18 88 01 80 08 ae 01 80 
31 00 30 00 10 41 01 80 00 00 00 00 
34 00 10 00 46 4e 01 80 00 00 00 00 
36 00 10 00 2a 2d 01 80 00 00 00 00 
37 00 10 00 32 3c 00 80 00 00 00 00 
3e 00 31 00 54 5b 01 80 00 b2 01 80 
85 00 31 00 6a 2f 01 80 00 00 00 00 

This output shows that at address 0x1234, a potential UDS database was found with a stride of 12 (meaning that UDS IDs are present in an array in which each element is 12-byte long). In this example, the UDS IDs are in the first column (10, 11, 22, 27, 28, 2e, 31, 34, 36, 37, 3e and 85).

The list of supported UDS IDs is hard-coded in binbloom.c, you can change it if needed.

This analysis is based on heuristics so it can give false positives. You have to read the list of potential UDS databases found by binbloom and check and see which one is the correct one, if any.

In this example, we can see that there is a pointer in little endian in each line (26 27 00 80 for the first line, which corresponds to address 0x80002726). There is probably a function at this address to manage UDS command 10. You have to disassemble the code to make sure, and search for cross-references to this UDS database.

About

Authors

Guillaume Heilles (@PapaZours)

Author: quarkslab
Source Code: https://github.com/quarkslab/binbloom
License: Apache-2.0 License

#firmware #analysis 

Binbloom: Raw Binary Firmware Analysis Software

¿Qué Es Firmware? Definición Y Ejemplos

¿Sabías que el firmware está literalmente en todas partes? Puede resultar extraño pensar en ello, pero es tan común como el hardware y el software.

De hecho, es gracias al firmware que:

  • Las impresoras funcionan
  • Los desfibriladores funcionan
  • Funciona la radio del coche
  • y más …

Según los ejemplos anteriores, probablemente ya tenga una idea de qué es el firmware. Pero no tienes una definición clara de ello.

Para comprender realmente qué es el firmware, primero debemos comprender el software, luego el hardware y, finalmente, podemos saltar al firmware.

En este tutorial, explicaré cada tema con una analogía. Al hacerlo, todos pueden entender.

¡No importa si te estás iniciando en la tecnología!

Con eso, me gustaría asegurarme de que todos entiendan qué es el software, el hardware y el firmware. No daré más detalles sobre los términos técnicos.

En este artículo exploraremos:

  • ¿Qué es exactamente el software?
  • ¿Qué es exactamente el hardware?
  • ¿Qué es exactamente el firmware?

¿Qué es el software?

libro

Foto de Kübra Doğu de Pexels

Imagina, si quieres, que no tienes idea de qué hacer para cenar hoy.

Por suerte, encuentras un viejo libro de cocina que tienes y decides cocinar una de las recetas que contiene.

El libro de cocina tiene muchas recetas. Cada una de estas recetas tiene sus propias instrucciones.

En el libro de cocina , una receta puede verse como un conjunto de pasos (o instrucciones) que juntos hacen una comida .

instrucciones de cocina

Foto de Luis Quintero en Pexels

También puede crear sus propias comidas en función de su experiencia en la cocina de muchas recetas diferentes, ¿verdad?

El software no es diferente.

Los programas de software pueden verse como un conjunto de instrucciones que trabajan juntas para formar un programa .

 global  _main
    extern  _printf

    section .text
_main:
    push    message
    call    _printf
    add     esp, 4
    ret
message:
    db  'Hello, World', 10, 0

Imprimir hola mundo en código máquina (Asamblea)HolaMundo.asm

Entonces, las aplicaciones son un gran conjunto de instrucciones que realizan tareas específicas.

Los sistemas operativos son grandes conjuntos de instrucciones que coordinan los recursos de software y hardware.

  • libro de cocina = software
  • Libro de cocina de la cena = tipo de software (aplicación o sistema operativo)
  • receta = programa

Necesitas una receta para hacer la cena. Debe seguir cada paso del libro de cocina para crear una receta.

Una vez que hayas completado todos los pasos, tu cena estará lista.

Necesita software para realizar una tarea en particular. Una computadora tiene que seguir todas las instrucciones para que el software funcione.

Por lo tanto, el software se ejecuta mientras se siguen las instrucciones o después de que se hayan completado.

receta---instrucciones-de-cocina

¿Qué es la ferretería?

alimento

Foto de ELEVATE de Pexels

Para preparar la cena, necesita una serie de pasos del libro de cocina que le indiquen cómo preparar una comida en particular.

También necesita varias herramientas para cocinar, como ollas y sartenes, cuchillos y la comida misma. Esto es como el hardware.

Entonces, un libro de cocina te da instrucciones que te permiten cocinar.

proceso-de-coccion-1

Para que el hardware funcione, necesita un software (un conjunto de instrucciones) que le diga qué hacer.

CPU-proceso-2

Entonces, el software le da instrucciones al hardware que le permite funcionar.

  • Herramientas de preparación de comidas = hardware
  • Receta = software

Sin software, no puede hacer que el hardware funcione.

Sin una receta, no sabrá qué hacer con sus diversas herramientas e ingredientes para preparar una comida.

Al igual que el hardware sin software, también puede comer solo alimentos crudos. Bruto.

De la misma manera que hay varios tipos de comidas, también hay varios tipos de hardware informático.

Por ejemplo:

  • UPC
  • RAM
  • GPU
  • y mucho más…

comparación de procesos

Comparación de procesos

¿Qué es Firmware?

postre

Foto de Ella Olsson de Pexels

Un programa es un conjunto de instrucciones leídas por una computadora.

Digamos que solo quieres hacer un refrigerio o un postre. Probablemente no necesites tantos ingredientes como cuando preparas una cena para tu familia, ¿verdad?

Supongamos que desea un software que se ejecute en un microondas. No necesitas todo el hardware que tiene la computadora para que el microondas funcione, ¿verdad? Solo necesita eso específico para hacer que el microondas funcione.

O diga que desea que el software se ejecute en una impresora. No necesita todo el hardware que tiene la computadora para que la impresora funcione, ¿verdad? Solo el software para la impresora.

  • Software de microondas = firmware
  • Software de impresoras = firmware

Entonces, esto significa que el firmware no es más que un software, pero en un dispositivo de hardware. No en una computadora.

El firmware permite que hardware muy específico complete tareas muy específicas.

Terminando

¡Gracias por leer! Ahora sabes más sobre:

  • Software
  • Hardware
  • firmware

Foto del microprocesador de Pok Rie de Pexels

Fuente: https://www.freecodecamp.org/news/what-is-firmware/

#firmware  #softwares  #hardware 

¿Qué Es Firmware? Definición Y Ejemplos
伊藤  直子

伊藤 直子

1650659580

ファームウェア (Firmware) とは何ですか?定義と例

ファームウェアが文字通りどこにでもあることをご存知ですか?考えるのは奇妙かもしれませんが、ハードウェアやソフトウェアと同じくらい一般的です。

実際、ファームウェアのおかげで次のことが可能になります。

  • プリンターは動作します
  • 除細動器は機能します
  • カーラジオは動作します
  • もっと …

上記の例に基づいて、おそらくファームウェアが何であるかについてすでにある程度の知識があります。しかし、あなたはそれの明確な定義を持っていません。

ファームウェアとは何かを真に理解するには、まずソフトウェア、次にハードウェアを理解し、最後にファームウェアに飛び込む必要があります。

このチュートリアルでは、各トピックを類推して説明します。そうすることで、誰もが理解できるようになります。

テクノロジーを始めたばかりかどうかは関係ありません。

それで、ソフトウェア、ハードウェア、ファームウェアが何であるかをみんなに理解してもらいたいと思います。専門用語については詳しく説明しません。

この記事では、以下について説明します。

  • ソフトウェアとは正確には何ですか?
  • ハードウェアとは正確には何ですか?
  • ファームウェアとは正確には何ですか?

ソフトウェアとは何ですか?

本

PexelsKübraDoğuによる写真

もしそうなら、今日の夕食に何を作ればいいのかわからないと想像してみてください。

幸いなことに、あなたはあなたが持っている古い料理本を見つけて、その中のレシピの1つを料理することに決めました。

クックブックには多くのレシピがあります。これらのレシピにはそれぞれ独自の手順があります。

クックブックでは、レシピは一緒に食事を作る一連のステップ(または指示)として見ることができます。

料理指導

PexelsのLuisQuinteroによる写真

また、さまざまなレシピを調理した経験に基づいて、独自の食事を作成することもできますよね?

ソフトウェアも例外ではありません。

ソフトウェアプログラムは、連携してプログラムを形成する一連の命令と見なすことができます。

 global  _main
    extern  _printf

    section .text
_main:
    push    message
    call    _printf
    add     esp, 4
    ret
message:
    db  'Hello, World', 10, 0

hello worldをマシンコードで出力する(アセンブリ)HelloWorld.asm

次に、アプリケーションは特定のタスクを実行する一連の大きな命令です。

オペレーティングシステムは、ソフトウェアとハ​​ードウェアのリソースを調整する一連の大きな命令です。

  • クックブック=ソフトウェア
  • ディナークックブック=ソフトウェアの種類(アプリケーションまたはオペレーティングシステム)
  • レシピ=プログラム

あなたは夕食を作るためのレシピが必要です。レシピを作成するには、クックブックの各ステップに従う必要があります。

すべての手順を完了すると、夕食の準備が整います。

特定のタスクを実行するにはソフトウェアが必要です。コンピュータは、ソフトウェアが機能するためにすべての指示に従う必要があります。

したがって、ソフトウェアは、指示に従っている間、または指示が完了した後に実行されます。

レシピ---調理-指示

ハードウェアとは何ですか?

食物

PexelsELEVATEによる写真

夕食を作るために、あなたは特定の食事を作る方法をあなたに教える料理本からの一連のステップを必要とします。

また、鍋やフライパン、ナイフ、食べ物自体など、さまざまな調理器具が必要です。これはハードウェアのようなものです。

したがって、クックブックには、料理を可能にする手順が記載されています。

調理プロセス-1

ハードウェアが機能するには、何をすべきかを指示するソフトウェア(一連の命令)が必要です。

CPUプロセス-2

次に、ソフトウェアは、それを機能させるハードウェアに指示を与えます。

  • 食事準備ツール=ハードウェア
  • レシピ=ソフトウェア

ソフトウェアがなければ、ハードウェアを機能させることはできません。

レシピがなければ、食事を作るためにさまざまな道具や材料をどうするかがわかりません。

ソフトウェアのないハードウェアのように、生の食品だけで食事をすることもできます。キモい。

さまざまな種類の食事があるのと同じように、さまざまな種類のコンピュータハードウェアもあります。

例えば:

  • CPU
  • GPU
  • そしてもっと…

プロセスの比較

プロセスの比較

ファームウェアとは何ですか?

デザート

PexelsEllaOlssonによる写真

プログラムは、コンピューターによって読み取られる一連の命令です。

おやつやデザートを作りたいだけだとしましょう。家族で夕食を作るときほど多くの材料は必要ないでしょう?

電子レンジで動作するソフトウェアが必要だとしましょう。コンピュータが電子レンジを機能させるために必要なすべてのハードウェアは必要ありませんよね?あなたはただマイクロ波を機能させるためにそれを必要とします。

または、ソフトウェアをプリンターで実行したいとします。コンピューターがプリンターを正しく動作させるために必要なすべてのハードウェアは必要ありませんか?プリンタ用のソフトウェアだけです。

  • マイクロ波ソフトウェア=ファームウェア
  • プリンターソフトウェア=ファームウェア

つまり、これはファームウェアがソフトウェアにすぎず、ハードウェアデバイスにあることを意味します。コンピューターではありません。

ファームウェアにより、非常に特定のハードウェアが非常に特定のタスクを完了できます。

まとめ

読んでくれてありがとう!今、あなたはもっと知っています:

  • ソフトウェア
  • ハードウェア
  • ファームウェア

PexelsPokRieによるマイクロプロセッサの写真

ソース:https ://www.freecodecamp.org/news/what-is-firmware/

#firmware  #softwares  #hardware 

ファームウェア (Firmware) とは何ですか?定義と例
Wilford  Pagac

Wilford Pagac

1602766800

Video-Game Piracy Group 'Team Xecuter' Leaders in Custody

The Department of Justice (DoJ) has nabbed two alleged leaders of a global, notorious video-game piracy group called Team Xecuter.

The two leaders in custody, Max Louarn (48, a French national of Avignon) and Gary Bowser (51, a Canadian national from Santo Domingo, Dominican Republic), allegedly led the criminal enterprise’s efforts to hack popular video-game consoles so they could be used to play pirated copies of video games. The DoJ also charged Team Xecuter member Yuanning Chen, 35, a Chinese national of Shenzhen, China.

Video-game manufacturers govern the use of major consoles to play copyrighted video-game titles with end-user licensing agreements, which prevents anyone from duplicating, modifying and selling the software. In addition, console manufacturers and game developers implement various technical measures – from specific game cartridge designs to cryptographic keys on the software – to prevent the use of unauthorized firmware that could be used to play pirated video games.

Team Xecuter, which says in underground advertisements that it’s been around since 2001, has bypassed these measures by developing and selling illegal “circumvention” devices. One example is a USB device that the group sold starting in 2018 called the SX Pro, which allows the Nintendo Switch console to run pirated games.

Beyond the Nintendo Switch, the cybercrime group also targeted popular consoles such as the Nintendo 3DS, the Nintendo Entertainment System Classic Edition, the Sony PlayStation Classic and Microsoft Xbox.

“These defendants were allegedly leaders of a notorious international criminal group that reaped illegal profits for years by pirating video game technology of U.S. companies,” said Acting Assistant Attorney General Brian Rabbitt of the Justice Department’s Criminal Division, in a Friday announcement. “These arrests show that the department will hold accountable hackers who seek to commandeer and exploit the intellectual property of American companies for financial gain, no matter where they may be located.”

According to court documents, the Team Xecuter group is comprised of more than a dozen individual members worldwide. That includes: Developers who exploit vulnerabilities in video-game consoles and design the circumvention devices; website designers who create the various websites promoting and advertising these devices; suppliers who manufacture the devices; and resellers who distribute the devices.

According to the DoJ, the group has continuously evaded law-enforcement efforts by using a wide variety of brand names, websites and distribution channels. Between June 2013 through August 2020, for instance, Team Xecuter used a variety of product names for its devices, such as the Gateway 3DS, the Stargate, the TrueBlue Mini, the Classic2Magic and the SX line of devices (that includes the SX OS, as well as the SX Pro, the SX Lite and the SX Core). The group also allegedly masked its illegal activity by pretending to support gaming enthusiasts who wanted to design their own video games for non-commercial use.

The DoJ also said that behind the scenes, Team Xecuter was supporting online libraries of pirated video games for its customers, and several of the devices also came preloaded with numerous pirated games. Ironically, the group also used a licensing scheme to protect its circumvention software from being pirated, the department said.

“According to the indictment, Team Xecuter was so brazen that it even required customers to purchase a ‘license’ to unlock the full features of its custom firmware, the SX OS, in order to enable the ability to play pirated video games,” according to the DoJ.

The video-game and enthusiast markets are lucrative industries for cybercriminals. A recent report highlighted that credential-theft targeting hardcore gamers has hit an all-time high as scams, illicit markets and account takeovers have become a booming business. Meanwhile, hackers are scoring more than a million dollars annually selling compromised accounts for the popular Fortnite video game in underground forums.

Video-game companies are cracking down on these security challenges, and in particular the issue of piracy – with Nintendo filing two lawsuits against Nintendo Switch piracy resellers that were part of Team Xecuter, as well as against UberChips, a website that sold Team Xecuter’s hardware. Last week, UberChips agreed to a $2 million settlement with Nintendo.

#hacks #web security #criminal charges #department of justice #firmware #gary bowser #indictment #max louarn #microsoft xbox #nintendo #nintendo 3ds #nintendo entertainment system classic edition #nintendo switch #piracy #pirated games #sony playstation classic #sx pro #team xecuter #video game #video game console #video game software

Video-Game Piracy Group 'Team Xecuter' Leaders in Custody
Tyrique  Littel

Tyrique Littel

1597399200

How To Build a GPS Tracker From Scratch Using Arduino

Combining 3 Arduino boards to create a GPS tracker & data logger.

I had an idea to combine the new Arduino Nano 33 BLE Sense with an SD card and GPS module for a side project that logs GPS and IMU data.

I decided to purchase the Nano 33, the MKR Mem Shield, and the MKR GPS Shield and connect them all together. Unbeknownst to me at the time, these boards aren’t footprint-compatible, so I combined them with a breadboard 😐.

It took a little while to get all the libraries installed and everything connected appropriately. The biggest challenge was the GPS module. It really helps to start debugging the GPS’ example code outside; where satellite signal is available 😉.

Prototype Code

The full Arduino sketch for the above connected system is here. But, might as well have a quick overview of the code. Throwing the imports and definitions below:

#include <SparkFun_Ublox_Arduino_Library.h>
#include <Arduino_LSM9DS1.h>
#include <Arduino_APDS9960.h>
#include <SPI.h>
#include <SD.h>

// SD Vars
File dataFile;
int chipSelect = 4;

// GPS Vars
SFE_UBLOX_GPS myGPS; // Connected via UART
long latitude = 0;
long longitude = 0;
long speed = 0;
byte satellites = 0;
int timeout = 50;
long lastGPSTime = 0;

// IMU Vars
float ax, ay, az;
float gx, gy, gz;

// Misc
bool DEBUG = true;
int counter = 0;

#define LEDR        (22u)
#define LEDG        (23u)
#define LEDB        (24u)

Next, we need to do all the GPS and SD card setup. The tricky part here was making sure to remove the DATALOG.csv file every time we start up.

void setup()
{
  // Setup User Terminal
  Serial.begin(115200); // UART to PC/Mac
  while(!Serial);
  Serial1.begin(9600);  // UART to GPS
  while(!Serial1);

  // Initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(LEDR, OUTPUT);
  pinMode(LEDB, OUTPUT);
  pinMode(LEDG, OUTPUT);

  digitalWrite(LEDR, HIGH); // LOW triggered LED....
  digitalWrite(LEDG, HIGH);
  digitalWrite(LEDB, HIGH);

  // Setup GPS
  if (!myGPS.begin(Serial1)) {
    Serial.println(F("GPS not detected!"));
    while (1);
  }
  Serial.println("GPS Started!");

  // Setup SD Card
  if (!SD.begin(chipSelect)) {
    Serial.println("SD Card failed or not present!");
    while (1);
  }

  // Remove Existing DATALOG.CSV file
  if(SD.exists("DATALOG.CSV")) {
    SD.remove("DATALOG.CSV");
    dataFile = SD.open("DATALOG.CSV", FILE_WRITE);
    dataFile.close();
  }

  delay(500); // Make sure existing DATALOG.CSV file is gone

  // Create new CSV file with appropriate headers
  dataFile = SD.open("DATALOG.CSV", FILE_WRITE);
  dataFile.println("Count,AccX,AccY,AccZ,GyrX,GyrY,GyrZ,Lat,Long,Speed");

  // Done with SD Card Init
  Serial.println("SD Card Initialized!");

  // Setup Gesture Sensor
  if (!APDS.begin()) {
    Serial.println("Error initializing gesture sensor!");
  }
  APDS.setGestureSensitivity(85);
  Serial.println("Gesture sensor initialized!");

  // Setup IMU
  if (!IMU.begin()) {
    Serial.println("Failed to initialize IMU!");
    while(1);
  }
  Serial.println("IMU initialized!");
}

Now we can log all of the data to the SD Card. Note that we could use the Gesture sensor to stop and start recording (in the main loop).

void loop()
{
  if (millis() - lastGPSTime > 500) {
    lastGPSTime = millis(); // Update the timer

    latitude = myGPS.getLatitude(timeout);
    longitude = myGPS.getLongitude(timeout);
    speed = myGPS.getGroundSpeed(timeout);
    satellites = myGPS.getSIV(timeout);

    if(DEBUG) {
      Serial.print(F("Lat: "));
      Serial.print(latitude);
      Serial.print(F(" Long: "));
      Serial.print(longitude);
      Serial.print(F(" (degrees * 10^-7)"));
      Serial.print(F(" Speed: "));
      Serial.print(speed);
      Serial.print(F(" (mm/s)"));
      Serial.print(F(" satellites: "));
      Serial.println(satellites);
    }
  }

  if (IMU.accelerationAvailable()) {
    IMU.readAcceleration(ax, ay, az);
    if(DEBUG) {
      Serial.print(F("Accel x: "));
      Serial.print(ax);
      Serial.print(F(" y: "));
      Serial.print(ay);
      Serial.print(F(" z: "));
      Serial.println(az);
    }
  }

  if (IMU.gyroscopeAvailable()) {
    IMU.readGyroscope(gx, gy, gz);
    if(DEBUG) {
      Serial.print(F("Gyro x: "));
      Serial.print(gx);
      Serial.print(F(" y: "));
      Serial.print(gy);
      Serial.print(F(" z: "));
      Serial.println(gz);
    }
  }

  if (APDS.gestureAvailable()) {
    // A gesture was detected, read and print to serial monitor
    switch (APDS.readGesture()) {
      case GESTURE_UP:
        Serial.println("Detected UP gesture");
        break;
      case GESTURE_DOWN:
        Serial.println("Detected DOWN gesture");
        break;
      case GESTURE_LEFT:
        Serial.println("Detected LEFT gesture");
        break;
      case GESTURE_RIGHT:
        Serial.println("Detected RIGHT gesture");
        break;
      default:
        // ignore
        break;
    }
  }

  if (dataFile) {
    counter += 1;
    String dataString = "";
    dataString += String(counter) + ",";
    dataString += String(ax) + ",";
    dataString += String(ay) + ",";
    dataString += String(az) + ",";
    dataString += String(gx) + ",";
    dataString += String(gy) + ",";
    dataString += String(gz) + ",";
    dataString += String(latitude) + ",";
    dataString += String(longitude) + ",";
    dataString += String(speed);
    dataFile.println(dataString);
  }

  delay(150); // Don't pound too hard
}

So this is all fine and good. Prototype concept has been vetted! Time to build a custom PCB with the same functionality.

#iot #arduino #imu #bluetooth #sensor #hardware #firmware #gps

How To Build a GPS Tracker From Scratch Using Arduino
Wiley  Mayer

Wiley Mayer

1597352400

Security starts in the Firmware

I am a pretty frequent user of LinkedIn — as I do like the style of the network much more than for example Xing, and I feel like it has a much more active community. And I get spammed a lot with advertisements about security appliance, firewall, identify management systems, and so on. But what most people do not know: Security, no matter if it is a firewall, VPN appliance or ballot system — it always starts at the firmware level. Let’s learn how to build such a system — and why security always starts in the firmware.

Image for post

Photo by Miltiadis Fragkidis on Unsplash

Security Engineers tend to speak about the chain of trust. This means that a system which has various components need to build the security on top of each other, chaining the trustworthiness through the complete system. And this chain always has a so called trust anchor, the root of trust. The root of trust is the one code block, binary or hardware part in your system you need to trust, in order to build up a chain of trust. Let’s do an example here:

One “Secure” System

First of all — there is no secure system. Security is measured in: How much effort does it take to break it. Anyways, imagine you want to build a VPN appliance. So what do wee need for this

  • The bare metal platform i.e. Hardware
  • Some operating system — might probably be Linux
  • VPN Server — because you are a fan of open-source just like me, let’s go for OpenVPN

Most people now throw these parts together, do some nice configuration in Linux so that it does only allow specific ports to pass through, no root login and your VPN appliance is good to go. But what does actually happen, from the point where the system starts booting until the application has been loaded?

Bootflow

Every computer always starts at the reset vector. The reset vector is a System-on-Chip specific address which points to a position with the storage, most of the time this could be a SPI flash chip, of the initial code that runs on the system, so called firmware.

The firmware will initialize most of the hardware running on your system and will jump to a bootloader, which then loads your operating system. Once your operating system has been loaded, in our scenario, the OpenVPN server will start up and provide the needed services to our clients.

So clearly the root, the beginning of the whole system is the firmware. And within the firmware we can even be more specific. The firmware consists of multiple parts. As my main area of expertise is x86 firmware, we can divide this into several stages. The first part of the code is called bootblock or security phase in UEFI. The security phase does not contain security at all, the name has been chosen unfortunate. The security phase does initialize the CPU and brings up the CPU cache as RAM, as no RAM is available yet.

The next phase is the Pre-Efi Init (PEI) or romstage. The romstage has mainly two purposes. Do additional hardware initialization and most important: bring up the RAM.

Next is the ramstage or Driver Execution (DXE) phase. The DXE phase does everything your system needs. Bring up hardware, talk to our devices in your system like the Baseboard Management Controller. Loads USB drivers if necessary and so on. We do not need to go into full detail here. After all drivers have been initialized the bootloader pops up, and start executing your operating system kernel (Yes — Windows does also have a Kernel).

The kernel basically does a lot of these steps that happened in the firmware again — especially the DXE part. Once the user-space has been loaded, the application starts up and we are good to go.

The Root of Trust

Within most systems the root of trust is just the complete firmware. As we do not really know what is happening down there, as most of it is closed source, we just have to take the firmware as one big blob which acts as our root of trust. From there where can build up a chain of trust using known techniques like UEFI Secure Boot.

#crypto #programming #computer-science #firmware #security

Security starts in the Firmware