summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--git-shell + cgit.md163
1 files changed, 85 insertions, 78 deletions
diff --git a/git-shell + cgit.md b/git-shell + cgit.md
index 89b9b75..b84b6c2 100644
--- a/git-shell + cgit.md
+++ b/git-shell + cgit.md
@@ -1,110 +1,117 @@
-Полная инструкция: простой Git-сервер на OpenBSD (git-shell + cgit)
+Full guide: lightweight Git server on OpenBSD (git-shell + cgit)
-Эта инструкция описывает настройку лёгкого, безопасного и полностью рабочего Git-сервера на OpenBSD. После её выполнения вы получите:
+This guide describes how to set up a light, secure, fully working Git server on OpenBSD. When you finish you will have:
- SSH-доступ к репозиториям для push/pull (пользователь git, аутентификация только по ключам).
+ SSH access to your repositories for push/pull (dedicated user, key‑only authentication).
- Веб-интерфейс cgit для просмотра репозиториев на поддомене git.drohiczyn-poleski.com.
+ A cgit web interface for browsing repositories at https://git.yourdomain.com.
- Автоматически обновляемый SSL-сертификат Let's Encrypt.
+ An automatically renewed Let’s Encrypt SSL certificate.
-Все шаги выполняются на сервере OpenBSD через SSH (желательно через VPN, так как прямой SSH заблокирован правилами pf).
-0. Предварительные условия
+All steps are performed on the OpenBSD server via SSH (preferably over a VPN, if direct SSH is blocked by your firewall rules).
+0. Prerequisites
- У вас есть сервер OpenBSD с настроенным httpd, pf, WireGuard (адрес VPN-сети 10.77.77.1).
+ You have an OpenBSD server with a working httpd, pf, and a VPN tunnel (for example, the VPN network is 10.0.0.1 – adjust as needed).
- Уже работают сайты на доменах drohiczyn-poleski.com и astro.drohiczyn-poleski.com (их конфигурация в /etc/httpd.conf сохранена).
+ Other websites may already be running on your server; their configuration in /etc/httpd.conf must be preserved.
- DNS-запись git.drohiczyn-poleski.com типа A указывает на ваш IP (199.247.31.17) и отключено проксирование Netlify (если используется Netlify, значок должен быть серым, не оранжевым).
+ A DNS A record for git.yourdomain.com points to your server’s public IP address (e.g., 203.0.113.10) and proxy/CDN (like Cloudflare’s orange cloud) is turned off (grey cloud / DNS‑only).
-1. Установка Git и создание пользователя git
+ You have root access or can execute doas.
+
+1. Install Git and create the dedicated user
bash
doas pkg_add git
-Создайте пользователя git с домашней директорией /home/git:
+Create a dedicated user that will own the repositories. In this guide we use the username gituser – you may choose any name.
bash
doas adduser
-Заполните интерактивно:
+Answer the prompts as follows:
- username: git
+ username : gituser
- full name: Git Server
+ full name : Git Server
- shell: ksh (позже сменим на git-shell)
+ shell : ksh (we will change it to git-shell later)
- home: /home/git
+ home : /home/gituser
- Пароль: оставьте пустым (только вход по ключам).
+ password : leave empty (only key‑based login will be used)
-Настройте домашнюю директорию:
+Set up the home directory:
bash
-doas mkdir -p /home/git/.ssh
-doas chmod 700 /home/git/.ssh
-doas touch /home/git/.ssh/authorized_keys
-doas chmod 600 /home/git/.ssh/authorized_keys
-doas chown -R git:git /home/git
+doas mkdir -p /home/gituser/.ssh
+doas chmod 700 /home/gituser/.ssh
+doas touch /home/gituser/.ssh/authorized_keys
+doas chmod 600 /home/gituser/.ssh/authorized_keys
+doas chown -R gituser:gituser /home/gituser
+
+2. Configure SSH keys for the administrator
+
+You need an SSH key pair that will be used to push to and manage the repositories.
-2. Настройка SSH-ключей администратора
+ If you already have a key, copy its public part (e.g. ~/.ssh/id_ed25519.pub) to the server.
+
+ If not, generate one on your local machine:
-Вам нужен SSH-ключ, который будет использоваться для управления репозиториями. Если у вас уже есть ключ (например, ~/.ssh/id_ed25519.pub), скопируйте его на сервер. Если нет — создайте на локальной машине:
bash
ssh-keygen -t ed25519 -C "git admin key"
-Скопируйте публичный ключ на сервер (предположим, что файл ключа лежит в /tmp/my_git_key.pub на сервере). Добавьте ключ в /home/git/.ssh/authorized_keys с ограничениями:
+Assume the public key file is now available on the server at, for example, /tmp/your_key.pub. Add it to the gituser account with the necessary restrictions:
bash
-echo 'no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ' | doas tee /home/git/.ssh/authorized_keys
-doas cat /tmp/my_git_key.pub | doas tee -a /home/git/.ssh/authorized_keys
-doas chown git:git /home/git/.ssh/authorized_keys
-doas chmod 600 /home/git/.ssh/authorized_keys
+echo 'no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ' | doas tee /home/gituser/.ssh/authorized_keys
+doas cat /tmp/your_key.pub | doas tee -a /home/gituser/.ssh/authorized_keys
+doas chown gituser:gituser /home/gituser/.ssh/authorized_keys
+doas chmod 600 /home/gituser/.ssh/authorized_keys
-Измените оболочку пользователя git на git-shell, чтобы запретить интерактивный вход:
+Change the user’s shell to git-shell – this forbids interactive logins and only allows Git operations:
bash
-doas chpass -s git-shell git
+doas chpass -s git-shell gituser
-Проверьте подключение (с локальной машины):
+Test the connection from your local machine (adjust the IP or VPN address accordingly):
bash
-ssh git@10.77.77.1
+ssh gituser@10.0.0.1
-Вы должны увидеть сообщение об ошибке «PTY allocation request failed» (вход запрещён) без запроса пароля.
-3. Создание каталога для репозиториев
+You should see a message like “PTY allocation request failed” (login is blocked) with no password prompt.
+3. Create the repositories directory
bash
doas mkdir -p /var/www/git-repos
-doas chown -R git:www /var/www/git-repos
+doas chown -R gituser:www /var/www/git-repos
doas chmod 750 /var/www/git-repos
-Создайте симлинк, чтобы разработчики могли использовать короткий путь /git:
+Create a symbolic link so developers can use the short path /git:
bash
doas ln -sf /var/www/git-repos /git
-Инициализируйте тестовый репозиторий:
+Initialise a bare test repository:
bash
-doas -u git git init --bare /var/www/git-repos/project1.git
+doas -u gituser git init --bare /var/www/git-repos/my_project.git
-Теперь с локальной машины можно пушить в него:
+Now from your local machine you can push to it (replace the host address):
bash
-git remote add origin git@10.77.77.1:/git/project1.git
+git remote add origin gituser@10.0.0.1:/git/my_project.git
git push -u origin master
-4. Установка cgit и подготовка chroot
+4. Install cgit and prepare the chroot
-Установите пакет cgit:
+Install cgit:
bash
doas pkg_add cgit
-Создайте конфигурационный файл cgit:
+Create the cgit configuration file:
bash
doas mkdir -p /var/www/conf
@@ -120,68 +127,67 @@ snapshots=tar.gz
readme=:README.md
EOF
-Скопируйте статические файлы cgit (логотип и стили):
+Copy static assets (logo, CSS) – these are shipped with the cgit package:
bash
doas cp /var/www/cgit/cgit.png /var/www/cgit/ 2>/dev/null || true
doas cp /var/www/cgit/cgit.css /var/www/cgit/ 2>/dev/null || true
doas chown -R www:www /var/www/cgit
-Добавьте пользователя www в группу git, чтобы cgit мог читать репозитории:
+Add the web server user (www) to the gituser group so cgit can read the repositories:
bash
-doas usermod -G www,git www
+doas usermod -G www,gituser www
doas chmod 750 /var/www/git-repos
doas find /var/www/git-repos -type d -exec chmod 750 {} \;
doas find /var/www/git-repos -type f -exec chmod 640 {} \;
-Теперь самое важное: git должен работать внутри chroot (из-за особенностей httpd). Скопируйте git и все необходимые библиотеки в /var/www:
+Critical step – because httpd on OpenBSD runs cgit inside a chroot at /var/www, you must copy the git binary and all its dependencies into that chroot:
bash
doas mkdir -p /var/www/usr/local/bin /var/www/usr/local/libexec /var/www/usr/lib /var/www/usr/local/lib /var/www/dev
-# Копируем сам git
+# Copy git
doas cp /usr/local/bin/git /var/www/usr/local/bin/
-# Копируем системный загрузчик и библиотеки
+# Copy the dynamic linker and required libraries
doas cp /usr/libexec/ld.so /var/www/usr/libexec/
for lib in $(ldd /usr/local/bin/git | awk '/\/usr\// {print $NF}' | sort -u); do
doas mkdir -p "/var/www/$(dirname "$lib")"
doas cp "$lib" "/var/www/$lib"
done
-# Создаём /dev/null (необходим git даже для чтения)
+# Create /dev/null (needed even for reading operations)
doas mknod /var/www/dev/null c 2 2
doas chmod 666 /var/www/dev/null
-Проверьте, что git работает внутри chroot:
+Verify that git works inside the chroot:
bash
doas chroot /var/www /usr/local/bin/git --version
-Вы должны увидеть версию git (например, git version 2.51.0). Если команда не выполняется, свяжитесь со мной.
-5. Настройка блока httpd для поддомена cgit
-
-Откройте /etc/httpd.conf и добавьте в конец следующие блоки (внимание: без однострочных location, только многострочные):
-nginx
+You should see the git version number. If the command fails, double‑check the copied libraries.
+5. Configure httpd for the cgit subdomain
+Edit /etc/httpd.conf and add the following blocks at the end (be careful to use only multi‑line location stanzas, no single‑line shortcuts):
+text
-# --- git.drohiczyn-poleski.com (cgit) ---
-server "git.drohiczyn-poleski.com" {
+# --- git.yourdomain.com (cgit) ---
+server "git.yourdomain.com" {
listen on egress port 80
location * {
block return 301 "https://$HTTP_HOST$REQUEST_URI"
}
}
-server "git.drohiczyn-poleski.com" {
+server "git.yourdomain.com" {
listen on egress tls port 443
log style combined
log access "git-access.log"
tls {
- certificate "/etc/ssl/git.drohiczyn-poleski.com.fullchain.pem"
- key "/etc/ssl/private/git.drohiczyn-poleski.com.key"
+ certificate "/etc/ssl/git.yourdomain.com.fullchain.pem"
+ key "/etc/ssl/private/git.yourdomain.com.key"
}
location "/cgit.css" {
@@ -204,48 +210,49 @@ server "git.drohiczyn-poleski.com" {
}
}
-Проверьте синтаксис и перезагрузите httpd:
+Check the syntax and restart httpd:
bash
doas httpd -n
doas rcctl restart httpd
-6. SSL-сертификат для поддомена
+6. SSL certificate for the subdomain
-Добавьте в /etc/acme-client.conf секцию (если её ещё нет):
+Add a section to /etc/acme-client.conf (if it does not already exist):
text
-domain git.drohiczyn-poleski.com {
- domain key "/etc/ssl/private/git.drohiczyn-poleski.com.key"
- domain full chain certificate "/etc/ssl/git.drohiczyn-poleski.com.fullchain.pem"
+domain git.yourdomain.com {
+ domain key "/etc/ssl/private/git.yourdomain.com.key"
+ domain full chain certificate "/etc/ssl/git.yourdomain.com.fullchain.pem"
sign with letsencrypt
}
-Выпустите сертификат:
+Issue the certificate:
bash
-doas acme-client -v git.drohiczyn-poleski.com
+doas acme-client -v git.yourdomain.com
doas rcctl restart httpd
-Для автоматического обновления раз в неделю добавьте строки в /etc/weekly.local:
+To renew the certificate automatically every week, append these lines to /etc/weekly.local:
bash
-echo 'acme-client -v git.drohiczyn-poleski.com' | doas tee -a /etc/weekly.local
+echo 'acme-client -v git.yourdomain.com' | doas tee -a /etc/weekly.local
echo 'rcctl restart httpd' | doas tee -a /etc/weekly.local
-7. Запуск slowcgi и финальная проверка
+7. Start slowcgi and final verification
bash
doas rcctl enable slowcgi
doas rcctl start slowcgi
doas rcctl restart httpd
-Перейдите в браузере на https://git.drohiczyn-poleski.com. Вы должны увидеть страницу cgit со списком репозиториев (пока только project1.git).
+Open your browser and go to https://git.yourdomain.com. You should see the cgit page listing your repositories (initially only the test repository my_project.git).
-Если вместо списка репозиториев отображается "No repositories found", очистите кэш cgit:
+If you see “No repositories found”, clear the cgit cache:
bash
doas rm -rf /var/cache/cgit/*
doas rcctl restart slowcgi httpd
-Всё готово! Ваш личный Git-сервер полностью работоспособен.
+Everything is ready! Your personal Git server is now fully operational.
+Replace every placeholder (gituser, git.yourdomain.com, your_server_ip, etc.) with your actual values throughout the configuration.