Based on https://www.hardill.me.uk/wordpress/2019/11/02/pi4-usb-c-gadget/
Tested on DietPi (Janurary 2023) on a RPI Zero W.
Download and install the latest DietPi and enable wifi configurations etc. Setup can be done headlessly - look in the boot partition of the sdcard
- Add
dtoverlay=dwc2
to the/boot/config.txt
- Add
modules-load=dwc2
to the end of/boot/cmdline.txt
- Add
libcomposite
to/etc/modules
- (Rasberry Pi OS ONLY) Add
denyinterfaces usb0
to /etc/dhcpcd.conf
- Install iptables and dnsmasq with:
apt install dnsmasq iptables
- Create
/etc/dnsmasq.d/usb
with following content
interface=usb0
dhcp-range=10.55.0.2,10.55.0.6,255.255.255.248,1h
dhcp-option=3,10.55.0.1
dhcp-option=6,9.9.9.9
leasefile-ro
- Create
/etc/network/interfaces.d/usb0
with the following content
auto usb0
allow-hotplug usb0
iface usb0 inet static
address 10.55.0.1
netmask 255.255.255.248
Create /opt/usb.sh
with the following content
#!/bin/bash
cd /sys/kernel/config/usb_gadget/
mkdir -p pi
cd pi
echo 0x1d6b > idVendor # Linux Foundation
echo 0x0104 > idProduct # Multifunction Composite Gadget
echo 0x0100 > bcdDevice # v1.0.0
echo 0x0200 > bcdUSB # USB2
echo 0xEF > bDeviceClass
echo 0x02 > bDeviceSubClass
echo 0x01 > bDeviceProtocol
mkdir -p strings/0x409
echo "fedcba9876543211" > strings/0x409/serialnumber
echo "Raspberry Pi" > strings/0x409/manufacturer
echo "PI USB Device" > strings/0x409/product
mkdir -p configs/c.1/strings/0x409
echo "Config 1: ECM network" > configs/c.1/strings/0x409/configuration
echo 250 > configs/c.1/MaxPower
# Add functions here
# see gadget configurations below
# End functions
mkdir -p functions/ecm.usb0
HOST="00:dc:c8:f7:75:14" # "HostPC"
SELF="00:dd:dc:eb:6d:a1" # "BadUSB"
echo $HOST > functions/ecm.usb0/host_addr
echo $SELF > functions/ecm.usb0/dev_addr
ln -s functions/ecm.usb0 configs/c.1/
udevadm settle -t 5 || :
ls /sys/class/udc > UDC
ifup usb0
service dnsmasq restart
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
iptables -A FORWARD -i wlan0 -o usb0 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i usb0 -o wlan0 -j ACCEPT
- Make /opt/usb.sh executable with
sudo chmod +x /opt/usb.sh
- Add that script to /etc/rc.local:
#!/bin/bash
/opt/usb.sh
exit 0
- Make rc.local executable
sudo chmod +x /etc/rc.local
- And reboot to finish!
A few things to note:
- You can ssh into the rpi at
[email protected]
- This is designed for Linux clients - untested on windows etc.
- This guide should work with the following PIs:
- Zero (although not that useful because no wifi)
- Zero W
- Zero 2 (aka 2W)
- 4B (aka 4)