necorouter

A software router with an industrial-router-style CLI. A single static binary, no dependencies. It provides routing, NAT, DHCP, NTP, OSPF, VLAN, and GRE features.Программный роутер с CLI в стиле промышленных маршрутизаторов. Один статический бинарник, без зависимостей. Поддерживает маршрутизацию, NAT, DHCP, NTP, OSPF, VLAN и GRE.

DebianCentOS / RHELAlpineamd64 · arm64CGO disabledCGO отключён

OverviewОбзор

necorouter turns a Linux machine into a router that is managed with commands in a familiar syntax. The configuration is written in the CLI, saved to a file and applied to the system: addresses, routes, NAT, DHCP, NTP, OSPF, VLANs, GRE tunnels.necorouter превращает Linux-машину в маршрутизатор, которым управляют командами в привычном синтаксисе. Конфигурация пишется в CLI, сохраняется в файл и применяется к системе: адреса, маршруты, NAT, DHCP, NTP, OSPF, VLAN, GRE-туннели.

DaemonДемон

The background process necorouter daemon holds the configuration. While it is not running, the router does not work and uses no resources.Фоновый процесс necorouter daemon держит конфигурацию. Пока он не запущен, роутер не работает и ресурсы не тратит.

Thin clientЛёгкий клиент

The login shell necorouter shell connects to the daemon over a socket and passes commands on. The daemon decides the rights by uid.Оболочка входа necorouter shell подключается к демону по сокету и передаёт команды. Права определяет демон по uid.

Lazy servicesЛенивые службы

dnsmasq (DHCP), FRR (OSPF), chrony (NTP) and nftables (NAT) start only when the configuration contains the matching setting, and stop when it is removed.dnsmasq (DHCP), FRR (OSPF), chrony (NTP) и nftables (NAT) запускаются, только когда в конфигурации есть соответствующая настройка, и останавливаются, когда она удалена.

What happens when you enter a commandЧто происходит при вводе команды

The command is parsed against the mode's tree, checked, applied to the in-memory configuration, and then the services are brought into line (reconcile). If the command did not change the configuration, nothing is restarted. The write commands save it to startup-config, and at the next daemon start it is replayed back.Команда разбирается по дереву режима, проверяется, применяется к конфигурации в памяти, а затем службы приводятся в соответствие (reconcile). Если команда не изменила конфигурацию, ничего не перезапускается. Команды write сохраняют её в startup-config, и при следующем старте демона она проигрывается обратно.

System requirementsСистемные требования

An estimate, not measured under real load.Оценка, не замерено на реальной нагрузке.

MinimumМинимумRecommendedРекомендуется
ArchitectureАрхитектураx86_64 or aarch64x86_64 или aarch64sameто же
CPU1 core / 2 threads1 ядро / 2 потока2 vCPU
RAM256 MB256 МБ512 MB–1 GB512 МБ–1 ГБ
DiskДиск~300 MB free~300 МБ свободно~1 GB~1 ГБ
PackagesПакетыopenssh, nftables, dnsmasq, frr, chrony, tzdata, iputils, traceroute, shadowsameто же
  • Alpine: a musl system on x86_64 or aarch64; armv7 and i386 are not supported. FRR is the largest package; without OSPF it can be skipped.Alpine: musl-система на x86_64 или aarch64; armv7 и i386 не поддерживаются. FRR — самый большой пакет; без OSPF его можно не ставить.
  • Services (FRR, dnsmasq, chrony, nftables) start only when the configuration needs them.Службы (FRR, dnsmasq, chrony, nftables) запускаются только когда нужны конфигурации.
  • Users: 1–5 accounts put no load on the system; dozens cause no noticeable load; hundreds work, but applying the configuration reads /etc/passwd for every user.Пользователи: 1–5 учёток не нагружают систему; десятки — без заметной нагрузки; сотни работают, но применение конфигурации читает /etc/passwd для каждого пользователя.
  • The daemon accepts up to 64 simultaneous sessions.Одновременных сессий демон принимает до 64.

InstallationУстановка

Root rights are required. By default the installer downloads the latest stable GitHub release, checks it against SHA256SUMS, installs the dependencies itself where possible (openssh-server, nftables, dnsmasq, frr, chrony), and enables the service. It installs required packages but does not upgrade the whole operating system.Нужны root-права. По умолчанию установщик скачивает последний стабильный релиз с GitHub, проверяет его по SHA256SUMS, по возможности ставит зависимости (openssh-server, nftables, dnsmasq, frr, chrony) и включает службу. Он ставит нужные пакеты, но не обновляет всю ОС.

