OpenBSD на рабочей станции: различия между версиями

Материал из OpenBSD-Wiki
Перейти к навигации Перейти к поиску
Строка 109: Строка 109:
  
 
==Using Disk Encryption==
 
==Using Disk Encryption==
 
+
==Использование шифрования для дисков==
OpenBSD provides software RAID by way of a virual host bust adaptor called softraid0. This HBA is also used for setting up disk encryption. To set use a disklabel (in my case for sd0g /home set the partition type to RAID
+
OpenBSD предоставляет программный RAID через виртуальный хост-адаптер шины ([https://ru.wikipedia.org/wiki/HBA HBA]). Также HBA применяется для настройки и использования шифрования дисков. Посредством [http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man8/disklabel.8 disklabel(8)] установим тип раздела RAID (в оригинальной статье автор использует блочное устройство '''/dev/sd0c''' как шифрованный том, монтируемый в '''/home'''): 
 
 
 
<pre>$ sudo disklabel -E /dev/sd0c
 
<pre>$ sudo disklabel -E /dev/sd0c
 
Label editor (enter '?' for help at any prompt)
 
Label editor (enter '?' for help at any prompt)
Строка 120: Строка 119:
 
FS type: [4.2BSD] RAID</pre>
 
FS type: [4.2BSD] RAID</pre>
  
Now configure it for crypto using -c C
+
Для настройки шифрования используем [http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man8/bioctl.8 bioctl(8)] с параметром -c C:
 
 
 
<pre># bioctl -c C -l /dev/sd0g softraid0
 
<pre># bioctl -c C -l /dev/sd0g softraid0
 
New passphrase: My Crypto Pass Phrase
 
New passphrase: My Crypto Pass Phrase
Строка 127: Строка 125:
 
softraid0: CRYPTO volume attached as sd1</pre>
 
softraid0: CRYPTO volume attached as sd1</pre>
  
Mount it using the same command. The kernel log will show a new virtual device appear
+
Монтирование выполняется той же командой, журнал ядра сообщит о появлении нового виртуального устройства:
 
 
 
<pre>sd1 at scsibus2 targ 1 lun 0: &lt;OPENBSD, SR CRYPTO, 005&gt; SCSI2 0/direct fixed
 
<pre>sd1 at scsibus2 targ 1 lun 0: &lt;OPENBSD, SR CRYPTO, 005&gt; SCSI2 0/direct fixed
 
sd1: 27168MB, 512 bytes/sector, 55641072 sectors</pre>
 
sd1: 27168MB, 512 bytes/sector, 55641072 sectors</pre>
  
Now add a disklabel and format the encrypted volume
+
Разметим и отформатируем шифрованный том:
 
 
 
<pre>$ sudo disklabel -E /dev/wd0c
 
<pre>$ sudo disklabel -E /dev/wd0c
 
$ sudo newfs /dev/rwd0a</pre>
 
$ sudo newfs /dev/rwd0a</pre>
  
Devices in OpenBSD may be mounted by device name or by disklabel UID which is a random id generated when the label is created.
+
Устройства в OpenBSD могут монтироваться по имени или с использованием disklabel UID, который случайным образом генерируется при разметке:
 
 
 
<pre>$ disklabel /dev/sd1c | grep uid
 
<pre>$ disklabel /dev/sd1c | grep uid
 
duid: 779d87bac3905122</pre>
 
duid: 779d87bac3905122</pre>
Строка 144: Строка 139:
 
It's this ID that we'll to mount the volume, in this way plugging in other drives won't confuse mount after we prompt the user for a password on boot. Adding the following to rc.local will ask for a password four times before giving up
 
It's this ID that we'll to mount the volume, in this way plugging in other drives won't confuse mount after we prompt the user for a password on boot. Adding the following to rc.local will ask for a password four times before giving up
  
 +
Полученный UID используется для монтирования тома, что позволяет избежать путаницы при. Код ниже, позволит выполнить четыре попытки ввода ключевой фразы для дешифрации тома:
 
<pre>#/etc/rc.local
 
<pre>#/etc/rc.local
 
for attept in 1 2 3 4; do
 
for attept in 1 2 3 4; do
Строка 152: Строка 148:
 
mount -o nodev,nosuid,softdep 779d87bac3905122.a /home</pre>
 
mount -o nodev,nosuid,softdep 779d87bac3905122.a /home</pre>
  
If you would like to enable crypto on the entire boot volume see [http://www.tedunangst.com/flak/post/OpenBSD-softraid-crypto-boot this post] by Ted Unangst.
+
Если необходим полностью шифрованный загрузочный том, ознакомьтесь с [http://www.tedunangst.com/flak/post/OpenBSD-softraid-crypto-boot публикацией] Ted Unangst.
  
 
==Reducing Password Fatique with YubiKey==
 
==Reducing Password Fatique with YubiKey==

Версия 02:03, 18 марта 2015

Вольный перевод статьи Eric Radman An OpenBSD Workstation с некоторыми дополнениями учитывающими изменения пришедшие в свежих релизах.

Выключение системы нажатием на кнопку питания

Безопасное выключение компьютера нажатием на кнопку питания, возможно после передачи ядру параметра:

# /etc/sysctl.conf
hw.allowpowerdown=1

Параметр может быть установлен только до перехода системы к уровню безопасности 1, подробнее в securelevel(7).

Больше никаких раздражающих сигналов

Одна из многих вещей, которую узнаешь прочитав Absolute OpenBSD - это как отключить раздражающий сигнал:

# /etc/wsconsctl.conf
keyboard.bell.volume=0

Начиная с релиза 5.4 способ с wsconsctl больше не работает. Отключить сигнал можно так:

# ~/.xinitrc
xset -b

или

# /etc/rc.conf.local
mixerctl inputs.spkr.mute=on

Монтирование съемных устройств пользователем

Удобно, когда можно смонтировать DVD или флеш-носитель без повышения привилегий, используя для этого членство в группе operator.

# usermod -G operator eradman
# chmod g=rw /dev/cd0*

Остаётся изменить параметр ядра и можно пользоваться.

# sysctl kern.usermount=1
$ mkdir -p mount/cdrom
$ mount /dev/cd0c mount/cdrom

Suspend & Resume

OpenBSD обладает хорошей поддержкой ACPI, подробнее в apmd(8). zzz и ZZZ быстрый способ перехода в режимы suspend и hibernate, если apmd запускается при загрузке.

# rc.conf.local
apmd_flags=""

Для релизов 5.6 и выше, управление сервисами осуществляется посредством утилиты rcctl(8).

# rcctl getdef apmd        
apmd_flags=NO
…
# rcctl enable apmd
…
# rcctl getdef apmd        
apmd_flags=

X Configuration: .xinitrc

# ~/.xinitrc

redshift -O 5600

while true; do
    batt="$(sysctl -n hw.sensors.acpibat0.watthour3 | cut -f1,2 -d" ")"
    xsetroot -name "$batt"
    sleep 60
done &
xsetroot -solid steelblue  &
exec dwm

redshift утилита предназначена для регулировки цветовой температуры экрана в зависимости от вашего окружения. Это работает и в случае ручной регулировки цветовой температуры. Например, подсветка экрана IBM T60p автора статьи по умолчанию "холодная", поэтому он изменяет значение цветовую температуры с 6500K до 5600K.

Запускаем циклический опрос сенсора времени жизни батареи (battery life (Wh)) с интервалом один раз в 60 сек, а полученное значение выводим "поверх" корневого окна.

Установим цвет фона и запустить свой любимый менеджер окон.

Переключение на внешний монитор

Разрешение дисплея на рабочем месте немного выше чем дисплея ноутбука, небольшой скрипт для переключения на внешний монитор:

#!/bin/sh
xrandr --output LVDS --off
xrandr --output VGA-0 --off
xrandr --output DVI-0 --auto
redshift -O 6200

Лично мне больше нравится немного другой вариант:

xrandr --query | grep "VGA1 connected" && xrandr --output LVDS1 --off --output VGA1 --mode 1920x1080

Подключение проектора

Если X-сервер запускается когда проектор подключен к VGA порту, то скорее всего сервер установит для встроенного и внешнего дисплеев одинаковое разрешение. На T60 например, это можно изменить:

xrandr --output LVDS --mode 1400x1050

Используя --query можно узнать какие режимы поддерживаются дисплеем, then I set up a viewport that pans with the mouse pointer

xrandr --output VGA-0 --mode 1024x768 --panning 1400x1050

Так же, я добавил в .xinitrc команды для автоматической конфигурации дисплеев, если при запуске X-сервера внешний монитор уже подключен:

xrandr --query | grep "DVI-0 connected" && ~/bin/docked-dvi
xrandr --query | grep "VGA-0 connected" && ~/bin/docked-vga

tmux

Несколько дополнений в мою конфигурацию мультиплексора терминалов. Я часто запускаю entr в небольшой панели снизу.

bind-key C-t split-window -p 25

Не знаю палитры цветов терминала, но её можно распечатать:

#!/bin/ksh

for i in `jot 255`; do
  printf "\033[38;5;${i}mcolour${i}\n"
done

Фон строки состояния и границы активного окна ярко-зеленый:

set -g status-bg colour118
set -g pane-active-border-fg colour118
set -g pane-border-fg colour30

Таблица с сопоставлением клавиатурных комбинаций для tmux и screen

Using Disk Encryption

Использование шифрования для дисков

OpenBSD предоставляет программный RAID через виртуальный хост-адаптер шины (HBA). Также HBA применяется для настройки и использования шифрования дисков. Посредством disklabel(8) установим тип раздела RAID (в оригинальной статье автор использует блочное устройство /dev/sd0c как шифрованный том, монтируемый в /home):

$ sudo disklabel -E /dev/sd0c
Label editor (enter '?' for help at any prompt)
  g:         55641600        100653824    RAID
> m g
offset: [100653824]
size: [55641600]
FS type: [4.2BSD] RAID

Для настройки шифрования используем bioctl(8) с параметром -c C:

# bioctl -c C -l /dev/sd0g softraid0
New passphrase: My Crypto Pass Phrase
Re-type passphrase: My Crypto Pass Phrase
softraid0: CRYPTO volume attached as sd1

Монтирование выполняется той же командой, журнал ядра сообщит о появлении нового виртуального устройства:

sd1 at scsibus2 targ 1 lun 0: <OPENBSD, SR CRYPTO, 005> SCSI2 0/direct fixed
sd1: 27168MB, 512 bytes/sector, 55641072 sectors

Разметим и отформатируем шифрованный том:

$ sudo disklabel -E /dev/wd0c
$ sudo newfs /dev/rwd0a

Устройства в OpenBSD могут монтироваться по имени или с использованием disklabel UID, который случайным образом генерируется при разметке:

$ disklabel /dev/sd1c | grep uid
duid: 779d87bac3905122

It's this ID that we'll to mount the volume, in this way plugging in other drives won't confuse mount after we prompt the user for a password on boot. Adding the following to rc.local will ask for a password four times before giving up

Полученный UID используется для монтирования тома, что позволяет избежать путаницы при. Код ниже, позволит выполнить четыре попытки ввода ключевой фразы для дешифрации тома:

#/etc/rc.local
for attept in 1 2 3 4; do
  bioctl -c C -l c3e2f405c96a8e10.g softraid0 && break
  sleep 1
done
fsck /dev/rsd1a
mount -o nodev,nosuid,softdep 779d87bac3905122.a /home

Если необходим полностью шифрованный загрузочный том, ознакомьтесь с публикацией Ted Unangst.

Reducing Password Fatique with YubiKey

Yubico makes a nice little hardware key that, among other things, can be used to generate one time passwords for user authentication. The yubikey-personalization-gui is a Qt-based program that can be used to write private keys to one of two "slots". Copy the 6-byte private identity and the 16-byte secret key without spaces to like so

echo "5c e1 e0 3e 63 a4" \
        | tr -d ' ' > /var/db/yubikey/$USER.id
echo "57 e3 af 3e 9b 51 2b 10 58 7d 33 fb d9 08 ef 7b" \
        | tr -d ' ' > /var/db/yubikey/$USER.key
chmod 600 /var/db/yubikey/$USER.*

Now set YubiKey as the authentication method for local logins as well as SSH.

# Default allowed authentication styles
auth-defaults:auth=yubikey,passwd,skey:

Finally rebuild the login DB

cap_mkdb /etc/login.conf

To reduce typing I use the second slot on the Yubikey as a relatively secure method of enabling ssh-agent in order to connect to remote systems where my public key (RSA, DSA, ECDSA) is installed. To start use the yubikey-personalization-gui to generate a random key, then set slot 2 to challange-response mode with this key

hexkey=$(echo "dd b6 68 81 c9 73 f9 64 84 21 7e f0 69 e8 2c 28 1b 6c ad e2" | tr -d ' ')
ykpersonalize -2 -ochal-resp -ochal-hmac -ohmac-lt64 -a $hexkey

Next I create new ssh keys (ssh-keygen) using part of the reply from ykchalresp. I installed script script as bin/ykauth

#!/bin/sh
ykchalresp -2 "$(whoami)@$(hostname)" | cut -c 1-15

Finally add this bit of logic to .profile to automatically activate these keys when I log in

ssh-add -l > /dev/null 2>&1 || {
    eval `ssh-agent`
    DISPLAY='' SSH_ASKPASS='/home/eradman/bin/ykauth' ssh-add < /dev/null
    exec ksh
}

Run -current on a Second Drive

Setting up a new disk in a way that OpenBSD expects is not very difficult, simply run fdisk's reinit

$ sudo fdisk -e wd0
Enter 'help' for information
fdisk: 1> p
Disk: wd0       geometry: 4133/240/63 [62500000 Sectors]
Offset: 0       Signature: 0xAA55
            Starting         Ending         LBA Info:
 #: id      C   H   S -      C   H   S [       start:        size ]
-------------------------------------------------------------------------------
*0: 83      0  32  33 -   3959  46  62 [        2048:    59860992 ] Linux files*
 1: 05   3959  79  30 -   4133 124  44 [    59865086:     2633730 ] Extended DOS
 2: 00      0   0   0 -      0   0   0 [           0:           0 ] unused
 3: 00      0   0   0 -      0   0   0 [           0:           0 ] unused

fdisk: 1> reinit
In memory copy is initialized to:
Offset: 0       Signature: 0xAA55
            Starting         Ending         LBA Info:
 #: id      C   H   S -      C   H   S [       start:        size ]
-------------------------------------------------------------------------------
 0: 00      0   0   0 -      0   0   0 [           0:           0 ] unused
 1: 00      0   0   0 -      0   0   0 [           0:           0 ] unused
 2: 00      0   0   0 -      0   0   0 [           0:           0 ] unused
*3: A6      0   1   2 -   4132 239  63 [          64:    62490896 ] OpenBSD
Use 'write' to update disk.
fdisk:*1> write
Writing MBR at offset 0.

Now Create a disk label on the second drive (wd0) based on the disklabel from the first drive (sd0)

$ sudo disklabel wd0
# /dev/rwd0c:
type: SCSI
disk: SCSI disk
label: HTS721010G9SA00
duid: 0dc2584c60057522
flags:
bytes/sector: 512
sectors/track: 63
tracks/cylinder: 255
sectors/cylinder: 16065
cylinders: 12161
total sectors: 195371568
boundstart: 64
boundend: 62490960
drivedata: 0

16 partitions:
#                size           offset  fstype [fsize bsize  cpg]
  a:          2104448               64  4.2BSD   2048 16384    1
  b:          2506143          2104512    swap
  c:        195371568                0  unused
  d:          4209024          4610656  4.2BSD   2048 16384    1
  e:          8385920          8819680  4.2BSD   2048 16384    1
  f:         45285344         17205600  4.2BSD   2048 16384    1

This roughly mirrors the layout I'm using on my first disk running -stable

$ df -h
Filesystem     Size    Used   Avail Capacity  Mounted on
/dev/sd0a     1003M   49.7M    903M     5%    /
/dev/sd0d      2.0G   14.0K    1.9G     0%    /tmp
/dev/sd0e      3.9G   19.6M    3.7G     1%    /var
/dev/sd0f     44.2G    2.3G   39.8G     5%    /usr
/dev/sd0i     39.4G   26.3G   11.0G    70%    /home

Create new file systems and then clone the existing install with dump/restore

newfs /dev/rwd0a
newfs /dev/rwd0d
newfs /dev/rwd0e
newfs /dev/rwd0f

mkdir -p /mnt/drive2

mount /dev/wd0a /mnt/drive2
cd /mnt/drive2 && dump -0 -f - / | restore -r -f -

mount /dev/wd0e /mnt/drive2/var
cd /mnt/drive2/var && dump -0 -f - /var | restore -r -f -

mount /dev/wd0f /mnt/drive2/usr
cd /mnt/drive2/usr && dump -0 -f - /usr | restore -r -f -

You can install a bootloader like so

# /usr/mdec/installboot -v /mnt/drive2/boot /usr/mdec/biosboot wd0
fs block shift 2; part offset 64; inode block 64, offset 680
master boot record (MBR) at sector 0
        partition 3: type 0xA6 offset 64 size 62490896
/boot will be written at sector 64

After rebooting make sure /tmp has the right permissions

chmod 1777 /mnt/drive2/tmp

The only changes left are to mount the new drive and change change sd0 to wd0 in /etc/fstab.

From here refer to Following -current on the OpenBSD FAQ. Performance Tuning

There is no documentation on improving the responsiveness of an OpenBSD desktop. These are the tweaks I make. First I allow applications to consume more RAM

# /etc/login.conf
staff:\
        :datasize-cur=2048M:\
        :datasize-max=2048M:\
        :datasize=2048M:\
        :openfiles-cur=1024:\
        :stacksize-cur=16M:\

Add the noatime option to mount points

c3e2f405c96a8e10.a / ffs rw,noatime 1 1
c3e2f405c96a8e10.d /tmp ffs rw,softdep 1 2
c3e2f405c96a8e10.f /usr ffs rw,nodev,noatime 1 2
# ...

If you know of other strategies for tuning desktop performance. please send me what you know.