Skip to content

Commit 86009ef

Browse files
committed
Add an example server (very slow)
This implements a simple HTTP and HTTPS server pair that serve a static HTML file. The HTTP server uses adafruit_httpserver in a straightforward, basic way. The HTTPS server works by wrapping a socket pool object in an object that wraps all sockets in SSLSockets. There are throwaway, self-signed certificates for testing under src/certificates. However, HTTPS is very slow. Probably need an optimized AES implementation.
1 parent 54b1dbe commit 86009ef

20 files changed

+201
-7
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,5 @@
11
# macOS
22
.DS_Store
3+
4+
# Python
5+
__pycache__/

.vscode/settings.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"python.analysis.diagnosticSeverityOverrides": {
3+
"reportMissingImports": "none",
4+
"reportMissingModuleSource": "none",
5+
"reportShadowedImports": "none"
6+
},
7+
"python.formatting.provider": "black"
8+
}

README.md

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,39 @@
11
# CircuitPython HTTPS Web Server (for Raspberry Pi Pico W)
22

3-
> Note: this example isn't complete! There is an issue with the TLS library, perhaps an incompatible certificate. Help investigating is appreciated!
4-
53
This is an example of an HTTPS web server written in [CircuitPython](https://circuitpython.org/), intended to run on a [Raspberry Pi Pico W](https://www.raspberrypi.com/documentation/microcontrollers/raspberry-pi-pico.html#raspberry-pi-pico-w-and-pico-wh). [Adafruit](https://www.adafruit.com/) (the makers of CircuitPython) and the CircuitPython documentation have [guides](https://learn.adafruit.com/pico-w-http-server-with-circuitpython/code-the-pico-w-http-server) on running an unsecured HTTP server but none on serving content over HTTPS. This example will show you how to run an HTTPS server from a Pico W.
64

5+
Note: the server is very slow and takes about 6 seconds to respond with a tiny HTML file over HTTPS. In comparison, responding with the same file over HTTP takes 75 to 350 milliseconds.
6+
7+
## Getting started
8+
9+
1. Follow [Adafruit's guide to connecting your Pico W to Wi-Fi](https://learn.adafruit.com/pico-w-wifi-with-circuitpython/overview). Make sure you can run the the basic Wi-Fi test successfully.
10+
11+
2. Clone this repository to your computer: `git clone https://github.com/ide/circuitpython-https-server.git`
12+
13+
3. Copy the contents of the **src** directory to your **CIRCUITPY** volume. On macOS, you can run `scripts/deploy.sh` if you have [`rsync`](https://formulae.brew.sh/formula/rsync) and [`circup`](https://github.com/adafruit/circup) installed. Make sure your **settings.toml** file on your Pico still has your Wi-Fi credentials you configured when following Adafruit's Wi-Fi guide.
14+
15+
4. Connect to your Pico W's serial console. See [Adafruit's guide](https://learn.adafruit.com/welcome-to-circuitpython/kattni-connecting-to-the-serial-console) on how to do this. On macOS you can run `scripts/repl.sh`. Reload the code running in CircuitPython by entering Ctrl-C in the console.
16+
17+
5. The program running on your Pico W will start a web server and print two URLs, one with the Pico W's local IP address (e.g. https://192.168.1.2) and one with its local mDNS hostname (configured to be https://picow.local).
18+
19+
6. Run `curl --insecure https://picow.local` (or specify your Pico W's IP address). After about 10 seconds, you should see a small HTML response.
20+
721
## Why HTTPS for Pico W? (A better user experience for IoT web apps)
822

923
In the context of a Pico W serving content to your local network, the main motivation for HTTPS is to enable [web browser features limited to secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts/features_restricted_to_secure_contexts). These include [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API), which are needed to implement websites that work offline or use push notifications, two common features you might want in an IoT application.
1024

11-
Imagine you're at home and you visit your Pico W's homepage from your web browser. You add the web app to your home screen and your phone presents the web app somewhat like a native app with a home screen icon and its own entry in the task switcher. The web app lets you subscribe to push notifications from your Pico that you'll receive even when you're away from home. And, the web app also loads in "offline" mode when you're away from home and can't connect to your Pico. This is what the user experience should be like for web-based IoT applications.
25+
Imagine you're at home and you visit your Pico W's homepage from your web browser. You add the web app to your home screen and your phone presents the web app somewhat like a native app with a home screen icon and its own entry in the task switcher. The web app lets you subscribe to push notifications from your Pico that you'll receive even when you're away from home. And, the web app also loads in "offline" mode when you're away from home and can't connect to your Pico. This is what the user experience should be like for private, web-based IoT applications.
1226

13-
The secondary motivation for HTTPS is security. The threat model of your Pico W accessed from your local network is different from a web server accessed from the internet. Your Pico W is already protected by your router and only trusted devices with your Wi-Fi password or physical Ethernet connections can access it. However, defense in depth is a good security principle and HTTPS prevents even your trusted devices from sniffing or tampering with traffic to your Pico W.
27+
The secondary motivation for HTTPS is security. The threat model of your Pico W accessed from your local network is different from that of a web server accessed from the internet. Your Pico W is already protected by your router and only trusted devices with your Wi-Fi password or physical Ethernet connections can access it. However, defense in depth is a good security principle and HTTPS prevents even your trusted devices from sniffing or tampering with traffic to your Pico W.
1428

1529
## Goals and non-goals
1630

17-
The main goal of this repository is to show how to set up a web server that serves content over HTTPS and runs with CircuitPython on a Raspberry Pi Pico W. It's intended for a small, private home network. It uses self-signed certificates and requires installing the CA certificate on client devices.
31+
The main goal of this repository is to show how to set up a web server that serves content over HTTPS and runs with CircuitPython on a Raspberry Pi Pico W. It's intended for a small, private home network. It uses self-signed certificates and requires installing the CA certificate on client devices.
32+
33+
There are also several non-goals of this repository, which help keep its scope small. The repository provides an example, not a Python package. If support for serving content over HTTPS with CircuitPython is actually important, it probably makes sense for Adafruit to steer developers towards a package they provide. The example server targets only the Pico W and not other boards that CircuitPython supports, though it might happen to work for them, too.
1834

19-
There are also several non-goals of this repository, which help keep its scope small. The example server targets only the Pico W and not other boards that CircuitPython supports, though it might happen to work for them, too. C
20-
4096-bit
35+
## Things to be aware of
2136

37+
This example uses a 1024-bit RSA certificate for performance. With a 1024-bit certificate, the server responds in about 6 seconds, while a 2048-bit certificate causes it to take about 9 seconds. However, 1024-bit certificates are considered cryptographically insecure. This said, the primary motivation of this project is to enable web browser APIs that require HTTPS on Pico W devices running in a private, local network that is already protected.
2238

2339

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
adafruit_httpserver==2.3.0

scripts/deploy.sh

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#!/usr/bin/env bash
2+
3+
set -euo pipefail
4+
5+
script_directory="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
6+
project_directory="$script_directory/.."
7+
8+
if ! command -v rsync &> /dev/null; then
9+
echo 'rsync is not installed on this computer. rsync is used to copy the application code to your device. Install it using the package manager you use with your OS.'
10+
exit 1
11+
fi
12+
13+
if ! command -v circup &> /dev/null; then
14+
echo 'circup is not installed on this computer. circup is used to install CircuitPython dependencies on your device. Install it by following the instructions in the circup repository at: https://github.com/adafruit/circup'
15+
exit 1
16+
fi
17+
18+
echo 'Detecting your CircuitPython device...'
19+
device_path=$(python3 -c 'import circup; print(circup.find_device())')
20+
if [ "$device_path" == 'None' ]; then
21+
echo 'circup could not detect a connected CircuitPython device. Make sure your device is flashed with CircuitPython and connected to your computer with a USB data cable.'
22+
exit 1
23+
fi
24+
echo "Found device at $device_path"
25+
26+
echo 'Copying application code...'
27+
rsync --verbose --recursive --delete --checksum \
28+
--include '/._*' --exclude '/.*' \
29+
--exclude '/boot_out.txt' --exclude '/settings.toml' \
30+
"$project_directory/src/" "$device_path"
31+
echo 'Finished copying application code'
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#!/usr/bin/env bash
2+
3+
set -euo pipefail
4+
5+
script_directory="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
6+
7+
# Derived from https://www.linode.com/docs/guides/create-a-self-signed-tls-certificate/
8+
openssl req -new -newkey rsa:1024 -x509 -sha256 -days 365 -nodes \
9+
-subj '/CN=picow.local' \
10+
-out "$script_directory/../src/certificates/certificate-chain.pem" \
11+
-keyout "$script_directory/../src/certificates/key.pem"

scripts/repl.sh

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#!/usr/bin/env bash
2+
3+
set -euo pipefail
4+
5+
device=$(ls -1 -t /dev/tty.usbmodem*)
6+
7+
# Reattach to an existing session if one exists; otherwise create a new one
8+
screen -D -R -S circuitpython "$device" 115200
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
-----BEGIN CERTIFICATE-----
2+
MIIBozCCAQwCCQCwlOkfTi8J9zANBgkqhkiG9w0BAQsFADAWMRQwEgYDVQQDDAtw
3+
aWNvdy5sb2NhbDAeFw0yMzAyMjgwNTQyNTZaFw0yNDAyMjgwNTQyNTZaMBYxFDAS
4+
BgNVBAMMC3BpY293LmxvY2FsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDq
5+
UQiuhGBzHCLaesEjk6e6Kx7iNAKneaPht0Q6TsvF+IgOpuQFNkvQTU5S7POKDl2c
6+
UGkMT9Q1x4xRdM3u3qT3OmutyAtfL94RkK1qsblJwIH8xop5p7P+gwHTT4UOEicj
7+
MOSYBmkI6YvO/QImGdEoezWBqxKjOzyYLnv4UrwtYQIDAQABMA0GCSqGSIb3DQEB
8+
CwUAA4GBABuzaLw1tcFNYZ0ViWnii1j97otemOFkM31TW8Ohm3zRS6f/aQi+hujN
9+
BYMWIhxlK2cr0zsN+mXCVZN5u2BY0Q/w/7cNMBPNcGG7dJCGoBJRKRbEoBb/AMaO
10+
vjp0giQ8kFOtRcf0Gun5gPdDcmZayZwU1n/V1Q7UjwKXcqe0+eXu
11+
-----END CERTIFICATE-----

src/certificates/key.pem

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
-----BEGIN PRIVATE KEY-----
2+
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAOpRCK6EYHMcItp6
3+
wSOTp7orHuI0Aqd5o+G3RDpOy8X4iA6m5AU2S9BNTlLs84oOXZxQaQxP1DXHjFF0
4+
ze7epPc6a63IC18v3hGQrWqxuUnAgfzGinmns/6DAdNPhQ4SJyMw5JgGaQjpi879
5+
AiYZ0Sh7NYGrEqM7PJgue/hSvC1hAgMBAAECgYEAvZ05s0/4ZO493iM8LDgOoP7I
6+
DTEdfL1Yuw19LtoY2GmYYJL5LqaTj0sfuMd7BRs+8YG4oHfxOFv01u34v/Z38vRa
7+
E0tzSMVz29CRF0LUcko7c8Q2TzeTVsk3tEb3Kuf3tfVh5bhhjSakhUIY7D+Gb6LT
8+
GRIUg72tP9wjayTDsCkCQQD6oyJqxUhxuuiL5D+e0ssp582YruEJK4f5CzRsjmVV
9+
COBbqzRkIMCxPMCJCB+DbiMPlu/6CuxGh6i8rczDlkdfAkEA71SAt9PFx3hLW0hu
10+
OBR9w7BF6B2YTR3cG5+SQXOiF1feMUIaAn/dDr1OxqAQ/hQ/QKUk5JDwquy6phYT
11+
9qWDPwJBAPMqGLccBkgI/ZrTbIILov5aHdcXO88ow7f0jf0QPfG9NebZ+G94c1rB
12+
RU7taZ2a2jtCxjqCJG/dJ/E+cZ4Ei+MCQFu3O3i2/FU7wU0jDbIKEEQc2j1gkgwD
13+
hGVFmovgn15ouuqPlV4d1/4dCAJQNxLXeYHxh5jb/o7SF5ksXswnk4sCQA7Jlj5M
14+
8+7qQV9DrOieFGpXMqlc9J6u9L0Tev2P9uE7a7z61NvLIdskGDpiaYOmADob5nHo
15+
Duv3lSMQg6ql7EE=
16+
-----END PRIVATE KEY-----

src/code.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import os
2+
import ssl
3+
import time
4+
import traceback
5+
6+
import socketpool
7+
import supervisor
8+
import wifi
9+
10+
from adafruit_httpserver.server import HTTPServer
11+
12+
13+
def main() -> None:
14+
print("Connecting to the local Wi-Fi network...")
15+
wifi.radio.hostname = "picow"
16+
wifi.radio.connect(
17+
os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")
18+
)
19+
print("Connected to the local network")
20+
print(f" IP address = {wifi.radio.ipv4_address}")
21+
print(f" Router = {wifi.radio.ipv4_gateway}")
22+
print(f" DNS server = {wifi.radio.ipv4_dns}")
23+
24+
host = str(wifi.radio.ipv4_address)
25+
pool = socketpool.SocketPool(wifi.radio)
26+
http_server = HTTPServer(pool)
27+
http_server.start(host, port=80, root_path="public_html")
28+
29+
ssl_context = ssl.create_default_context()
30+
# The Pico is the server and does not require a certificate from the client, so disable
31+
# certificate validation by explicitly specifying no verification CAs
32+
ssl_context.load_verify_locations(cadata="")
33+
ssl_context.load_cert_chain(
34+
"certificates/certificate-chain.pem", "certificates/key.pem"
35+
)
36+
tls_pool = TLSServerSocketPool(pool, ssl_context)
37+
https_server = HTTPServer(tls_pool)
38+
https_server.start(host, port=443, root_path="public_html")
39+
40+
print()
41+
print("The web server is listening on:")
42+
print(f" http://{host}")
43+
print(f" https://{host}")
44+
print(f" http://{wifi.radio.hostname}.local")
45+
print(f" https://{wifi.radio.hostname}.local")
46+
print()
47+
48+
while True:
49+
http_server.poll()
50+
try:
51+
https_server.poll()
52+
except OSError as error:
53+
if error.strerror.startswith("MBEDTLS_ERR_"):
54+
print(f"TLS library error {error.strerror} with code {error.errno}")
55+
else:
56+
raise
57+
58+
59+
class TLSServerSocketPool:
60+
def __init__(self, pool, ssl_context):
61+
self._pool = pool
62+
self._ssl_context = ssl_context
63+
64+
@property
65+
def AF_INET(self):
66+
return self._pool.AF_INET
67+
68+
@property
69+
def SOCK_STREAM(self):
70+
return self._pool.SOCK_STREAM
71+
72+
def socket(self, *args, **kwargs):
73+
socket = self._pool.socket(*args, **kwargs)
74+
return self._ssl_context.wrap_socket(socket, server_side=True)
75+
76+
def getaddrinfo(self, *args, **kwargs):
77+
return self._pool.getaddrinfo(*args, **kwargs)
78+
79+
80+
try:
81+
main()
82+
except Exception as exception:
83+
print("".join(traceback.format_exception(exception, limit=8)))
84+
print("Reloading in 3 seconds...")
85+
time.sleep(3)
86+
supervisor.reload()
150 Bytes
Binary file not shown.
891 Bytes
Binary file not shown.
190 Bytes
Binary file not shown.
2.58 KB
Binary file not shown.
1.01 KB
Binary file not shown.
1.86 KB
Binary file not shown.

src/lib/adafruit_httpserver/route.mpy

338 Bytes
Binary file not shown.
2.19 KB
Binary file not shown.
486 Bytes
Binary file not shown.

src/public_html/index.html

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
<!DOCTYPE html>
2+
<title>Hello world &middot; Raspberry Pi Pico W</title>
3+
<p>Hello world from Raspberry Pi Pico W!</p>

0 commit comments

Comments
 (0)