# Micro Bit

## Extract source code from firmware

When the source has been build from [makecode.microbit.org](https://makecode.microbit.org/#editor), the Javascript code is embedded into the firmware.

```python
import bincopy
import lzma
import sys
import subprocess
import json

# split firmware into raw and code
with open(sys.argv[1],'r') as f:
    fwstring = f.read()
    fwsplit = fwstring.split('\n\n')
    
    with open('fw_raw.hex', 'w') as g:
        g.write(fwsplit[0])
    with open('fw_code.hex', 'w') as g:
        g.write(fwsplit[1])

# Convert ihex to bin
f = bincopy.BinFile()
f.add_ihex_file('fw_code.hex')
binary = f.as_binary()
print("[+] ihex converted to binary")

## Extract code firmware, bruteforce offset
for i in range(200):
    with open('firmware.bin', 'w+b') as g:
        g.write(binary[i:])

    try:
        data = subprocess.run(["lzma", "firmware.bin", "-d", "--stdout"], capture_output=True)
        data = data.stdout.decode().split('}',1)
        data = data[1][1:]
        data = json.loads(data)
        print(data)
        print("\n[+] Javascript code")
        print(data['main.ts'])
    except Exception as e:
        continue
```

## Extract firmware using SWD

### Connection

Solder wires on SWD pins:

![swd-wire](https://577287991-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LZxnCyqJaYdEmxpiYjn%2Fuploads%2Fgit-blob-1787d6230f7686b2bc06f84d6573c700465ffd37%2FUART_sigrok_dump.png?alt=media)

Connect to an ST-LINK v2:

![swd-connect](https://577287991-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LZxnCyqJaYdEmxpiYjn%2Fuploads%2Fgit-blob-f1f85324eb3d5861a2f30e149eda3915d8810101%2FUART_1bit_period.png?alt=media)

### OpenOCD profile

Official datasheet of the nRF51822: [nRF51822\_PS\_v3.4.pdf](https://docs.nordicsemi.com/bundle/nRF51-Series/resource/nRF51822_PS_v3.4.pdf)

Code section size:

![memory-map](https://577287991-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LZxnCyqJaYdEmxpiYjn%2Fuploads%2Fgit-blob-1a5f953b6fba15c2553e3ea7691f0af05f36a68e%2Fpin2pwn_practical_example.png?alt=media)

![chip-variant](https://577287991-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LZxnCyqJaYdEmxpiYjn%2Fuploads%2Fgit-blob-240352047f81bf775ef16bb88563fc394f898ea4%2Fesp32-pin20.png?alt=media)

> hex(1024\*256) = 0x40000 => 0x00040000

```bash
init
reset init
halt
dump_image image.bin 0x00000000 0x00040000
exit
```

```bash
sudo openocd  -f /home/maki/tools/hardware/openocd/tcl/interface/stlink-v2-1.cfg -f /home/maki/tools/hardware/openocd/tcl/target/nrf51.cfg -f dump_fw.cfg
```

### Python code

Content of `image.dd` file:

```bash
$ strings image.bin
[...]
main.py# Add your Python code here. E.g.
from microbit import *
while True:
    display.scroll('Hello, World!')
    displa
y.show(Image.HEART)
    sleep(1000)
    print("coucou")
    sleep(2000)
```
