In this article a howto is outlined for mass deployment of LEDE on commodity hardware:
TP-Link WDR3600 - 802.11an, 70€
TP-Link WDR4300 - 802.11an, 70€
TP-Link Archer C7 - 802.11ac, cost 100€
Comfast E380AC - 802.11ac, 48V PoE, cost 120€
All of those devices use Atheros chipsets, which means you get multiple SSID support and good compatibility with various client devices.
With WDR3600/4300 you get about 150Mbps actual throughput on 5Ghz band and 300-400Mbps with Comfast and Archer. Note that some mobile devices may be utilize only half of the bandwidth because of having only 1 receive stream available.
In noisy environment some of the devices drop to 2.4GHz band giving you about 70Mbps throughput there. 5GHz and 2.4GHz bands in total can serve 30 iPads for sure.
In order to include custom configuration within the flashable image LEDE image builder can be used.
First fetch LEDE image builder:
wget http://downloads.lede-project.org/releases/17.01.4/targets/ar71xx/generic/lede-imagebuilder-17.01.4-ar71xx-generic.Linux-x86_64.tar.xz
tar xvf lede-imagebuilder-17.01.4-ar71xx-generic.Linux-x86_64.tar.xz
cd lede-imagebuilder-17.01.4-ar71xx-generic.Linux-x86_64/
mkdir -p overlay/etc/uci-default
To set colorful command prompt and window title in terminal emulator drop following to overlay/etc/profile:
#!/bin/sh
[ -f /etc/banner ] && cat /etc/banner
[ -e /tmp/.failsafe ] && cat /etc/banner.failsafe
export PATH=/usr/bin:/usr/sbin:/bin:/sbin
export HOME=$(grep -e "^${USER:-root}:" /etc/passwd | cut -d ":" -f 6)
export HOME=${HOME:-/root}
export PS1='\u@\h:\w\$ '
[ -z "$KSH_VERSION" -o \! -s /etc/mkshrc ] || . /etc/mkshrc
[ -x /bin/more ] || alias more=less
[ -x /usr/bin/vim ] && alias vi=vim || alias vim=vi
[ -x /usr/bin/arp ] || arp() { cat /proc/net/arp; }
[ -x /usr/bin/ldd ] || ldd() { LD_TRACE_LOADED_OBJECTS=1 $*; }
HOSTNAME=$(uci get system.@system[0].hostname)
DOMAIN=$(uci -q get dhcp.@dnsmasq[0].domain)
if [ $? -eq 0 ]; then
FQDN=$HOSTNAME.$DOMAIN
else
FQDN=$HOSTNAME
fi
export PS1='\[\033[01;31m\]$FQDN\[\033[01;34m\] \W #\[\033[00m\] '
case "$TERM" in
xterm*|rxvt*)
echo -ne "\033]0;${USER}@${FQDN}:${PWD}\007"
;;
*)
;;
esac
Generate unique hostname using overlay/etc/uci-defaults/40-hostname:
MODEL=$(cat /etc/board.json | jsonfilter -e '@["model"]["id"]')
# Hostname prefix
case $MODEL in
tl-*|archer-*) VENDOR=tplink ;;
cf-*) VENDOR=comfast ;;
*) VENDOR=ap ;;
esac
# Network interface with relevant MAC address
case $MODEL in
tl-wdr*) NIC=wlan1 ;;
archer-*) NIC=eth1 ;;
cf-e380ac-v2) NIC=eth0 ;;
*) NIC=wlan0 ;;
esac
HOSTNAME=$VENDOR-$(cat /sys/class/net/$NIC/address | cut -d : -f 4- | sed -e 's/://g')
uci set system.@system[0].hostname=$HOSTNAME
uci set network.lan.hostname=$HOSTNAME
Reconfigure device to work as access point overlay/etc/uci-defaults/50-access-point:
# Disable DHCP servers
/etc/init.d/odhcpd disable
/etc/init.d/dnsmasq disable
# Remove firewall rules since AP bridges ethernet to wireless anyway
uci delete firewall.@zone[1]
uci delete firewall.@zone[0]
uci delete firewall.@forwarding[0]
for j in $(seq 0 10); do uci delete firewall.@rule[0]; done
# Remove WAN interface
uci delete network.wan
uci delete network.wan6
# Reconfigure DHCP client for bridge over LAN and WAN ports
uci delete network.lan.ipaddr
uci delete network.lan.netmask
uci delete network.lan.ip6assign
uci delete network.globals.ula_prefix
uci delete network.@switch_vlan[1]
uci delete dhcp.@dnsmasq[0].domain
uci set network.lan.proto=dhcp
uci set network.lan.ipv6=0
uci set network.lan.ifname='eth0'
uci set network.lan.stp=1
# Radio ordering differs among models
case $(uci get wireless.radio0.hwmode) in
11a) uci rename wireless.radio0=radio5ghz;;
11g) uci rename wireless.radio0=radio2ghz;;
esac
case $(uci get wireless.radio1.hwmode) in
11a) uci rename wireless.radio1=radio5ghz;;
11g) uci rename wireless.radio1=radio2ghz;;
esac
# Reset virtual SSID-s
uci delete wireless.@wifi-iface[1]
uci delete wireless.@wifi-iface[0]
# Pseudorandomize channel selection, should work with 80MHz on 5GHz band
case $(uci get system.@system[0].hostname | md5sum) in
1*|2*|3*|4*) uci set wireless.radio2ghz.channel=1; uci set wireless.radio5ghz.channel=36 ;;
5*|6*|7*|8*) uci set wireless.radio2ghz.channel=5; uci set wireless.radio5ghz.channel=52 ;;
9*|0*|a*|b*) uci set wireless.radio2ghz.channel=9; uci set wireless.radio5ghz.channel=100 ;;
c*|d*|e*|f*) uci set wireless.radio2ghz.channel=13; uci set wireless.radio5ghz.channel=132 ;;
esac
# Create bridge for guests
uci set network.guest=interface
uci set network.guest.proto='static'
uci set network.guest.address='0.0.0.0'
uci set network.guest.type='bridge'
uci set network.guest.ifname='eth0.156' # tag id 156 for guest network
uci set network.guest.ipaddr='0.0.0.0'
uci set network.guest.ipv6=0
uci set network.guest.stp=1
# Disable switch tagging and bridge all ports on TP-Link WDR3600/WDR4300
case $(cat /etc/board.json | jsonfilter -e '@["model"]["id"]') in
tl-wdr*)
uci set network.@switch[0].enable_vlan=0
uci set network.@switch_vlan[0].ports='0 1 2 3 4 5 6'
;;
*) ;;
esac
Configure site-specific settings in overlay/etc/uci-defaults/99-site-name:
# Configure tagging
uci set network.lan.ifname='eth0.3' # Password protected network VLAN3 tagged
uci set network.guest.ifname='eth0.4' # Public network VLAN4 tagged
# Configure wireless networks
for band in 2ghz 5ghz; do
uci delete wireless.radio$band.disabled
uci set wireless.radio$band.country=EE
uci set wireless.lan$band=wifi-iface
uci set wireless.lan$band.network=lan
uci set wireless.lan$band.mode=ap
uci set wireless.lan$band.device=radio$band
uci set wireless.lan$band.encryption=psk2+ccmp
uci set wireless.lan$band.ssid=Robootikaklubi
uci set wireless.lan$band.key='salakala'
uci set wireless.guest$band=wifi-iface
uci set wireless.guest$band.network=guest
uci set wireless.guest$band.mode=ap
uci set wireless.guest$band.device=radio$band
uci set wireless.guest$band.encryption=none
uci set wireless.guest$band.ssid=RobootikaklubiAvalik
done
# Add Lauri's Yubikey
cat > /etc/dropbear/authorized_keys << \EOF
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCb4iqSrJrA13ygAZTZb6ElPsMXrlXXrztxt3bcKuEbAiWOm9lR17puRLMZbM2tvAW+iwsDHfQAs0E6HDprP68nt+SGkQvItUtYeJBWDI405DbRodmDMySahmb6o6S3sqI4vryydOg1G+Z0DITksZzp91Ow+C++emk6aqWfXh7xATexCvKphfwXrBL+MDIwx6drIiN0FD08yd/zxGAlcQpR8o6uecmXdk32wL5W3+qqwbJrLjZmOweij5KSXuEARuQhM20KXzYzzQIAKqhIoALRSEX31L0bwxOqfVaotzk4TWKJSeetEhBOd7PtH0ZrmOHF+B20Ym+V3UkRY5P4calF
EOF
# Set root password to 'salakala'
sed -i 's|^root::|root:$1$LLo9T/Zr$cCp.dy5W.Om9oQ4LboQNz.:|' /etc/shadow
Use following command to build the image, this shall include collectd, strongswan and some other useful utils:
export PACKAGES="luci luci-app-commands \
collectd collectd-mod-conntrack collectd-mod-interface \
collectd-mod-iwinfo collectd-mod-load collectd-mod-memory \
collectd-mod-network collectd-mod-protocols collectd-mod-tcpconns \
collectd-mod-uptime \
openssl-util curl ca-certificates \
strongswan-mod-aes strongswan-mod-gmp strongswan-mod-hmac \
strongswan-mod-kernel-netlink strongswan-mod-md5 strongswan-mod-random \
strongswan-mod-sha1 strongswan-mod-updown strongswan-mod-curl \
strongswan-mod-resolve strongswan-minimal \
kmod-crypto-authenc kmod-crypto-cbc kmod-crypto-hmac \
kmod-crypto-md5 kmod-crypto-sha1 \
htop iftop tcpdump nmap nano -odhcp6c -odhcpd -dnsmasq \
-luci-app-firewall \
-pppd -luci-proto-ppp -kmod-ppp -ppp -ppp-mod-pppoe \
-kmod-ip6tables -ip6tables -luci-proto-ipv6 -kmod-iptunnel6 -kmod-ipsec6"
for MODEL in tl-wdr3600-v1 tl-wdr4300-v1 archer-c7-v2 cf-e380ac-v2; do
make image PROFILE=$MODEL FILES=overlay/ PACKAGES="$PACKAGES"
done
I use Turris as my portable flashing unit since it has enough built in storage to house all the images I need:
mkdir -p /srv/tftpboot
uci set dhcp.@dnsmasq[0].enable_tftp=1
uci set dhcp.@dnsmasq[0].tftp_root=/srv/tftpboot
uci commit
/etc/init.d/dnsmasq restart
Create IP aliases, I put this in /etc/rc.local:
ifconfig br-lan:1 192.168.0.66 # WDR3600, WDR3400 uses 192.168.0.86
ifconfig br-lan:2 192.168.1.66 # TP-Link Archer C7 uses 192.168.1.86
ifconfig br-lan:3 192.168.1.10 # Comfast E380AC uses 192.168.1.1
Copy image builder generated images to your TFTP server:
scp bin/targets/ar71xx/generic/*-cf-e380ac-v2-squashfs-sysupgrade.bin \
root@router:/srv/tftpboot/
scp bin/targets/ar71xx/generic/*-archer-c7-v2-squashfs-factory-eu.bin \
root@router:/srv/tftpboot/
scp bin/targets/ar71xx/generic/*-tl-wdr4300-v1-squashfs-factory.bin \
root@router:/srv/tftpboot/
scp bin/targets/ar71xx/generic/*-tl-wdr3600-v1-squashfs-factory.bin \
root@router:/srv/tftpboot/
The bootloaders of the devices expect to find firmware images on the TFTP by known filenames, so rename the files:
cd /srv/tftpboot/
cp *-tl-wdr3600-v1-squashfs-factory.bin wdr3600v1_tp_recovery.bin
cp *-tl-wdr4300-v1-squashfs-factory.bin wdr4300v1_tp_recovery.bin
cp *-archer-c7-v2-squashfs-factory-eu.bin ArcherC7v2_tp_recovery.bin
cp *-cf-e380ac-v2-squashfs-sysupgrade.bin firmware_auto.bin
TP-Link WDR3600 from v1.5 on expects u-boot prepended image, to work around the issue you can prepend the u-boot blob from the original firmware:
opkg update
opkg install unzip
wget http://www.tplink.com/res/down/soft/TL-WDR3600_V1_150518.zip
unzip -n TL-WDR3600_V1_150518.zip
dd if='wdr3600v1_en_3_14_3_up_boot(150518).bin' bs=512 count=257 of=/tmp/recovery-header.bin
cat /tmp/recovery-header.bin *-tl-wdr3600-v1-squashfs-factory.bin > /tmp/concat.bin
dd if=/tmp/concat.bin of=wdr3600v1_tp_recovery.bin bs=512 count=16001
Same goes for TP-Link WDR4300:
wget http://www.tplink.com/res/down/soft/TL-WDR4300_V1_150518.zip
unzip -n TL-WDR4300_V1_150518.zip
dd if='wdr4300v1_en_3_14_3_up_boot(150518).bin' bs=512 count=257 of=/tmp/recovery-header.bin
cat /tmp/recovery-header.bin *-tl-wdr4300-v1-squashfs-factory.bin > /tmp/concat.bin
dd if=/tmp/concat.bin of=wdr4300v1_tp_recovery.bin bs=512 count=16001
To force device to flash itself from TFTP server:
TP-Link Archer C7, WDR4300 - Plug network cable into one of the yellow ports, hold reset and power on the device
Comfast E380AC always tries to load firmware over TFTP during boot, on one hand this might look like a security flaw, yet again this makes updating image easier, just double flip the circuit braker
Observe TFTP server log, in case of Turris:
tail -f /var/log/messages | grep dnsmasq
logread -f | grep dnsmasq
You should see something similar:
2017-09-15T06:17:15+02:00 info dnsmasq-tftp[18681]: sent /srv/tftpboot/ArcherC7v2_tp_recovery.bin to 192.168.1.86
2017-09-15T07:59:16+02:00 info dnsmasq-tftp[22031]: sent /srv/tftpboot/wdr3600v1_tp_recovery.bin to 192.168.0.86
2017-09-15T08:30:10+02:00 info dnsmasq-tftp[22031]: sent /srv/tftpboot/firmware_auto.bin to 192.168.1.1
For a budget wireless networks this is a competitive alternative.
Only missing bit is central management
Virtualization enables better utilization of hardware by making it possible to run multiple operating systems on same computer. Even in a small company you might need to run Active Directory on Windows Server and WordPress on Ubuntu server, but purchasing two physical servers for each application is suboptimal.
The problem with virtualization is that it can refer to several different approaches and nuances. In classic terms virtualization usually refers to emulation of a whole computer with all accompanying hardware - that means CPU, memory management unit, storage, network, timers etc.
For example on IBM S390 processor and memory virtualization was supported from the start whereas on Intel x86 CPU and memory virtualization were added later incrementally.
VirtualBox and similar products made it possible to reach near-native speeds by the means of dynamic translation even on processors without hardware support for CPU or memory virtualization, but breakthrough for x86 was achieved in 2005, when Intel and AMD added hardware support.
In case of server consolidation the deduplication of memory and storage is important. For example Linux supports kernel samepage merging since version 2009. The kernel regularly scans the memory and calculates checksums for memory blocks. Memory blocks with identical checksums are merged and marked as copy-on-write. Running identical guest operating systems on such host yields significant memory usage drop regardless of virtualization software used. To enable deduplication for storage an approrpiate filesystem should be used. ZFS supports inline deduplication if enabled, this means that once a block is written to filesystem the kernel looks up the checksum of the block from RAM.
QEMU is a emulator created by Fabrice Bellard and at this point it supports x86, MIPS, Sun SPARC, ARM, PowerPC and several other architectures.
With KVM project CPU and memory virtualization support was added to Linux as a kernel module, hence the name kernel virtual machine. Additionally QEMU was patched to take advantage of the newly added functionality:
Under KVM unmodified Windows can be booted without significant performance loss. To make sure KVM works as expected check that kvm-intel or kvm-amd appears in lsmod, it might be that virtualization extensions are disabled in BIOS or if BIOS battery is dead and motherboard keeps forgetting the settings.
To run local virtual machine with 1GB of RAM and dual core CPU on Ubuntu:
apt install qemu-kvm
truncate -s 20G hdd.bin
qemu-kvm -m 1024 -smp 2 \
-hda hdd.bin \
-cdrom ubuntu-mate-16.04.2-desktop-amd64.iso
By default QEMU emulates IDE controller for storage and Intel network interface card (e1000). QEMU also takes care of emulating a router with DHCP server, so the virtual machine is assigned an IP address of 10.0.2.15 and the router sits at 10.0.2.2. The TCP and UDP network traffic generated by the guest OS appears as if it was generated the QEMU process, note that with user-mode networking ping is not available.
For more complex networking scenarios TAP interface can be used, in which case a virtual network interface is created in the host and guest's network traffic appears on that interface. This can be used to talk to the host or in conjuction with bridges can be used to expose virtual machines's traffic to external network interfaces.
Paravirtualization is a technique which allows significant performance boost for virtualized operating systems which are aware of running on virtualized hardware. Paravirtualization usually covers storage and networking, but paravirtualization could also refer to memory ballooning, which means that the guest OS marks unused memory blocks and the host OS can reclaim those blocks.
In case of paravirtualization the guest operating system is presented with hardware optimized for virtualization which in real life does not exist. In many cases first guest OS is installed as usual presenting let's say standard SATA controller and emulated Intel network card. Once guest additions package provided by the virtualization software vendor is installed the hypervisor swaps out the hardware presented to the guest OS. In case of VMware for example VMnet is presented, under KVM virtio network device by Red Hat is presented although Red Hat has never developed or manufactured any hardware.
The virtio paravirtualization framework is now used for storage and networking and it is out of the box supported under Linux and BSD guests, this means no additional drivers need to be installed for KVM based virtual machines. Microsoft Hyper-V and VMware use similar but different approach, but are not virtio compatible. Currently Linux guests should work out of the box under Hyper-V and ESXi.
To enable network, storage and video output paravirtualization for KVM based virtual machine started from command line:
qemu-kvm -m 1024 -smp 2 -cpu host -boot menu=on \
-drive file=ubuntu-mate-16.04.2-desktop-amd64.iso,if=virtio,media=cdrom \
-drive file=hdd.bin,format=raw,if=virtio,discard=unmap \
-net nic,vlan=42,model=virtio -net user,vlan=42 \
-balloon virtio \
-vga virtio
In the past paravirtualization also referred to running modified guest operating systems on hardware that didn't support for example CPU or memory virtualization. For example Microsoft created a modified version of Windows suitable for running on Xen hypervisor.
LXC (Linux Containers) is essentially OpenVZ successor and both of them are similar to BSD Jails and Solaris Zones. Even Microsoft has added containers to Windows Server. Docker used LXC in the past but now has moved to it's own direction whilst making use of the same kernel infrastructure.
In case of containers the root filesystems are split, that is folders which contain OS files are separate, but the kernel which is used by the containers is same and hence shared. Using control groups allows separation of processes and network interfaces.
In case of LXC memory or disk space is not reserved for the container, keeping the resource usage optimal accross the containers.
Process tree for such setup looks approximately something like following:
systemd
├─acpid
├─agetty --noclear tty1 linux
├─atd -f
├─cron -f
├─dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation
├─dhclient -v -pf /run/dhclient.lxcbr0.pid -lf /var/lib/dhcp/dhclient.lxcbr0.leases lxcbr0
├─lxc-start -d -n ubuntu-trusty-test
│ └─init
│ ├─dbus-daemon --system --fork
│ ├─dhclient -1 -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0
│ ├─getty -8 38400 console
│ ├─cron
│ ├─sshd -D
│ ├─systemd-logind
│ ├─systemd-udevd --daemon
│ ├─upstart-file-br --daemon
│ ├─upstart-socket- --daemon
│ └─upstart-udev-br --daemon
├─lxc-start -g debian-wheezy-test
│ └─systemd
│ ├─dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation
│ ├─dhclient -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0
│ ├─agetty --noclear -s console 115200 38400 9600
│ ├─cron
│ ├─sshd -D
│ ├─systemd-journal
│ ├─systemd-logind
│ └─systemd-udevd
├─lxc-start -d -n debian-jessie-test
│ └─systemd
│ ├─dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation
│ ├─dhclient -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0
│ ├─sshd -D
│ ├─systemd-journal
│ └─systemd-logind
├─sshd -D
├─systemd-journal
├─systemd-logind
└─systemd-udevd
Here it is seen that each container has it's own virtual eth0 interface and DHCP client has been started in each container. Since every container appears on the network with it's distinct IP address, connecting to a container is as easy as installing OpenSSH server in the container.
Note that containers have security implications - kernel vulnerabilities can make it possible to hijack the host machine. Additionally each syscall needs to be aware whether any namespace restrictions apply. For example as of this writing Btrfs syscalls haven't been refactored to accommodate filesystem namespacing, executing following command in an LXC container lists the subvolumes of the host machine as well, even though you would assume it wouldn't. Combining kernel vulnerability with short-sightedness of some kernel module might have disasterous consequences.
User-mode emulation of QEMU allows executing binaries compiled for foreign CPU architectures under Linux and Darwin/Mac OS X. Note that in case of user-mode emulation only the code that runs in userspace is translated, but syscalls which invoke kernelspace code are not. This means that emulated architectures are slower than native binaries, but not as slow as emulating the whole computer. This for example enables armhf development on x86-64.
Static binaries can be executed with either enabling the execute bit on the binary or supplying the binary as the argument for corresponding qemu command, eg qemu-arm-static. With dynamically linked programs the situation is stickier because the program will attempt to look up dependand shared libraries, so using a LXC container is the easiest way to run dynamically linked foreign programs:
apt install qemu-user-static binfmt-support
lxc-create -n fedora-arm-test -t download -- -d fedora -r 25 -a armhf
cp /usr/bin/qemu-arm-static /var/lib/lxc/fedora-arm-test/rootfs/usr/bin/
lxc-start -d -n fedora-arm-test
lxc-attach -n fedora-arm-test
Similarly it should be possible to run kfreebsd flavor of Debian or Ubuntu under FreeBSD Jail.
libvirt is a framework for managing hypervisors of different sorts - VirtualBox, KVM, ESXi, LXC, Xen, bhyve etc. It provides a daemon for creating, managing and deleting virtual machines and API-s to talk that daemon over SSH connection.
To turn your clean Ubuntu server installation to remotely managed KVM hypervisor:
apt install qemu-kvm libvirt-bin openssh-server bridge-utils vlan
To connect virtual machines with eachother and to the external world, reconfigure /etc/network/intefaces something similar to following:
# Management network to robotics club, replace address with unused IP
auto br-mgmt
iface br-mgmt inet static
address 192.168.12.4
netmask 255.255.255.0
gateway 192.168.12.1
dns-nameserver 192.168.12.1
bridge_ports enp3s0
# Bridge to connect virtual machines to public internet,
# exposed on one of the NIC-s on the physical machine
auto br-wan
iface br-wan inet static
address 0.0.0.0
bridge_ports enp5s0
# Internal network to connect virtual machines to eachother,
# not exposed on any NIC on the physical machine
auto br-lan
iface br-lan inet static
address 0.0.0.0
bridge_ports none
Set up public key based root access from your laptop to the machine and use virt-manager to connect to it. In fact you can use same virt-manager instance on your laptop to connect to several hypervisor machines:
To get best out of the storage performance add virtio SCSI controller and switch harddisk interfaces from SATA to SCSI. More tweaking is required to reclaim free disk space in the host and have optimal performance for SSD-s - see more information here. For each network interface select virtio as model. Note that on multi CPU installations it is also important to have NUMA configured correctly.
ESP8266 is a WiSoC running a custom 32bit RISC CPU core clocked at 80MHz with 64KiB of RAM for instructions and 96KiB for data.
ESP32 is ESP8266 successor running at 160MHz, includes 520KiB SRAM.
Both of them are basis for series of interesting SoM-s and development boards.
ESP-01 incorporates ESP8266 with 1MiB (8MBit) SPI Flash and PCB antenna. It's sold at around 1.5 USD on AliExpress. On ESP-01 two GPIO-s are available (numbered 0 and 2). When more pins are needed it's possible to make use of UART pins (numbered 1 and 3). Note that PWM is available only on pins 0 and 2.
ESP32 in very often packaged as ESP-WROOM-32 which includes 4MiB (32MBit) of SPI Flash and it's sold at Aliexpress for 4 USD.
Both ESP8266 and ESP32 have development boards available for around 10 USD. There are open source GCC toolchains and are suitable for building IoT devices.
NodeMCU is based on ESP-12 SOM and includes USB-UART bridge, 3.3V voltage regulator and PCB antenna
WeMos Lolin32 uses ESP-WROOM-32, includes LiPo charging circuit, voltage regulators and USB-UART bridge:
Note that board pin numbering rarely matches ESP-s pin numbering:
Even different revisions of the same board model have different pin mappings.
MicroPython is Python 3 for microcontrollers that runs on bare metal (no OS) and it implements a subset of the standard library. It was originally developed for STM32F405RG microcontroller, but later ported to others including ESP8266 and now ESP32 as well.
First install esptool, note that you need to upgrade to 2.x for ESP32 support:
pip install esptool
To install on ESP8266 based boards:
wget http://micropython.org/resources/firmware/esp8266-20170612-v1.9.1.bin
esptool.py -p /dev/ttyUSB0 -b 460800 erase_flash
esptool.py -p /dev/ttyUSB0 -b 460800 write_flash 0 esp8266-*.bin
To install on ESP32 based boards:
wget http://micropython.org/resources/firmware/esp32-20171206-v1.9.2-445-g84035f0f.bin
esptool.py -p /dev/ttyUSB0 -b 460800 erase_flash
esptool.py -p /dev/ttyUSB0 -b 460800 write_flash --flash_mode dio 0x1000 esp32-*.bin
Important
If your board doesn't have integrated USB-UART bridge, eg in case of ESP-01 you need a USB-UART bridge and to manually ground pin 0 to enable programming mode
First use following to open up Python prompt from the device, note that you can exit picocom by pressing Ctrl-A followed by Ctrl-Q:
picocom -b115200 /dev/ttyUSB0
First step is to press enter to see that Python interpreter is running, it should return >>> which is the indicator for Python prompt.
Next you can check what Python version is running:
import sys
sys.version # This should return 3.4.0 at the moment
To connect to wireless network, synchronize time and start web command prompt server paste following statements to the Python prompt:
# Connect to wireless network as client
import network
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("itcollege")
# Synchronize clock
import ntptime
ntptime.settime()
# Create a variable for hostname based on MAC address:
import ubinascii as binascii
name = "esp-%s" % binascii.hexlify(wlan.config("mac")[-3:]).decode("ascii")
# Clean up
import gc
gc.collect()
Save the same snippet into boot.py and then use either REPL over UART or WebREPL client upload the boot.py file. Note that you have to disconnect picocom to use REPL over UART.
pip install adafruit-ampy # Install Adafruit MicroPython Tool
ampy -p /dev/ttyUSB0 put boot.py # Upload boot.py over UART
Next reboot the script will be automatically executed and you'll have persistent connection to your wireless network.
MicroPython partitions the SPI Flash so the unused space is formatted as FAT filesystem and exposed over Python's filesystem interfaces. You can use WebREPL or REPL to list and upload files from your PC. Within Micropython you can use os.listdir to list files and open to manipulate file contents.
import os
block_size, _, blocks, blocks_free, _, _, _, _, _, _ = os.statvfs("")
print("Filesystem size: %d KiB" % (blocks * block_size >> 10))
print("Free space: %d KiB" % (blocks * blocks_free >> 10))
You should have couple hundred kilobytes free space for configuration files and some media files.
Machine specific interfaces are grouped to module machine at least on ESP8266 and ESP32. To blink on-board LED-s on WeMos D1:
# WeMos D1
from time import sleep
from machine import Pin
som_led = Pin(2, mode=Pin.OUT) # D9 on Wemos D1, LED on the SOM
sck_led = Pin(14, mode=Pin.OUT) # D13 on Wemos D1, LED connected to SCK
for i in range(0,10):
som_led.value(0) # Polarity inverted, pin sinks 3.3v
sck_led.value(1) # Pin sources voltage
sleep(0.2)
som_led.value(1)
sck_led.value(0)
sleep(0.2)
Even ESP-01 has a LED hooked to serial transmit pin:
# ESP-01
from time import sleep
from machine import Pin, reset
tx = Pin(1, mode=Pin.OUT)
for i in range(0,10):
tx.value(0) # Polarity inverted, pin sinks 3.3v
sleep(0.2)
tx.value(1)
sleep(0.2)
reset() # UART transmit pin is dead by now, reset device to restore serial
In this case an external push button is connected to D8 on WeMos D1, note that you can just use a jumper cable hanging freely and to simulate a button press the other end is just clicked against the USB port shielding (the ground).
from machine import Pin
from time import sleep
pin_led = Pin(14, mode=Pin.OUT) # D13 on Wemos D1, on-board LED connected (SCK)
pin_button = Pin(0, mode=Pin.IN) # D8 on Wemos D1
turned_on = False
while True:
if not pin_button.value():
turned_on = not turned_on
pin_led.value(turned_on)
sleep(0.01) # Sleep for 10ms
For other pins which dont have pull up resistors on-board an internal pull up resistor (fused into the integrated circuit) may be used:
pin = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP)
Note that on Wemos D1 pin 0 (D8) is connected via pull up to 3.3v rail to prevent accidental boots into flashing mode. This also keeps the voltage level high on the pin 0 (D8) if the wire is freely hanging.
Interrupts allow CPU to sleep for most time, in following example LED is toggled when button is released.
from machine import Pin
from time import sleep
pin_led = Pin(14, mode=Pin.OUT) # D13 on Wemos D1, on-board LED connected (SCK)
pin_button = Pin(0, mode=Pin.IN) # D8 on Wemos D1
turned_on = False
def callback(p):
global turned_on
turned_on = not turned_on
pin_led(turned_on)
pin_button.irq(trigger=Pin.IRQ_FALLING, handler=callback)
Note that most buttons don't have very realiable mechanics giving you several falling edge events during button press. Use capacitor on the switch pin to have more reliable operation or add code for debounce.
Timers are sort of like interrupts but instead of being triggered by a pin, they're triggered after certain amount of time.
from machine import Pin, Timer
from time import sleep
pin_led = Pin(14, mode=Pin.OUT) # D13 on Wemos D1, on-board LED connected (SCK)
pin_button = Pin(0, mode=Pin.IN) # D8 on Wemos D1
timer = Timer(-1)
def timeout_callback(t):
pin_led(0)
def button_callback(p):
pin_led(1)
timer.init(period=1000, mode=Timer.ONE_SHOT, callback=timeout_callback)
pin_button.irq(trigger=Pin.IRQ_FALLING, handler=button_callback)
Timer that executes callback repeatedly can be initialized with mode=Timer.PERIODIC.
Both ESP-s have hardware PWM generators which means you can get accurately timed squarewave signals which can be used to dim LED-s or drive motors.
# NodeMCU
from time import sleep_ms
from machine import Pin, PWM
led = PWM(Pin(2, Pin.OUT), freq=400) # Initialize at 400Hz
for j in range(0,10):
for i in range(1023,-1,-10):
led.duty(i)
sleep_ms(5)
for i in range(0, 1024, 10):
led.duty(i)
sleep_ms(2)
MicroPython doesn't come with HTTP server wrapper classes, but you can use Berkeley sockets style programming interfaces out of the box:
import socket
from machine import Pin
led_pin = Pin(5, Pin.OUT)
CONTENT = """\
HTTP/1.0 200 OK
Content-Type: text/html
<html>
<head>
</head>
<body>
<p>Hello #%d from MicroPython!</p>
<a href="/toggle">Click here to toggle LED hooked to pin 5</a>
</body>
</html>
"""
def main():
s = socket.socket()
ai = socket.getaddrinfo("0.0.0.0", 8080)
print("Bind address info:", ai)
addr = ai[0][-1]
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(5)
print("Listening, connect your browser to http://<this_host>:8080/")
counter = 0
while True:
sock, addr = s.accept()
print("Client address:", addr)
stream = sock.makefile("rwb")
req = stream.readline().decode("ascii")
method, path, protocol = req.split(" ")
print("Got", method, "request for", path)
if path == "/toggle":
led_pin.value(1-led_pin.value())
while True:
h = stream.readline().decode("ascii").strip()
if h == "":
break
print("Got HTTP header:", h)
stream.write((CONTENT % counter).encode("ascii"))
stream.close()
sock.close()
counter += 1
print()
main() # Press Ctrl-C to stop web server
MicroPython has BSD sockets style API for IP-based networks. For high level protocols such as HTTP and WebSockets modules are popping up.
In this example ESP is connected nchan enabled nginx web server. The configuration of nginx/nchan looks something like this. This configuration basically allows broadcasting messages between nodes connected to same nginx server even if the nodes are behind NAT or firewall:
server {
listen 80;
server_name iot.koodur.com;
root /var/www/iot;
location ~ "^/ws/(.*?)" {
nchan_channel_id $1;
nchan_pubsub websocket;
nchan_message_buffer_length 0;
}
}
Pull a Python module for creating websockets and upload it to ESP:
wget https://gist.githubusercontent.com/laurivosandi/2983fe38ad7aff85a5e3b86be8f00718/raw/cfa52f739080d42029d21017c5ae2a7b97793b06/uwebsockets.py
ampy -p /dev/ttyUSB0 put uwebsockets.py
Example code for ESP:
import sys
import uwebsockets
from machine import Pin, PWM
led = PWM(Pin(14, mode=Pin.OUT), freq=400) # SCK LED on WeMos D1
uri = "ws://iot.koodur.com:80/ws/living-room-of-lauri"
print("Connecting to:", uri)
conn = uwebsockets.connect(uri)
conn.send("alive")
while True:
print("Reading message...")
try:
fin, opcode, data = conn.read_frame()
except OSError: # Connection timeout or reset
sys.exit() # Soft reset
if data.startswith(b"duty:"):
led.duty(int(data[5:]))
else:
print("Got unknown command:", data)
Relevant code for the web:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var ws = new WebSocket("ws://iot.koodur.com:80/ws/living-room-of-lauri/");
ws.onopen = function (event) { console.info("websocket connected"); };
ws.onmessage = function (event) { console.log(event.data); }
var lastValue = false;
function duty(e) {
if (lastValue == e.value) return;
lastValue = e.value;
ws.send("duty:" + e.value);
}
</script>
</head>
<body>
<input type="range" min="0" max="1023" step="10" onMouseMove="duty(this);" onTouchMove="duty(this);"/>
</body>
</html>
Important
Replace living-room-of-lauri with an unique string, otherwise you'll end up flicking switch in my living room
In the example above the messages are broadcasted to all nodes connected to the same WebSockets URI, including the message publisher itself. For IoT lamp this is great, all lamps get the message and browsers as well - this helps keeping things in sync.
If you want to have sort of unicast communications between two nodes, you can try following nchan config:
server {
listen 80;
server_name iot.koodur.com;
root /var/www/iot;
location ~ "^/p2p/([\w\d\-]+)/([\w\d\-]+)" {
nchan_pubsub websocket;
nchan_message_buffer_length 0;
nchan_publisher_channel_id $1/$2;
nchan_subscriber_channel_id $2/$1;
}
}
On the ESP end use:
uri = "ws://iot.koodur.com:80/p2p/lamp-123456/browser/"
On the browser end use:
var ws = new WebSocket("ws://iot.koodur.com:80/p2p/browser/lamp-123456/");
This config shall prevent echoing messages to publisher as well.
Python module for driving such OLED screens can be pulled from MicroPython's Git repo:
wget https://raw.githubusercontent.com/micropython/micropython/master/drivers/display/ssd1306.py
ampy -p /dev/ttyUSB0 put ssd1306.py
Random ESP32 based board with a screen from AliExpress used I2C interface but the chip also supports SPI interace. In this case the I2C interace is bit banged on pins 4 and 5.
To paste chunks of indented text like the one below press Ctrl-E, paste the text as usual by right clicking in the terminal and selecting Paste. Once finished press Ctrl-D to tell Python interpreter that you're done.
from time import sleep_ms
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
i2c = I2C(-1, Pin(4),Pin(5),freq=400000) # Bitbanged I2C bus
assert 60 in i2c.scan(), "No OLED display detected!"
oled = SSD1306_I2C(128, 64, i2c)
buf = "wubba lubba dub dub "
oled.invert(0) # White text on black background
oled.contrast(255) # Maximum contrast
j = 0
while True:
oled.fill(0)
oled.text(buf[j%len(buf):]+buf, 10, 10)
oled.show()
sleep_ms(20)
j += 1
And it works!
According to datasheet ESP32 can be powered with 2.3V to 3.6V power source, but fiddling around with bench power supply the basic functionality seemed to be intact even with voltages from 2V to 4V drawing constantly 60mA. Below 2V or over 4V the ESP32 cuts it's power consumption.
ESP8266 is just enough to build WiFi connected LED lights or a Nixie clock. ESP32 is a bit beefier and suitable for building a sumorobot. Schematics and up to date code of MicroPython based, NTP-synchronized and IN-12 based Nixie clock can be found at GitHub.
KiCad is open source electronic design automation tool with a long history starting from 1992. CERN started supporting the project since 2013 which has contributed to the maturity of the project considerably.
KiCad distinctly separates logical design and physical design. First the electrical circuits are described with symbols. Then footprints are associated with the components. Footprints are then laid out on the PCB:
Some important default keyboard shortcuts:
M - Move component without affecting surrounding objects
G - Grab component while keeping wires intact
X - Flip component along X axis
Y - Flip component along Y axis
R - Rotate component
W - Insert wire
Del - Remove track object
F1 and F2 - Zoom in and out
V - Change value of component
From Eeschema main menu select Tools -> Assign Component Footprint, this will open up Cvpcb. From the Cvpcb toolbar disable filtering footprints by keywords and enable filtering by pin count and library. Select categroy from leftmost panel, click on the middle panel to select target component and double click in the rightmost panel to assign a footprint.
Some important default keyboard shortcuts:
M - Move footprint without affecting surrounding objects
G - Grab footprint while keeping tracks intact
F - Flip a footprit to the other side of PCB
R - Rotate footprint
X - Insert track
Del - Remove track object
F1 and F2 - Zoom in and out
Alt-3 - Open 3D viewer
V - Swap layers, while inserting a track places via
On the status bar Pcbnew shows absolute coordinates and also relative ones. The relative coordinates are measured to point set by pressing the spacebar. This comes very handy in ensuring that you place footprints correctly.
Once tracks have been placed it's time to specify cutout area for the PCB. This will define the dimensions of your PCB. Select Edge.Cuts layer from the layers combobox. From the toolbar select Add graphic line or polygon and draw the rectangle around your design. Hit V to go back to copper layers.
It's possible to fill in rest of the PCB with copper areas usually connected to ground. This reduces the amount of solvent required when etching PCB-s later on. From the main menu select Place -> Zone, click on the cutout corner and select GND as the net where zone shall be connected to. Follow the corners of the cutout and doule click on the corner where you started. Hit V to select the other copper layer and repeat the zone add procedure again. Once both zones have been placed hit B to fill in the zones. Filled zones make it harder to work with footprints, use Ctrl-B to clear zones for the time being.
KiCad doesn't include tool for automatic routing, instead integration with FreeRoute tool is provided. From the main menu select Tools -> FreeRoute, in the toolbar in can be found by yellow icon. In the dialog hit Export a Specctra Design and Launch FreeRoute. Your PCB layout is exported to a .dsn file and opened with FreeRoute. FreeRoute is a Java program so appropriate Java Runtime might have to be additionally installed.
In FreeRouter click Autorouter button on the top, FreeRouting will do it's magic and stop when ready. Note that in certain corner cases it might get stuck between two possible outcomes and you might have to stop the autorouting process manually. Click File -> Export Specctra Session File in the FreeRouting main menu to export .ses file. Now in Pcbnew click Back import the Specctra Session. Press B to refill zones.
If you want FreeRouter to use wider tracks make necessary changes by opening Design Rules from Pcbnew main menu, repeat the export .dsn process and reopen file with FreeRoute. Note that it's perfectly okay to manually route some tracks before running FreeRoute.
In KiCad PCB layout editor press Alt-3 to open 3D viewer of the PCB. From the 3D viewer Preferences menu enable Realistic Mode, disable axes, hide grid and under Render Options enable everything.
Once PCB is laid out in KiCad, it can be converted to Gerber. Gerber files basically describe polygons that need to be carved out of the copper layer. You can use gerbview to view Gerber files, command to view all relevant files in current directory:
gerbview *.g*
If the Gerbers look alright you can upload them to PCB manufacturing company such as OSH Park, DirtyPCBs, Seeed Studio or probably many others you can find on the internet. Note that for cheap options the shipping time can be anywhere between 1 to 2 months.
Alternatively you can use a CNC machine to mill a PCB.
For anyone who were wondering how much throughput you might expect from different hardware/software combinations. In this case iperf was used to measure throughput, for applications (eg. fileserver) your mileage will vary due to WAN link latency etc.
Device |
OS |
Software |
CPU load |
Throughput |
---|---|---|---|---|
TP-Link Archer C7 |
OpenWrt 15.05.1 |
OpenVPN |
100% |
25Mbps |
TP-Link Archer C7 |
OpenWrt 15.05.1 |
StrongSwan |
100% |
40Mbps |
Omnia Turris |
Turris OS |
OpenVPN 2.4.0 |
100% |
96Mbps |
Omnia Turris |
Turris OS |
StrongSwan 5.3.5 |
100% |
300Mbps |
Intel i7-6500U |
Linux 4.10 |
OpenVPN 2.3.10 |
100% |
483Mbps |
Intel i7-6500U |
Linux 4.4 |
OpenVPN 2.3.10 |
100% |
420Mbps |
Intel i7-4770R |
Linux 4.9 |
OpenVPN 2.4.1 |
85% |
483Mbps |
Intel i7-6500U |
Linux 4.4 |
StrongSwan 5.3.5 |
20% |
895Mbps |
1GbE |
N/A |
none |
<1% |
940Mbps |
Conclusions:
StrongSwan throughput is double the the OpenVPN on average
Since TP-Link Archer C7 is running MIPS CPU at 720MHz and there is no hardware acceleration for crypto the both StrongSwan and OpenVPN the CPU becomes the bottleneck
Omnia Turris can easily saturate 100MBps WAN link
Note: Since all these applications are single-threaded CPU load means single core CPU usage
Don't be hasty to draw conclusions on whether StrongSwan is better than OpenVPN or not, both have pros and cons. StrongSwan heavily relies on Linux kernel modules, from security perspecive IPSec is very intrusive and opens up whole lot of new attack vectors while OpenVPN makes use of TUN/TAP driver and everything else happens in userspace - if the OpenVPN process crashes it won't take your machine along.
]]>Reaalsus on see, et kui saadad kirja, siis juhtub umbestäpselt midagi säärast:
HTTPS SMTP IMAP (POP3)
Veebiliides --------> 1. server -------> 2. server -------> E-posti tarkvara
^ |
| |
E-posti tarkvara --------+ +-------------> Veebiliides
SMTP HTTP
Igal sammul on erinevad puudused, veebiliidese puhul ei ole kindel kas veebiliidesele minnakse ligi HTTPS abil (turvatuna). E-posti serverite vahel liiguvad kirjad päris tihti krüpteerimata. E-post ei kao nii pea kuskile kuna kiirsuhtlusplatvormid on äärmiselt fragmenteerunud ning otspunktist-otspunkti sisu krüpteerimine on toetatud varieeruva eduga.
E-posti turvamise juures on meil kaks aspekti:
Krüpteerimine, et keegi teine sidet pealt kuulates ei saaks sõnumit lugeda
Allkirjastamine saatja identiteedi tõendamiseks
Otspunktide vahel mõlemi jaoks on sisuliselt kolm varianti:
ID-kaardi abil, kasutades ID-kaardi tarkvara
S/MIME abil (ID-kaart e-posti klienttarkvaras või ise genereeritud X.509 sertifikaadid)
PGP/GPG abil, tükk maad keerukam aga fooliummütsikestele kõige sobivam
E-posti tarkvara on vajalik selleks et suhelda e-posti serveriga. Gmaili puhul on põhiline postkastile ligisaamise viis veebiliides ise. Suuremates ettevõtetes on kasutusel Microsoft Outlook. Aga need ei ole ainsad viisid postkastile ligi pääsemiseks, üks populaarsemaid avatud lähtekoodiga programme on Mozilla Thunderbird. E-postiserverid kasutavad SMTP protokolli kirjade saatmiseks ning IMAP protokolli kirjade lugemiseks serverist. POP protokolli tänapäeval kasutada pole mõistlik kuna inimesel on rohkem kui üks seade. Thunderbirdi nii nagu pea suvalise e-posti tarkvara saab seadistada kirju alla laadima e-posti serverist IMAP protokolli abil ning saatma SMTP protokolli abil.
Kui kasutad veebiliidest veendu et lähed veebilehele ligi HTTPS abil, indikaatoriks roheline tabalukk aadressiribal
E-posti tarbimiseks kohalikust masinast paigalda Mozilla Thunderbird, seadistamisel veendu et kasutad SMTPS/IMAPS (TLS abil turvatud variante SMTP/IMAP protokollidest):
Windows, Mac OS X puhul aadressilt https://www.mozilla.org/et/thunderbird/
Ubuntu, Debian puhul: apt install thunderbird
Fedora, Red Hat puhul: dnf install thunderbird
Isegi kui kasutad praegu kolmanda osapoole e-posti serverit siis proovi oma arvutis seadistada e-posti klienttarkvara seadistada.
PGP ehk Pretty Good Privacy oli 1991 aastal loodud tarkvara sõnumite krüpteerimiseks ja allkirjastamiseks. Sellest tarkvarast loodi tagasiulatuvalt OpenPGP avalik standard. GPG ehk GNU Privacy Guard on PGP protokolli avatud lähtekoodiga realisatsioon. GPG kasutab RSA võtmeid, kõige suurem vaev ongi võtmete üles seadmine ning oma usaldusvõrgustiku ehitamine. Näiteks minu GPG võtme sõrmejälg on E1BC859AFC900AA925F1BAF33E1E3B1EE82AD8C0, võtmeserverist saad alla laadida minu võtme E82AD8C0 lühendi järgi, so viimased 8 sümbolit võtme sõrmejäljest. Enne kui asud allkirjastama minu võtit (sümboliseerib sinu usaldust minu võtmemajanduse vastu) peaksid enne allkirjastamist veenduma et selle võtmega on tõepoolest seotud minu identiteet - helista, tule külla vms.
Paigalda võtmete haldamiseks tarkvara:
Windows puhul GPG4Win
Mac OS X puhul GPG Suite
Linuxiliste puhul kõige lihtsam piirduda käsurea tööriistadega: apt install gpg2
Paigalda Thunderbirdi pistikprogramm:
Windows puhul ava peamenüüst Lisad ning paigalda Enigmail
Ubuntu, Debian puhul: apt install thunderbird-enigmail
Fedora, Red Hat puhul: dnf install thunderbird-enigmail
Pikemas perspektiivis otstarbekas hankida riistvaraline seade võtmete hoiustamiseks a'la Yubikey, selle kohta leiab juhendi siitsamast blogist.
Tehtav kui on juba kuskil avalikus internetis tiksumas mõni Linuxiga arvuti, nt Zone pilveserver (~10€/kuu), DigitalOcean virtuaalmasin (5USD/kuu). Õiged häkkerid on vähemalt kord elus käima pannud Linuxi serveri oma koduse ruuteri taha, selle jaoks piisab SMTP ja IMAP portide ringi suunamisest (port forward), hea oleks kui on staatiline IP aadressiga internetiühendus (~6€/kuu).
Lisaks on vaja registreerida domeen (~8-9€ aastas). Domeeni registrari DNS serverisse lisa MX kirje mis ütleb missugune masin sinu domeeni e-posti teenindab ning SPF kirje, et teised kirju vastu võtvad serverid oskaks kindlaks teha, et sinu domeeniga saadetud kirjad tõepoolest sinu serverist pärinevad.
Paigalda ning seadista Postfix ja Dovecot. Seadista Postfixi jaoks spämmifiltrid a'la Spamhaus. Seadista TLS sertifikaadid Let's Encrypt abil, et sinu serverisse kirju üldse saaks saata üle turvatud kanali.
Kui sul on juba olemas domeenikontroller (Microsoft Active Directory või Samba 4.x) liida e-posti server domeeni realmd abil, vastasel korral loo kohalikud kasutajakontod kes postkasti kasutada saavad.
Kui üksi teha tundub üle mõistuse ehk oleks vaja luua kommuun säärase teenuse jaoks a'la nagu rootslastel on Fripost.
Kui oma postkasti ei julge teha siis uuri Protonmail teenuse kohta.
Comfast E380AC is a pretty neat 802.11ac capable AP sold on AliExpress that comes Atheros chipsets and 48V POE support.
Right now the price is around 110€ VAT inclusive. OpenWrt builds for this device are not available yet, but LEDE (OpenWrt fork) has stable build for this device.
To install LEDE on the device hold reset button while powering up the device. Device boots into recovery mode where firmware can be overwritten. Assign static IP address to your laptop, eg 192.168.1.2 and upload the firmware:
wget https://downloads.lede-project.org/releases/17.01.0/targets/ar71xx/generic/lede-17.01.0-r3205-59508e3-ar71xx-generic-cf-e380ac-v2-squashfs-sysupgrade.bin
curl -F firmware=@lede-17.01.0-r3205-59508e3-ar71xx-generic-cf-e380ac-v2-squashfs-sysupgrade.bin 192.168.1.1
Alternatively original firmware can be booted up and third party firmware can also be loaded via the regular web interface as firmware upgrade.
Current LEDE release configures the only ethernet port as LAN interface meaning there is DHCP server running. To make the device work actually like a access point we need to tweak the configuration a little bit. Connect to the command line via ssh:
ssh root@192.168.1.1
Apply following configuration:
# Disable DHCP server(s)
/etc/init.d/dnsmasq stop
/etc/init.d/dnsmasq disable
/etc/init.d/odhcpd stop
/etc/init.d/odhcpd disable
# AP gets IP address via DHCP
uci set network.lan.proto=dhcp
uci delete network.lan.ipaddr
uci delete network.lan.netmask
uci delete network.lan.ip6assign
# Remove firewall rules since AP bridges ethernet to wireless anyway
uci delete firewall.@zone[1]
uci delete firewall.@zone[0]
uci delete firewall.@forwarding[0]
for j in $(seq 0 10); do uci delete firewall.@rule[0]; done
# Set unique hostname
uci set system.@system[0].hostname=comfast-$(cat /sys/class/net/eth0/address | cut -d : -f 4- | sed -e 's/://g')
uci set network.lan.hostname=$(uci get system.@system[0].hostname)
# Reconfigure 2.4GHz and 5GHz radios
for i in 0 1; do
uci delete wireless.radio$i.disabled
uci set wireless.default_radio$i.encryption=psk2+ccmp
uci set wireless.default_radio$i.ssid=Akvaarium
uci set wireless.default_radio$i.key=salakala
done
# Save changes and reboot
uci commit
reboot
OpenWrt/LEDE image builder can be used to generate custom firmware which already incorporates your network SSID and pre-shared key so post-installation tweaking is not necessary.
After reboot the wireless network should be visible. With Google Nexus 5X at 5GHz band throughput between 400MBps-500MBps was benchmarked with Speedtest.net. Considering that on-board QCA9880 has 3 spatial streams, throughput between 600MBps-750MBps should be possible with fancier client devices. For this price Comfast E380AC has very good open-source third party firmware support, and proves again that picking device based on the chipset yields good results.
I tried to boot regular FreeBSD ISO as described in some older versions of documentation, for FreeBSD 11.0 none of them worked as expected - kernel gets booted but when it wishes to mount root filesystem that never works.
Instead I resorted to downloading another version which is completely loaded to memory:
wget http://mfsbsd.vx.sk/files/iso/11/amd64/mfsbsd-se-11.0-RELEASE-amd64.iso \
-O /var/lib/tftpboot/mfsbsd-se-11.0-RELEASE-amd64.iso
Create following entry at your PXE host:
label freebsd110
menu label FreeBSD 11.0
keeppxe
linux memdisk
initrd mfsbsd-se-11.0-RELEASE-amd64.iso
append iso raw
Boot the machine from PXE and let it start up, once started up log in with root and mfsroot.
Use following command to figure out what is the /dev/blah corresponding to your disk:
geom disk list
In my case the disk was at /dev/da0 exposed via SAS HBA, to perform install using ZFS filesystem:
zfsinstall -d /dev/da0
Log in with root, no password should be prompted. Change password for user root:
passwd
Set hostname:
echo hostname=bsd.example.lan >> /etc/rc.conf
List network interfaces:
ifconfig
Acquire IP address for one of the interfaces, in my case bce0 was the interface:
dhclient -v bce0
echo 'ifconfig_bce0="DHCP"' >> /etc/rc.conf
Install OpenSSH server:
pkg install openssh
Note that pkg install is basically equivalent to apt install or yum install. Ports is somewhat like Portage in Gentoo and AUR in ArchLinux.
Enable familiar /proc:
echo "proc /proc procfs rw,auto 0 0" >> /etc/fstab
mount /proc
Add SSD as read cache device:
zpool add tank cache da1
Add another SSD as write log, this speeds up synchronous writes to the pool:
zpool add tank log da2
Enable online block-level deduplication on the ZFS pool:
zfs set dedup=on tank
Important
Enabling deduplication later will only affect newly written data, also you should plan for at least 20GB of system RAM per TB of pool data
To monitor usage:
zpool list -v 2 # Press Ctrl-C to stop
Monitor harddisks
pkg install smartmontools
/usr/local/sbin/smartctl -a /dev/da0
There is no realmd so some steps have to be done manually.
Install Samba 4.4 software suite:
pkg install samba44
Edit /usr/local/etc/smb4.conf, most notably there is no nogroup group, instead it's nobody:
[global]
invalid users = administrator root krbtgt guest
security = ads
netbios name = BSD
workgroup = EXAMPLE
realm = EXAMPLE.LAN
kerberos method = system keytab
winbind trusted domains only = no
winbind use default domain = yes
winbind refresh tickets = yes
winbind enum users = yes
winbind enum groups = yes
map acl inherit = yes
store dos attributes = yes
template homedir = /home/%U
template shell = /bin/bash
idmap config *:backend = rid
allow dns updates = disabled
idmap config *:range = 1000000-16777216
[shared]
path = /home/shared
writable = yes
guest ok = yes
writable = yes
force user = nobody
force group = nobody
create mask = 0666
directory mask = 2777
Authenticate with domain administrator account:
kinit administrator@EXAMPLE.COM
Proceed to join domain:
net ads join -k
Start the service:
cat << EOF >> /etc/rc.conf
samba_server_enable="YES"
smbd_enable="YES"
nmbd_enable="YES"
winbindd_enable="YES"
EOF
service samba_server restart
Reconfigure user lookup:
sed -i -e "s/^passwd_compat:.*/passwd: compat winbind/" /etc/nsswitch.conf
sed -i -e "s/^group_compat:.*/group: compat winbind/" /etc/nsswitch.conf
This should suffice to be used as fileserver, if you need SSH login for AD accounts tweaking /etc/pam.d/sshd is necessary.
On the FreeBSD server:
pkg install mate-desktop mate xauth \
firefox pulseaudio vlc mpv \
pavucontrol paratype virt-manager
On a local Ubuntu or Fedora machine:
Xephyr -resizeable :1 &
DISPLAY=:1 ssh -X username@bsd.example.lan mate-session
FreeBSD has SSH and desktop applications are compiled with X11 support as you would expect on any other Ubuntu machine such as LTSP server. Firefox package for FreeBSD even includes PulseAudio support so audio works. VLC and mpv unfortunately come without PulseAudio support.
Tricky part is that there is no ldminfod package available for FreeBSD which is serving the list of languages and desktop sessions available on the server. But we can easily emulate that behaviour.
On your FreeBSD box append into your /etc/inetd.conf:
echo ldminfo 9571/tcp >> /etc/services
ldminfo stream tcp nowait nobody /usr/libexec/tcpd /bin/cat /etc/ldminfo
You can extract current configuration from the LTSP server and store it to be served by internet superserver:
telnet ltsp.example.lan 9571 > /etc/ldminfo
Edit /etc/ldminfo, in this case following was the result:
language:et_EE.UTF-8
session:mate-session
session-with-name:MATE:mate-session
xsession:/etc/X11/Xsession
rating:99
Create very basic /etc/X11/Xsession:
#!/bin/sh
# redirect errors to a file in user's home directory if we can
errfile="$HOME/.xsession-errors"
if ( umask 077 && cp /dev/null "$errfile" 2> /dev/null )
then
exec > "$errfile" 2>&1
else
mktemp=/usr/bin/mktemp
for errfile in "${TMPDIR-/tmp}/xses-$USER" "/tmp/xses-$USER"
do
if ef="$( umask 077 && $mktemp "$errfile.XXXXXX" 2> /dev/null)"
then
exec > "$ef" 2>&1
mv "$ef" "$errfile" 2> /dev/null
break
fi
done
fi
exec /usr/local/bin/mate-session
# The startup script is not intended to have arguments.
startup=$HOME/.xsession
resources=$HOME/.Xresources
if [ -s "$startup" ]; then
if [ -x "$startup" ]; then
exec "$startup"
else
exec /bin/sh "$startup"
fi
else
if [ -r "$resources" ]; then
/usr/local/bin/xrdb -load "$resources"
fi
exec /usr/local/bin/xsm
fi
Start internet superserver:
echo inetd_enable=yes >> /etc/rc.conf
service inetd start
In your lts.conf usually located at /var/lib/tftpboot/ltsp/lts.conf add additional LTSP servers like this:
LDM_SERVER=bsd.example.lan ltsp.example.lan
Additionally FreeBSD password prompt is slightly different from Ubuntu's, so LDM which is trying to log in on behalf of the user goes nuts. Again we can fix that easily by modifying /etc/pam.d/sshd on the FreeBSD box:
sed -E -e 's/^auth[[:space:]]+required[[:space:]]+pam_unix.so[[:space:]]+.*/auth required pam_unix.so no_warn try_first_pass authtok_prompt=Enter\ password,\ please:\\ /' -i.bak /etc/pam.d/sshd
Over at your LTSP server add additional SSH server keys to LTSP client known hosts file:
ssh-keyscan ltsp.example.lan bsd.example.lan | tee /opt/ltsp/*/etc/ssh_known_hosts
ltsp-update-image
Pics or it didn't happen:
GPG is most often used to encrypt and sign e-mails within software developer communities and cyberpunk circles. You also find that GPG is used to verify packages when you install software on your Ubuntu or Fedora box. GPG keyring can also be used for authenticating SSH connections.
Yubikey 4 Nano is one of the tiniest OpenPGP compatible hardware tokens on the market. With hardware token the your RSA private keys used by the GPG are not readable in the filesystem as it would usually be under ~/.gnupg directory.
Using GPG to send encrypted/signed e-mail can be done via variety of applications each one coming with a different support level for hardware tokens such as Yubikey:
Encrypting on command line as shown below works perfectly with Yubikey, but is cumbersome to use for newbies.
Evolution has full GPG support built-in on Fedora, supports hardware tokens such as Yubikey for signing and encrypting. Retrieving correspondent's keys and setting trust level still has to be performed on command-line as shown below.
Enigmail is a GPG plugin for Mozilla Thunderbird, supports hardware tokens, good user interface integration - untrusted senders key can easily be signed.
Mailvelope generates keys internally and currently can't make use of hardware token
Important
PIV and PGP modes can't be used simultaneously
scdaemon which is used by GPG as backend to access smartcards exclusively locks the card even if configured to use PCSC-Lite as backend. Firefox similarily wants to have exclusive access to the token when there are valid certificates present in the PIV applet. This means that currently PGP and PIV modes can't be used simultaneously.
Important
GPG has most often two versions installed: gpg and gpg2
Following guide focuses on gpg2 only. When gpg command happens to be executed accidentally at wrong time gpg-agent could be started with flags incompatible with gpg2, in that case kill gpg-agent process.
Install GPG v2.x if it hasn't been installed yet:
apt install gnupg2
First check whether GPG detects your token:
gpg2 --card-status
If you have Estonian ID-card reader hooked up to the computer you might have conflicts with web browsers, so it's a good idea to tell GPG reader name:
cat << \EOF >> ~/.gnupg/scdaemon.conf
reader-port "Yubico Yubikey 4 CCID"
EOF
Set up Yubikey, this is roughly equivalent to gpg2 --full-gen-key:
gpg2 --card-edit
admin
generate
Add identities, eg. when you use multiple e-mail addresses or aliases and set the trust level to ultimate for all of your identities:
gpg2 --edit-key first.last@example.com
adduid
trust
Export your public keys and upload it to a HTTP(S) accessible URL:
gpg2 --export --armor > lauri.asc
As the root of trust is your own key, everything that is to be implicitly trusted has to be signed by yourself - hence to trust someone you first need to retreive their public key:
wget https://www.koodur.com/lauri.asc
Import it to your keyring located in your home directory (~/.gnupg/keyring.kbx):
gpg2 --import lauri.asc
Verify that the 40-character fingerprint of the imported key matches via other means eg. by giving a call via phone, meeting face to face or taking part of a keysigning party. Finally sign the public key identified by e-mail address:
gpg2 --sign-key lauri.vosandi@gmail.com
Alternatively keys can be fetched and imported from publicly operated keyservers, in that case 40-character key fingerprint and keyserver hostname is required. For example in order to import key used to sign CERT-EE (RIA) e-mails following commands should suffice. In this case pgp.mit.edu is keyserver operated by Massachusetts Institute of Technology:
gpg2 --keyserver pgp.mit.edu --recv 48319D213649047F197EA9CD86C6D4D43601B6D1
gpg2 --sign-key cert@cert.ee
Use following to list your keys, your key fingerprint is the 40-character string just above your identities and e-mail addresses:
gpg2 --list-keys
Most commonly used keyservers can be found at Wikipedia. To prevent key collision attacks it might be good idea to upload your key to all of the listed servers there as it is very common that users specify only last 8 digits of the fingerprint to import keys.
gpg2 --keyserver pgp.mit.edu --send-key E1BC859AFC900AA925F1BAF33E1E3B1EE82AD8C0
To encrypt a file you need to have recipient's public key in your keyring as shown above. To encrypt a file and output it in ASCII armored format:
gpg2 -r lauri@koodur.com -a -o encrypted.asc -e plain.txt
To dump decrypted document on command line:
gpg2 -d encrypted.asc
To save it into a file:
gpg2 -d encrypted.asc -o decrypted.txt
Following starts up GPG agent and exports SSH agent environment variables for currently running shell:
eval `gpg-agent --daemon --enable-ssh-support`
To export public keys from the GPG applet on Yubikey in SSH format use following command, you should see Yubikey keys with comment cardno: 000123456789 where the number is your Yubikey serial number:
ssh-add -L
As usual copy the public key to your server's ~/.ssh/authorized_keys.
When attempting to log into the server you're supposed to be prompted with a graphical PIN code dialog. Any subsequent login attempts in the same shell should proceed without having to ask for the PIN code.
It's very tricky to get this right. Following was tested on Fedora 25.
GPG agent wants to show PIN dialog on demand so it has to get graphical session environment variables right ($DISPLAY, $WAYLAND_DISPLAY etc).
Easiest way is to create autostart file:
cat << \EOF > ~/.config/autostart/gpg-agent.desktop
[Desktop Entry]
Type=Application
Name=gpg-agent
Comment=Autostart GPG agent
Exec=/usr/bin/gpg-connect-agent /bye
Terminal=false
EOF
Tell gpg-agent to export ssh-agent compatible socket:
cat << \EOF >> ~/.gnupg/gpg-agent.conf
enable-ssh-support
default-cache-ttl 90
ignore-cache-for-signing
EOF
Override environment variables when terminal is opened:
cat << \EOF >> ~/.bashrc
unset SSH_AGENT_PID
export SSH_AUTH_SOCK="${XDG_RUNTIME_DIR}/gnupg/S.gpg-agent.ssh"
EOF
Kill all the relevant processes, log out and log in again. When attempting to ssh to a remote box PIN dialog should pop up.
Import your public keyring, eg in my case:
gpg2 --keyserver pgp.mit.edu --recv-key E1BC859AFC900AA925F1BAF33E1E3B1EE82AD8C0
On the first computer export secrets, in Yubikey case this should export only stubs which tell GPG to look for the key on a hardware token:
gpg2 --export-secret-keys -a -o secrets
Copy the file to new machine:
scp secrets new-machine:
On the new machine:
gpg2 --import secrets
On Ubuntu you might want to try to use PPA maintaned by folks at Yubikey. On Fedora install following packages:
yum install libykneomgr libu2f-host yubico-piv-tool
pip install yubikey-neo-manager
To start Yubikey Neo Manager:
neoman
Disable OTP and U2F, otherwise touching Yubikey causes one time passwords to be typed. Leaving CCID on provides still GPG and PKI applets. In this example PKI token mode is explored.
First let Yubikey generate the private key and dump the corresponding public key to a file.
yubico-piv-tool -s 9a -a generate -o pubkey.pem
In case you have a Certifiate Authority set up and you want to use Yubikey for HTTPS authentication create certificate signing request. Send the resulting req.pem to your CA administrator and wait for signed certificate file, store it in cert.pem and proceed with certificate import below:
yubico-piv-tool -s 9a -a verify -a request \
-S /CN=$USER \
-i pubkey.pem \
-o req.pem
In case you're not operating CA or you're only interested in using Yubikey for SSH authentication sign the public key with the same private key and PIN code (default 123456), this is just to satisfy the quirks of the device used as PKI token even though SSH doesn't care about certificates in that sense:
yubico-piv-tool -a verify-pin -a selfsign-certificate -s 9a -S "/CN=SSH key/" -i public.pem -o cert.pem
Finally import the signed certificate back to Yubikey:
yubico-piv-tool -a import-certificate -s 9a -i cert.pem
Now check the status of your Yubikey:
yubico-piv-tool -a status
Extract public keys on the Yubikey in the SSH format:
ssh-keygen -D opensc-pkcs11.so -e
Copy the public key and paste it to server's ~/.ssh/authorized_keys file.
Test logging in with following, the default PIN is 123456:
ssh -I opensc-pkcs11.so username@hostname
Getting SSH agent to work is a bit tricky because ssh-agent wants to set up some environment variables used by ssh-agent, so far the easiest way to achieve it is this:
eval `ssh-agent -s`
ssh-add -s /usr/lib64/opensc-pkcs11.so
To make it sort-of permanent add an alias into your shell configuration:
cat << \EOF >> ~/.bashrc
alias y='eval `ssh-agent -s`; ssh-add -s /usr/lib64/opensc-pkcs11.so'
EOF
Spawn a new shell session and use alias y to load keys and enter PIN code for the hardware token.
Assuming all packages have been installed no configuration should be necessary. When accessing properly configured web server where client validation is required the browser should automatically try to offer certificate stored on Yubikey, just enter pin code to unlock the token:
If multiple certificates can be offered certificate selection is prompted:
Using Yubikey reduces the risk of leaking private RSA keys from your computer via malware or losing access to servers when ransomware hits your computer. If keylogger happens to be installed PIN codes can easily be captured and recognized, so if token happens to be lost corresponding certificates should still be immideately revoked and public keys removed from SSH server (s). If attacker has gained access to a computer where Yubikey is used he can still from there on hop to the servers accessible using the key without having physical access to the key assuming that knowledge about the PIN code has been gained or ssh-agent is used.
Also Yubikey has tool for managing the PKI applet, might become handy:
pip install yubikey-piv-manager
pivman
CIFS (common internet filesystem) is the official name of the fileserver protocol used by Windows filesharing subsystem. It's very similar to NFS (network filesystem) developed by Sun which is commonly found in UNIX-based systems. Samba software suite provides CIFS support for UNIX-like systems such as Linux and Mac OS X.
CIFS can make use of Kerberos protocol for authentication when used in conjunction with a domain controller software such as Active Directory or with another Samba instance configured to work as domain controller.
In this tutorial Samba fileserver setup on Ubuntu 16.04 and Fedora 25 is outlined.
In this case users accessing the shares are identified by Kerberos credentials eg. when accessing from domain computers. If Kerberos credentials are not available fallback to NTLM is provided and username and password is prompted upon network share access.
First install software components:
apt install packagekit samba samba-vfs-modules krb5-user \
realmd libnss-winbind libpam-winbind
Create /etc/realmd.conf, this will tell realmd to make use of winbind when joining the domain. Also it switches off fully qualified usernames (username@realm) and use the short ones instead (username), this of course assumes no local user accounts will be created:
[active-directory]
default-client = winbind
[users]
default-home=/home/%U
[office.lan]
default-shell=/bin/bash
fully-qualified-names=no
Join the machine to domain, this will do several things: create /etc/krb5.keytab, generate /etc/samba/smb.conf, reconfigure PAM modules, create machine account in the domain controller, create host principal in the domain controller and add DNS record for the fully qualified hostname:
realm join office.lan -U administrator
Reconfigure /etc/samba/smb.conf, keep netbios name, workgroup and realm as the ones generated by realm join:
[global]
# Server operates as domain member server
security = ads
netbios name = DEV
workgroup = OFFICE
realm = OFFICE.LAN
kerberos method = system keytab
winbind trusted domains only = no
winbind use default domain = yes
winbind refresh tickets = yes
winbind enum users = yes
winbind enum groups = yes
# Bind nmbd, smbd services on certain interface, eg when others go to WAN
interfaces = ens3
bind interfaces only = yes
# How AD accounts are mapped to POSIX accounts on the fileserver
obey pam restrictions = yes
guest account = nobody
invalid users = root krbtgt guest
template homedir = /home/%U
template shell = /bin/bash
idmap config *:backend = rid
idmap config *:range = 1000000-16777216
[homes]
comment = Home Directories
valid users = %S
writable = yes
[shared]
comment = Shared folder for authenticated users
writable = yes
path = /shared
The winbind support in realmd is still a bit quirky, make sure name services are reconfigured so usernames and groups are looked up via winbind:
sed -i -e "s/^passwd:.*/passwd: compat winbind/" /etc/nsswitch.conf
sed -i -e "s/^group:.*/group: compat winbind/" /etc/nsswitch.conf
sed -i -e "s/^shadow:.*/shadow: compat/" /etc/nsswitch.conf
Also home directories need to be created on the fly. On Debian following file is missing completely and for Ubuntu a slightly incorrect version is supplied, but this file can easily be reset:
cat > /usr/share/pam-configs/mkhomedir << EOF
Name: Create home directory on login
Default: no
Priority: 0
Session-Type: Additional
Session:
optional pam_mkhomedir.so
EOF
Ubuntu and Debian ship with following command, use spacebar to tick 'Create home directory on login' and press enter:
pam-auth-update
Restart services or just reboot the box. It is of course possible to add anonymous shares as shown in the previous example, and it is possible to create shares where authentication is required. In case of authenticated shares Samba will try to do it's best to map Windows permissions to POSIX permissions and ACL-s.
Once machine is up check that both commands list the users from AD:
wbinfo -u
getent passwd
Create shared directory and reset permissions:
mkdir -p /shared
chown administrator:"domain users" /shared
chmod 775 /shared/
Depending on your organization's needs it might be that when files get overwritten or deleted it is necessary to have the logs about who did it and when. In the 'global' section of /etc/samba/smb.conf add following:
vfs objects = full_audit
full_audit:prefix = %u|%I|%m|%S
full_audit:success = rename unlink rmdir pwrite
full_audit:failure = none
full_audit:facility = local7
full_audit:priority = NOTICE
Also configure syslog to forward events to your SIEM.
As usual stop the service and start it up in interactive mode with raised verbosity level.
For fileserver portion:
systemctl stop smbd
smbd -d3 -i
For user mapping:
systemctl stop winbind
winbindd -d3 -i
After installing OpenWrt on TP-Link WDR3600/4300 or Archer C7 following script can be used to convert the machine to a dummy access point which does not serve DHCP, but just bridges wireless and wired ports on the device.
Guest wireless network is also enabled and it's tagged as VLAN 156 on the ethernet ports.
# Disable DHCP servers
/etc/init.d/odhcpd disable
/etc/init.d/dnsmasq disable
# Remove all firewall rules
uci delete firewall.@zone[2]
uci delete firewall.@zone[1]
uci delete firewall.@zone[0]
uci delete firewall.@forwarding[0]
for j in $(seq 0 20); do uci delete firewall.@rule[0]; done
# Remove WAN interface
uci delete network.wan
uci delete network.wan6
# Reconfigure DHCP client for bridge over LAN and WAN ports
uci delete network.lan.ipaddr
uci delete network.lan.netmask
uci delete network.lan.ip6assign
uci delete network.globals.ula_prefix
uci delete network.@switch_vlan[1]
uci set network.lan.proto=dhcp
uci set network.lan.ipv6=0
uci set network.lan.ifname='eth0 eth1'
uci set network.lan.stp=1
# Disable switch tagging and bridge all ports
uci set network.@switch[0].enable_vlan=0
uci set network.@switch_vlan[0].ports='0 1 2 3 4 5 6'
# Enable wireless
uci delete wireless.radio0.disabled
uci delete wireless.radio1.disabled
# Radio ordering differs among models
case $(uci get wireless.radio0.hwmode) in
11a) uci rename wireless.radio0=radio5ghz;;
11g) uci rename wireless.radio0=radio2ghz;;
esac
case $(uci get wireless.radio1.hwmode) in
11a) uci rename wireless.radio1=radio5ghz;;
11g) uci rename wireless.radio1=radio2ghz;;
esac
# Reset virtual SSID-s
uci delete wireless.@wifi-iface[1]
uci delete wireless.@wifi-iface[0]
for band in 2ghz 5ghz; do
uci set wireless.lan$band=wifi-iface
uci set wireless.lan$band.mode=ap
uci set wireless.lan$band.device=radio$band
uci set wireless.lan$band.encryption=psk2
uci set wireless.lan$band.ssid=KoodurProtected
uci set wireless.lan$band.key='salakala'
uci set wireless.lan$band.network=lan
done
# Generate unique hostname based on wireless MAC
uci set system.@system[0].hostname=tp-link-$(cat /sys/class/net/wlan1/address | cut -d : -f 4- | sed -e 's/://g')
uci set network.lan.hostname=$(uci get system.@system[0].hostname)
# Commit changes
uci commit
# Skip following to keep guests network disabled
# Create bridge for guests
uci set network.guest=interface
uci set network.guest.proto='static'
uci set network.guest.address='0.0.0.0'
uci set network.guest.type='bridge'
uci set network.guest.ifname='eth0.156 eth1.156' # tag id 156 for guest network
uci set network.guest.ipaddr='0.0.0.0'
uci set network.guest.ipv6=0
uci set network.guest.stp=1
# Add guest SSID-s
for band in 2ghz 5ghz; do
uci set wireless.guest$band=wifi-iface
uci set wireless.guest$band.mode=ap
uci set wireless.guest$band.device=radio$band
uci set wireless.guest$band.encryption=none
uci set wireless.guest$band.ssid=KoodurPublic
uci set wireless.guest$band.network=guest
done
uci commit
For lazy people convenience hack for adding SSH keys:
# Create script for fetching SSH keys once interface goes up
cat > /etc/hotplug.d/iface/update-ssh-authorized-keys << EOF
wget https://www.koodur.com/authorized_keys -O /etc/dropbear/authorized_keys.part
mv /etc/dropbear/authorized_keys.part /etc/dropbear/authorized_keys
EOF
opkg update
opkg install openssl-util nano htop
]]>The router is based on Mediatek MT7621 dual core SoC clocked at 880MHz with 16MiB SPI Flash chip and 512MiB DDR3 RAM chip. There are two MT7662E wireless chipsets and ASMedia ASM1062 SATA controller soldered onboard and connected via PCI lanes.
This router can be purchased from AliExpress for 80USD, bulk orders from Alibaba should decrease item price considerably.
The device comes already with OpenWrt albeit an older version. Gain access to command line and use following to update the firmware.
Older OpenWrt firmware, 3.18.x kernel, 3G works, illegal instruction and core dumps under high load, poor SATA throughput:
cd /tmp
wget http://downloads.openwrt.org/chaos_calmer/15.05.1/ramips/mt7621/openwrt-15.05.1-ramips-mt7621-zbt-wg2626-squashfs-sysupgrade.bin
sysupgrade openwrt-15.05.1-ramips-mt7621-zbt-wg2626-squashfs-sysupgrade.bin
Newer OpenWrt firmware, 4.4.x kernel, QMI based 3G cards fail, old school USB-to-serial based 3G cards work, installing microSD card support crashes router:
cd /tmp
wget http://downloads.openwrt.org/snapshots/trunk/ramips/mt7621/openwrt-ramips-mt7621-zbt-wg2626-squashfs-sysupgrade.bin
sysupgrade openwrt-ramips-mt7621-zbt-wg2626-squashfs-sysupgrade.bin
LEDE based firmware, 4.4.x kernel, QMI untested, old school 3G works, microSD card support unsable, SATA performance okay (50MB/s):
cd /tmp
http://downloads.lede-project.org/snapshots/targets/ramips/mt7621/lede-ramips-mt7621-zbt-wg2626-squashfs-sysupgrade.bin
sysupgrade lede-ramips-mt7621-zbt-wg2626-squashfs-sysupgrade.bin
Once router is up and running with OpenWrt update package lists:
opkg update
Install software packages:
opkg install comgt fdisk htop kmod-atm kmod-mii kmod-usb-acm kmod-usb-atm kmod-usb-net kmod-usb-net-qmi-wwan kmod-usb-serial kmod-usb-serial-option kmod-usb-serial-wwan kmod-usb-wdm kmod-usb2 kmod-usb3 luci mc nano usbutils pciutils
For 3G/LTE support:
opkg install luci-proto-3g luci-proto-ppp luci-proto-qmi ppp uclient-fetch uqmi usb-modeswitch wwan
opkg install luci-proto-qmi_git-17.130.58552-d04f667-1_all.ipk
If you don't have ethernet connectivity, on your laptop:
wget http://downloads.lede-project.org/releases/17.01.1/targets/ramips/mt7621/packages/kmod-usb-net-qmi-wwan_4.4.61-1_mipsel_24kc.ipk
wget http://downloads.lede-project.org/releases/17.01.1/targets/ramips/mt7621/packages/uqmi_2016-12-19-8ceeab69-1_mipsel_24kc.ipk
wget http://downloads.openwrt.org/snapshots/trunk/ramips/mt7620/packages/luci/luci-proto-qmi_git-17.130.58552-d04f667-1_all.ipk
wget http://downloads.lede-project.org/releases/17.01.1/targets/ramips/mt7621/packages/kmod-usb-wdm_4.4.61-1_mipsel_24kc.ipk
wget http://downloads.lede-project.org/releases/17.01.1/targets/ramips/mt7621/packages/kmod-usb-net_4.4.61-1_mipsel_24kc.ipk
scp *.ipk root@192.168.1.1:/tmp/
ssh root@192.168.1.1 opkg install /tmp/*.ipk
For fileserver and DLNA:
opkg install luci-app-samba minidlna
For storage in general:
opkg install kmod-scsi-generic blkid block-mount kmod-fs-btrfs kmod-fs-ext4 kmod-fs-vfat btrfs-progs
For USB storage:
opkg install kmod-usb-storage kmod-usb-storage-extras
For SATA:
opkg install kmod-ata-core kmod-ata-ahci
For microSD card support:
opkg install kmod-sdhci-mt7620
For OpenVPN:
opkg install openvpn-openssl luci-app-openvpn
Insert 3G card to mini PCI express, attach antennas and insert SIM card to the slot underneath the mini PCI express slot. In this case Ericsson F3507G Mobile Broadband Module salvaged from an old Thinkpad was used. Append following to /etc/config/network, adjust apn accordingly and reboot the box:
config interface 'wwan'
option proto '3g'
option device '/dev/ttyACM0'
option apn 'internet.tele2.ee'
option delegate '0'
option ipv6 '0'
option service 'umts_only'
option pppd_options 'noipdefault'
option dialnumber '*99#'
Mediatek support in mainline kernel needs still some time to mature but otherwise Mediatek based devices look promising alternative to Qualcomm/Atheros.
Install scapy module:
apt install python-scapy
Create monitoring interface to capture 802.11 packets:
iw wlan0 interface add mon0 type monitor
ifconfig mon0 up
Run the script:
from scapy.all import *
def PacketHandler(pkt) :
if pkt.haslayer(Dot11) :
if pkt.type == 0 and pkt.subtype == 8 :
if pkt.haslayer(Dot11Beacon) or pkt.haslayer(Dot11ProbeResp):
try:
extra = pkt.notdecoded
rssi = -(256-ord(extra[-4:-3]))
except:
rssi = -100
print "WiFi signal strength:", rssi, "dBm of", pkt.addr2, pkt.info
sniff(iface="mon0", prn = PacketHandler)
]]>Juhend eeldab Ubuntu 16.04 server paigaldust.
Iseseisev (standalone) server antud kontekstis tähendab seda, et LTSP serveril on kaks võrguliidest, millest üks vaatab Interneti poole ning teine on ühendatud eraldatud võrgusegmenti kus terminalid asuvad. Sellisel juhul serveeritakse terminalide võrku kõiki vajalikke teenuseid: DHCP, TFTP, NBD, SSH, LDM jne.
Esiteks uuenda pakette:
apt update
apt full-upgrade
Paigalda LTSP metapakett, see seadistab kõik teenused mis on LTSP toimimiseks vajalikud:
apt install -y ltsp-server-standalone wget ca-certificates apt-transport-https
Seadista võrk failis /etc/network/interfaces, asenda 192.168.77.1 omale sobiliku sisevõrgu aadressiga:
cat << EOF > /etc/network/interfaces
auto lo
iface lo inet loopback
auto en1
iface en1 inet dhcp
auto en0
iface en0 inet static
address 192.168.77.1
netmask 255.255.255.0
EOF
Asenda vaikimisi alamvõrk 192.168.0.0/24 ka DHCP serveri seadistustes:
sed -i "s/192\.168\.0\./192.168.77./g" /etc/ltsp/dhcpd.conf
Taaskäivita teenused:
systemctl restart networking
systemctl restart network-manager
systemctl restart isc-dhcp-server
systemctl restart nbd-server
Kui sul on juba toimiv DHCP server võid asendada ltsp-server-standalone paketi ltsp-server paketiga:
apt install -y ltsp-server ltspfs wget ca-certificates apt-transport-https
Sellisel juhul pead vajalikud teenused, nagu näiteks TFTP ise seadistama:
apt install -y tftpd-hpa
sed -e 's/TFTP_ADDRESS=.*/TFTP_ADDRESS=":69"/' /etc/default/tftpd-hpa
Kontrolli üle, et ka muud teenused oleks kättesaadavad terminalidele.
Ubuntu töölaud on üsna resursinõudlik ning terminal-serveri puhul äärmiselt aeglane, kuna pilt liigub üle võrgu. Terminal-serverile on soovitatud paigaldada MATE töölaud:
apt update
apt full-upgrade
apt install -y mate-desktop-environment-extras
Kui serverisse on paigaldatud mitu erinevat töölaua keskkonda, saab vaikimisi töölauda vahetada järgnevalt:
update-alternatives --config x-session-manager
Lisa ka Eesti ID-kaardi baastarkvara varamu:
echo "deb https://installer.id.ee/media/ubuntu/ xenial main" > /etc/apt/sources.list.d/ria-repository.list
wget https://installer.id.ee/media/install-scripts/ria-public.key -O - | apt-key add -
wget https://installer.id.ee/media/install-scripts/C6C83D68.pub -O - | apt-key add -
apt update
apt install -y open-eid
Lisa Xsession skript mis näitab uut PCSC-lite sokkli asukohta:
echo "export PCSCLITE_CSOCK_NAME=\$HOME/.pcscd.comm" > /etc/X11/Xsession.d/80-pcsclite
Enamus PC riistvara toetab PXE-alglaadimist. Alusta terminali tarkvara juurfailisüsteemi loomisega:
MIRROR="http://ee.archive.ubuntu.com/ubuntu/" \
LANG=C \
ARCH=i386 \
ltsp-build-client
ID-kaardi jaoks vajalike komponentide paigaldamiseks sisene terminali juurfailisüsteemi:
chroot /opt/ltsp/i386 /bin/bash
Paigalda PCSC-Lite deemon:
apt install -y pcscd
Lisa SSH kliendi seadistused, tärni võib asendada oma serveri IP-ga:
cat << EOF > /etc/ssh/ssh_config
Host *
SendEnv LANG LC_*
PermitLocalCommand yes
LocalCommand /bin/sh -c "sh -c \"ssh -S /var/run/ldm_socket_* -l %r server rm .pcscd.comm; ssh -S /var/run/ldm_socket_* -O forward -R /home/%r/.pcscd.comm:/run/pcscd/pcscd.comm -l %r server\"&"
EOF
VIA terminalide UniChrome graafika tüürelite seis on suht halb seega ma lülitaks välja ka 3D kiirenduse:
cat << EOF > /etc/X11/xorg.conf
Section "Module"
Disable "glx"
Disable "dri"
EndSection
EOF
Mälupulkade haakimiseks paigalda ka NTFS ning exFAT jaoks vajalikud komponendid:
apt install -y ntfs-3g exfat-fuse
Välju terminali juurikast:
exit
Uuenda terminali juurfailisüsteemi SquashFS tõmmist:
ltsp-update-image
Lisa terminali juurikasse rdesktop pakett:
chroot /opt/ltsp/i386 apt install -y rdesktop
Genereeri uuendatud tõmmis:
ltsp-update-image
Seadista ringi /var/lib/tftpboot/ltsp/i386/lts.conf:
[default]
SCREEN_07="rdesktop -x l -k et -u '' -f -r scard -r sound -r disk:floppy=/run/drives aken.edu.ee"
SCREEN_08="ldm"
Sisselogimisdialoogi aegumise vältimiseks ava Windowsi register ning lisa HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp alla DWORD tüüpi LogonTimeout=0xffffffff võti-väärtus paar 2.
Kuna PXE on x86 platvormi spetsiifiline siis säärast võimekust näiteks Cubietrucki kasutada ei saa. Küll aga saab Cubietruckile kõrvetada püsivara, mis analoogselt PXE-le laadib võrgust alla tuuma, initrd ning jätakb operatsioonisüsteemi alglaadimisega.
Esmalt paigalda QEMU emulatsioonikiht:
apt install -y qemu-user-static binfmt-support
Keela OMAP4 tuuma paigaldus, see pole naguinii enam kättesaadav tarkvaravaramutest:
sed -i -e 's/KERNEL_ARCH="omap4"/KERNEL_ARCH=""/' /usr/share/ltsp/plugins/ltsp-build-client/Ubuntu/020-kernel-selection
Loo ARM juurfailisüsteem:
DEBOOTSTRAP=qemu-debootstrap ARCH=armhf LANG=C ltsp-build-client
Lisa serveri SSH võti:
ltsp-update-sshkeys
Sisene Cubietrucki juurfailisüsteemi:
chroot /opt/ltsp/armhf /bin/bash
Cubietrucki jaoks paigalda Igori 3.4.x tuum ja moodulid kuhu sai külge poogitud LTSP jaoks vajalik overlayfs:
echo "deb http://apt.armbian.com xenial main" > /etc/apt/sources.list.d/armbian.list
apt-key adv --keyserver keys.gnupg.net --recv-keys 0x93D6889F9F0E78D5
apt update
apt install -y linux-image-sun7i
Uuenda pakettide nimekirju:
apt update
Paigalda kohandatud OpenSSH, PCSC-deemon, LTSP-kliendi metapakett ja muu tilu-lilu:
apt install -y openssh-client pcscd
Lisa SSH kliendi seadistused, et terminal võimaldaks serveris ligipääsu terminalis jooksvale PCSC deemonile, vajadusel asenda tärn oma serveri IP-ga:
cat << EOF > /etc/ssh/ssh_config
Host *
SendEnv LANG LC_*
PermitLocalCommand yes
LocalCommand /bin/sh -c "sh -c \"ssh -S /var/run/ldm_socket_* -l %r server rm .pcscd.comm; ssh -S /var/run/ldm_socket_* -O forward -R /home/%r/.pcscd.comm:/run/pcscd/pcscd.comm -l %r server\"&"
EOF
Kui soovid kasutada ka RDP sessioone siis uuendatud RDP kliendi paigaldamiseks:
apt install -y rdesktop
Mälupulkade haakimiseks paigalda ka NTFS ning exFAT jaoks vajalikud komponendid:
apt install -y ntfs-3g exfat-fuse
Välju juurikast:
exit
Uuenda NBD kaudu serveeritavat tõmmist:
ltsp-update-image
Paigalda esmalt u-boot tööriistad:
apt install -y u-boot-tools
Sikuta Cubietrucki riistvara konfiguratsioon, mis paneb VGA pesa käima resolutsioonil 1024x768 ja lülitab välja terminali jaoks ebaolulised komponendid (WiFi, Bluetooth jms):
wget https://www.koodur.com/cubietruck/1024x768.bin -O /var/lib/tftpboot/ltsp/armhf/1024x768.bin
Loo u-boot jaoks skript mis laeb tuuma, initrd ning riistvara konfiguratsiooni:
cat << EOF > /var/lib/tftpboot/ltsp/armhf/1024x768.scr
setenv bootm_boot_mode sec
setenv bootargs 'ro init=/sbin/init-ltsp init=/sbin/init-ltsp root=/dev/nbd0'
tftp 0x43000000 /ltsp/armhf/1024x768.bin
tftp 0x42000000 /ltsp/armhf/uImage
tftp 0x50000000 /ltsp/armhf/initramfs.uImage
bootm 0x42000000 0x50000000
EOF
Genereeri u-boot tõmmised:
mkimage -A arm -O linux -T script -C none -n boot.scr -d \
/var/lib/tftpboot/ltsp/armhf/1024x768.scr \
/var/lib/tftpboot/ltsp/armhf/1024x768.scr.uimg
mkimage -A arm -T ramdisk -C none -n uInitrd -d \
/var/lib/tftpboot/ltsp/armhf/initrd.img-3.4.*-sun7i \
/var/lib/tftpboot/ltsp/armhf/initramfs.uImage
mkimage -A arm -O linux -T kernel -C none -n Linux -a 42000000 -e 42000000 -d \
/var/lib/tftpboot/ltsp/armhf/vmlinuz-3.4.*-sun7i \
/var/lib/tftpboot/ltsp/armhf/uImage
Seadista ringi ka DHCP serverit failis /etc/ltsp/dhcpd.conf, siinkohal on välja nopitud Cubietruckid millel on 1024x768 resolutsiooniga ekraanid ning mõned mis on 1280x1024 resolutsiooniga ekraanid. Ülejäänud masinad sooritavad x86 terminali alglaadimise PXE abil:
authoritative;
group {
filename "ltsp/armhf/1024x768.scr.uimg";
host term1 { hardware ethernet 02:c1:08:c3:10:9f; }
host term2 { hardware ethernet 02:8d:06:c0:c5:36; }
host term3 { hardware ethernet 02:15:07:c2:ff:cc; }
}
group {
filename "ltsp/armhf/1280x1024.scr.uimg";
host term4 { hardware ethernet 02:c1:0a:01:d3:0f; }
host term5 { hardware ethernet 02:c1:08:82:f6:9f; }
host term6 { hardware ethernet 02:c8:07:c1:cc:93; }
}
subnet 192.168.77.0 netmask 255.255.255.0 {
range 192.168.77.100 192.168.77.250;
option routers 192.168.77.1;
option domain-name-servers 192.168.77.1;
option domain-name "ltsp";
filename "pxelinux.0";
}
Viimase sammuna peab Cubietrucki jaoks ette valmistama mälukaardi mis oskab võrgust alglaadimist sooritada. Laadi alla selle jaoks sobilik u-boot ning kirjuta see microSD mälukaardile.
wget http://os.archlinuxarm.org/os/sunxi/boot/cubietruck/u-boot-sunxi-with-spl.bin
sudo dd if=/dev/zero of=/dev/sdX bs=1M count=8
sudo dd if=u-boot-sunxi-with-spl.bin of=/dev/sdX bs=1024 seek=8
Sisemisele mälule modernse u-booti kirjutamine on jätkuvalt problemaatiline, MLC mälukivi kasutuse tõttu kipub selle sisu korrumpeeruma andmete lugemisel.
Mälupulkade haakimine peaks toimima automaatselt, kui see pole nii kontrolli et serveris oleks paigaldatud ltspfs pakett.
apt install ltspfs
Terminali juurfailisüsteemis kontrolli, et oleks paigaldatud tarkvara NTFS ning exFAT failisüsteemide haakimiseks:
apt purge -y flash-kernel # armhf juurikas muidu püüab kernelit flashima hakata
apt install ntfs-3g exfat-fuse
LinuxCNC is a Debian based distribution which includes realtime kernel for running stepper drivers connected to a parallel port, EMC2 the graphical user interface for working with CNC machines. This howto assumes you have already produced Gerber files, eg by plotting your KiCad PCB layout.
Utility for converting Gerber files to .ngc files which are understood by LinuxCNC.
To install pcb2gcode on Fedora 25:
dnf install pcb2gcode
To install pcb2gcode on LinuxCNC itself or a Ubuntu workstation:
apt install pcb2gcode
Following generates front.ngc, back.ngc, drill.ngc toolpath files with coordinates reset to resulting toolpaths instead of original PCB layout coordinates. All drilling is squashed into single tool path, in our case we used only 1mm drill. The design will not be tiled, increase tile-x and tile-y to cut multiple identical copies of the design.
pcb2gcode \
--zero-start \
--onedrill \
--software linuxcnc \
--tile-x 1 \
--tile-y 1 \
--front *-F.Cu.g* \
--back *-B.Cu.g* \
--drill *.drl \
--front-output front.ngc \
--back-output back.ngc \
--drill-output drill.ngc \
--metric \
--zwork 0 --offset 0.2 \
--zsafe 3 --zchange 40 \
--mill-feed 500 \
--mill-speed 6000 \
--zdrill -3 \
--drill-feed 500 \
--drill-speed 6000
Milling depth is set to 0mm, make sure you home Z axis to desired cutting depth before executing the toolpath. Milling offset is 0.2mm, that is to compensate for the milling bit cut width. When moving between paths tool is raised 3mm above the surface. Drilling depth is set to 5mm, make sure you home Z axis before drilling to the surface of the PCB. Milling and drilling feed is set to 500mm/minute. Milling and drilling speed is set to 6000rpm if your setup supports setting spindle speed.
To use LinuxCNC in production you need realtime capable kernel. Folks at LinuxCNC have packaged it up and it's installable as a separate ISO file. To download it and copy to a memory stick, make sure you replace sdz with the device corresponding to the block device of your memory stick:
wget http://www.linuxcnc.org/linuxcnc-2.7-wheezy.iso
cat linuxcnc-2.7-wheezy.iso | pv > /dev/sdz
Install it to a PC which has parallel port, USB-parallel port converters we tried didn't have drivers for the rather outdated realtime kernel included with LinuxCNC.
Following is not going to go in depth with CNC frame construction. CNC frames can be ordered from AliExpress for reasonable price, 3020T has (trapezoidal) lead screw and can be ordered for around 500USD. Note that lead screw is cheaper and requires less torque to hold the position whereas ball screw is more precise but expensive and might need more powerful stepper motors to hold position, see pros and cons here.
Use a breakout board to make it easier to connect stepper drivers to the parallel port. Note that the breakout board does not include any essential functionality, it simply makes things more convenient, has a relay for turning the spindle on and off and as a cherry on the top uses optocouplers to electrically separate parallel port from the rest of the machinery to protect the PC in case of a disaster.
Poor man's solution is to simply use a printer cable, connect individual wires to the stepper drivers. In our case we used Toshiba TB6600 based stepper drivers:
For 3020T the NEMA 23 stepper motors were suitable, NEMA 17 steppers were also tested but didn't deliver enough torque to drive the CNC. Note that NEMA 17 and NEMA 23 in reality refer to the mounting hole dimensions, there are variety of motors made by different manufacturers and slightly different dimensions and electrical characteristics.
Note that in certain configurations the CNC frame comes without stepper mounting bracket. You can try your luck with threaded rod or use a 3D printer to print one. Also shaft couplers are required to connect NEMA motors to the CNC frame's lead screws:
Note that it is probably easier to purchase whole kit which includes at least steppers and spindle.
Most PCB milling and drilling bits have 1/8 inch (3.175mm) diameter shank, that's the end mounted to spindle.
After experimenting with 90°, 60°, 30°, 10° mill bits and different drill bits it eventually boiled down to two.
For milling traces 60° carbide mill bit is suitable:
For most drilling holes 1mm drill bit is enough:
The pcb2gcode command example merges all drill tool paths so you can leave the machine unattended during the drilling job, otherwise tool change is requested while moving to a drilling hole of different size.
Place PCB on the sacrificial material and use paper tape to fix it to the board. Make sure spindle is stopped and insert 60 degree mill bit. Press F1 to toggle Emergency Stop and press F2 to turn on stepper drivers. Use up, down, left, right arrow and Page Up/Down buttons to drive the CNC head along X, Y and Z axes. Slide Jog speed to the max to move faster.
Important
Press Shift-1 to switch between imperial (inch) and metric systems (mm).
Move the head along X and Y axes to the starting point. Select X axis hit Home button, select Y axis and hit Home again. Press Page Down to drive the mill bit into the copper layer into desired cutting depth. Select Z axis and hit Home button. Press Page Up to drive mill bit away.
Open front.ngc, press R to begin executing the current file:
Once the milling is ready do not power down the steppers as you would lose the X and Y axis alignment. If you have manually controlled spindle simply stop the spindle. Replace the mill bit with drill bit. Use Page Up and Page Down to drive the drill bit near the copper surface, but not into it. Select Z axis and hit Home button to rehome Z axis for drill bit.
Move the head away while making sure you don't accidentally run into the frame limits as this would again lose the X and Y alignment.
Use cordless drill to cut though some of the mounting holes into the sacrificial material, preferably the ordermost ones. Remove mounting tapes, flip the PCB along Y axis. Use bolts to align flipped PCB to the holes in sacrificial material. Retape the PCB and remove bolts.
It might become handy to run EMC2 the graphical user interface of LinuxCNC on your daily driver distro simply to test your *.ngc files, but there are no packages available for Ubuntu or Fedora. The graphical user interface can still be fortunately compiled from source.
To install dependencies on Fedora 25:
dnf install libudev-devel libmodbus-devel libusb-devel gtk2-devel bwidget \
tkimg-devel tclx boost-devel libXmu-devel autoconf git gcc-c++ \
readline-devel pygtk2
To install dependencies on Ubuntu 14.04:
apt install libudev-dev libmodbus-dev libusb-1.0-0-dev tcl-dev tk-dev \
bwidget libtk-img tclx libboost-python-dev libxmu-dev libreadline-dev \
freeglut3-dev libglib2.0-dev libgtk2.0-dev autoconf git
Fetch source code:
git clone https://github.com/LinuxCNC/linuxcnc
cd linuxcnc/
Compile from source:
cd src/
./autogen.sh
./configure --enable-non-distributable=yes
make -j4
cd ..
Run from source tree without installing to system:
./scripts/rip-environment linuxcnc
In the menu select axis and click OK.
Nowadays it's not realistic to observe logs on different machines manually. Instead log messages should be collected at a central logging server and not stored on individual servers at all to reduce disk space usage and disk writes.
Install rsyslog daemon:
apt-get install rsyslog
Create /etc/rsyslog.d/server.conf with following content:
# Provide UDP syslog reception
$ModLoad imudp
$UDPServerRun 514
# Provide TCP syslog reception
$ModLoad imtcp
$InputTCPServerRun 514
# Use custom filenaming scheme
$template FILENAME,"/var/log/remote/%HOSTNAME%.log"
*.* ?FILENAME
$PreserveFQDN on
Restart service:
service rsyslog restart
Make sure your network equipment of server firewall won't filter TCP 514 traffic.
Again, install rsyslog daemon:
apt-get install rsyslog
Create /etc/rsyslog.d/client.conf and substitute 1.2.3.4 with your log server IP-aadress:
$PreserveFQDN on
$ActionQueueType LinkedList
$ActionQueueFileName srvrfwd
$ActionResumeRetryCount -1
$ActionQueueSaveOnShutdown on
*.* @@1.2.3.4:514
Such configuration makes sure no messages will be lost due to network glitches or reboots.
Finally restart the service:
service rsyslog restart
On server leave following running:
tail -f /var/log/remote/*.log
On workstation:
logger -s "Hello world"
Nowadays the web browser are capable of playing back video without additional plugins. As a content publisher you just have to make it sure that the videos are available in supported formats. Mozilla Firefox relies on royality-free OGG Theora and OGG Vorbis codecs for video and audio. For Google Chrome you need to use h264 video codec and AAC or MP3 audio codec. Note that in US where software patents apply, you need to pay license fee for using these patented codecs even if you're using open-source implementation!
VIDEO_HEIGHT=720
for j in $@; do \
# Transcode for Firefox
ffmpeg -i $j \
-vcodec libtheora -q:v 5 -vf scale=-2:$VIDEO_HEIGHT \
-acodec libvorbis \
transcode/$(basename $j .mov).ogv
# Transcode for Chrome
ffmpeg -i $j \
-c:v libx264 -preset veryslow -tune film -vf scale=-2:$VIDEO_HEIGHT \
-c:a copy \
transcode/$(basename $j .mov).mp4
# You might want to add WebM here as well, but oh well
done
Another script for generating nice looking index.html for listing the video files. Also make sure your webserver reports Content-Type header properly, see the mimetypes below in the HTML snippet.
POSTER_WIDTH=384
POSTER_HEIGHT=216
cat << EOF > transcode/index.html
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, user-scalable=no"/>
</head>
<body>
EOF
for j in korgem_kvaliteet/*/*; do \
# Generate poster for the video
ffmpeg -i $j \
-ss 15 -vframes 1 -q:v 2 -vf scale=-2:$POSTER_HEIGHT \
-y transcode/$(basename $j .mov).jpg
cat << EOF >> transcode/index.html
<div style="display: inline-block; float:left; width: 400px; height: 250px;">
<h>$(basename $j .mov)</h>
<br/>
<video width="$POSTER_WIDTH" height="$POSTER_HEIGHT" controls poster="$(basename $j .mov).jpg">
<source src="$(basename $j .mov).ogv" type="video/ogg">
<source src="$(basename $j .mov).mp4" type="video/mp4">
</video>
</div>
EOF
done
cat << EOF >> transcode/index.html
</body>
</html>
EOF
]]>Microsoft Active Directory'st ning Samba-baasil domeenikontrollerist saab andmeid pärida üle LDAP protokolli. Mõlemad toetavad ka GSSAPI-t, mis võimaldab autentida osapooli ning krüpteerida liiklust.
Python 3.x jaoks pole veel saadaval LDAP-i moodulit mis toetaks Kerberost ja GSSAPI-t. Python 2.x jaoks saab säärase mooduli paigaldada:
apt-get install python-ldap
Igaks juhuks veendu, et ka vastavad SASL moodulid ning Kerberose tööriistad on paigaldatud:
apt-get install krb5-user libsasl2-modules-gssapi-heimdal
Järgnevas näites küsitakse kasutajate nimed ja e-posti aadressid AD-st üle LDAP-i kasutades SASL teeke autentimiseks ning ka transportkihi krüpteerimiseks analoogselt ldapsearch käsule. Näide eeldab et on autenditud Kerberosega -- logi sisse domeeni kontoga või tee lihtsalt:
kinit kasutaja@EXAMPLE.COM
Pista järgnev .py faili ning käivita see Python abil:
#!/usr/bin/python2
import ldap, ldap.sasl
conn = ldap.initialize('ldap://dc1.example.com')
conn.set_option(ldap.OPT_REFERRALS, 0)
conn.sasl_interactive_bind_s('', ldap.sasl.gssapi())
attribs = 'cn','mail', 'userPrincipalName'
search_filter = '(&(objectClass=user)(objectCategory=person))'
r = conn.search_s('dc=example,dc=com', ldap.SCOPE_SUBTREE, search_filter, attribs)
for dn,entry in r:
if not dn: continue
full_name, = entry.get("cn")
mail, = entry.get("mail") or entry.get("userPrincipalName") or (None,)
if not mail: continue
print "%s <%s>, " % (full_name, mail),
Arvuti domeeni liitmisel luuakse /etc/krb5.keytab, mille abil saab masin end tuvastada domeenikontrollerile. Täielikult automatiseeritud variant mida peab käitama root kasutaja õigustes ning mille saab näiteks croni pista oleks järgnev:
import ldap, ldap.sasl
from subprocess import call
from ConfigParser import ConfigParser
cp = ConfigParser()
cp.read("/etc/samba/smb.conf")
domain = cp.get("global", "realm").lower()
base = ",".join(["dc=" + j for j in domain.split(".")])
cmd = "kinit", "-k", cp.get("global", "netbios name") + "$"
call(cmd)
conn = ldap.initialize('ldap://' + domain)
conn.set_option(ldap.OPT_REFERRALS, 0)
conn.sasl_interactive_bind_s('', ldap.sasl.gssapi())
attribs = 'cn','mail', 'userPrincipalName'
search_filter = '(&(objectClass=user)(objectCategory=person))'
for dn,entry in conn.search_s(base, ldap.SCOPE_SUBTREE, search_filter, attribs):
if not dn: continue
full_name, = entry.get("cn")
mail, = entry.get("mail") or entry.get("userPrincipalName") or (None,)
if not mail: continue
print "%s <%s>, " % (full_name, mail),
Käesolevatele koodijuppidele võib leida tosin huvitavat rakendusala - sisselogimisel võrguketaste lisamine järjehoidjatesse, printerite lisamine grupipoliitika alusel vms aga sellest juba järgmine kord.
Broadcom is continuously doing terrible work with their wired and wireless cards, basically any other hardware vendor is doing better job maintaining open-source drivers than Broadcom.
Important
Avoid procuring Broadcom equipment
HP EliteDesk 705 G1 SFF contains Broadcom BCM5762 (14e4:1687) wired ethernet and at least with kernels from 3.13 up to 4.1 the machine loses connectivity if there is high load on the network interface 1.
It took several days to come up with a workaround for the issue and here it is. Following disables some fancy DMA functionality on the card keeping it at least usable:
ethtool -K eth0 highdma off
Create /etc/udev/rules.d/80-tg3-fix.rules with following content to make the changes permanent:
ACTION=="add", SUBSYSTEM=="net", ATTRS{vendor}=="0x14e4", ATTRS{device}=="0x1687", RUN+="/sbin/ethtool -K %k highdma off"
If you're using Puppet simply add following to your manifest:
file { "/etc/udev/rules.d/80-tg3-fix.rules":
ensure => present,
mode => 644,
owner => root,
group => root,
content => 'ACTION=="add", SUBSYSTEM=="net", ATTRS{vendor}=="0x14e4", ATTRS{device}=="0x1687", RUN+="/sbin/ethtool -K %k highdma off"'
}
Hopefully the fix will be merged upstream soon.
]]>Ubuntu 14.04 kaasa pandud riistvara tugi hakkab tasapisi ajast maha jääma ning näiteks AMD A10 ja A8 APU-dega varustatud masinates peaks paigaldama värskemad Ubuntu 15.10 videokaardi draiverid:
sudo apt-get install -y \
xserver-xorg-core-lts-wily \
xserver-xorg-lts-wily \
xserver-xorg-video-all-lts-wily \
xserver-xorg-input-all-lts-wily \
mesa-vdpau-drivers-lts-wily \
libwayland-egl1-mesa-lts-wily \
libgl1-mesa-glx-lts-wily \
libgl1-mesa-glx-lts-wily:i386 \
libglapi-mesa-lts-wily:i386 \
libgles2-mesa-lts-wily \
libgles1-mesa-lts-wily \
xserver-xorg-video-qxl-lts-wily
Paigalda ka värske LTS tuum, see pole veel Ubuntu repodesse maandunud:
wget -c \
http://kernel.ubuntu.com/~kernel-ppa/mainline/v4.4.2-wily/linux-headers-4.4.2-040402_4.4.2-040402.201602171633_all.deb \
http://kernel.ubuntu.com/~kernel-ppa/mainline/v4.4.2-wily/linux-headers-4.4.2-040402-generic_4.4.2-040402.201602171633_amd64.deb \
http://kernel.ubuntu.com/~kernel-ppa/mainline/v4.4.2-wily/linux-image-4.4.2-040402-generic_4.4.2-040402.201602171633_amd64.deb
sudo dpkg -i \
linux-headers-4.4.2-040402_4.4.2-040402.201602171633_all.deb \
linux-headers-4.4.2-040402-generic_4.4.2-040402.201602171633_amd64.deb \
linux-image-4.4.2-040402-generic_4.4.2-040402.201602171633_amd64.deb
sudo rm -fv \
linux-headers-4.4.2-040402_4.4.2-040402.201602171633_all.deb \
linux-headers-4.4.2-040402-generic_4.4.2-040402.201602171633_amd64.deb \
linux-image-4.4.2-040402-generic_4.4.2-040402.201602171633_amd64.deb
Lõpuks tee masinale taaskäivitus.
]]>This guide is for anyone interested in installing printers remotely using Puppet for Ubuntu 14.04.
Important
Avoid procuring Canon printers
So far I haven't seen a sane way to install Canon printers. A reasonable printer doesn't need local drivers/filters and uses platform independent protocol such as Internet Printing Protocol.
First install the CUPS module for Puppet on the Puppetmaster:
puppet module install mosen-cups
For the workstations add some packages to enable printing stack:
# Install CUPS and filters
package { "system-config-printer-gnome": ensure => installed }
package { "cups": ensure => installed }
package { "ghostscript": ensure => installed }
package { "unpaper": ensure => installed }
package { "printer-driver-all" => installed }
# PPD-s
package { "openprinting-ppds": ensure => installed }
package { "hpijs-ppds": ensure => installed }
package { "hp-ppd": ensure => installed }
package { "foomatic-db-compressed-ppds": ensure => installed }
Following should discover printers sitting on the network as well as ones connected via USB:
lpinfo -v
If that's not helpful use nmap to discover the ports on the printer's IP-address:
nmap 192.168.?.?
This printer uses JetDirect protocol which means the document has to prepared locally on the computer and then sent via TCP 9100 port to the printer. Use the vendor name and model name bits to figure out which is the most suitable PPD for the printer:
lpinfo -m | grep HP | grep Laser | grep 2100 | grep recommended
Corresponding Puppet snippet:
printer { "HP-LaserJet-2100":
ensure => present,
uri => 'socket://192.168.2.12',
description => 'HP LaserJet 2100',
model => 'foomatic-db-compressed-ppds:0/ppd/foomatic-ppd/HP-LaserJet_2100-pxlmono.ppd',
page_size => 'A4'
}
In lpinfo -v you can identify such printers by socket:// protocol used in the URI.
This printer uses Internet Printing Protocol over TCP port 631. In this case the document is sent over network in PostScript format and printer takes care of the rest. Printer definition file still has to supply some information about the supported page sizes, duplex support etc.
printer { "Lexmark-MS410dn":
ensure => present,
uri => 'ipp://10.254.201.50:631/ipp',
description => 'Lexmark MS410dn',
model => 'foomatic-db-compressed-ppds:0/ppd/foomatic-ppd/Lexmark-MS410dn-Postscript.ppd',
page_size => 'A4'
}
In lpinfo -v you can identify such printers by ipp:// protocol used in the URI.
Here are some examples how USB printers are installed. In most cases lpinfo -v was used to determine the device URI and lpinfo -m was grepped to identify suitable printer model:
HP LaserJet 1505:
printer { "HP-LaserJet-1505n":
ensure => present,
uri => "usb://HP/LaserJet%20P1505n?serial=KQ154T9",
description => "HP LaserJet 1505n",
model => "foo2zjs:0/ppd/foo2zjs/HP-LaserJet_P1505n.ppd",
page_size => 'A4'
}
HP LaserJet 1200:
printer { "HP-LaserJet-1200":
ensure => present,
uri => 'usb://HP/LaserJet%201200?serial=00CNBP009193',
description => 'HP LaserJet 1200',
model => 'lsb/usr/hplip/HP/hp-laserjet_1200n-hpijs.ppd',
page_size => 'A4'
}
HP DeskJet 2540:
printer { "HP-DeskJet-2540":
ensure => present,
uri => 'usb://HP/Deskjet%202540%20series?serial=CN4CO5F38C0604&interface=1',
description => 'HP DeskJet 2540',
model => 'lsb/usr/hplip/HP/hp-deskjet_2540_series-hpijs.ppd',
page_size => 'A4'
}
OpenWrt on tüüpiliselt paigaldatud MIPS või ARM protsessoriga miniarvutitesse nagu Mikrotik, Gateworks, Compex ja OpenWrt on saadaval ka paljudele off-the-shelf marsruuteritele. Samas võib OpenWrt paigaldada ka tavalisele x86 riistvarale. Käesolevas blogipostituses on kirjeldatud kolm viisi OpenWrt paigalduseks x86 raual: otse füüsilisele, virtuaalmasinale VirtualBoxis ning virtuaalmasinale KVM-is. Esimene võrguliides on ühendatud sisevõrgu tsooni ning teine võrguliides küsib DHCP-ga aadressi väljapoolt.
Laadi alla OpenWrt kõvakettatõmmis ning paki see lahti:
wget https://downloads.openwrt.org/chaos_calmer/15.05.1/x86/generic/openwrt-15.05.1-x86-generic-combined-ext4.img.gz
gunzip openwrt-15.05.1-x86-generic-combined-ext4.img.gz
Paigaldada saad näiteks olles teinud alglaadimise Ubuntu LiveCD-lt.
Kirjuta tõmmis esimesele kettale:
umount /dev/sda*
cat openwrt-15.05-x86-generic-combined-ext4.img > /dev/sda
Suurenda viimane ext4 failisüsteem ketta suuruseks.
echo "d\n2" | fdisk /dev/sda
resize2fs /dev/sda2
Tee taaskäivitus kõvakettalt.
Kas nimeta fail ümber .raw lõpuliseks:
mv openwrt-15.05-x86-generic-combined-ext4.img \
openwrt-15.05-x86-generic-combined-ext4.raw
Või teisenda VMware formaati ümber:
qemu-img convert \
-f raw openwrt-15.05-x86-generic-combined-ext4.img \
-O vmdk openwrt-15.05-x86-generic-combined-ext4.vmdk
VirtualBox tahab kettatõmmist saada VirtualBoxile söödavas formaadis, mistõttu 1:1 kettatõmmis tuleb esmalt teisendada VDI failiks:
qemu-img convert \
-f raw openwrt-15.05-x86-generic-combined-ext4.img \
-O vdi openwrt-15.05-x86-generic-combined-ext4.vdi
Seejärel tuleb luua marsruuteri jaoks virtuaalmasin, selle jaoks piisab täiesti ühest tuumast ning 32MB mälust. Ülal teisendatud kettatõmmis määra esimeseks kõvakettaks.
Laadi alla KVM jaoks kohandatud tõmmis
wget https://downloads.openwrt.org/chaos_calmer/15.05.1/x86/kvm_guest/openwrt-15.05.1-x86-kvm_guest-combined-ext4.img.gz
gunzip openwrt-15.05.1-x86-kvm_guest-combined-ext4.img.gz
Käivitamiseks KVM virtuaalmasinas loo esmalt sild mille külge ühendada sisevõrk:
brctl addbr br0
Seejärel loo skript /etc/qemu-ifup millega virtuaalmasin silla külge ühendatakse:
#!/bin/bash
ifconfig $1 0.0.0.0 promisc up
brctl addif br0 $1
Tee see ka käivitatavaks:
chmod +x /etc/qemu-ifup
Seejärel käivita virtuaalmasin:
kvm -smp 2 -m 32 \
-hda openwrt-15.05-x86-generic-combined-ext4.img \
-netdev tap,script=/etc/qemu-ifup,id=lan -device e1000,netdev=lan \
-netdev user,id=wan -device e1000,netdev=wan
Antud juhul esimene võrguliides ühendatakse br0 sillaga ning teisele võrguliidesele teeb QEMU ise NAT-i.
Important
Käesolev juhend on aegunud, Ubuntu 16.04 jaoks sobiv juhend on aadressil http://lauri.vosandi.com/2016/09/xenial-ltsp-ja-id-kaart.html
Juhend eeldab Ubuntu 14.04 server paigaldust.
Iseseisev (standalone) server antud kontekstis tähendab seda, et LTSP serveril on kaks võrguliidest, millest üks vaatab Interneti poole ning teine on ühendatud eraldatud võrgusegmenti kus terminalid asuvad. Sellisel juhul serveeritakse terminalide võrku kõiki vajalikke teenuseid: DHCP, TFTP, NBD, SSH, LDM jne.
Esiteks uuenda pakette:
apt-get update
apt-get dist-upgrade
Paigalda LTSP metapakett, see seadistab kõik teenused mis on LTSP toimimiseks vajalikud:
apt-get install -y ltsp-server-standalone wget ca-certificates apt-transport-https
Seadista võrk failis /etc/network/interfaces, asenda 192.168.77.1 omale sobiliku sisevõrgu aadressiga:
cat << EOF > /etc/network/interfaces
auto lo
iface lo inet loopback
auto eth1
iface eth1 inet dhcp
auto eth0
iface eth0 inet static
address 192.168.77.1
netmask 255.255.255.0
EOF
Asenda vaikimisi alamvõrk 192.168.0.0/24 ka DHCP serveri seadistustes:
sed -i "s/192\.168\.0\./192.168.77./g" /etc/ltsp/dhcpd.conf
Taaskäivita teenused:
/etc/init.d/networking restart
/etc/init.d/network-manager restart
/etc/init.d/isc-dhcp-server restart
/etc/init.d/nbd-server restart
Kui sul on juba toimiv DHCP server võid asendada ltsp-server-standalone paketi ltsp-server paketiga:
apt-get install -y ltsp-server wget ca-certificates apt-transport-https
Sellisel juhul pead vajalikud teenused, nagu näiteks TFTP ise seadistama:
apt-get install -y tftpd-hpa
sed -e 's/TFTP_ADDRESS=.*/TFTP_ADDRESS=":69"/' /etc/default/tftpd-hpa
Kontrolli üle, et ka muud teenused oleks kättesaadavad terminalidele.
Ubuntu töölaud on üsna resursinõudlik ning terminal-serveri puhul äärmiselt aeglane, kuna pilt liigub üle võrgu. Terminal-serverile on soovitatud paigaldada MATE töölaud:
sudo apt-add-repository ppa:ubuntu-mate-dev/ppa
sudo apt-add-repository ppa:ubuntu-mate-dev/trusty-mate
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install -y mate-desktop-environment-extras
Kui serverisse on paigaldatud mitu erinevat töölaua keskkonda, saab vaikimisi töölauda vahetada järgnevalt:
update-alternatives --config x-session-manager
Lisa ka Eesti ID-kaardi baastarkvara varamu:
echo "deb https://installer.id.ee/media/ubuntu/ trusty main" > /etc/apt/sources.list.d/ria-repository.list
wget https://installer.id.ee/media/install-scripts/ria-public.key -O - | apt-key add -
apt-get update
apt-get install -y estonianidcard
Lisa Xsession skript mis näitab uut PCSC-lite sokkli asukohta:
echo "export PCSCLITE_CSOCK_NAME=\$HOME/.pcscd.comm" > /etc/X11/Xsession.d/80-pcsclite
Lisa minu tarkvara varamu, kust saab kohandatud OpenSSH serveri mis oskab ümber suunatud ID-kaardi tarkvara sokleid vastu võtta:
echo "deb http://packages.koodur.com trusty main ltsp" > /etc/apt/sources.list.d/koodur.list
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 054C36F8
apt-get update
apt-get upgrade
Enamus PC riistvara toetab PXE-alglaadimist. Alusta terminali tarkvara juurfailisüsteemi loomisega:
MIRROR="http://ee.archive.ubuntu.com/ubuntu/" \
LANG=C \
ARCH=i386 \
ltsp-build-client
ID-kaardi jaoks vajalike komponentide paigaldamiseks sisene terminali juurfailisüsteemi:
chroot /opt/ltsp/i386 /bin/bash
Lisa minu tarkvara varamu, kust saab kohandatud OpenSSH kliendi mis oskab ID-kaardi sokleid serverisse suunata:
echo "deb http://packages.koodur.com trusty main ltsp" > /etc/apt/sources.list.d/koodur.list
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 054C36F8
Paigalda PCSC-Lite deemon:
apt-get install -y pcscd
Lisa SSH kliendi seadistused, tärni võib asendada oma serveri IP-ga:
cat << EOF > /etc/ssh/ssh_config
Host *
SendEnv LANG LC_*
RemoteForward ~/.pcscd.comm /run/pcscd/pcscd.comm
EOF
VIA terminalide UniChrome graafika tüürelite seis on suht halb seega ma lülitaks välja ka 3D kiirenduse:
cat << EOF > /etc/X11/xorg.conf
Section "Module"
Disable "glx"
Disable "dri"
EndSection
EOF
Välju terminali juurikast:
exit
Uuenda terminali juurfailisüsteemi SquashFS tõmmist:
ltsp-update-image
Lisa terminali juurikasse rdesktop pakett:
chroot /opt/ltsp/i386 apt-get install -y rdesktop
Genereeri uuendatud tõmmis:
ltsp-update-image
Seadista ringi /var/lib/tftpboot/ltsp/i386/lts.conf:
[default]
SCREEN_07="rdesktop -x l -k et -u '' -f -r scard -r sound -r disk:floppy=/run/drives aken.edu.ee"
SCREEN_08="ldm"
Ubuntu 14.04 baasil terminalist Windows 2012 serveri pihta käies on mingi häda kursorite kadumisega, sellest saab mööda kui Windowsi poolel välja lülitada kursori vari 1 või terminali juurikasse paigaldada uuendatud RDP klient:
chroot /opt/ltsp/i386 apt-get install -y libgssglue1
chroot /opt/ltsp/i386 wget http://launchpadlibrarian.net/193620368/rdesktop_1.8.3-1_i386.deb
chroot /opt/ltsp/i386 dpkg -i rdesktop_1.8.3-1_i386.deb
chroot /opt/ltsp/i386 rm -fv rdesktop_1.8.3-1_i386.deb
ARCH=i386 ltsp-update-image
Sisselogimisdialoogi aegumise vältimiseks ava Windowsi register ning lisa HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp alla DWORD tüüpi LogonTimeout=0xffffffff võti-väärtus paar 2.
Kuna PXE on x86 platvormi spetsiifiline siis säärast võimekust näiteks Cubietrucki kasutada ei saa. Küll aga saab Cubietruckile kõrvetada püsivara, mis analoogselt PXE-le laadib võrgust alla tuuma, initrd ning jätakb operatsioonisüsteemi alglaadimisega.
Esmalt paigalda QEMU emulatsioonikiht:
apt-get install -y qemu-user-static binfmt-support
Keela OMAP4 tuuma paigaldus, see pole naguinii enam kättesaadav tarkvaravaramutest:
sed -i -e 's/KERNEL_ARCH="omap4"/KERNEL_ARCH=""/' /usr/share/ltsp/plugins/ltsp-build-client/Ubuntu/020-kernel-selection
Loo ARM juurfailisüsteem:
DEBOOTSTRAP=qemu-debootstrap ARCH=armhf LANG=C ltsp-build-client
Lisa serveri SSH võti:
ltsp-update-sshkeys
Sisene Cubietrucki juurfailisüsteemi:
chroot /opt/ltsp/armhf /bin/bash
Cubietrucki jaoks paigalda Igori 3.4.x tuum ja moodulid kuhu sai külge poogitud LTSP jaoks vajalik overlayfs:
echo "deb http://apt.armbian.com trusty main" > /etc/apt/sources.list.d/armbian.list
apt-key adv --keyserver keys.gnupg.net --recv-keys 0x93D6889F9F0E78D5
apt-get update
apt-get install -y linux-image-sun7i
Lisa minu tarkvara varamu, kust saab kohandatud OpenSSH kliendi mis oskab ID-kaardi sokleid serverisse suunata:
echo "deb http://packages.koodur.com trusty main ltsp" > /etc/apt/sources.list.d/koodur.list
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 054C36F8
Uuenda pakettide nimekirju:
apt-get update
Paigalda kohandatud OpenSSH, PCSC-deemon, LTSP-kliendi metapakett ja muu tilu-lilu:
apt-get install -y openssh-client pcscd xf86-video-fbturbo
Lisa SSH kliendi seadistused, et terminal võimaldaks serveris ligipääsu terminalis jooksvale PCSC deemonile, vajadusel asenda tärn oma serveri IP-ga:
cat << EOF > /etc/ssh/ssh_config
Host *
SendEnv LANG LC_*
RemoteForward ~/.pcscd.comm /run/pcscd/pcscd.comm
EOF
Kui soovid kasutada ka RDP sessioone siis uuendatud RDP kliendi paigaldamiseks:
apt-get install -y libgssglue1
wget http://launchpadlibrarian.net/193620260/rdesktop_1.8.3-1_armhf.deb
dpkg -i rdesktop_1.8.3-1_armhf.deb
rm -fv rdesktop_1.8.3-1_armhf.deb
Välju juurikast:
exit
Uuenda NBD kaudu serveeritavat tõmmist:
ltsp-update-image
Paigalda esmalt u-boot tööriistad:
apt-get install -y u-boot-tools
Sikuta Cubietrucki riistvara konfiguratsioon, mis paneb VGA pesa käima resolutsioonil 1024x768 ja lülitab välja terminali jaoks ebaolulised komponendid (WiFi, Bluetooth jms):
wget https://www.koodur.com/cubietruck/1024x768.bin -O /var/lib/tftpboot/ltsp/armhf/1024x768.bin
Loo u-boot jaoks skript mis laeb tuuma, initrd ning riistvara konfiguratsiooni:
cat << EOF > /var/lib/tftpboot/ltsp/armhf/1024x768.scr
setenv bootm_boot_mode sec
setenv bootargs 'ro init=/sbin/init-ltsp init=/sbin/init-ltsp root=/dev/nbd0'
tftp 0x43000000 /ltsp/armhf/1024x768.bin
tftp 0x42000000 /ltsp/armhf/uImage
tftp 0x50000000 /ltsp/armhf/initramfs.uImage
bootm 0x42000000 0x50000000
EOF
Genereeri u-boot tõmmised:
mkimage -A arm -O linux -T script -C none -n boot.scr -d \
/var/lib/tftpboot/ltsp/armhf/1024x768.scr \
/var/lib/tftpboot/ltsp/armhf/1024x768.scr.uimg
mkimage -A arm -T ramdisk -C none -n uInitrd -d \
/var/lib/tftpboot/ltsp/armhf/initrd.img-3.4.110-sun7i \
/var/lib/tftpboot/ltsp/armhf/initramfs.uImage
mkimage -A arm -O linux -T kernel -C none -n Linux -a 42000000 -e 42000000 -d \
/var/lib/tftpboot/ltsp/armhf/vmlinuz-3.4.110-sun7i \
/var/lib/tftpboot/ltsp/armhf/uImage
Seadista ringi ka DHCP serverit failis /etc/ltsp/dhcpd.conf:
authoritative;
subnet 192.168.77.0 netmask 255.255.255.0 {
range 192.168.77.20 192.168.77.250;
option domain-name "ltsp";
option domain-name-servers 8.8.8.8;
option broadcast-address 192.168.77.255;
option routers 192.168.77.1;
next-server 192.168.77.1;
option subnet-mask 255.255.255.0;
if substring( option vendor-class-identifier, 0, 3 ) = "PXE" {
filename "/ltsp/i386/pxelinux.0";
option root-path "/opt/ltsp/i386";
} else {
filename "/ltsp/armhf/1024x768.scr.uimg";
option root-path "/opt/ltsp/armhf";
}
}
Viimase sammuna peab Cubietruckile peale laskma uue u-booti mis püüab võrku seadistada DHCP-ga ning siis sealt TFTP-ga skripti alla sikutada. IT Kolledži Robootikaklubist saab laenutada SD-kaarti millel on Priit Laes kirjutatud skript, mis uue u-booti kirjutab Cubietrucki sisemisele mälule, nii et eraldi mälukaarti hiljem vaja pole:
# Seda tuleb siis Cubietrucki peal jooksutada ;)
wget -c https://www.koodur.com/cubietruck/u-boot-sunxi-with-spl.bin -O /root/u-boot-sunxi-with-spl.bin
echo nand-disk >/sys/class/leds/cubietruck\:blue\:usr/trigger
flash_erase -N /dev/mtd0 0 0 && \
nandwrite -p /dev/mtd0 /root/u-boot-sunxi-with-spl.bin && \
flash_erase -N /dev/mtd1 0 0 && \
nandwrite -p /dev/mtd1 /root/u-boot-sunxi-with-spl.bin && \
echo 1 > /sys/class/leds/cubietruck\:orange\:usr/brightness && \
sync && \
echo 0 > /sys/class/leds/cubietruck\:orange\:usr/brightness && \
echo 1 > /sys/class/leds/cubietruck\:green\:usr/brightness
Linux-põhiste serverite monitoorimiseks leiab mitmesuguseid vahendeid Nagiosest Zabbixini. Tüüpilise monitooringu lahenduse jaoks on vaja sättida üles andmebaas ning monitooringutarkvara reguaarselt uuendada. Käesolevas näites on välja toodud collectd, mis on minimalistik statistika kogumise tarkvara, mis kasutab RRD-põhist andmebaasi ning millel on palju erinevaid pistikprogramme funktsionaalsuse laiendamiseks.
Important
RRD andmebaasi majutamiseks on kõige sobilikum SSD, kirjutades RRD andmebaasi pöörlevatele ketastele võib kogu masin talumatult aeglaseks muutuda!
apt-get install collectd
Esmalt lähtesta collectd konfiguratsioon failis /etc/collectd/collectd.conf järgnevalt:
FQDNLookup true
LoadPlugin logfile
LoadPlugin syslog
LoadPlugin cpu # Protsessori kasutus
LoadPlugin df # Kettakasutus
LoadPlugin disk # Ketaste koormus
LoadPlugin interface # Võrguliidesed
LoadPlugin load # Süsteemi koormus
LoadPlugin memory # Mälukasutus
LoadPlugin network
LoadPlugin processes
LoadPlugin swap # Saaleala
LoadPlugin uptime
LoadPlugin users
<Plugin syslog>
LogLevel err
</Plugin>
<Plugin df>
FSType rootfs
FSType sysfs
FSType proc
FSType devtmpfs
FSType devpts
FSType tmpfs
FSType fusectl
FSType cgroup
IgnoreSelected true
</Plugin>
<Plugin disk>
Disk "/[sv]d[a-z]/" # Raporteeri ainult SATA ja VirtIO kettaid
</Plugin>
<Include "/etc/collectd/collectd.conf.d">
Filter "*.conf"
</Include>
Vaikimisi seadetega kirjutatakse RRD andmebaas välja /var/lib/collectd kataloogi. Kasutades Btrfs failisüsteemi tuleks copy-on-write funktsionaalsus välja lülitada:
chattr +C -Rf /var/lib/collectd
Lõpuks tuleks teenus ka käivitada:
sudo service collectd restart
Statistikat saatvates masinates lisa täiendav konfiguratsioon:
cat << EOF | sudo tee /etc/collectd/collectd.conf.d/client.conf
<Plugin network>
Server "serveri.aadress.siia.ee"
</Plugin>
EOF
Statistikat vastu võtvas masinas lisa vastav konfiguratsioon:
cat << EOF | sudo tee /etc/collectd/collectd.conf.d/server.conf
<Plugin network>
Listen "0.0.0.0"
</Plugin>
EOF
Tähelepanu peaks pöörama sellele, et vaikimisi seadetega on võimatu tuvastada kes statistikat saadab. Kohtvõrgus võib see aksepteeritav olla, kuid üle Interneti saates peaks vähemasti tulemüüris blokeerima võõrad aadressid, turvama ühendust VPN abil või kasutama paroole/sertifikaate ühenduse autentimiseks.
Esmalt paigalda lm-sensors tarkvarapakett:
sudo apt-get install lm-sensors
Vaikimisi seadetega tuvastab lm-sensors juba ära päris palju riistvara:
sensors
Täiendavate sensorite tuvastamiseks:
sudo sensors-detect
Selleks, et collectd neid näite raporteeriks tuleb täiendada collectd konfiguratsiooni:
echo "LoadPlugin sensors" | sudo tee /etc/collectd/collectd.conf.d/sensors.conf
Seejärel taaskäivita teenus:
sudo service collect restart
Kuna collectd on tarkvara puhtalt andmete kogumiseks, ei sisaldu selles ka veebiliidest. Collectd Graph Panel on PHP-s kirjutatud veebiliides collectd graafikute kuvamiseks, selle saab paigaldada järgnevalt:
sudo apt-get install apache2 libapache2-mod-php5
sudo git clone https://github.com/pommi/CGP /var/www/html/cgp
Teadupärast on IPv4 aadressid seostatavad geograafiliste asukohtadega. GeoIP andmebaas võimaldab IP-aadressidest tuletada ühenduse lähteriik.
apt-get install -y --no-install-recommends xtables-addons-common libtext-csv-xs-perl wget unzip
Laadi alla GeoIP andmebaas ning genereeri andmed tulemüürimise jaoks:
mkdir -p /usr/share/xt_geoip
cd /usr/share/xt_geoip && /usr/lib/xtables-addons/xt_geoip_dl
/usr/lib/xtables-addons/xt_geoip_build -D /usr/share/xt_geoip/ /usr/share/xt_geoip/*.csv
Lisaks on vaja paigaldada täiendavad tuuma moodulid, kui tahad reegleid rakendada LXC konteineris, siis selle peab paigaldama emamasinas:
apt-get install xtables-addons-dkms
modprobe ip_tables xt_geoip
Reegli lisamiseks:
iptables -I INPUT -p tcp --dport 22 -m geoip --src-cc EE -m comment --comment "Allow SSH from Estonia" -j ACCEPT
iptables -I INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -I INPUT -s 127.0.0.0/8 -i lo -j ACCEPT
iptables -P INPUT DROP
Tee tulemüürireeglid püsivaks:
apt-get install iptables-persistent
Peale Linuxi masina domeeni liitmist saab LDAP päringud domeenikontrolleri pihta teha kasutades arvuti keytabi. Selleks paigalda:
sudo apt-get install ldap-utils dnsutils libsasl2-modules-gssapi-heimdal
Viimane neist on vajalik päringute autentimiseks Kerberose abil.
Esmalt veendu, et domeenikontrolleri IP lahendub tagasi hostinimeks:
nslookup dc1.example.com
nslookup 192.168.?.?
Seejärel küsi domeenikontrollerist arvutile vastav ticket-granting-ticket:
sudo -i
kinit -k NETBIOS-NIMI\$
Või lihtsalt:
kinit -k $(grep "netbios name" /etc/samba/smb.conf | cut -d "=" -f 2)\$
Seejärel proovi kas saad päringut sooritada:
ldapsearch -Y GSSAPI -H ldap://dc1.example.com -b dc=example,dc=com
Päring peaks tagastama kõik domeenikontrolleris olevad objektid ühtegi parooli tippimata.
Trükkimisvaeva vähendamiseks võib kõik selle lisada faili /etc/ldap/ldap.conf järgnevalt:
URI ldap://dc1.example.com
BASE dc=example,dc=com
Edaspidi piisab lihtsalt järgnevast, et kuvada kõik domeenikontrolleris olevad objektid:
ldapsearch
Kasutajate saamiseks lisa otsingufilter:
ldapsearch '(&(objectClass=user)(objectCategory=person))'
Parajasti sisse logitud kasutaja leidmine:
ldapsearch samaccountname=$USER
Kasutaja konkreetseete attribuutide leidimine:
ldapsearch -LLL samaccountname=$USER cn
Täpitähtedega nime puhul peab veidi rohkem võimlema:
ldapsearch -LLL samaccountname=$USER cn | grep cn | cut -d ' ' -f 2 | base64 -d
Nii saame näiteks automatiseerida võrguketta järjehoidja lisamise /etc/X11/Xsession.d/95generate-gtk-bookmarks skriptis:
URL=$(ldapsearch -LLL samaccountname=$USER homeDirectory | sed -e 's/^\\\\/smb:\/\//' | sed -e 's/\\/\//g')
echo "$URL Võrguketas" > ~/.gtk-bookmarks
You can use following Puppet snippet to set the URL opened by default. Mozilla Firefox and Chromium were rather undocumented and the examples on the Internet were outdated:
# Set Mozilla Firefox homepage
file_line { "firefox-homepage":
path => "/etc/firefox/syspref.js",
ensure => present,
match => '^user_pref\("browser\.startup\.homepage",',
line => 'user_pref("browser.startup.homepage", "https://www.koodur.com");'
}
# Set Chromium homepage
file { "/etc/chromium-browser/policies/recommended/homepage.json":
ensure => file,
mode => 644,
owner => root,
group => root,
content => "{\n \"RestoreOnStartup\":4, \"RestoreOnStartupURLs\":[\"https://www.koodur.com\"]\n}\n"
}
Note that on your Puppetmaster you might have to install additional module:
puppet module install puppetlabs-stdlib
]]>OpenSSH kasutab vaikimisi kasutaja autentimiseks parooli. Tihtipeale see pole just kõige turvalisem viis kasutajat autentida, kuna parooli tippimine võib kõrvalt vaatajale näha olla ning lühikese parooli puhul on realistlik ka sisse murdmine toore jõuga. Selle vastu aitab võtmepaari genereermine ning avaliku võtme serverisse kopeerimine.
Vaikimisi ssh-keygen loob RSA võtmed, mis on 2048-bit ja suurema võtmepikkuse puhul piisavalt tugevad, aga järgnevas näites kasutame ECDSA (elliptic-curve digital signature algorithm), kuna see on üks kõige modernsemaid asümmeetrilise võtme algoritme:
ssh-keygen -t ecdsa -P ''
Programm küsib sisendiks kuhu salvestada võtmed, seal võib vajutada Enter, et kasutada vaikimisi kataloogi .ssh kodukataloogis kuhu kirjutatakse privaatne võti failinimiega id_ecdsa ning avalik võti failinimega id_ecdsa.pub. Väljund peaks välja nägema umbkaudu järgnev:
Generating public/private ecdsa key pair.
Enter file in which to save the key (/home/kasutaja/.ssh/id_ecdsa):
Your identification has been saved in /home/kasutaja/.ssh/id_ecdsa.
Your public key has been saved in /home/lauri/.ssh/id_ecdsa.pub.
The key fingerprint is:
2e:36:33:9b:3e:ec:23:62:4f:be:82:b5:8a:de:72:2b kasutaja@localhost
The key's randomart image is:
+--[ECDSA 256]---+
| |
| |
| |
| |
| S |
| . . |
| o ...* . |
|oE*+..+B |
|+++*===o |
+-----------------+
Loodud võtmepaar vastab konkreetse arvuti parajasti sisse logitud kasutajale ning avalik võti sobib selle kasutaja autentimiseks teistes arvutites.
Enne kui jätkad veendu et sihtmasinas oleks OpenSSH server paigaldatud, vastasel korral võid serverist vastuseks saada Connection refused:
sudo apt-get install openssh-server
Ülal loodud id_ecdsa.pub alusel saab kasutajat autentida ning selleks, et võimaldada sihtarvuti paroolita ligipääs avaliku võtme alusel võib kasutada ssh-copy-id käsku:
ssh-copy-id kasutaja@sihtmasin
See käsk logib sihtmasinasse sisse parooliga, vajadusel loob .ssh kataloogi sihtmasinas ning lisab sinna authorized_keys faili lõppu avaliku võtme.
Kui võtmed on olemas ning avalik võti lisatud sihtmasinasse, peaks autentmine toimima ilma paroolita. Kui võtmepaar on olemas pakub klient seda autentmismeetodit serverile, kui serverile sobib kliendi pakutav võti lastakse kasutaja sisse.
Kui võtmega autentmine toimib ning parooli pole vaja mõneks muuks otstarbeks (nt sudo), võib eemaldada ja keelata kasutaja parooli sihtmasinas:
# Parooli eemaldada ja keelata saab vaid root
passwd -d -l kasutajanimi
Kui parooliga sisselogimist on siiski tarvis aga üle SSH ligipääs võiks olla lubatud vaid avaliku võtmega, võib SSH serveri konfiguratsioonis välja lülitada parooliga autentmise kasutades PasswordAuthentication no rida:
sed -r -e 's/^.?PasswordAuthentication .*/PasswordAuthentication no/' -i /etc/ssh/sshd_config
service ssh reload
Linux konteinerid (Linux Containers) või lühidalt LXC on tehnoloogia, mis kasutab Linux tuuma control groups funktsionaalsust võimaldades ühe Linux tuuma all käitada mitut isoleeritud Linux-põhist operatsioonisüsteemi ehk teiste sõnadega partitsioneerida Linux-põhise masina ressursse. Tegu on operatsioonisüsteemi tasemel virtualiseerimisega nagu BSD Jails 1 või OpenVZ 2, kus samamoodi mitu operatsioonisüsteemi instantsi jagavad ühte tuuma. Käesolev juhend eeldab Debian 8 jessie, Ubuntu 15.04 või hilisemate väljalasete paigaldust.
Konteinerite puhul on juurfailisüsteemid, st kataloogid mis sisaldavad operatsioonisüsteemi faile eraldatud, aga Linuxi tuum mida konteinerid kasutavad on sama ning jagatud.
Kontrollgruppidega (control groups), saab isoleerida ka võrguliidesed ja protsessid ning piirata protsessori ja mälu kastutust.
Protsessipuu säärase süsteemi käivitamisel näeks välja umbkaudu järgnev:
systemd
├─acpid
├─agetty --noclear tty1 linux
├─atd -f
├─cron -f
├─dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation
├─dhclient -v -pf /run/dhclient.lxcbr0.pid -lf /var/lib/dhcp/dhclient.lxcbr0.leases lxcbr0
├─lxc-start -d -n ubuntu-trusty-test
│ └─init
│ ├─dbus-daemon --system --fork
│ ├─dhclient -1 -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0
│ ├─getty -8 38400 console
│ ├─cron
│ ├─sshd -D
│ ├─systemd-logind
│ ├─systemd-udevd --daemon
│ ├─upstart-file-br --daemon
│ ├─upstart-socket- --daemon
│ └─upstart-udev-br --daemon
├─lxc-start -g debian-wheezy-test
│ └─systemd
│ ├─dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation
│ ├─dhclient -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0
│ ├─agetty --noclear -s console 115200 38400 9600
│ ├─cron
│ ├─sshd -D
│ ├─systemd-journal
│ ├─systemd-logind
│ └─systemd-udevd
├─lxc-start -d -n debian-jessie-test
│ └─systemd
│ ├─dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation
│ ├─dhclient -v -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases eth0
│ ├─sshd -D
│ ├─systemd-journal
│ └─systemd-logind
├─sshd -D
├─systemd-journal
├─systemd-logind
└─systemd-udevd
Siit on näha, et iga konteineri jaoks on oma virtuaalne võrguliides eth0 ning DHCP klientrakendus on käivitatud iga konteineri jaoks. Kuna iga konteiner paistab eraldi IP-ga võrgus on igas konteineris jooksmas ka OpenSSH server.
Paigalda LXC ja mallide skriptid:
apt-get install lxc lxc-templates bridge-utils
Loo Debian 8 konteiner:
lxc-create -n test1 -t debian -- -r jessie
LXC konteinereid saab paigutada ka failisüsteemi jaotistesse a'la Btrfs või ZFS subvolume:
lxc-create -n test2 -t debian -B btrfs -- -r jessie
Niiviisi paigutatakse konteineri juurfailisüsteem /var/lib/lxc/test2/rootfs Btrfs subvolume sisse, mida saab hõlpsalt varundada.
Ubuntu 14.04 i386 konteineri saab luua järnevalt:
lxc-create -n katse -B btrfs -t ubuntu -- -r trusty -a i386
Paigaldada saab ka eel-valmistatud juurfailisüsteemi, see on pisut kiirem kui ülemine:
lxc-create -n katse -B btrfs -t download -- -d ubuntu -r trusty -a i386
Important
Ubuntu 15.04 ning Debian 8 võtsid kasutusele systemd, mis tähendab et vanemal peremeesoperatsioonisüsteemil nende või hilisemate külalisopeartsioonisüsteemide käitamine on veel problemaatiline.
64-bitise x86 protsessori peal saab otse käitada ka 32-bitist konteinerit, kui konteineri loomisel kasutada -a i386 võtit:
lxc-create -n test2 -t debian -B btrfs -- -r jessie -a i386
Võõra arhitektuuriga (ARM, MIPS, PowerPC jms) konteinerite käitamiseks tuleb paigaldada QEMU emulatsioonikiht:
apt-get install qemu-user-static
Nii saab luua näiteks ARMv7 arhitektuuriga konteineri:
lxc-create -n test3 -t download -B btrfs -- -d debian -r wheezy -a armhf
Enne käivitamist peaks paigaldama QEMU binaarid ka konteineri sisse:
cp /usr/bin/qemu-*-static /var/lib/lxc/test3/rootfs/usr/bin/
Emuleeritud arhitetuurid on muidugi aeglased, aga see võimaldab näiteks x86-64 riistvara peal teha tarkvaraarendust armhf platvormile.
Käivita konteiner:
lxc-start -n katse -d
Haagi konteineri käsureale:
lxc-attach -n katse
Konteineri seest saab konteineri kinni panna ja taaskäivitada tavapäraste halt ja reboot käskudega.
Peremeesmasinast saab konteineri viisakalt kinni panna järgnevalt:
lxc-stop -n katse
Konteinerite nimekiri:
lxc-ls -f
Konteineri automaatseks käivitamiseks alglaadimisel lisa järgnev rida faili /var/lib/lxc/katse/config:
lxc.start.auto = 1
Vaikimisi kointeinerid kas ei saa võrku üldse (Debian 8, Ubuntu 14.04) või nad liidetakse lxcbr0 silla koosseisu (Ubuntu 15.04+), kus neile küll pakutakse IP aadress aga selle kaudu internetti veel ei pääse. Kõige pealt tee kindlaks et on paigaldatud sildade seadistamiseks ette nähtud tööriistad:
apt-get install bridge-utils
Peata võrguliides eth0, vastasel korral jääb talle IP aadress külge ja tekivad anomaaliad kui sillal ja võrguliidesel mõlemal sama IP aadress on.
ifdown eth0
Selleks, et mõlemas keskkonnas füüsilisse võrku ligipääs anda ning mitte konflikti minna eelseadistatud võrguliidestega nagu lxcbr0 võime ümber seadistada peremeesmasina võrgu failis /etc/network/interfaces:
auto lo
iface lo inet loopback
auto br0
iface br0 inet dhcp
# Lisa füüsiline eth0 silla koosseisu
bridge_ports eth0
# Eemalda võrguliidese definitsioon füüsilise võrguliidese jaoks:
#auto eth0
#iface eth0 inet ...
Käivita sild:
ifup br0
Veendu, et br0 saab legitiimse IP-aadressi ning et eth0 ning teistel silla koosseisu kuuluvatel võrguliidestel poleks IP-aadressi määratud. Kui jäi eelnevalt eth0 kinni panemata saab võrguliidese lülitada nn promiscuous režiimi järgnevalt:
ifconfig eth0 0.0.0.0 promisc up
Seadista külalismasina võrk ümber failis /var/lib/lxc/katse/config:
# Kasuta virtuaalset ethernet võrguliidest
lxc.network.type = veth
# Võrguliides käivitatakse konteineri käivitamisel
lxc.network.flags = up
# Võrguliides lisatakse selle silla koosseisu
lxc.network.link = br0
Silla olekut saad kontrollida brctl ja ifconfig abil:
ifconfig br0 # Liidesel peaks olema füüsilise võrgu aadress
ifconfig eth0 # Liidesel ei tohiks olla IP aadressi
brctl show br0 # Interfaces all peaks olema eth0 ja vethXXXX (per-konteiner) liidesed