make all                                   # builds dist/necorouter-x86_64 and dist/necorouter-aarch64
sh packaging/install.sh --bin dist/necorouter-x86_64
systemctl enable --now necorouter        # Alpine: rc-update add necorouter default && rc-service necorouter start

sh packaging/install.sh --uninstall      # removes the router and its accounts, restores /etc/issue and sshd_config

What the installer doesЧто делает установщик

  • By default downloads the latest stable GitHub release and verifies its SHA256 checksum. Downloads use curl, wget, BusyBox wget or Python 3; if none is available, curl is installed through the package manager when dependencies are enabled.По умолчанию скачивает последний стабильный релиз GitHub и проверяет SHA256. Для загрузки используются curl, wget, wget из BusyBox или Python 3; если их нет, curl устанавливается пакетным менеджером, когда установка зависимостей включена.
  • The checksum file comes from the same release, so it detects transfer damage but is not a separate release signature. Package signatures are checked according to the system package manager's repository configuration.Файл контрольных сумм скачивается из того же релиза: он выявляет повреждение загрузки, но не является отдельной подписью релиза. Подписи пакетов проверяются согласно настройкам репозиториев системного пакетного менеджера.
  • Selects a binary from --bin, --local, or the default release download; builds from source only with --build.Выбирает бинарник через --bin, --local или загрузку релиза по умолчанию; сборка из исходников выполняется только с --build.
  • Detects the distribution and the init system (systemd or OpenRC) and installs the service.Определяет дистрибутив и систему инициализации (systemd или OpenRC) и ставит службу.
  • Creates the required links: /usr/local/bin/necorouter, /usr/bin/necorouter (for sudo's secure_path), necorouter-shell.Кладёт необходимые ссылки: /usr/local/bin/necorouter, /usr/bin/necorouter (для secure_path sudo), necorouter-shell.
  • Registers the necorouter-shell shell in /etc/shells and a restriction block in sshd_config (accounts in the necorouter group are denied port forwarding, agent forwarding and X11).Регистрирует оболочку necorouter-shell в /etc/shells и блок ограничений в sshd_config (аккаунтам группы necorouter запрещены проброс портов, агента и X11).
  • Creates the banner /etc/necorouter/banner and writes it to /etc/issue for the console.Создаёт баннер /etc/necorouter/banner и записывает его в /etc/issue для консоли.
  • On Alpine it generates the sshd host keys and enables sshd at boot.На Alpine генерирует host-ключи sshd и включает sshd в автозагрузку.

Login and rolesВход и роли

Login is handled by plain Linux: login on the console and sshd over ssh. The password is checked by PAM. Rights inside the CLI come from the role in the daemon's configuration.Вход выполняет штатный Linux: login на консоли и sshd по ssh. Пароль проверяет PAM. Права внутри CLI задаёт роль из конфигурации демона.

admin

Full access: user and privileged modes, configuration. The built-in admin account is created on the first start (password admin, change it with passwd admin).Полный доступ: пользовательский и привилегированный режим, конфигурация. Встроенная учётная запись admin создаётся при первом запуске (пароль admin, сменить: passwd admin).

noc

User mode only: viewing, ping, traceroute.Только пользовательский режим: просмотр, ping, traceroute.

helpdesk

Same as noc. The role has no rights of its own yet.То же, что noc. Отдельных прав у роли пока нет.

A user without a role is considered untrusted: enable is denied (least privilege). show running-config and show startup-config (which contain OSPF keys) are shown only to the admin role.Пользователь без роли считается недоверенным: enable ему запрещён (least privilege). show running-config и show startup-config (в них ключи OSPF) показываются только роли admin.

AccountsУчётные записи

  • username NAME in the configuration creates a Linux account with the router's shell and the necorouter group.username NAME в конфигурации создаёт Linux-аккаунт с оболочкой роутера и группой necorouter.
  • The password is set with password PASS in the CLI (it changes the Linux account's password) or with passwd NAME in the system. The configuration holds no passwords.Пароль задаётся через password PASS в CLI (меняет пароль Linux-аккаунта) или командой passwd NAME в системе. В конфигурации паролей нет.
  • Removing username from the configuration deletes the account the router created. Accounts that existed before the router are not deleted; they only get its shell.Удаление username из конфигурации удаляет созданный роутером аккаунт. Аккаунты, существовавшие до роутера, не удаляются, а только получают его оболочку.
  • The router does not touch root and system accounts (uid < 1000): root keeps its normal shell and emergency login.root и системные аккаунты (uid < 1000) роутер не трогает: root сохраняет обычную оболочку и аварийный вход.

Pre-login bannerБаннер до входа

The banner from /etc/necorouter/banner is visible before login: on the console through /etc/issue (visible before root logs in too), over ssh through the Banner directive. The previous /etc/issue is saved and restored on removal. Your own ASCII art: put it in /etc/necorouter/banner and run necorouter issue sync.Баннер из /etc/necorouter/banner виден до логина: на консоли через /etc/issue (его видно и перед входом root), по ssh через директиву Banner. Прежний /etc/issue сохраняется и возвращается при удалении. Свой ASCII-арт: поместите его в /etc/necorouter/banner и выполните necorouter issue sync.

CLI modesРежимы CLI

The mode is shown in the prompt. Every mode is left with exit; to return to privileged mode use end or Ctrl-Z.Режим показан в приглашении. Из каждого режима выход — exit, возврат в привилегированный — end или Ctrl-Z.

router>

User modeПользовательский режим

Available to all roles. Viewing, ping, traceroute, terminal.Доступен всем ролям. Просмотр, ping, traceroute, терминал.

router#

Privileged modeПривилегированный режим

Admin role only (the enable command). Saving, restarting services, entering config.Только роль admin (команда enable). Сохранение, перезапуск служб, вход в config.

router(config)#

ConfigurationКонфигурация

configure terminal. Global settings: name, DNS, pools, users, ports, interfaces, OSPF, DHCP.configure terminal. Глобальные настройки: имя, DNS, пулы, пользователи, порты, интерфейсы, OSPF, DHCP.

router(config-if)#

InterfaceИнтерфейс

interface NAME. Addresses, tunnels, OSPF on the interface, NAT roles, connection to a port.interface NAME. Адреса, туннели, OSPF на интерфейсе, NAT-роли, подключение к порту.

router(config-port)#

PortПорт

port teN. Service instances (logical subinterfaces) and the port description.port teN. Сервис-инстансы (логические подинтерфейсы) и описание порта.

router(config-si)#

Service instanceСервис-инстанс

service-instance teN/NAME. Encapsulation: untagged or dot1q VLAN.service-instance teN/NAME. Инкапсуляция: untagged или dot1q VLAN.

router(config-router)#

OSPF

router ospf ID. OSPF networks and areas.router ospf ID. Сети и области OSPF.

router(config-dhcp)#

DHCP serverDHCP-сервер

dhcp-server N. Pool, network, gateway, DNS for clients.dhcp-server N. Пул, сеть, шлюз, DNS для клиентов.

router(config-user)#

UserПользователь

username NAME. The account's role and password.username NAME. Роль и пароль учётной записи.

FeaturesВозможности

AddressingАдресация

  • Interface addresses as A.B.C.D/M or A.B.C.D MASK; repeating the command replaces the address.Адреса интерфейсов в форме A.B.C.D/M или A.B.C.D МАСКА; повторная команда заменяет адрес.
  • Static routes: ip route PREFIX NEXTHOP.Статические маршруты: ip route PREFIX NEXTHOP.
  • DNS servers and domain name: ip name-server, ip domain-name.DNS-серверы и доменное имя: ip name-server, ip domain-name.
  • Address pools: ip pool NAME RANGE[,RANGE...] (each range is A.B.C.D[-A.B.C.D]).Пулы адресов: ip pool NAME ДИАПАЗОН[,ДИАПАЗОН...] (каждый: A.B.C.D[-A.B.C.D]).

Ports and VLANsПорты и VLAN

  • port teN → mapping to a Linux network card (ports.map, auto-detection by MAC).port teN → сопоставление с сетевой картой Linux (ports.map, автообнаружение по MAC).
  • Service instances: service-instance teN/NAME, encapsulation untagged or dot1q VID.Сервис-инстансы: service-instance teN/NAME, encapsulation untagged или dot1q VID.
  • Connecting an interface to an instance: connect port teN service-instance teN/NAME.Подключение интерфейса к инстансу: connect port teN service-instance teN/NAME.
  • GRE tunnels: interface tunnel.N → ip tunnel SRC DST mode gre.Туннели GRE: interface tunnel.N → ip tunnel SRC DST mode gre.

NAT

  • Pool of inside addresses: ip nat pool NAME RANGE[,RANGE...].Пул внутренних адресов: ip nat pool NAME RANGE[,RANGE...].
  • Dynamic NAT: ip nat source dynamic inside-to-outside pool P overload (A.B.C.D | interface NAME).Динамический NAT: ip nat source dynamic inside-to-outside pool P overload (A.B.C.D | interface NAME).
  • Static NAT is in the interface command tree (ip nat ...).Статический NAT — в дереве команд интерфейса (ip nat ...).

OSPF routingМаршрутизация OSPF

  • router ospf ID; network PREFIX area N or network ADDR WILDCARD area N.router ospf ID; network PREFIX area N или network ADDR WILDCARD area N.
  • Authentication on the interface (simple or message-digest).Аутентификация на интерфейсе (простая или message-digest).
  • Checking: show ip ospf neighbor, show ip route, show services.Проверка: show ip ospf neighbor, show ip route, show services.
  • The zebra and ospfd daemons (FRR) start only when the configuration contains OSPF.Демоны zebra и ospfd (FRR) поднимаются только при наличии OSPF в конфигурации.

DHCP

  • dhcp-server N: network, pool, gateway, DNS.dhcp-server N: сеть, пул, шлюз, DNS.
  • Dnsmasq starts only if at least one DHCP server is configured.Dnsmasq запускается только если настроен хотя бы один DHCP-сервер.
  • Leases: show dhcp-server clients.Аренды: show dhcp-server clients.

NTP

  • ntp server ADDRESS, ntp timezone utc+3 (or Region/City).ntp server ADDRESS, ntp timezone utc+3 (или Регион/Город).
  • chrony starts only when there is an ntp server.chrony запускается только при наличии ntp server.
  • State: show ntp status.Состояние: show ntp status.

Users and accessПользователи и доступ

  • username NAME; role admin | noc | helpdesk.
  • admin: full access (enable, config). noc and helpdesk: user mode only.admin: полный доступ (enable, config). noc и helpdesk: только пользовательский режим.
  • Passwords live only in Linux accounts (passwd, or password in the CLI). The configuration holds no passwords.Пароли — только в Linux-аккаунтах (passwd, либо password в CLI). В конфигурации паролей нет.
  • Accounts are created by the router with the necorouter-shell shell; root and system accounts are not touched.Учётные записи создаются роутером с оболочкой necorouter-shell; root и системные аккаунты не трогаются.

Saving and viewingСохранение и просмотр

  • write (or copy running-config startup-config) saves startup-config.write (или copy running-config startup-config) сохраняет startup-config.
  • show running-config, show startup-config, show version, show clock, show hostname, show arp.
  • Paged output: a long show opens in a pager; terminal length N sets lines per page, 0 turns it off.Постраничный вывод: длинный show открывается в пейджере; terminal length N задаёт строки на страницу, 0 — выключить.

CLI conveniencesУдобство CLI

  • ? — hint anywhere; Tab — completion; arrows — history.? — подсказка в любой точке; Tab — дополнение; стрелки — история.
  • Ctrl-C interrupts ping and traceroute without leaving the CLI.Ctrl-C прерывает ping и traceroute, не выходя из CLI.
  • clear — clear the screen; mge [TEXT] — an animated steam train with lettering on the tender.clear — очистка экрана; mge [TEXT] — анимированный паровозик с надписью на тендере.
  • Abbreviated commands: sh run, sh ip int br.Сокращения команд: sh run, sh ip int br.

Bufferbloat controlУстранение bufferbloat

For WAN bandwidth limits, create a service-policy, set bandwidth, then apply it to the WAN service-instance with direction in or out. The Linux backend uses CAKE; inbound traffic is redirected through IFB. Begin around 90–95% of measured sustained link speed. The kernel must provide sch_cake; iproute2 provides ip and tc.Задайте ограничения скорости WAN: создайте service-policy, задайте bandwidth, затем примените политику к WAN service-instance в направлении in или out. Linux backend использует CAKE; входящий трафик перенаправляется через IFB. Начните примерно с 90–95% устойчивой измеренной скорости. Ядро должно предоставлять sch_cake; iproute2 содержит команды ip и tc.

configure terminal
service-policy WAN-DOWN
 bandwidth mbps 95
exit
service-policy WAN-UP
 bandwidth mbps 9
exit
port te0
 service-instance wan
  encapsulation untagged
  connect ip interface wan
  service-policy WAN-DOWN in
  service-policy WAN-UP out
end
write
show service-policy

Configuration exampleПример конфигурации

enable
configure terminal
hostname example-1
ip domain-name example.local
username net_admin
 password P@ssw0rd
 role admin
 exit
port te1
 service-instance te1/isp
  encapsulation untagged
  exit
 exit
interface isp
 ip address 172.16.1.2/28
 connect port te1 service-instance te1/isp
 exit
ip route 0.0.0.0/0 172.16.1.1
ip nat pool server-pool 192.168.100.1-192.168.100.30
ip nat source dynamic inside-to-outside pool server-pool overload 172.16.1.2
router ospf 1
 network 10.10.10.0/30 area 0
 exit
ntp server 172.16.1.1
ntp timezone utc+3
end
write

A complete example configuration is in the README.Полный пример конфигурации — в README.

Command referenceСправочник команд

The tree is built from the same command table as the CLI itself, so it matches what ? shows. Pick a mode, expand the branches or use search. The "copy" button takes the command path with argument placeholders. Command descriptions come from the program and are in English.Дерево построено из той же таблицы команд, что и сам CLI, поэтому совпадает с тем, что показывает ?. Выберите режим, раскройте ветки или воспользуйтесь поиском. Кнопка «копировать» берёт путь команды с шаблонами аргументов. Описания команд берутся из программы и приведены на английском.

Keys and pagerКлавиши и пейджер

Line editorРедактор строки

KeyКлавишаActionДействие
?hint for the current inputподсказка по текущему вводу
Tabcomplete the command; twice — the list of optionsдополнение команды; дважды — список вариантов
↑ / ↓command historyистория команд
← / →, Home, Endmove the cursorперемещение курсора
Ctrl-A / Ctrl-Estart / end of lineначало / конец строки
Ctrl-U / Ctrl-Kerase to the start / to the endстереть до начала / до конца
Ctrl-Werase a wordстереть слово
Ctrl-Lclear the screen and redraw the lineочистить экран и перерисовать строку
Ctrl-Cinterrupt a command (ping, mge); on the line — cancel the inputпрервать команду (ping, mge); в строке — отменить ввод
Ctrl-Zsame as end: return to privileged modeто же, что end: выход в привилегированный режим

Paged outputПостраничный вывод

Long output of show commands opens page by page (like less) when the terminal is small enough. Short output is printed at once. Through ssh host "command" and in scripts the pager is not used.Длинный вывод команд show открывается постранично (как less), если терминал достаточно мал. Короткий вывод печатается сразу. Через ssh host "команда" и в скриптах пейджер не используется.

KeyКлавишаActionДействие
spaceпробел, f, PgDnpage downстраница вниз
Enter, j, ↓line downстрока вниз
b, PgUppage upстраница вверх
k, ↑line upстрока вверх
g / Gstart / endначало / конец
d / uhalf a page down / upполстраницы вниз / вверх
/text, n/текст, nsearch forward, next matchпоиск вперёд, следующее совпадение
q, Q, Ctrl-C, Escquitвыход

The terminal length N command sets the number of lines per page, terminal length 0 turns the pager off.Команда terminal length N задаёт число строк на страницу, terminal length 0 отключает пейджер.

Configuration and filesКонфигурация и файлы

PathПутьPurposeНазначение
/etc/necorouter/startup-configsaved configuration (mode 0600, no passwords)сохранённая конфигурация (права 0600, паролей нет)
/etc/necorouter/crash-configcopy of running-config after an abnormal termination (mode 0600)копия running-config после аварийного завершения (права 0600)
/etc/necorouter/configs/NAME.confnamed files (write file NAME)именованные файлы (write file NAME)
/etc/necorouter/startup-history/, autosave-history/history of copies (feature config-history)история копий (фича config-history)
/var/lib/necorouter/config.journaloperations journal (feature config-journal)журнал операций (фича config-journal)
/var/lib/necorouter/running.confrunning-config snapshot for the crash copy; running.lock is the run markerснимок running-config для аварийной копии; running.lock — метка работы
/etc/necorouter/bannerpre-login banner (ssh and /etc/issue)баннер до входа (ssh и /etc/issue)
/etc/necorouter/ports.mapteN ↔ network cards mapping; updated automatically by MACсоответствие teN ↔ сетевые карты; автообновляется по MAC
/var/log/necorouter/necorouter.logevent log and command audit (show log)журнал событий и аудит команд (show log)
/run/necorouter/ctl.sockdaemon socketсокет демона
/var/lib/necorouter/state.jsonwhat the router created: the only thing it deletesчто создал роутер: только это он и удаляет
/var/lib/necorouter/issue/backup of the previous /etc/issueрезервная копия прежнего /etc/issue
/usr/local/bin/necorouterthe binary; required links: necorouter-shell, /usr/bin/necorouterбинарник; необходимые ссылки: necorouter-shell, /usr/bin/necorouter

SavingСохранение

  • An unsaved configuration lives in the daemon's memory and is already applied to the system. Logging out does not roll it back, and every session sees it. Save it with write; otherwise a daemon restart returns the configuration to startup-config.Несохранённая конфигурация живёт в памяти демона и уже применена к системе. Выход из учётки её не откатывает, и её видят все сессии. Сохраните командой write; иначе при перезапуске демона конфигурация вернётся к startup-config.
  • write or copy running-config startup-config — save the current configuration.write или copy running-config startup-config — сохранить текущую конфигурацию.
  • show running-config — what is in effect now; show startup-config — what is saved.show running-config — то, что действует сейчас; show startup-config — то, что сохранено.
  • Crash copy. If the daemon terminated abnormally, at start running-config from the last snapshot is saved to crash-config and startup-config is left unchanged. The admin sees a warning at login; read it with show config file crash.Аварийная копия. Если демон завершился не штатно, при старте running-config из последнего снимка сохраняется в crash-config, а startup-config не меняется. Админ видит предупреждение при входе; читать: show config file crash.
  • Baseline file commands: write file NAME, write terminal, show files config, show config file NAME, copy file NAME startup-config (with a warning).Ванильные команды файлов: write file NAME, write terminal, show files config, show config file NAME, copy file NAME startup-config (с предупреждением).
  • startup-config archives: copy startup-config storage [description TEXT], show backups, delete backup storage NAME|*; files /etc/necorouter/backups/startup_backup_NAME_YYYY-MM-DD_hh-mm-ss.tar.gz. Ctrl-D on an empty line works as exit: it leaves a mode one level up, and the shell only from the base level.Архивы startup-config: copy startup-config storage [description TEXT], show backups, delete backup storage NAME|*; файлы /etc/necorouter/backups/startup_backup_ИМЯ_ГГГГ-ММ-ДД_чч-мм-сс.tar.gz. Ctrl-D на пустой строке работает как exit: из режима на уровень выше, из оболочки — только с базового уровня.
  • Copying over SSH (the system scp/sftp): copy startup-config scp|sftp USER@HOST[:PATH] — send a startup-config archive; copy scp|sftp backup NAME USER@HOST[:PATH] — an archive from storage; copy scp|sftp startup-config USER@HOST:FILE — receive an archive or a plain configuration file (checking, warning, confirmation). An empty path or a path ending in / is a directory (the home directory by default). The password is asked without echo (empty input means only root's keys from ~/.ssh), passed through SSH_ASKPASS and not stored. A new host key is remembered in /var/lib/necorouter/known_hosts, a changed one is refused.Копирование по SSH (системные scp/sftp): copy startup-config scp|sftp USER@HOST[:ПУТЬ] — отправить архив startup-config; copy scp|sftp backup ИМЯ USER@HOST[:ПУТЬ] — архив из хранилища; copy scp|sftp startup-config USER@HOST:ФАЙЛ — принять архив или обычный файл конфигурации (проверка, предупреждение, подтверждение). Пустой путь или путь на / — каталог (по умолчанию домашний). Пароль спрашивается без эха (пустой ввод — только ключи root из ~/.ssh), передаётся через SSH_ASKPASS и не хранится. Новый ключ хоста запоминается в /var/lib/necorouter/known_hosts, изменившийся — отказ.
  • Security profiles: security-profile N → rule 0 permit|deny PROTO SRC DST [eq|gt|lt|range PORT], no rule N; security N / security none / no security; show security-profile. The default profile is on by default and closes SSH, Telnet and SNMP on the router's interfaces; remove it with no security default. Established connections are not dropped, network cards outside the router configuration are not affected. A bound profile cannot be changed — run no security first. Implemented in nftables (table ip necorouter_sec).Профили безопасности: security-profile N → rule 0 permit|deny PROTO SRC DST [eq|gt|lt|range PORT], no rule N; security N / security none / no security; show security-profile. Профиль default включён по умолчанию и закрывает SSH, Telnet и SNMP на интерфейсах роутера; снять: no security default. Установленные соединения не обрываются, сетевые карты вне конфигурации роутера не затрагиваются. Привязанный профиль менять нельзя — сначала no security. Реализовано в nftables (table ip necorouter_sec).
  • enable password: enable password PASS or enable secret PASS (up to 8 Latin letters and digits, starting with a letter); enable asks for the password without echo, no enable password removes it. Only a hash is stored in the configuration (enable password 8 HASH, a custom format, not DES). The local root is not asked for a password.Пароль enable: enable password PASS или enable secret PASS (до 8 латинских букв и цифр, с буквы); enable спрашивает пароль без эха, no enable password снимает. В конфигурации хранится только хеш (enable password 8 ХЕШ, свой формат, не DES). Локальный root пароль не спрашивается.
  • Autosave is off by default. Enable it with autosave interval MIN through feature config-history (5 minutes by default, only when there are changes, into the autosave history); no autosave turns it off. feature ssh-copy — copying over scp/sftp (non-baseline syntax); show features — the state of the features. service password-encryption is a baseline command; passwords are stored as hashes anyway.Автосейв выключен по умолчанию. Включается командой autosave interval MIN через feature config-history (по умолчанию 5 минут, только при изменениях, в историю автокопий); no autosave выключает его. feature ssh-copy — копирование по scp/sftp (неванильный синтаксис); show features — состояние фич. service password-encryption — ванильная команда, пароли и так хранятся хешами.
  • Extensions are hidden (not shown by ?) until they are enabled with the feature command in configuration mode: feature config-history — startup-config history (startup-history keep N), running-config autosaves (autosave interval MIN [keep N], no autosave), write description TEXT, show config history; feature config-manage — copy between files and into running-config (checking, a warning, protection against losing access), delete config file NAME, show config diff A B; feature config-journal — show config journal [N]. no feature ... turns a function off; settings and files remain. keep: 1–64, 10 by default. Priority: running → crash → startup → history → files; the history is never loaded by itself.Расширения скрыты (не видны в ?), пока не включены командой feature в режиме конфигурации: feature config-history — история startup-config (startup-history keep N), автокопии running-config (autosave interval MIN [keep N], no autosave), write description TEXT, show config history; feature config-manage — copy между файлами и в running-config (проверка, предупреждение, защита от потери доступа), delete config file NAME, show config diff A B; feature config-journal — show config journal [N]. no feature ... отключает функцию, настройки и файлы остаются. keep: 1–64, по умолчанию 10. Приоритет: running → crash → startup → история → файлы; история сама не загружается.
  • An old password line in startup-config is applied once, when the account is created, and is not written again.Старая строка password в startup-config применяется один раз, при создании аккаунта, и больше не записывается.

AdvantagesПреимущества

  • Runs on ordinary Linux: no device-specific OS is needed; routing and services are proven daemons (FRR, dnsmasq, chrony, nftables, strongSwan).Работает на обычном Linux: не нужна собственная ОС устройства; маршрутизация и сервисы — проверенные демоны (FRR, dnsmasq, chrony, nftables, strongSwan).
  • teN ports are mapped to network cards through ports.map, so interfaces can be assigned to fit a lab setup.Порты teN сопоставляются сетевым картам через ports.map, интерфейсы можно назначать под стенд.
  • Login and passwords are ordinary Linux accounts; there is no separate user database.Вход и пароли — обычные Linux-аккаунты, отдельной базы пользователей нет.
  • The commands cover what is needed for practice and exams; anything non-standard is enabled explicitly through feature.Команды покрывают нужное для практики и экзаменов; нестандартное включается явно через feature.
  • The event log and the audit of user actions are kept by the router itself, independent of journald or syslog, and work the same on systemd and OpenRC.Журнал событий и аудит действий пользователей ведутся самим роутером, не зависят от journald или syslog и одинаково работают на systemd и OpenRC.

LimitationsОграничения

What has already been checked automatically and what remains to be checked on the target systems.Что уже проверено автоматически и что остаётся проверить на целевых системах.

  • Real FRR (OSPF) on Alpine and RedOS: the tests use daemon stubs.Реальный FRR (OSPF) на Alpine и RedOS: в тестах используются заглушки демонов.
  • Real getty/login on a tty and sshd with a Match block on the target systems.Реальный getty/login на tty и sshd с блоком Match на целевых системах.
  • useradd/userdel and chpasswd on Alpine (busybox) and CentOS; the RedOS PAM stack.useradd/userdel и chpasswd на Alpine (busybox) и CentOS; PAM-стек RedOS.
  • Installing packages from repositories (openssh-server, nftables, dnsmasq, frr, chrony).Установка пакетов из репозиториев (openssh-server, nftables, dnsmasq, frr, chrony).
  • Kernel: VLAN, GRE and DHCP on real hardware (the sandbox has only virtual interfaces).Ядро: VLAN, GRE и DHCP на реальном оборудовании (в песочнице только виртуальные интерфейсы).
  • The syntax was checked against the user manual and the tests; before the exam, check individual commands against the documentation of your lab setup.Синтаксис сверяется с руководством пользователя и тестами; перед сдачей проверяйте отдельные команды по документации вашего стенда.

TroubleshootingУстранение неполадок

SymptomСимптомWhat to doЧто делать
"the router is not running"The daemon is not running. As root: systemctl start necorouter (Alpine: rc-service necorouter start).Демон не запущен. Root: systemctl start necorouter (Alpine: rc-service necorouter start).
"no access to the router socket"The user is not in the router group and is not root. Add them to the necorouter group or log in as the administrator.Пользователь не входит в группу роутера или не root. Добавьте в группу necorouter или войдите под администратором.
"% OSPF is not running: … frrvty"Fixed: the daemons run as the service user frr, or root joins the frrvty group. Check show services and show ip ospf.Исправлено: демоны запускаются от служебного пользователя frr или root входит в группу frrvty. Проверьте show services и show ip ospf.
The banner is not visible on the consoleБаннер не виден на консолиRun necorouter issue sync (as root). The previous /etc/issue is kept in /var/lib/necorouter/issue.Выполните necorouter issue sync (от root). Прежний /etc/issue хранится в /var/lib/necorouter/issue.
"has no password yet"The account has no password: passwd NAME (as root) or password PASS in the CLI as admin.Аккаунту не задан пароль: passwd NAME (от root) или password PASS в CLI под admin.
The admin password is forgottenПароль admin забытLog in as root and run passwd admin.Войдите как root и выполните passwd admin.
sshd refuses to start after installationsshd отказывается запускаться после установкиThe "Match Group necorouter" block is rolled back automatically if sshd -t does not accept it. Run sshd -t by hand to check.Блок «Match Group necorouter» откатывается автоматически, если sshd -t его не принимает. Проверьте sshd -t вручную.

TestingТестирование

The full set is run with make test (root and unshare are required). Running the interactive tests from a namespace without a network: unshare -n -u -m python3 test/pty_cli.py.Полный набор запускается командой make test (нужны root и unshare). Запуск интерактивных тестов из пространства имён без сети: unshare -n -u -m python3 test/pty_cli.py.

SuiteНаборWhat it checksЧто проверяет
go test ./...unit tests of the CLI, services, pager, users, banner, FRR startюнит-тесты CLI, служб, пейджера, пользователей, баннера, FRR-запуска
test/pty_cli.pyinteractive CLI through a PTY: Tab, ?, history, Ctrl-Z, exitинтерактивный CLI через PTY: Tab, ?, история, Ctrl-Z, выход
test/pty_ping.pyping, Ctrl-C interruption, rolesping, прерывание Ctrl-C, роли
test/pty_mge.pythe mge animation, lettering, interruptionанимация mge, надпись, прерывание
test/pty_pager.pypaged output, terminal length, searchпостраничный вывод, terminal length, поиск
test/e2e.sh, persist.sh, examples.shfull cycle on virtual interfaces, restart, example configurationsполный цикл на виртуальных интерфейсах, перезапуск, примеры конфигураций
test/install_alpine.sh, install_find.shthe installer under sh/dash and busybox ash (Alpine emulation)установщик под sh/dash и busybox ash (эмуляция Alpine)