Let me describe what was my needs and how I achieved what I needed.
Need
Connect RPI to WiFi using WiFi USB adapter and share internet connection to Ethernet cable, connected to actual router. RPI configuration done via SSH.
Steps
Insert WiFi USB adapter and internet cable to RPI. In the following steps - WiFi adapter will be called wlan0 and Ethernet interface will be called eth0.
Connect RPI to WiFi using your preferred method (nmtui
or netctl
). Ensure it connects automatically after boot.
Execute this script on boot (as root):
#!/bin/bash
# Enable IPv4 and IPv6 forwarding (feature):
sysctl net.ipv4.ip_forward=1
sysctl net.ipv6.conf.default.forwarding=1
sysctl net.ipv6.conf.all.forwarding=1
# Assign IP address to eth0:
ip link set up dev eth0
ip addr add 10.42.0.1/24 dev eth0
# Set up NAT:
iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i eth0 -o wlan0 -j ACCEPT
- Connect Ethernet cable to Router (so it's RPI <--> Router) and use the following WAN settings in router configuration page. Note that RPI does not have DHCP server, so you need to use static IP:
IP address: 10.42.0.100
Subnet mask: 255.255.255.0
Gateway: 10.42.0.1
Additional suggestions
Computer instead of Router
Yes, you can do it. Since I will not cover DHCP server configuration on RPI, you are on your own, otherwise use static IP address as I've described for router.
DNS
In router WAN settings, do not forget to set your preferred DNS settings as well. I would suggest using pi-hole (or any other) DNS server on RPI, so in WAN settings you would set DNS IP the same as gateway IP. Same DNS server could be used in RPI network settings.
Firewall
If this is the case that you do not want WiFi owner to be able to connect to your RPI via SSH or see any service, append the following lines at the end of script file, which you execute on boot:
# Firewall stuff:
iptables -A INPUT -s 192.168.0.1 -j ACCEPT
iptables -A INPUT -s 192.168.0.0/24 -j DROP
iptables -A OUTPUT -d 192.168.0.1 -j ACCEPT
iptables -A OUTPUT -d 192.168.0.0/24 -j DROP
Explanation: first 2 lines blocks all incoming traffic from 192.168.0.* except 192.168.0.1 (router). last 2 lines does the same, but for outgoing traffic.
Share internet from eth0 to wlan0
Just use create_ap script. Search in official repositories - it should be in there. There is no easier way that this - no additional configuration or scripting required - just single command line to start WiFi AP.