E:\> tools\fdimage floppies\kern.flp A:
FreeBSD 使用手冊
This translation may be out of date. To help with the translations please access the FreeBSD translations instance.
註冊商標
FreeBSD 是 FreeBSD 基金會的註冊商標。
IBM, AIX, OS/2, PowerPC, PS/2, S/390 以及 ThinkPad 是 International Business Machines Corporation 在美國和其他國家的商標。
IEEE, POSIX 以及 802 是 Institute of Electrical and Electronics Engineers, Inc. 在美國的註冊商標。
Red Hat, RPM, 是 Red Hat, Inc. 在美國和其他國家的註冊商標。
3Com 和 HomeConnect 是 3Com Corporation 的註冊商標。
Adobe, Acrobat, Acrobat Reader, Flash 以及 PostScript 是 Adobe Systems Incorporated 在美國和/或其他國家的商標或註冊商標。
Apple, AirPort, FireWire, iMac, iPhone, iPad, Mac, Macintosh, Mac OS, Quicktime 以及 TrueType 是 Apple Inc. 在美國以及其他國家的註冊商標。
Intel, Celeron, Centrino, Core, EtherExpress, i386, i486, Itanium, Pentium 以及 Xeon 是 Intel Corporation 及其分支機構在美國和其他國家的商標或註冊商標。
Linux 是 Linus Torvalds 的註冊商標。
Microsoft, IntelliMouse, MS-DOS, Outlook, Windows, Windows Media 以及 Windows NT 是 Microsoft Corporation 在美國和/或其他國家的商標或註冊商標。
Motif, OSF/1, 和 UNIX 是 The Open Group 在美國和其他國家的註冊商標; IT DialTone 和 The Open Group 是其商標。
Sun, Sun Microsystems, Java, Java Virtual Machine, JDK, JRE, JSP, JVM, Netra, OpenJDK, Solaris, StarOffice, SunOS 以及 VirtualBox 是 Sun Microsystems, Inc. 在美國和其他國家的商標或註冊商標。
RealNetworks, RealPlayer, 和 RealAudio 是 RealNetworks, Inc. 的註冊商標。
Oracle 是 Oracle Corporation 的註冊商標。
3ware 是 3ware Inc 的註冊商標。
ARM 是 ARM Limited. 的註冊商標。
Adaptec 是 Adaptec, Inc. 的註冊商標。
Android is a trademark of Google Inc.
Heidelberg, Helvetica, Palatino 以及 Times Roman 是 Heidelberger Druckmaschinen AG 在美國以及其他國家的商標或註冊商標。
Intuit 和 Quicken 是 Intuit Inc., 或其子公司在美國和其他國家的商標或註冊商標。
LSI Logic, AcceleRAID, eXtremeRAID, MegaRAID 和 Mylex 是 LSI Logic Corp 的商標或註冊商標。
MATLAB 是 The MathWorks, Inc. 的註冊商標。
SpeedTouch 是 Thomson 的商標。
VMware 是 VMware, Inc. 的商標。
Mathematica 是 Wolfram Research, Inc 的註冊商標。
Ogg Vorbis 和 Xiph.Org 是 Xiph.Org 的商標。
XFree86 是 The XFree86 Project, Inc 的商標。.
許多製造商和經銷商使用一些稱為商標的圖案或文字設計來區別自己的產品。 本文件中出現的眾多商標,以及 FreeBSD Project 本身廣所人知的商標,後面將以 “™” 或 “®” 符號來標示。
目錄
摘要
歡迎使用 FreeBSD! 本使用手冊涵蓋範圍包括了 FreeBSD 12.0-RELEASE 與 FreeBSD 11.3-RELEASE 的安裝與平日操作的說明。 這份使用手冊是很多人的集體創作,而且仍然『持續不斷』的進行中,因此部份章節可能尚未仍未完成,如果您有興趣協助本計畫的話,請寄電子郵件至 FreeBSD 文件專案郵遞論壇。
在 FreeBSD 網站 可以找到本手冊的最新版本,舊版文件可從 https://docs.FreeBSD.org/doc/ 取得。本文件也提供各種格式與不同壓縮方式的版本可自 FreeBSD FTP 伺服器 或是其中一個 鏡像網站 下載。 列印出來的實體書面資料可在 FreeBSD 商城 購買。 此外,您可在 搜尋頁面 中搜尋本文件或其他文件的資料。
序
給讀者的話
若您是第一次接觸 FreeBSD 的新手,可以在本書第一部分找到 FreeBSD 的安裝程序,同時會逐步介紹 UNIX™ 的基礎概念與一些常用、共通的東西。而閱讀這部分並不難,只需要您有探索的精神和接受新概念。
讀完這些之後,手冊中的第二部分花很長篇幅介紹的各種廣泛主題,相當值得系統管理者去注意。 在閱讀這些章節的內容時所需要的背景知識,都註釋在該章的大綱裡面,若不熟的話,可在閱讀前先預習一番。
延伸閱讀方面,可參閱 參考書目。
自第三版後的主要修訂
您目前看到的這本手冊代表著上百位貢獻者歷時 10 年所累積的心血之作。以下為自 2014 年發佈的兩冊第三版後所做的主要修訂:
DTrace 增加說明有關強大的 DTrace 效能分析工具的資訊。
其他檔案系統 增加有關 FreeBSD 非原生檔案系統的資訊,如:來自 Sun™ 的 ZSF。
安全事件稽查 增加的內容涵蓋 FreeBSD 的新稽查功能及其使用說明。
虛擬化 增加有關在虛擬化軟體安裝 FreeBSD 的資訊。
安裝 FreeBSD 增加的內容涵蓋使用新安裝工具 bsdinstall 來安裝 FreeBSD。
自第二版後的主要修訂 (2004)
您目前看到的這本手冊第三版是 FreeBSD 文件計劃的成員歷時兩年完成的心血之作。因文件內容成長到一定大小,印刷版需要分成兩冊發佈。新版的主要修訂部分如下:
設定與調校 已針對新內容作更新,如:ACPI 電源管理、
cron
以及其他更多的核心調校選項說明內容。安全性 增加了虛擬私人網路 (VPN)、檔案系統的存取控制 (ACL),以及安全報告。
強制存取控制 (MAC) 是此版本新增的章節。該章介紹:什麼是 MAC 機制?以及如何運用它來使您的 FreeBSD 系統更安全。
儲存設備 新增了像是:USB 隨身碟、檔案系統快照 (Snapshot)、檔案系統配額 (Quota) 、檔案與網路為基礎的檔案系統、以及如何對硬碟分割區作加密等詳解。
PPP 增加了疑難排解的章節。
電子郵件 新增有關如何使用其它的傳輸代理程式、SMTP 認證、UUCP、fetchmail、procmail 的運用以及其它進階主題。
網路伺服器 是該版中全新的一章。這一章介紹了如何架設 Apache HTTP 伺服器、ftpd 以及用於支援 Microsoft™Windows™ 客戶端的 Samba。其中有些段落來自原先的 進階網路設定 。
進階網路設定 新增有關在 FreeBSD 中使用藍牙™裝置、設定無線網路以及使用非同步傳輸模式 (Asynchronous Transfer Mode, ATM) 網路的介紹。
增加詞彙表,用以說明全書中出現的術語。
重新美編書中所列的圖表。
自第一版後的主要修訂 (2001)
本手冊的第二版是 FreeBSD 文件計劃的成員歷時兩年完成的心血之作。第二版包的主要變動如下:
增加完整的目錄索引。
所有的 ASCII 圖表均改成圖檔格式的圖表。
每個章節均加入概述,以便快速的瀏覽該章節內容摘要、讀者所欲了解的部分。
內容架構重新組織成三大部分:"入門"、"系統管理" 以及 "附錄"。
FreeBSD 基礎 新增了程序、Daemon 以及信號 (Signal) 的介紹。
安裝應用程式:套件與 Port 新增了介紹如何管理 Binary 套件的資訊。
X Window 系統 經過全面改寫,著重於在 XFree86™ 4.X 上的現代桌面技術,如: KDE 和 GNOME。
FreeBSD 開機程序 更新相關內容。
儲存設備 分別以兩個章節 "磁碟" 與 "備份" 來撰寫。我們認為這樣子會比單一章節來得容易瞭解。還有關於 RAID (包含硬體、軟體 RAID) 的段落也新增上去了。
序列通訊 架構重新改寫,並更新至 FreeBSD 4.X/5.X 的內容。
PPP 有相當程度的更新。
進階網路設定 加入許多新內容。
電子郵件 大量新增了設定 sendmail 的介紹。
Linux® Binary 相容性 增加許多有關安裝 Oracle™ 以及 SAP™ R/3™ 的介紹。
此外,第二版還新加章節,以介紹下列新主題:
本書架構
本書主要分為五大部分,第一部份入門:介紹 FreeBSD 的安裝、基本操作。 讀者可根據自己的程度,循序或者跳過一些熟悉的主題來閱讀; 第二部分一般作業:介紹 FreeBSD 常用功能,這部分可以不按順序來讀。 每章前面都會有概述,概述會描述本章節涵蓋的內容和讀者應該已知的, 這主要是讓讀者可以挑喜歡的章節閱讀; 第三部分系統管理:介紹 FreeBSD 老手所感興趣的各種主題部分; 第四部分網路通訊:則包括網路和各式伺服器主題;而第五部分則為附錄包含各種有關 FreeBSD 的資源。
- 簡介
向新手介紹 FreeBSD。該篇說明了 FreeBSD 計劃的歷史、目標和開發模式。
- 安裝 FreeBSD
帶領使用者走一次使用 bsdinstall 在 FreeBSD 9.x 及之後版本的完整安裝流程。
- FreeBSD 基礎
涵蓋 FreeBSD 作業系統的基礎指令及功能。若您熟悉 Linux™ 或其他類 UNIX® 系統,您則可跳過此章。
- 安裝應用程式:套件與 Port
涵蓋如何使用 FreeBSD 獨創的 "Port 套件集" 與標準 Binary 套件安裝第三方軟體。
- X Window 系統
介紹 X Windows 系統概要及在 FreeBSD 上使用 X11,同時也會介紹常用的桌面環境如 KDE 與 GNOME。
- 桌面應用程式
列出一些常用的桌面應用程式,例如:網頁瀏覽器、辦工工具並介紹如何安裝這些應用程式到 FreeBSD。
- 多媒體
示範如何在您的系統設定音效及影像播放支援,同時會介紹幾個代表性的音訊及視訊應用程式。
- 設定 FreeBSD 核心
說明為何需要設定新的核心並會提供設定、編譯與安裝的詳細操作說明。
- 列印
介紹如何在 FreeBSD 管理印表機,包含橫幅頁面、列印帳務以及初始設定等資訊。
- Linux® Binary 相容性
介紹 FreeBSD 的 Linux™ 相容性功能,同時提供許多熱門的 Linux™ 應用程式詳細的安裝操作說明,例如 Oracle™ 及 Mathematica™。
- 設定與調校
介紹可供系統管理者用來調校 FreeBSD 系統的可用參數來最佳化效率,同時也介紹 FreeBSD 用到的各種設定檔以及到何處尋找這些設定檔。
- FreeBSD 開機程序
介紹 FreeBSD 開機流程並說明如何使用設定選項控制開機流程。
- 安全性
介紹許多可讓您的 FreeBSD 系統更安全的各種工具,包含 Kerberos, IPsec 及 OpenSSH。
- Jail
介紹 Jail Framework,以及 Jail 改進那些 FreeBSD 傳統 chroot 不足的地方。
- 強制存取控制 (MAC)
說明什麼是強制存取控制 (Mandatory Access Control, MAC) 及這個機制如何用來確保 FreeBSD 系統的安全。
- 安全事件稽查
介紹什麼事 FreeBSD 事件稽查,如何安裝與設定,以及如何檢查與監控稽查線索。
- 儲存設備
介紹如何在 FreeBSD 管理儲存媒體及檔案系統,這包含了實體磁碟、RAID 陣列、光碟與磁帶媒體、記憶體為基礎的磁碟以及網路檔案系統。
- GEOM. 模組化磁碟轉換框架
介紹在 FreeBSD 中的 GEOM Framework 是什麼,以及如何設定各種支援的 RAID 階層。
- 其他檔案系統
查看 FreeBSD 還支援那些非原生檔案系統,如 Sun™ 的 Z 檔案系統。
- 虛擬化
介紹虛擬化系統提供了那些功能,以及如何在 FreeBSD 上使用。
- 在地化 - i18n/L10n 使用與安裝
介紹如何在 FreeBSD 使用非英文的語言,這涵蓋了系統及應用層的在地化。
- 更新與升級 FreeBSD
說明 FreeBSD-STABLE、FreeBSD-CURRENT 以及 FreeBSD 發佈版之間的差異,並介紹那些使用者適何追蹤開發系統以及程序的概述,這涵蓋了使用者更新系統到最新安全性發佈版本的方法。
- DTrace
介紹如何在 FreeBSD 設定及使用 Sun™ 的 DTrace 工具,動態追蹤可以透過執行真實時間系統分析來協助定位效能問題。
- 序列通訊
介紹如何使用撥入及撥出連線到您的 FreeBSD 系統的終端機與數據機。
- PPP
介紹如何在 FreeBSD 使用 PPP 來連線遠端的系統。
- 電子郵件
說明組成電子郵件伺服器的各種元件,並深入說明如何設定最熱門的郵件伺服器軟體:sendmail。
- 網路伺服器
提供詳細的操作說明與範例設定檔,讓您可安裝您的 FreeBSD 機器為網路檔案伺服器、網域名稱伺服器、網路資訊系統伺服器或時間同步伺服器。
- 防火牆
說明軟體為基礎的防火牆背後的理念,並提供可用於 FreeBSD 中不同的防火牆設定的詳細資訊。
- 進階網路設定
介紹許多網路主題,包含在您的區域網路 (LAN) 分享網際網路連線給其他電腦、進階路由主題、無線網路、Bluetooth™、ATM、IPv6 以及更多相關主題。
- 取得 FreeBSD
列出取得 FreeBSD CDROM 或 DVD 媒體的各種來源,以及在網際網路上的各種網站,讓您可以下載並安裝 FreeBSD。
- 參考書目
本書觸及許多不同主題,可能會讓您想更深入的了解,參考書目列出了在文中引用的許多優秀書籍。
- 網路資源
介紹了可讓 FreeBSD 使用者提出問題以及參與有關 FreeBSD 技術會談的許多論壇。
- OpenPGP 金鑰
列出了數個 FreeBSD 開發人員的 PGP 指紋。
本書的編排體裁
為了提供有一致性且易於閱讀的內容,以下是一些本書所遵循的編排體裁。
文字編排體裁
- 斜體字
斜體字用於:檔名、目錄、網址 (URL)、 強調語氣、以及第一次提及的技術詞彙。
等寬字
等寬字
用於: 錯誤訊息、指令、環境變數、Port 名稱、主機名稱、帳號、群組、裝置名稱、變數、程式碼等。- 粗體字
以粗體字表示:應用程式、指令、按鍵。
使用者輸入
鍵盤輸入以粗體字表示,以便與一般文字做區隔。 組合鍵是指同時按下一些按鍵,我們以 +
來表示連接,像是:
Ctrl+Alt+Del
是說,一起按 Ctrl、 Alt 以及 Del 鍵。
若要逐一按鍵,那麼會以逗號 (,) 來表示,像是:
Ctrl+X, Ctrl+S
是說:先同時按下 Ctrl 與 X 鍵, 然後放開後再同時按 Ctrl 與 S 鍵。
範例
範例以 C:\> 為開頭代表 MS-DOS™ 的指令。 若沒有特殊情況的話,這些指令應該是在 Microsoft™ Windows™ 環境的 "指令提示字元 (Command Prompt)" 視窗內執行。
範例以 #
為開頭代表在 FreeBSD 中以超級使用者權限來執行的指令。 你可以先以 root
登入系統並下指令,或是以你自己的帳號登入再使用 su(1) 來取得超級使用者權限。
# dd if=kern.flp of=/dev/fd0
範例以 %
為開頭代表在 FreeBSD 中以一般使用者帳號執行的指令。 除非有提到其他用法,否則都是預設為 C-shell 語法,用來設定環境變數以及下其他指令的意思。
% top
銘謝
您所看到的這本書是經過數百個分散在世界各地的人所努力而來的結果。 無論他們只是糾正一些錯誤或提交完整的章節,所有的點滴貢獻都是非常寶貴有用的。
也有一些公司透過提供資金讓作者專注於撰稿、提供出版資金等模式來支持文件的寫作。 其中,BSDi (之後併入 Wind River Systems) 資助 FreeBSD 文件計劃成員來專職改善這本書直到 2000 年 3 月第一版的出版。(ISBN 1-57176-241-8) Wind River Systems 同時資助其他作者來對輸出架構做很多改進,以及給文章增加一些附加章節。這項工作結束於 2001 年 11 月第二版。(ISBN 1-57176-303-1) 在 2003-2004 兩年中,FreeBSD Mall, Inc 把報酬支付給改進這本手冊以使第三版印刷版本能夠出版的志工。
這部份是提供給初次使用 FreeBSD 的使用者和系統管理者。 這些章節包括:
介紹 FreeBSD 給您。
在安裝過程給您指引。
教您 UNIX™ 的基礎及原理。
展示給您看如何安裝豐富的 FreeBSD 的應用軟體。
向您介紹 X,UNIX™ 的視窗系統以及詳細的桌面環境設定,讓您更有生產力。
我們試著儘可能的讓這段文字的參考連結數目降到最低,讓您在讀使用手冊的這部份時可以不太需要常常前後翻頁。
Part I: 入門
這部份是提供給初次使用 FreeBSD 的使用者和系統管理者。 這些章節包括:
介紹 FreeBSD 給您。
在安裝過程給您指引。
T教您 UNIX® 的基礎及原理。
展示給您看如何安裝豐富的 FreeBSD 的應用軟體。
向您介紹 X,UNIX® 的視窗系統以及詳細的桌面環境設定,讓您更有生產力。
我們試著儘可能的讓這段文字的參考連結數目降到最低,讓您在讀使用手冊的這部份時可以不太需要常常前後翻頁。
Chapter 1. 簡介
1.1. 概述
非常感謝您對 FreeBSD 感興趣!以下章節涵蓋 FreeBSD 計劃的各方面:比如它的歷史、目標、開發模式等等。
讀完這章,您將了解:
FreeBSD 與其他作業系統之間的關係。
FreeBSD 計劃的歷史。
FreeBSD 計劃的目標。
FreeBSD 開源開發模式的基礎概念。
當然囉,還有 "FreeBSD" 這名字的由來。
1.2. 歡迎使用 FreeBSD!
FreeBSD 是一套開源、符合標準的類 Unix 的作業系統,適用於 x86 (32 與 64 位元), ARM™, AArch64, RISC-V™, MIPS™, POWER™, PowerPC™ 以及 Sun UltraSPARC™ 的電腦。它提供了現代作業系統所應具備的所有功能,例如:先佔式多工、記憶體保護、虛擬記憶體、多使用者架構、對稱多工處理 (SMP)、各種針對不同語言和框架的開源開發工具以及以 X Window 系統、KDE 及 GNOME 為主的桌面功能,而它有以下優勢:
自由的開放原始碼授權,授予您自由修改和擴充其原始碼並將其合併到開放原始碼專案或封閉的產品中的權力,不會對 Copyleft 授權施加典型的限制,也避免了授權不相容的潛在問題。
強大的 TCP/IP 網路 - FreeBSD 以工業標準實作通訊協定並不斷改善效能與擴展性,這使得 FreeBSD 非常適合應用在伺服器、路由器/防火牆的角色 - 這也是許多公司和供應商使用它的原因。
完全整合 OpenZFS,包含 root-on-ZFS、ZFS 開機環境、故障管理、委託管理、對 Jail 的支援、FreeBSD 專屬的文件以及系統安裝程式的支援。
鉅細靡遺的安全性功能,從強制存取控制 (Mandatory Access Control, MAC) 框架到 Capsicum 功能以及沙盒機制。
超過 3 萬個預編的套件供所有支援的架構以及可簡單編譯依您的需求所客製的 Port 套件集。
說明文件 - 除了操作手冊及由許多作者著作從系統管理到核心內部主題的書籍外,也有不僅只針對 Userspace Daemon、工具及設定檔,同樣也有針對核心驅動程式 APIs (第 9 節) 及各別驅動程式 (第 4 節) 的操作說明頁 (man(1) page)。
簡單且具一致性的檔案庫架構與編譯系統 - FreeBSD 對所有的元件、核心與 Userspace 使用單一的檔案庫,加上統一、易於客製的編譯系統以及嚴謹的開發流程,讓 FreeBSD 的編譯基礎架構更容易與您產品的整合。
忠於 Unix 哲學,偏好可組合而非具寫死的 "多合一" 單一 Daemon。
Linux 執行檔 (Binary) 相容性,無需虛擬化即可執行許多 Linux 執行檔。
FreeBSD 系統是基於美國加州大學柏克萊分校的電腦系統研究組 (Computer Systems Research Group 也就是 CSRG) 所發行的 4.4BSD-Lite,繼承了 BSD 系統開發的優良傳統。 除了由 CSRG 所提供的高品質的成果外,FreeBSD 計劃也投入了上千人時在擴充及微調,來讓系統在真實情境下能達到最大的效能與可靠性。 FreeBSD 提供了其他開源與商業產品的效能及穩定性,並結合其他產品所沒有的尖端功能。
1.2.1. FreeBSD 能做什麼?
FreeBSD 能應用的情境完全限制在你的想像力上。 從軟體開發到工廠自動化,庫存管控到遠程衛星天線的方位角校正;若您的需求可以用商用的 UNIX™ 產品來達成,那麼極有可能使用 FreeBSD 也能辦到! FreeBSD 也受益於來自於全球各研究中心及大學所開發的數千個高品質的軟體 ,這些通常只需要花費很少的費用或根本就是免費的。
由於每個人都可以取得 FreeBSD 的原始程式碼, 這個系統可以被量身訂做成能執行任何原本完全無法想像的功能或計劃, 而對於從各廠商取得的作業系統通常沒有辦法這樣地被修改。 以下提供一些人們使用 FreeBSD 的例子:
網際網路服務: FreeBSD 內建強勁的網路功能使它成為網路服務 (如下例) 的理想平台:
網頁伺服器
IPv4 及 IPv6 路由
防火牆以及 NAT ("IP 偽裝") 通訊閘
檔案傳輸協定伺服器
電子郵件伺服器
還有更多…
教育:您是電腦科學相關領域的學生嗎?再也沒有比使用 FreeBSD 能學到更多作業系統、計算機結構、及網路的方法了。其中許多免費提供的 CAD,數學和圖形設計套件對於那些需要在電腦完成 其他 工作的人也非常有用!
研究:有了完整的原始程式碼,FreeBSD 是研究作業系統及電腦科學的極佳環境。 具有免費且自由取得特性的 FreeBSD 也使得一個分置兩地的合作計劃,不必擔心版權及系統開放性的問題, 而能自在的交流。
網路: 你如果需要 路由器、名稱伺服器 (DNS) 或安全的防火牆, FreeBSD 可以輕易的將你沒有用到的 386 或 486 PC 變身成為絕佳的伺服器,甚至具有過濾封包的功能。
嵌入式: FreeBSD 是一套可用來建立嵌入式系統的傑出平台。 支援 ARM™, MIPS™ 以及 PowerPC™ 平台,再加上健全的網路環境、尖端的功能以及自由的 BSD 授權條款,FreeBSD 成為用來建置嵌入式路由器、防火牆及其他裝置的絕佳基礎。
桌面: FreeBSD 同時也是低成本桌面解決方案中不錯的選擇,使用了免費的 X11 伺服器。FreeBSD 提供許多開源桌面環境可選擇,包含了標準 GNOME 及 KDE 圖型化使用者介面。FreeBSD 甚至可以透過中央伺服器做 "無磁碟" 開機,讓個人工作站變的更便宜、更易於管理。
軟體開發: 基本安裝的 FreeBSD 就包含了完整的程式開發工具,如 C/C++ 編譯器及除錯器。 透過 Port 與套件管理系統也可支援需多其他語言。
你可以經由燒錄 CD-ROM、DVD 或是從 FTP 站上抓回 FreeBSD。 詳情請參閱 取得 FreeBSD 取得 FreeBSD。
1.2.2. 誰在用 FreeBSD?
FreeBSD 以其網頁 (Web) 服務功能而聞名 - 在 FreeBSD 上運作的網站包括 Hacker News, Netcraft, NetEase, Netflix, Sina, Sony Japan, Rambler, Yahoo! 及 Yandex。
FreeBSD 先進的功能、成熟的安全性、可預測的發佈週期以及自由的授權條款,讓 FreeBSD 已經被用來做為建立許多商業、開源應用、裝置以及產品的平台,有許多世界上最大的資訊公司使用 FreeBSD:
Apache - Apache 軟體基金會中大部分面對大眾的基礎設施,包括可能是世界上最大的 SVN 檔案庫 (擁有超過 140 萬次提交) 都是在 FreeBSD 上運作。
Apple - OS X 大量借鑒 FreeBSD 的網路 Stack、虛擬檔案系統以及許多使用者空間的元件。Apple iOS 中含有從 FreeBSD 借鑒來的元素。
Cisco - IronPort 網路安全及反垃圾郵件設備是採用改良後 FreeBSD 核心來運作。
Citrix - 安全設備的 NetScaler 產品線提供的第 4-7 層的負載均衡、內容快取、應用層防火牆、安全的 VPN 以及行動雲端網路存取,皆運用了 FreeBSD Shell 強大的功能。
Dell EMC Isilon - Isilon 的企業存儲設備是以 FreeBSD 為基礎。非常自由的 FreeBSD 授權條款讓 Isilon 整合了它們的智慧財產到整個核心,並專注打造自己的產品,而不是一個作業系統。
Quest KACE - KACE 系統管理設備中運作了 FreeBSD,是因為 FreeBSD 的可靠性、可擴展性以及支持其持續發展的社群。
iXsystems - 統合存儲 (Unified Storage) 設備的 TrueNAS 產品線是以 FreeBSD 為基礎。除了該公司自己的商業產品外,iXsystems 也管理著 TrueOS 和 FreeNAS 兩個開源計劃的開發。
Juniper - JunOS 作業系統驅動了所有的 Juniper 網絡設備 (包括路由器,交換器,安全與網絡設備) 便是以 FreeBSD 為基礎。Juniper 在眾多廠商之中,展現了計劃與商業產品供應商之間的共生關係。由 Juniper 所開發的改進內容會回饋給 FreeBSD 來降低未來新功能從 FreeBSD 整合回 JunOS 的複雜性。
McAfee - SecurOS 是 McAfee 企業防火牆產品的基礎,其中包含了 Sidewinder ,也是以 FreeBSD 為基礎。
NetApp - 存儲設備中的 Data ONTAP GX 產品線是以 FreeBSD 為基礎。除此之外,NetApp 還貢獻了回 FreeBSD 許多功能,包括新 BSD 條款授權的 hypervisor, bhyve。
Netflix - Netflix 用來以串流傳送電影到客戶的 OpenConnect 設備是以 FreeBSD 為基礎。 Netflix 也做了大量貢獻到程式碼庫,並致力於維持與主線 FreeBSD 的零修正關係。Netflix 的 OpenConnect 設備負責了北美所有的網路流量 32% 以上。
Sandvine - Sandvine 使用 FreeBSD 作為它的高性能即時網路處理平台的基礎來建立它們的智慧網路策略控制產品。
Sony - PlayStation 4 遊戲主機使用了修改過的 FreeBSD 版本來運作。
Sophos - Sophos 電子郵件設備產品是以加強防護 (Hardened) 的 FreeBSD 為基礎,可掃描入站郵件中的垃圾郵件和病毒,同時也可監控出站郵件中的惡意軟體及敏感資訊。
Spectra Logic - 儲藏級儲存設備的 nTier 產品線以 FreeBSD 和 OpenZFS 來運作。
Stormshield - Stormshield 網路安全設備使用了硬體化版本的 FreeBSD 做為基礎,BSD 授權條款讓他們可將其智慧財產與系統整合並同時回饋大量有趣的發展給社群。
The Weather Channel - 被安裝在各地有線電視營運商前端,負責加入當地天氣預報到有線電視網路節目的 IntelliStar 設備便是使用 FreeBSD。
Verisign - VeriSign 主要經營 .com 與 .net 根網域名稱註冊業務以及隨附的 DNS 基礎設施運作。這些基礎設施的運作仰賴各種不同的網路作業系統包括 FreeBSD 來確保不會有單點故障的問題。
Voxer - Voxer 使用了 FreeBSD 的 ZFS 來驅動行動語音通訊平台,讓 Voxer 從 Solaris 改使用 FreeBSD 的原因是 FreeBSD 擁有詳盡的文件、更大型且活躍的社群、較便利的開發人員環境。除了提供關鍵的 ZFS 和 DTrace 功能之外 FreeBSD 的 ZFS 也支援了 TRIM。
WhatsApp - 當 WhatsApp 面臨需要一個每台伺服器能夠同時處理超過 100 萬個 TCP 連線的平台時,它們選擇了 FreeBSD。它們接著擴大規模到每台伺服器處理超過 250 萬的連線。
Wheel Systems - FUDO 安全性設備讓企業可以監控、控制、記錄以及稽查在其系統中作業的承包商與管理員。這些功能皆是以 FreeBSD 最佳的安全性功能為基礎,包括 ZFS, GELI, Capsicum, HAST 及 auditdistd。
FreeBSD 也催生了數個相關的開源計劃:
BSD Router - 以 FreeBSD 為基礎的大型企業路由器替代方案,專門設計為可在標準 PC 硬體上運作。
FreeNAS - 專為網路檔案伺服器設備使用所設計的 FreeBSD。提供了以 Python 為基礎的網頁介面來簡化 UFS 與 ZFS 檔案系統的管理,支援了 NFS、SMB/ CIFS、AFP、FTP 與 iSCSI,還有以 FreeBSD Jail 為基礎的套件系統。
GhostBSD - 採用 Gnome 桌面環境的 FreeBSD 發行版。
mfsBSD - 用來建置可完全從記憶體執行 FreeBSD 系統映像檔工具。
NAS4Free - 以 FreeBSD 及 PHP 驅動網頁介面為基礎的檔案伺服器。
OPNSense - OPNsense 是一個以 FreeBSD 為基礎的開源、易於使用及易於建置的防火牆和路由平台。OPNsense 有大多數在昂貴的商業防火牆上才有的功能。它帶來了商業產品的豐富功能集,同時擁有開放和安全的來源。
TrueOS - 訂製版本的 FreeBSD,裝備了給桌面使用者使用的圖型化工具來展示 FreeBSD 強大的功能給所有使用者,專門設計來緩解使用者在 Windows 與 OS X 間的過渡。
pfSense - 以 FreeBSD 為基礎的防火牆發行版,支援巨型陣列及大規模 IPv6。
ZRouter - 嵌入式裝置韌體的開源替代方案,以 FreeBSD 為基礎,專門設計來取代現成路由器上的專用韌體。
在 FreeBSD 基金會網站上可以找到以 FreeBSD 為基礎的產品與服務的公司的推薦 清單。 Wikipedia 也維護了一份以 FreeBSD 為基礎的產品清單。
1.3. 關於 FreeBSD 計劃
接下來講的是 FreeBSD 計劃的背景,包含歷史、計劃目標以及開發模式。
1.3.1. FreeBSD 歷史簡介
FreeBSD 計畫起源於 1993 年初, 那是源自於維護一組『非官方 386BSD 修正工具』計劃的最後三個協調人 Nate Williams,Rod Grimes 和 Jordan Hubbard。
最初的目標是做出一份 386BSD 的中間版本的快照 (Snapshot) 來修正使用修正工具 (Patchkit) 機制無法解決的數個問題,也因此早期的計劃名稱叫做 386BSD 0.5 或 386BSD Interim 便是這個原因。
386BSD 是 Bill Jolitz 的作業系統,在當時就已經忍受了將近一年的忽視,隨著修正工具日漸龐大的令人不舒服,他們決定提供一份過渡性的 "簡潔" 快照來幫助 Bill。 然而,由於 Bill Jolitz 忽然決定取消其對該計劃的認可,且沒有明確指出未來的打算,所以該計劃便突然面臨中止。
這三人認為這個目標即始沒有 Bill 的支持仍有保留的價值,最後他們採用 David Greenman 丟銅板決定的名字,也就是 "FreeBSD"。在詢問了當時的一些使用者意見之後決定了最初的目標,隨著目標越來越明確便開始著手進行。Jordan 找了 Walnut Creek CD-ROM 商討,著眼於如何改進 FreeBSD 的發行通路,讓那些不便上網的人可簡單的取得。 Walnut Creek CD-ROM 不只贊成以 CD 來發行 FreeBSD 的想法,同時提供了一台機器以及快速的網路。 若不是 Walnut Creek CD-ROM 在那個時間上史無前例的信任,這個默默無名的計劃很可能不會成為現在的 FreeBSD 快速的成長到今日這樣的規模。
第一張以 CD-ROM (及網路) 發行的版本為 FreeBSD 1.0,是在 1993 年十二月發佈。 該版本採用了 U.C. Berkeley 以磁帶方式發行的 4.3BSD-Lite ("Net/2") 及許多來自於 386BSD 和自由軟體基金會的元件為基礎。對於第一次發行而言還算成功,我們又接著於 1994 年 5 月發行了相當成功的 FreeBSD 1.1。
然而此後不久,另一個意外的風暴在 Novell 與 U.C. Berkeley 關於 Berkeley Net/2 磁帶之法律地位的訴訟確定之後形成。 U.C. Berkeley 承認大部份的 Net/2 的程式碼都是"侵佔來的"且是屬於 Novell 的財產 — 事實上是當時不久前從 AT&T 取得的。 Berkeley 得到的是 Novell 對於 4.4BSD-Lite 的"祝福",最後當 4.4BSD-Lite 終於發行之後,便不再是侵佔行為。 而所有現有 Net/2 使用者都被強烈建議更換新版本,這包括了 FreeBSD。 於是,我們被要求於 1994 年 6 月底前停止散佈以 Net/2 為基礎的產品。在此前提之下,本計劃被允許在期限以前作最後一次發行,也就是 FreeBSD 1.1.5.1。
FreeBSD 便開始了這宛如『重新發明輪子』的艱鉅工作 — 從全新的且不完整的 4.4BSD-Lite 重新整合。 這個 "Lite" 版本是不完整的,因為 Berkeley 的 CSRG 已經刪除了大量在建立一個可以開機執行的系統所需要的程式碼 (基於若干法律上的要求),且該版本在 Intel 平台的移植是非常不完整的。 直到 1994 年 11 月本計劃才完成了這個轉移, 同時在該年 12 月底以 CD-ROM 以及網路的形式發行了 FreeBSD 2.0。 雖然該份版本在當時有點匆促粗糙,但仍是富有意義的成功。 隨之於 1995 年 6 月又發行了更容易安裝,更好的 FreeBSD 2.0.5。
自那時以來,FreeBSD 在每一次對先前版本改進穩定性、速度及功能時便會發佈一個新的發佈版本。
目前,長期的開發計畫繼續在 10.X-CURRENT (trunk) 分支中進行,而 10.X 的快照 (Snapshot) 版本可以在 快照伺服器 取得。
1.3.2. FreeBSD 計劃目標
FreeBSD 計劃的目標在於提供可作任意用途的軟體而不附帶任何限制條文。 我們之中許多人對程式碼 (以及計畫本身) 都有非常大的投入, 因此,當然不介意偶爾有一些資金上的補償,但我們並沒打算堅決地要求得到這類資助。 我們認為我們的首要"使命"是為任何人提供程式碼, 不管他們打算用這些程式碼做什麼, 因為這樣程式碼將能夠被更廣泛地使用,從而發揮其價值。 我認為這是自由軟體最基本的,同時也是我們所倡導的一個目標。
我們程式碼樹中,有若干是以 GNU 通用公共授權條款 (GPL) 或者 GNU 較寬鬆通用公共授權條款 (LGPL) 發佈的那些程式碼帶有少許的附加限制,還好只是強制性的要求開放程式碼而不是別的。 由於使用 GPL 的軟體在商業用途上會增加若干複雜性,因此,如果可以選擇的話, 我們會比較喜歡使用限制相對更寬鬆的 BSD 版權來發佈軟體。
1.3.3. FreeBSD 開發模式
FreeBSD 的開發是一個非常開放且具彈性的過程,就像從 貢獻者名單 所看到的,是由全世界成千上萬的貢獻者發展起來的。 FreeBSD 的開發基礎架構允許數以百計的開發者透過網際網路協同工作。 我們也經常關注著那些對我們的計畫感興趣的新開發者和新的創意, 那些有興趣更進一步參與計劃的人只需要在 FreeBSD 技術討論郵遞論壇 連繫我們。 FreeBSD 公告郵遞論壇 對那些希望了解我們進度的人也是相當有用的。
無論是單獨開發者或者封閉式的團隊合作,多瞭解 FreeBSD 計劃和它的開發過程會是不錯的:
- SVN 檔案庫
過去數年來 FreeBSD 的中央原始碼樹 (Source tree) 一直是以 CVS (Concurrent Versions System) 來維護的, 它是一套免費的原始碼控管工具。 從 2008 年 6 月起, FreeBSD 計劃開始改用 SVN (Subversion)。 這是一個必要的更換動作,因為隨著原始碼樹及歷史版本儲存的數量不斷快速擴張,CVS 先天的技術限制越來越明顯。 文件計劃與 Port 套件集檔案庫也同樣於 2012 年 5 月及 2012 年 7 月由 CVS 改為 SVN。請參考 同步您的原始碼樹 一節來取得有關如何取得 FreeBSD
src/
檔案庫的更多資訊,以及 使用 Port 套件集 了解如何取得 FreeBSD Port 套件集。- 提交者名單
所謂的 提交者 (Committer) 指的是對 Subversion 原始碼樹有 寫入 權限的人, 並且被授予修改 FreeBSD 原始碼的權限。 ("committer" 一詞源自版本管理系統中的
commit
指令,該指令是用來把新的修改提交給檔案庫)。 任何人都可以回報問題到 Bug Database,在回報問題之前,可以使用 FreeBSD 郵遞清單、IRC 頻道或論壇來確認問題真的是一個錯誤 (Bug)。- FreeBSD 核心團隊
如果把 FreeBSD 看成是一家公司的話, FreeBSD 核心團隊 (FreeBSD core team) 就相當於公司的董事會。 核心團隊的主要職責在於確保此計劃的整體有良好的架構,以朝著正確的方向發展。 此外,邀請敬業且負責的開發者加入提交者的行列也是核心團隊的職責之一,隨著其他新成員的加入也招募新的核心團隊成員。 目前的核心團隊是在 2018 年 7 月從提交者候選人之中選出來的,這個選舉每兩年會舉辦一次。
如同多數的開發者,核心團隊大部分成員加入 FreeBSD 開發都是志工性質而已, 並未從本計劃中獲得任何薪酬,所以這只是一個 "承諾" 不應該被誤解為 "保證支援" 才對。 前面用 "董事會" 來舉例可能不是很恰當,或許我們應該說: 他們是一群自願放棄原本的優渥生活、個人其他領域成就, 而選擇投入 FreeBSD 開發的熱血有為者才對!
- 非官方貢獻者
最後一點,但這點絕非最不重要的, 最大的開發者團隊就是持續為我們提供回饋以及錯誤修正的使用者自己。 與 FreeBSD 非核心開發者互動的主要方式,便是透過訂閱 FreeBSD 技術討論郵遞論壇 來進行溝通,這方面可參考,請參閱 網路資源 以瞭解各式不同的 FreeBSD 郵遞論壇。
FreeBSD 貢獻者名單 相當長且不斷成長中, 只要有貢獻就會被列入其中, 要不要立即考慮貢獻 FreeBSD 一些回饋呢?
提供原始碼並非為這個計劃做貢獻的唯一方式; 需要大家投入的完整工作清單請參閱 FreeBSD 計畫網站。
總而言之,我們的開發模式像是由鬆散的同心圓所組織。這個集中模式的設計為的是讓 FreeBSD 的使用者更便利,可以很容易的追蹤同一個中央的程式庫,避免把潛在的貢獻者排除在外!而我們的目標是提供一個穩定的作業系統,並有大量相關的 應用程式,讓使用者能夠輕鬆的安裝與使用 — 而這個開發模式對我們要完成這個目標來說運作的非常好。
我們對於那些想要加入 FreeBSD 開發者的期待是: 請保持如同前人一樣的投入,以確保繼續成功!
1.3.4. 第三方程式
除了基礎發行版之外,FreeBSD 提供了擁有上千個常用的程式的移植軟體的套件集,在撰寫本文的同時,已有超過 24,000 個 Port!Port 的範圍從 HTTP 伺服器到遊戲、語系、編輯器,幾乎所有東西都在裡面。完整的 Port 套件集需要將近 500 MB。要編譯一個 Port 您只需要切換目錄到您想安裝的程式目錄,然後輸入 make install
,接著系統便會處理剩下的動作。您編譯的每個 Port 完整原始發行版內容是動態下載的,所以您只需要有足夠的磁碟空間來編譯您想要的 Port。幾乎所有 Port 都提供已經預先編譯好的"套件",您可以透過簡單的指令來安裝 (pkg install
),提供那些不想要自行從原始碼編譯的人使用。更多有關套件與 Port 的資訊可於 安裝應用程式:套件與 Port 取得。
1.3.5. 其他文件
所有支援的 FreeBSD 版本都會在安裝程式中提供一個選項,讓您可以在初始化系統安裝的階段安裝額外的說明文件到 /usr/local/shared/doc/freebsd。說明文件也可在往後隨時使用套件安裝,詳細說明於 自 Port 更新說明文件。您也可以使用任何支援 HTML 的瀏覽器進入下列 URL 檢視已安裝在本機的手冊:
- FreeBSD 使用手冊
- FreeBSD 常見問答集
此外,可在下列網址找到最新版 (也是更新最頻繁的版本):https://www.FreeBSD.org/。
Chapter 2. 安裝 FreeBSD
2.1. 概述
有多種不同的方法可以執行 FreeBSD,根據所在環境,包含:
一般虛擬機映像檔,可下載並匯入到您所選擇的虛擬環境。映像檔可從 Download FreeBSD 頁面下載,KVM ("qcow2"), VMWare ("vmdk"), Hyper-V ("vhd") 及原始裝置的映像檔都支援。這些並非安裝程式的映像檔,而是已經預先設定好 ("已安裝好") 的實例,可直接使用並執行安裝後的作業。
託管服務虛擬機映像檔,可在 Amazon 的 AWS Marketplace, Microsoft Azure Marketplace 和 Google Cloud Platform 等託管服務上運行的虛擬機映像檔。有關如何在 Azure 上部署 FreeBSD 的資訊可查詢 Azure 說明文件中的相關章節。
SD 卡映像檔,供嵌入式系統,如 Raspberry Pi 或 BeagleBone Black 使用的映像檔,可從 Download FreeBSD 頁面下載,這些檔案必須先解壓縮後以原始映像檔的格式寫入 SD 卡以讓這些開發電路板能夠啟動。
安裝程式映像檔,用來安裝 FreeBSD 到硬碟,供一般的桌機、筆電或伺服器系統使用。
此章接下來的部份會介紹第四個案例,說明如何使用文字介面為基礎的安裝程式 bsdinstall 安裝 FreeBSD。
一般來說,本章所寫的安裝說明是針對 i386™ 和 AMD64 架構。如果可以用於其他平台,將會列表說明。 安裝程式和本章所敘述的內容可能會有些微差異,所以請將本章視為通用的指引,而不是完全照著來做。
喜歡用圖形化安裝程式安裝 FreeBSD 的使用者, 可能會對 pc-sysinstall 有興趣,這是 TrueOS 計畫所使用的。 他可以用來安裝圖形化桌面 (TrueOS) 或是指令列版本的 FreeBSD。 細節請參考 TrueOS 使用者 Handbook (https://www.trueos.org/handbook/trueos.html)。 |
讀完這章,您將了解:
最低的硬體需求和 FreeBSD 支援的架構。
如何建立 FreeBSD 的安裝媒體。
如何開始執行 bsdinstall。
bsdinstall 會詢問的問題,問題代表的意思,以及如何回答。
安裝失敗時如何做故障排除。
如何在正式安裝前使用 live 版本的 FreeBSD。
在開始閱讀這章之前,您需要:
閱讀即將安裝的 FreeBSD 版本所附帶的硬體支援清單,並核對系統的硬體是否有支援。
2.2. 最低硬體需求
安裝 FreeBSD 的硬體需求隨 FreeBSD 的版本和硬體架構而不同。 FreeBSD 發行版支援的硬體架構和裝置會列在 FreeBSD 發佈資訊 頁面。FreeBSD 下載頁面 也有建議如何正確的選擇在不同架構使用的映像檔。
FreeBSD 安裝程序需要至少 96 MB 的 RAM 以及 1.5 GB 的硬碟空間。然而,如此少的記憶體及磁碟空間只適合在客製的應用上,如嵌入式設備。一般用途的桌面系統會需要更多的資源,2-4 GB RAM 與至少 8 GB 的硬碟空間是不錯的起點。
每一種架構的處理器需求概述如下:
- amd64
桌面電腦與筆記型電腦最常見的處理器類型,運用在近代的系統。Intel™ 稱該類型為 Intel64,其他製造商則稱該類型為 x86-64。
與 amd64 相容的處理器範例包含:AMD Athlon™64, AMD Opteron™, 多核心 Intel™ Xeon™ 以及 Intel™ Core™ 2 與之後的處理器。
- i386
舊型的桌面電腦與筆記型電腦常使用此 32-bit, x86 架構。
幾乎所有含浮點運算單元的 i386 相容處理器都有支援。所有 Intel™ 486 或是更高階的處理器也有支援。
FreeBSD 可在有支援實體位址延伸 (Physical Address Extensions, PAE) 功能的 CPU 上運用該功能所帶來的優點。有開啟 PAE 支援的核心會偵測超過 4 GB 的記憶體,並讓這些超過的記憶體能夠被系統使用。 但使用 PAE 會限制裝置驅動程式及 FreeBSD 的其他功能,詳情請見 pae(4)。
- ia64
目前支援的處理器是 Itanium™ 和 Itanium™ 2。支援的晶片組包括 HP zx1, Intel™ 460GX 和 Intel™ E8870。 單處理器 (Uniprocessor, UP) 和對稱多處理器 (Symmetric Multi-processor, SMP) 的設定都有支援。
- powerpc
所有內建 USB 的 New World ROMApple™Mac™ 系統都有支援。 SMP 在多 CPU 的機器都有支援。
32 位元的核心只能使用前 2 GB 的 RAM。
- sparc64
FreeBSD/sparc64 支援的系統列在 FreeBSD/sparc64 計劃。
所有超過一個處理器的系統都有支援 SMP。需要專用的磁碟系統,因為此時無法和其他作業系統共用磁碟。
2.3. 安裝前準備工作
一旦確定系統符合安裝 FreeBSD 的最低硬體需求,就可以下載安裝檔案並準備安裝的媒體。 做這些之前,先檢查以下核對清單的項目是否準備好了:
備份重要資料
安裝任何作業系統前, 總是 要先備份所有重要資料。 不要儲存備份在即將安裝的系統上,而是將資料儲存在可移除磁碟,像是 USB 隨身碟、網路上的另一個系統或是線上備份服務上。 開始安裝程序前要檢查備份,確定備份含有所有需要的檔案,一旦安裝程式格式化系統的磁碟,所有儲存在上面的資料都會遺失。
決定 FreeBSD 安裝在哪裡
如果 FreeBSD 是唯一一套要安裝到電腦的作業系統,這個步驟可以略過。 但是假如 FreeBSD 要和其他作業系統共用磁碟空間的話,就要決定 FreeBSD 要安裝在哪個磁碟或是哪個分割區 (Partition)。
在 i386 和 amd64 架構,可將磁碟分割成多個分割區,可以選擇下列兩種分割表格式 (Partitioning scheme) 的其中一種達成。 傳統的主開機紀錄 (Master Boot Record, MBR) 的一個分割區表定義最多可有四個主分割區 (Primary partition),因一些歷史淵源,FreeBSD 稱這些主分割區為 slice,其中一個主分割區可作為延伸分割區 (Extended partition),延伸分割區又可分割成多個邏輯分割區 (Logical partition)。 GUID 分割區表 (GUID Partition Table, GPT) 是較新和較簡單的分割磁碟的方法,一般 GPT 實作允許每個磁碟多達 128 個分割區,不再需要使用邏輯分割區。
一些比較舊的作業系統,像是 Windows™ XP 並不相容 GPT 分割表格式。 如果 FreeBSD 將和這類作業系統共用一個磁碟,則需要用 MBR 分割表格式。
FreeBSD 開機啟動程式需要主分割區或是 GPT 分割區。如果所有的主分割區或 GPT 分割區都已使用,必須釋放其中一個分割區讓 FreeBSD 使用。如果要建立一個分割區而不刪除原有的資料,可以使用磁碟重設大小的工具來縮小現有的分割區,並使用釋放出來的空間建立新分割區。
各種免費和付費的磁碟重設大小工具列於 http://en.wikipedia.org/wiki/List_of_disk_partitioning_software。GParted Live (http://gparted.sourceforge.net/livecd.php) 是內含分割區編輯程式 GParted 的免費 Live CD。 GParted 同時也被許多 Linux Live CD 發行版所收錄。
在正確使用的情況下,磁碟重設大小的工具可以安全的建立讓新的分割區使用的空間。 但因仍有可能會誤選已經存在的分割區,所以在修改磁碟分割區前, 一定要備份重要資料,並確認備份的完整性。
在磁碟分割區中儲存不同的作業系統讓一台電腦可以安裝多個作業系統,另一種作法是使用虛擬化技術 (虛擬化) ,可讓多個作業系統同時間執行而不需要改變任何磁碟分割區。
收集網路資訊
部份 FreeBSD 安裝方式需要網路連線來下載安裝檔,因此之後的安裝程序,安裝程式進入設定系統網路的介面。
如果網路中有 DHCP 伺服器,則可透過該伺服器自動設定網路,若無法使用 DHCP,則需要從區域網路管理者或是網際網路服務供應商 (Internet Service Provider, ISP) 取得以的網路資訊供系統使用:
IP 位址
子網路遮罩
預設通訊閘 IP 位址
網路的網域名稱
網路 DNS 伺服器 IP 位址
檢查 FreeBSD 勘誤表
儘管 FreeBSD 計劃努力確保每個 FreeBSD 發行版能夠儘可能地穩定,但臭蟲偶爾還是會悄悄出現,並有極小的可能會發生影響安裝流程的錯誤,當這些問題被發現並修正後,會被紀錄在 FreeBSD 網站的 FreeBSD 勘誤表 (https://www.freebsd.org/releases/12.0r/errata/)。 安裝前先檢查勘誤表,以確保沒有會影響到安裝的問題。
所有發行版的資訊和勘誤表可以在 FreeBSD 網站的發行資訊找到 (https://www.freebsd.org/releases/)。
2.3.1. 準備安裝的媒體
FreeBSD 安裝程式並不是一個可以在其他作業系統上執行的應用程式,反而您需要下載 FreeBSD 安裝檔,燒錄安裝檔到符合其檔案類型與大小的媒體 (CD, DVD 或 USB),然後開機從插入的媒體來安裝。
FreeBSD 的安裝檔可於 www.freebsd.org/where/#download 取得。安裝檔的名稱由 FreeBSD 發佈版本、架構、以及檔案類型所組成,舉例,要從 DVD 安裝 FreeBSD 10.2 到 amd64 的系統,需下載 [.filename]#FreeBSD-10.2-RELEASE-amd64-dvd1.iso,並燒錄這個檔案到 DVD,然後使用插入 DVD 來開機。
安裝檔有許多種可用的格式,格式會依據電腦架構及媒體類型的不同而異。
還有另一種安裝檔是給使用 UEFI (Unified Extensible Firmware Interface) 開機的電腦使用,這些安裝檔的名稱會含有 uefi。
檔案類型:
-bootonly.iso
:這是最精簡的安裝檔,檔案中只含安裝程式。 安裝時需要網際網路連線來下載所需的檔案以完成 FreeBSD 安裝。這個檔案應使用 CD 燒錄應用程式燒錄到 CD 使用。-disc1.iso
:這個檔案含有所有安裝 FreeBSD 所需的檔案,包含原始碼及 Port 套件集。這個檔案應使用 CD 燒錄應用程式燒錄到 CD 使用。-dvd1.iso
:這個檔案含有所有安裝 FreeBSD 所需的檔案,包含原始碼及 Port 套件集,也內含熱門的 Binary 套件可安裝視窗管理程式以及一些應用程式,如此便可從媒體安裝完整的系統,無須連線到網際網路。這個檔案應使用 DVD 燒錄應用程式燒錄到 DVD 使用。-memstick.img
:這個檔案含有所有安裝 FreeBSD 所需的檔案,包含原始碼及 Port 套件集。這個檔案應依據以下操作指示寫入到 USB 隨身碟使用。-mini-memstick.img
:類似-bootonly.iso
,但不含安裝檔 (可依所要下載),安裝時需要網際網路連線,可依 寫入映象檔到 USB 的說明將此檔案寫入至 USB 隨身碟。
映像檔下載完成之後,下載同一個目錄之中的 CHECKSUM.SHA256。FreeBSD 提供 sha256(1) 可用來計算映像檔的 校驗碼 (Checksum),使用方式為 sha256 imagefilename
,其他作業系統也會有類似的程式。
比對計算後的校驗碼與 CHECKSUM.SHA256 檔案中的值,校驗碼應該要完全相符,若校驗碼不相符,則代表該映像檔是損壞的,必須再下載一次。
2.3.1.1. 寫入映象檔到 USB
*.img 檔案是隨身碟的完整內容的映像檔 (image),該檔案不能直接用檔案的方式複製到目標裝置。有許多應用程式可用來寫入 *.img 到 USB 隨身碟,本節會介紹其中兩種。
在繼續之前,請先備份 USB 上的重要資料,這個程序會清除在隨身碟上既有的資料。 |
Procedure: 使用 dd
來寫入映像檔
本範例使用 /dev/da0 做為目標裝置,是映像檔將會寫入的位置。 務必十分小心確認要使用的裝置正確,因為這個指示會摧毀所有在指定目標裝置上已存在的資料。 |
dd(1) 指令列工具在 BSD, Linux™ 以及Mac OS™ 系統皆可使用。要使用
dd
燒錄映像檔需先插入 USB 隨身碟,然後確認隨身碟的裝置名稱。然後指定已下載的安裝檔名稱以及 USB 隨身碟的裝置名稱。本例示範在已有的 FreeBSD 系統燒錄 amd64 安裝映像檔到第一個 USB 裝置。# dd if=FreeBSD-10.2-RELEASE-amd64-memstick.img of=/dev/da0 bs=1M conv=sync
Procedure: 使用 Windows™ 來寫入映象檔
務必確認指定的磁碟機代號正確,因在指定磁碟機上的既有資料將會被覆蓋與摧毀。 |
取得 Image Writer Windows™ 版
Image Writer Windows™ 版 是一個免費的應用程式,可以正確地將映像檔寫入隨身碟。可從 https://sourceforge.net/projects/win32diskimager/ 下載,並解壓縮到一個資料夾。
用 Image Writer 寫入映象檔
雙擊 Win32DiskImager 圖示啟動程式。 確認
Device
顯示的磁碟機代號是隨身碟的磁碟機代號。 按下資料夾圖示選擇要寫入隨身碟的映像檔。 按下 Save 按鈕確定映像檔名。 確認所有東西都正確,隨身碟的資料夾並沒有在其他視窗開啟。 所有東西準備好後,按下 Write 將映像檔寫入隨身碟。
您現在可以開始安裝 FreeBSD 。
2.4. 開始安裝
預設安裝程序在下列訊息顯示之前不會對磁碟做任何更動: Your changes will now be written to disk. If you have chosen to overwrite existing data, it will be PERMANENTLY ERASED. Are you sure you want to commit your changes? 在這個警告訊息之前可以隨時中止安裝,若有任何設定錯誤的疑慮,只需在此時關閉電腦,將不會對系統磁碟做任何更改。 |
本節將介紹如何使用根據 準備安裝的媒體 指示所準備的安裝媒體來開機。要使用可開機的 USB,請在開啟電腦前插入 USB 隨身碟。要使用 CD 或 DVD,則可開啟電腦後在第一時間插入媒體。如何設定系統使用插入的媒體開機依不同的系統架構會有所不同。
2.4.1. 在 i386™ 及 amd64 開機
這兩種架構提供了 BIOS 選單可選擇開機的裝置,依據要使用的安裝媒體類型,選擇 CD/DVD 或 USB 裝置做為第一個開機裝置。大多數的系統也會提供快速鍵可在啟動時選擇開機裝置,而不需要進入BIOS,通常這個按鍵可能是 F10, F11, F12 或 Escape 其中之一。
若電腦仍載入了現有的作業系統,而不是 FreeBSD 安裝程式,原因可能為:
執行開機程序時安裝媒體插入主機的時間不夠早,請讓安裝媒體留在電腦中並重新啟動電腦。
未正確修改 BIOS 或未儲檔,請再三檢查第一個開機裝置選擇了正確的裝置。
系統太舊,無法支援使用選擇的開機媒體開機,發生這個情況可以使用 Plop Boot Manager (http://www.plop.at/en/bootmanagers.html) 來從選擇的開機媒體開機。
2.4.2. 在 PowerPC™ 開機
在大部份機型,可於開機時按住鍵盤上的 C,便可從 CD 開機。若在非 Apple™ 的鍵盤則可按住 Command+Option+O+F 或 Windows+Alt+O+F,出現 0 >
提示時,輸入
boot cd:,\ppc\loader cd:0
2.4.3. 在 SPARC64™ 開機
大多數 SPARC64™ 系統會自動從磁碟開機,要從 CD 安裝 FreeBSD 需要進入 PROM。
要進入 PROM,需重新開機系統然後等候開機訊息出現。訊息會依機型而有所不同,但大致結果會如:
Sun Blade 100 (UltraSPARC-IIe), Keyboard Present
Copyright 1998-2001 Sun Microsystems, Inc. All rights reserved.
OpenBoot 4.2, 128 MB memory installed, Serial #51090132.
Ethernet address 0:3:ba:b:92:d4, Host ID: 830b92d4.
若系統繼續從磁碟開機,此時按下鍵盤上的 L1+A 或 Stop+A 或透過序列 Console 送出 BREAK
。當使用 tip 或 cu, ~#
發出一個 BREAK 後,PROM 的提示會在單 CPU 的系統出現 ok
,SMP 的系統出現 ok {0}
,其中的數字代表啟動的 CPU 數。
此時,放入 CD 到磁碟機然後在 PROM 提示畫面輸入 boot cdrom
。
2.4.4. FreeBSD 開機選單
從安裝媒體開機之後,會顯示如下的選單:
預設在開機進入 FreeBSD 安裝程式前選單會等候使用者輸入 10 秒鐘,若已經安裝 FreeBSD,則會在開機進入 FreeBSD 前等候。要暫停開機計時器來仔細查看選項,請按 Space 鍵。要選擇選項,按下明顯標示的數字、字元或按鍵。選單有以下選項可選。
啟動多使用者模式 (
Boot Multi User
):這個選項會繼續 FreeBSD 開機程序,若開機計時器已經暫停,可按 1、大寫或小寫 B 或 Enter 鍵。啟動單使用者模式 (
Boot Single User
):這個模式用來修正已安裝的 FreeBSD,如 單使用者模式 所述。可按 2、大寫或小寫 S 進入這個模式。離開到載入程式提示 (
Escape to loader prompt
):這個選項會開機進入修復提示,這個模式含有有限數量的低階指令,這個模式詳細說明於 階段三。可按 3 或 Esc 進入這個提示。重新開機 (
Reboot
):重新開啟系統。設定開機選項 (
Configure Boot Options
):開啟內部選單,詳細說明於 FreeBSD 開機選項選單。
開機選項選單分成兩個部份。第一個部份用來返回主開機選單或重設任何已切換的選項回預設值。
第二個部份用來切換可用的選項為開 (On
) 或關 (Off
),透過按下選項明顯標示的編號或字元。系統將會一直使用這些選項開機,直到選項被修改。有數個選項可以在這個選單做切換:
ACPI 支援 (
ACPI Support
):若系統在開機時卡住,可嘗試切換這個選項為關 (Off
)。安全模式 (
Safe Mode
):若系統在 ACPI 支援 (ACPI Support
) 設為關 (Off
) 時開機時仍然會卡住,可嘗試將此選項設為開 (On
)。單使用者 (
Single User
):切換這個選項為開 (On
) 來修正已存在的 FreeBSD 如 單使用者模式 所述,問題修正後,將其設回關 (Off
)。詳細資訊 (
Verbose
):切換這個選項為開 (On
) 來查看開機程序中更詳細的訊息,這在診斷硬體問題時非常有用。
在做完所需的選擇後,按下 1 或 Backspace 返回主開機選單,然後按下 Enter 繼續開機進入 FreeBSD。FreeBSD 執行裝置偵測及載入安裝程式時會顯示一系列的開機訊息,開機完成之後,會顯示歡迎選單如 歡迎選單。

按下 Enter 選擇預設的 Install 進入安裝程式,接下來本章將介紹如何使用這個安裝程式。 若要選擇其他項目,可使用右或左方向鍵或顏色標示的字母選擇想要的選單項目。Shell 可用來進入 FreeBSD 的 Shell 使用指令列工具在安裝之前準備磁碟。Live CD 選項可用來在安裝之前試用 FreeBSD,Live 版本的詳細說明於 使用 Live CD。
要重新檢視開機訊息,包含硬體裝置偵測,請按大寫或小寫 S 然後再按 Enter 進入 Shell。在 Shell 提示之後輸入 |
2.5. 使用 bsdinstall
本節將告訴您在系統安裝之前 bsdinstall 選單的順序以及會詢問的資訊類型,可使用方向鍵來選擇選單的選項,然後按下 Space 選擇或取消選擇選單項目。當完成之後,按下 Enter 儲存選項然後進入下一個畫面。
2.5.1. 選擇鍵盤對應表選單
依據使用的系統 Console,bsdinstall 可能一開始顯示的選單會如 鍵盤對應表選擇。

要設定鍵盤配置,請選擇 YES 按下 Enter,接著會顯示選單如 選擇鍵盤選單。若要使用預設的配置,則可使用方向鍵選擇 NO 然後按下 Enter 跳過這個選單畫面。

設定鍵盤配置時,可使用上與下方向鍵來選擇最接近已連接到系統的鍵盤的鍵盤對應表 (Keymap),然後按下 Enter 儲存選項。
按 Esc 會離開這個選單然後使用預設的鍵盤對應表,若不清楚要使用那種鍵盤對應表, 是也是保險的選項。 |
在 FreeBSD 10.0-RELEASE 以及之後的版本,已經加強了這個選單,會顯示完整的鍵盤對應表選項,並預先選擇預設值。另外,當選擇其他鍵盤對應用時,在繼續之前會顯示對話框讓使用者測試鍵盤對應表來確認。

2.5.2. 設定主機名稱
下一個 bsdinstall 選單用來為新安裝的系統設定主機名稱。

輸入在網路上獨一無二的主機名稱,主機名稱要是完整的主機名稱,如 machine3.example.com
。
2.5.3. 選擇要安裝的元件
接下來 bsdinstall 會提示選擇要安裝的選用元件。

決定要安裝的元件主要會根據系統的用途以及可用的磁碟空間容量。FreeBSD 核心 (Kernel) 及 Userland 統稱為 基礎系統 (Base system),是必須安裝的部份。依據系統的架構,部份元件可能不會顯示:
doc
- 額外的說明文件,大部份是經年累月的產物,會安裝到 /usr/shared/doc。由 FreeBSD 文件計劃所提供的說明文件可在之後安裝,依照 更新文件集 中的指示操作。games
- 數個傳統 BSD 遊戲,包含 fortune, rot13 以及其他。lib32
- 在 64-bit 版本的 FreeBSD 供執行 32-bit 應用程式使用的相容性程式庫。ports
- FreeBSD Port 套件集是一套可自動下載、編譯安裝第三方軟體套件的集合,安裝應用程式:套件與 Port 中會討論到如何使用 Port 套件集。安裝程式並不會檢查是否有充足的磁碟空間,FreeBSD Port 套件集會使用約 500 MB 的磁碟空間,只有在有足夠的磁碟空間時才選擇這個選項。
src
- 完整的 FreeBSD 原始碼,包含核心 (Kernel) 與 Userland。雖然大多數的應用程式並不需要,但它可以編譯裝置驅動程式、核心模組或部份來自 Port 套件集的應用程式,它同時也用來做為開發 FreeBSD 本身所使用。完整的原始碼樹需要 1 GB 的磁碟空間,重新編譯整個 FreeBSD 系統需要額外再 5 GB 的空間。
2.6. 配置磁碟空間
接下來的選單用來決定配置磁碟空間的方式。
引導式 (Guided
) 磁碟分割會自動設定磁碟的分割區 (Partition),手動 (Manual
) 磁碟分割可讓進階的使用者使用選單項目建立自訂的分割區,而 Shell
會開啟 Shell 提示讓進階的使用者可以使用指示列工具如 gpart(8), fdisk(8) 以及 bsdlabel(8) 來建立自訂的分割區。ZFS
磁碟分割只在 FreeBSD 10 及之後的版本可以使用,可建立選擇性加密的 root-on-ZFS 系統並支援 開機環境 (Boot environment)。
本節會介紹在配置磁碟分割時需要考量那些事情,並且會示範各種磁碟分割的方式。
2.6.1. 規劃分割區配置
配置檔案系統時要記得硬碟的資料傳輸的速度外軌較內軌快,因此較小且大量存取的檔案系統應要較接近磁碟的外軌,而較大的分割區如 /usr 應放置在磁碟較內部,建議建立分割區的順序如下:/, swap, /var 然後 /usr。
機器預期的用途會反映到 /var 分割區的大小,這個分割區用來保存郵件 (Mailbox)、日誌檔 (Log file) 及印表機緩衝 (Spool)。依使用者數及保存的期間,郵件及日誌檔可能成長到無法預期的大小,一般來說大部份的使用很少會在 /var 需要超過 1 GB 的可用磁碟空間。
有時在 /var/tmp 會需要較多的空間,當新軟體安裝,套件工具會從套件中取出暫存的複本置於 /var/tmp。若在 /var/tmp 沒有足夠的空間,要安裝大型軟體套件,例如 Firefox, Apache OpenOffice 或 LibreOffice 會很困難。 |
/usr 分割區保存了許多支持系統運作的檔案,包含 FreeBSD Port 套件集以及系統原始碼,這個分割區建議至少要有 2 GB 的空間。
在規劃分割區大小時,請牢記空間需求,當因某個分割區空間不足時要改使用其他分割區時會很麻煩。
根據經驗,交換分割區應為是實體記憶體 (RAM) 的兩倍。使用最低需求的 RAM 來運作的系統會需要更多的交換空間來取得更好的表現。配置太小的交換交間可能導致 VM 分頁掃描碼效率不佳,且往後增加更多記憶體時可能會產生問題。
在有數個 SCSI 磁碟或數個 IDE 磁碟在不同控制器的大型系統建議在每個磁碟機上都設定交換空間,最多可至四個磁碟機。每個交換分割區的大小應接近相同。核心雖可以處以任意大小的交換空間,但內部資料結構擴充到 4 倍的最大交換分割區大小時,讓交換分割區擁有相同的大小可以讓核心可以最佳的方式串連各個磁碟的交換空間。規劃較大交換空間是可以的,即使沒有使用到多少交換空間,這也會讓要從失控的程式恢復運作更容易,而不需強制重新啟動系統。
正確的做磁碟分割,可以區隔頻繁寫入所產生的資料碎片與經常讀取的分割區,將寫入頻繁的分割區放在磁碟的邊緣可以增加 I/O 效率。雖然較大的分割區可能也需要增加 I/O 效率,但將這些分割區往磁碟邊緣移動所增加的效率並不會比將 /var 移到磁碟邊緣所增加的效率來的顯著。
2.6.2. 引導式磁碟分割
當選擇這個方法,選單上會顯示可用的磁碟,若電腦有安裝多個磁碟,則需選擇其中一個來安裝 FreeBSD。

選擇磁碟之後,接下來選單會提示是否要安裝到整個磁碟或是使用剩餘的空間建立新的分割區。若選擇 Entire Disk,會自動建立通用的分割區配置來填滿整個磁碟。選擇 Partition 則會使用磁碟上未使用的空間來建立分割區配置。

分割區配置建立完成之後,再檢查一次確定是否符合安裝的需求。選擇 Revert 會重設分割區回復為原來的設定值,選擇 Auto 會重新建立自動配置的 FreeBSD 分割區。分割區也可以手動建立、修改或刪除。當確認磁碟分割正確之後,選擇 Finish 繼續安裝。

2.6.3. 手動磁碟分割
選擇這個方法會開啟分割區編輯程式:

選擇要安裝的磁碟機 (在這個例子為 ada0) 然後選擇 Create 會以選單顯示可用的分割表格式 (Partition scheme):

amd64 電腦最適合的選擇通常是 GPT,無法相容 GPT 的舊電腦則應使用 MBR。而其他分割表格式一般會用在那些較罕見或較舊的電腦上。
縮寫 | 說明 |
---|---|
APM | Apple Partition Map,用於 PowerPC™。 |
BSD | 無 MBR 的 BSD 標籤,因非 BSD 的磁碟工具可能無法辨識該標籤,有時被稱做 危險專用模式 (Dangerously dedicated mode)。 |
GPT | GUID 分割區表 (http://en.wikipedia.org/wiki/GUID_Partition_Table)。 |
MBR | |
PC98 | 使用 MBR 改編,用於 NEC PC-98 電腦 (http://en.wikipedia.org/wiki/Pc9801)。 |
VTOC8 | Volume Table Of Contents,用於 Sun SPARC64 及 UltraSPARC 電腦。 |
選擇完分割區表格式並建立之後,再選擇 Create 一次來建立分割區。Tab 鍵可用來在欄位間移動游標。

標準的 FreeBSD GPT 安裝會使用至少三種分割區:
freebsd-boot
- 儲存 FreeBSD 開機程式 (Boot code)。freebsd-ufs
- FreeBSD 的 UFS 檔案系統。freebsd-swap
- FreeBSD 交換空間。
另一個值得注意的分割區類型是 freebsd-zfs
,這個分割區用來放置 FreeBSD ZFS 檔案系統 (Z 檔案系統 (ZFS))。請參考 gpart(8) 取得可用的 GPT 分割區類型說明。
檔案系統分割區可建立多個,且有部份人會偏好使用傳統的配置方式將 /, /var, /tmp 以及 /usr 分開存放在不同的分割區。請參考 建立傳統分割的檔案系統分割區 的範例。
大小 (Size
) 欄位可以使用常用的縮寫來輸入:K 代表 KB, M 代表 MB, G 代表 GB。
適當的對齊磁碟扇區 (Sector) 會提供最佳的效能,而且讓分割區大小為 4 KB 的偶數倍數可協助確保對齊在磁碟機上的 512-byte 或 4K-byte 扇區。一般來說,使用分割區大小為 1M 或 1G 的偶數倍數是最簡單的方式確保每個分割區以 4K 的偶數倍數做為開始。唯一一個例外是:freebsd-boot 分割區因目前開機程式 (Boot code) 的限制,不可大於 512K。 |
若分割區內含檔案系統便會需要一個掛載點 (Mountpoint
),若只要建立一個 UFS 分割區,那麼掛載點應設為 /。
標籤 (Label
) 是分割區的名稱,磁碟機名稱或編號可能因為磁碟機連接到不同的控制器或連結埠而有所不同,但分割區標籤並不會改變。因此在檔案如 /etc/fstab 中參照時,使用標籤來替代磁碟機名稱與分割區編號會讓系統對硬體變更有更多的容錯空間。GPT 標籤會於磁碟連結之後出現在 /dev/gpt/。其他分割表格式的標籤格有不同功能,且標籤會在 /dev/ 中有各自的目錄。
每個分割區請使用獨一無二的標籤來避免相同名稱的衝突,標籤可以加入與電腦名稱、用途、地點有關的文字。例如,使用 |
傳統的分割區配置會將 /, /var, /tmp 以及 /usr 分別使用不同的檔案系統與分割區。先建立 GPT 分割表格式,然後依照下表所示建立分割區。下表是針對 20G 目標磁碟的分割區大小,若在目標磁碟有更多可用的空間,則可增加交換空間 (Swap) 或 /var 會比較有用。以下所示的標籤皆以 ex
為字首,代表 "example",讀者應照前面的說明使用其他獨一無二的標籤。
預設 FreeBSD 的 gptboot 會預期第一個 UFS 分割區為 / 分割區。
分割區類型 | 大小 | 掛載點 | 標籤 |
---|---|---|---|
|
|
|
|
/ |
|
|
|
|
|
| |
/var |
|
|
|
/tmp |
|
| 接受預設值 (依磁碟提示) |
自訂的分割區建立完後,選擇 Finish 繼續安裝。
2.6.4. Root-on-ZFS 自動磁碟分割
在 FreeBSD 10.0-RELEASE 之後支援了自動建立 root-on-ZFS 的安裝程序。這種磁碟分割模式只能使用整個磁碟,並會清除整個磁碟內的內容。安裝程式會自動建立對齊 4k 邊界的分割區然後強制 ZFS 使用 4k 扇區 (Sector)。即使在 512 位元扇區的磁碟使用也很安全,並增加了確保在 512 位元的磁碟上建立儲存池 (Pool) 也可在未來加入 4k 扇區磁碟的好處,無論是作為額外的存儲空間或作為故障磁碟的替代品。安裝程式也可選擇性採用 GELI 磁碟加密,如 使用 geli 做磁碟加密 所介紹,若開啟磁碟加密,會建立一個內含 /boot 目錄的 2 GB 未加密的開機儲存池,這個儲存池中會儲存核心及其他開機必要的檔案。然後剩餘的空用會給 ZFS 儲存池使用。
主要 ZFS 設定選單提供了數個設定選項來控制儲存池的建立。
選擇 T 來設定儲存池類型 (Pool Type
) 以及要組成儲存池的磁碟。自動 ZFS 安裝程式目前僅支援建立單一頂層 vdev,除了在串連 (Stripe) 模式。要建立更複雜的儲存池,需使用 Shell 模式磁碟分割 的操作來建立儲存池。安裝程式支援建立各種儲存池類型,包含串連 Stripe (不建議,沒有備援功能)、鏡像 Mirror (效能較佳,但可用空間較少) 以及 RAID-Z 1, 2, 與 3 (分別有能力承受同時 1, 2 與 3 個磁碟的損壞)。在選擇儲存池類型時會在螢幕的下方提示所需的磁碟數量,以及在使用 RAID-Z 時,每種配置最佳的磁碟數。

選擇儲存池 (Pool Type
) 之後,會顯示可用的磁碟清單,然後會提示使用者選擇一個或多個磁碟來建立儲存池。接著會檢驗設定來確定選擇的磁碟足夠,若不足,選擇更改選項 (<Change Selection>) 來返回磁碟清單或取消 (<Cancel>) 來更改儲存池類型。


若有一個或多磁碟未出現在清單上,或在安裝程式啟動後才連接的磁碟,可選擇重新掃描裝置 (- Rescan Devices) 來更新可用磁碟的清單。要避免清除掉錯的磁碟,可用磁碟資訊 (- Disk Info) 來檢查每個磁碟,包含磁碟中的分割表以及各種其他資訊如裝置型號與序號 (若有的話)。

主 ZFS 設定選單也允許使用者輸入儲存池名稱、關閉強制 4k 扇區對齊、開啟或關閉加密、切換 GPT (建議) 與 MBR 分割表類型以及選擇交換空間容量。設定所有選項為想要的值之後,請選擇選單上方的安裝 (>>> Install) 選項。
若開啟了 GELI 磁碟加密,安裝程式會提示輸入兩次用來加密磁碟的密碼。

安裝程式接著會提供最後一次修改的機會可取消先前所選擇摧毀用來建立 ZFS 儲存池的磁碟機。

然後安裝程序會正常繼續。
2.7. 確認安裝
磁碟設定完之後,接下來的選單會讓您在格式化所選的硬碟之前有最後一次機會做變更,若需要做變更,可選 Back 返回到主磁碟分割選單。Revert & Exit 則會離開安裝程式,不會對硬碟做任何變更。

要開始實際的安裝,請選擇 Commit 然後按下 Enter。
安裝時間會依據選擇的發行版、安裝媒體、電腦的速度而有所不同,接下來會有一系列訊息會告知目前的進度。
首先,安裝程式會格式化選擇的磁碟,然後初始化分割區。然後,若使用僅可開機 (Boot only) 的媒體則會開始下載選擇的元件:

接著,會檢驗發行版的檔案完整性來確保沒有因下載過程中或安裝媒體的讀取過程中讀取錯誤造成的損壞:

最後,檢驗過的發行版檔案會被取出儲存至磁碟:

所有選擇的發行版檔案取出後,bsdinstall 會顯示第一次安裝後設定畫面,可用的安裝後設定選項會在下一節說明。
2.8. 安裝後注意事項
FreeBSD 安裝完之後,bsdinstall 會在開機進入新安裝的系統之前提示設定數個選項,本節將介紹這些設定選項。
系統開機之後, |
2.8.2. 設定網路介面卡
接著,會顯示在電腦上找到的網路介面卡清單。請選擇要設定的介面卡。
若使用 bootonly 的方式安裝在先前已有設定過網路,將會跳過網路設定選單。 |

若選擇的是乙太網路介面卡,安裝程式會跳過這部份直接到 選擇 IPv4 網路,若選擇的是無線網路介面卡,系統則會開始掃描無線存取點 (Wireless Access Point):

網線網路會使用 Service Set Identifier (SSID) 來辦識,SSID 是一段簡短、獨一無二的名稱,用來命名每個網路。 掃描時找到的 SSID 會列到清單,並會說明該網路可用的加密類型。 若想要連線的 SSID 並未出現在清單上,可選擇 Rescan 再掃描一次,若想要連線的網路仍然沒有出現,請檢查天線的連線是否有問題,或者嘗試將電腦移至更靠近存取點的位置,然後再掃描一次。

然後,輸入加密資訊來連線到選擇的無線網路。強列建議使用 WPA2 加密,因較舊的加密類型,如 WEP 僅提供微弱的安全性。若網路使用 WPA2 則需輸入密碼,也稱作 Pre-Shared Key (PSK)。考量安全性,輸入到輸入框的字元會以星號顯示。

接下來,選擇是否要設定乙太網路或無線網路介面卡的 IPv4 位址:

有兩種方式可以設定 IPv4。 DHCP 會自動設定網路介面卡且該網路上需有 DHCP 伺服器才可使用。否則,必須手動輸入位址的資訊來做靜態設定。
請不要隨便輸入網路資訊,因為這不管用。如果沒有可用的 DHCP 伺服器,可向網路管理者或網路服務供應商 (Internet Service Provider, ISP) 索取列於 需要的網路資訊 的資訊。 |
若有可用的 DHCP 伺服器,請在接下來的選單中選擇 Yes 則會自動設定網路介面卡。當找到 DHCP 伺服器並且取得系統的位址資訊時,安裝程式會出現一分鐘左右的停頓。

若沒有可用的 DHCP 伺服器,則選擇 No 然後在這個選單中輸入以下位址資訊:

IP 位址 (
IP Address
) - 要分配給這台電腦的 IPv4 位址。位址必須獨一無二且不可已被其他在區域網路上的設備使用。子網路遮罩 (
Subnet Mask
) - 網路的子網路遮罩。預設路由器 (
Default Router
) - IP 位址所在網段的預設通訊閘。
接下來的畫面會詢問是否要設定介面卡的 IPv6 位址,若可以且想要使用 IPv6,請選擇 Yes。

同樣有兩種方式可以設定 IPv6。StateLess Address AutoConfiguration (SLAAC) 會自動向區域路由器請求取得正確的設定資訊,請參考 http://tools.ietf.org/html/rfc4862 取得進一步資訊。靜態設定則需要手動輸入網路資訊。
若有可用的 IPv6 路由器,請在接下來的選單選擇 Yes 來自動設定網路介面卡。當找到路由器並且取得系統的位址資訊時,安裝程式會出現一分鐘左右的停頓。

若沒有可用的 IPv6 路由器,請選擇 No 然後在這個選單中輸入以下位址資訊:

IPv6 位址 (
IPv6 Address
) - 要分配給這台電腦的 IPv6 位址。位址必須獨一無二且不可已被其他在區域網路上的設備使用。預設路由器 (
Default Router
) - IPv6 位址所在網段的預設通訊閘。
最後的網路設定選單是用來設定網域名稱系統 (Domain Name System, DNS) 的解析器,解析器會轉換主機名稱為網路位址。若已使用 DHCP 或 SLAAC 來自動設定網路介面卡,解析器設定 (Resolver Configuration
) 的值可能會事先已填入,否則需輸入區域網路的網域名稱到搜尋 (Search
) 欄位。 DNS #1
與 DNS #2
要填寫 DNS 伺服器的 IPv4 及/或 IPv6 位址,至少需填寫一個 DNS 伺服器。

2.8.3. 設定時區
接下來的選單會詢問系統時鐘要使用 UTC 或者當地時間。 若有疑問時可選擇 No使用更常用的當地時間。

接下來一系列的選單會透過選擇地理區域、城市及時區來判斷正確的當地時間。設定時區可讓系統自動更正區域時間的更改,如日光節約時間以及正確執行其他時區相關的功能。
此處以位於美國東部時區的機器為例,選擇會依據地理位置不同改變。

使用方向鍵選擇適當的區域然後按下 Enter。

使用方向鍵選擇適當的城市然後按下 Enter。

使用方向鍵選擇適當的時區然後按下 Enter。

確認時區的縮寫是否正確,若正確,按下 Enter 繼續安裝後設定。
2.8.4. 開啟服務
接下來的選單用來設定有那些系統服務要在系統啟動時執行。所有的服務為選用,只需開啟系統運作真正需要的服務。

這是可以在這個選單開啟的服務摘要:
sshd
- Secure Shell (SSH) Daemon 可從遠端透過加密的連線存取系統,只有在系統允許遠端登入時開啟這個服務。moused
- 若在指令列系統 Console 會使用到滑鼠時,可開啟此服務。ntpd
- 網路時間通訊協定 (Network Time Protoco, NTP) Daemon 用來自動同步時間。若在網路上有使用 Windows™, Kerberos 或 LDAP 伺服器時,可開啟此服務。powerd
- 系統電源控制工具用來做電源控制與節能。
2.8.5. 開啟當機資訊 (Crash Dump)
接下來的選單用來設定是否開啟當機資訊 (Crash dump),開啟當機資訊對系統除錯非常有用,因此建議使用者開啟當機資訊。

2.8.6. 新增使用者
下個選單會提示建立至少一個使用者帳號。建議使用 root
以外的使用者帳號登入系統,當使用 root
登入時,基本上沒有任何的限制或保護。 使用一般使用者登入較保險且安全。
選擇 Yes 來新增新使用者。

請依照提示輸入請求的使用者帳號資訊,輸入使用者資訊 的範例示範建立 asample
使用者帳號。

這裡是要輸入的資訊摘要:
使用者名稱 (
Username
) - 登入時使用者要輸入的名稱,常見的慣例是用姓的前一個字母與名結合,只要每個使用者名稱在系統唯一的皆可。使用者名稱區分大小寫且不應含有任何空白字元。全名 (
Full name
) - 使用者的全名,這個欄位可使用空白並且會用來描述該使用者帳號。Uid
- 使用者 ID,通常這個欄位會留空,系統會自動分配一個值。登入群組 (
Login group
) - 使用者的群組,通常這個欄位會留空來使用預設值。邀請使用者進入其他群組? (
Invite user into other groups?
) - 使用者要加入成為其成員的其他群組,若該使用者需要管理權限,則在此輸入wheel
。登入類別 (
Login class
) - 通常會留空來使用預設值。Shell
- 輸入清單中的其中一項來設定使用者所互動的 Shell,請參考 Shell 取得更多有關 Shell 的資訊。家目錄 (
Home directory
) - 使用者的家目錄,預設值通常是沒有問題的。家目錄權限 (
Home directory permissions
) - 使用者家目錄的權限,預設值通常是沒有問題的。使用密碼為基礎的認証方式? (
Use password-based authentication?
) - 通常為是 (yes
),使用者才可於登入時輸入密碼。使用空白密碼? (
Use an empty password?
) - 通常為否 (no
),因為使用空白密碼並不安全。使用隨機密碼? (
Use a random password?
) - 通常為否 (no
),這樣使用者接下來才可設定自己的密碼。輸入密碼 (
Enter password
) - 這個使用者的密碼,輸入的字元不會顯示在畫面上。再輸入密碼一次 (
Enter password again
) - 再輸入一次密碼來確認無誤。建立後鎖定使用者帳號? (
Lock out the account after creation?
) - 通常為否 (no
),這樣使用者才可以登入。
在輸入完全部的資料後,會顯示摘要供檢查,若發現錯誤,可輸入否 (no
) 然後再輸入一次,若輸入的所有資訊皆正確,輸入是 (yes
) 以後便會建立新使用者。

若還有其他要新增的使用者,則在詢問新增其他使用者? (Add another user?
) 時回答是 (yes
)。輸入否 (no
) 來完成加入使用者然後繼續安裝。
要取得新增使用者與使用者管理的更多資訊,請參考 使用者與基礎帳號管理。
2.8.7. 最後設定
在所有東西安裝並設定完之後,會提供最後一次修改設定的機會。

使用這個選單在完成安裝前做任何更改或做任何額外的設定。
完成最後的設定之後,選擇 Exit。

bsdinstall 會提示是否有任何額外的設定需要在重新開機進入新系統之前完成。選擇 Yes 會離開進入到新系統的 Shell 或 No 繼續最後的安裝步驟。

若有需要做進一步或特殊的設定,選擇 Live CD 會開機進入安裝媒體的 Live CD 模式。
若安裝已完成,選擇 Reboot 重新開啟電腦然後啟動新的 FreeBSD 電腦。不要忘了移除 FreeBSD 安裝媒體,否則電腦會再次開機進入安裝程式。
FreeBSD 開機的過程會顯示許多可以參考的訊息,系統開機完成後,會顯示登入提示,在 login:
提示,輸入安裝時新增的使用者名稱。登入時避免直接使用 root
,請參考 超級使用者帳號 來取得當需要管理權限時如何成為超級使用者的說明。
要查看開機過程顯示的訊息可按 Scroll-Lock 鍵來開啟卷軸暫存,然後可使用 PgUp, PgDn 以及方向鍵來捲動訊息。查看完成之後再按 Scroll-Lock 鍵一次來解除畫面鎖定並返回 Console。系統開機一段時間之後要查看這些訊息可在指令提示後輸入 less /var/run/dmesg.boot
,查看後按下 q 鍵便可返回指令列。
若在 選擇要開啟的其他服務 有開啟 sshd,因系統會產生 RSA 及 DSA 金鑰第一次開機可能會有點慢,之後的開機便會恢復正常速度。接著會顯示金鑰的指紋 (Fingerprint),如這個範例:
Generating public/private rsa1 key pair.
Your identification has been saved in /etc/ssh/ssh_host_key.
Your public key has been saved in /etc/ssh/ssh_host_key.pub.
The key fingerprint is:
10:a0:f5:af:93:ae:a3:1a:b2:bb:3c:35:d9:5a:b3:f3 root@machine3.example.com
The key's randomart image is:
+--[RSA1 1024]----+
| o.. |
| o . . |
| . o |
| o |
| o S |
| + + o |
|o . + * |
|o+ ..+ . |
|==o..o+E |
+-----------------+
Generating public/private dsa key pair.
Your identification has been saved in /etc/ssh/ssh_host_dsa_key.
Your public key has been saved in /etc/ssh/ssh_host_dsa_key.pub.
The key fingerprint is:
7e:1c:ce:dc:8a:3a:18:13:5b:34:b5:cf:d9:d1:47:b2 root@machine3.example.com
The key's randomart image is:
+--[ DSA 1024]----+
| .. . .|
| o . . + |
| . .. . E .|
| . . o o . . |
| + S = . |
| + . = o |
| + . * . |
| . . o . |
| .o. . |
+-----------------+
Starting sshd.
請參考 OpenSSH 來取得更多有關指紋與 SSH 的資訊。
FreeBSD 預設並不會安裝圖型化介面,請參考 X Window 系統 取得有關安裝與設定圖型化視窗管理程式的資訊。
正確的將 FreeBSD 電腦關機對保護資料及避免硬體損壞有幫助。在系統尚未正常關機之前請不要關閉電源! 若使用者為 wheel
群組的成員之一,可在指令列輸入 su
然後輸入 root
密碼來成為超級使用者。接著輸入 shutdown -p now
系統便會關機,若硬體支援的話,電腦會自行關閉電源。
2.9. 疑難排解
本節涵蓋基礎的安裝疑難排解,例如一些已有人回報的常見問題。
查看該 FreeBSD 版本的 Hardware Notes (https://www.freebsd.org/releases/) 文件來確認是否支援該硬體。若確定有支援該硬體但仍然卡住或發生其他問題,請依照 設定 FreeBSD 核心 的指示編譯自訂核心來加入未在 GENERIC 核心的裝置。預設的核心會假設大部份的硬體裝置會使用原廠預設的 IRQs, I/O 位址,及 DMA 通道,若硬體已經被重新設定過,自訂的核心設定檔可以告訴 FreeBSD 到那找到這些裝置。
部份安裝問題可以透過更各種硬體元件的韌體來避免或緩解,特別是主機板。主機板的韌體通常稱為 BIOS,大部份主機板與電腦製造商會有網站可以取得升級程式與升級資訊。 製造商通常會建議若沒有特殊原因盡量避免升級主機板 BIOS,例如:重大更新,升級的程多可能會出錯,導致未更新完成的 BIOS 並讓電腦無法運作。 |
若系統在開機偵測硬體時卡住或安裝時運作異常,可能主因為 ACPI,FreeBSD 在 i386, amd64 及 ia64 平台廣泛的使用了系統 ACPI 服務來協助設定系統組態,若在開機時有偵測到該功能。不幸的是,ACPI 驅動程式與系統主機板及 BIOS 韌體之間仍存在部份問題。可於開機載入程式的第三階段設定 hint.acpi.0.disabled
Hint 來關閉 ACPI:
set hint.acpi.0.disabled="1"
每一次系統重開之後便會重設,因此需要在 /boot/loader.conf 檔案加入 hint.acpi.0.disabled="1"
。更多有關開機載入程式的資訊可於 概述 取得。
2.10. 使用 Live CD
如 歡迎選單 所示 bsdinstall 的歡迎選單提供了 Live CD 選項,這對那些對 FreeBSD 是否為正確的作業系統尚存疑慮的人非常有幫助,這可讓這些人在安裝前測試一部份功能。
在使用 Live CD 之前必須注意以下幾點事項:
若要增加存取權限,必須透過認証。使用者名稱為
root
而密碼則是空白。系統是直接從安裝媒體上執行,比起安裝到硬碟的系統,效能可能較差。
這個選項只提供指令提示,不會有圖型化介面。
Chapter 3. FreeBSD 基礎
3.1. 概述
接下來的這一章將涵蓋 FreeBSD 作業系統的基本指令及功能。 大部份的內容在 UNIX™-like 作業系統中都是相通的。 如果您對這些內容熟悉的話,可以放心的跳過。 如果您剛接觸 FreeBSD,那您一定要仔細的讀完這章。
讀完這章,您將了解:
如何使用 FreeBSD 的虛擬 Console。
如何在 FreeBSD 建立與管理使用者與群組。
UNIX™ 檔案權限以及 FreeBSD 檔案標記的運作方式。
預設的 FreeBSD 檔案系統配置。
FreeBSD 的磁碟組織。
如何掛載 (Mount)、卸載 (Umount) 檔案系統。
什麼是程序、Daemon 以及信號 (Signal)。
什麼是 Shell,以及如何變更您預設的登入環境。
如何使用基本的文字編輯器。
什麼是裝置 (Device) 和裝置節點 (Device node)。
如何閱讀操作手冊以獲得更多的資訊。
3.2. 虛擬 Console 與終端機
如果您沒有將 FreeBSD 設定成開機時自動進入圖形化模式,系統會進入指令登入提示像是這樣的東西:
FreeBSD/amd64 (pc3.example.org) (ttyv0)
login:
第一行包含了剛開機完系統的資訊,amd64
代表此範例所使用的系統是執行 64-位元版本的 FreeBSD,這台主機的名稱是 pc3.example.org
,ttyv0 代表這是個 "系統 Console"。第二行則是登人的提示訊息。
FreeBSD 是一個多使用者的系統,需要一套可以分辨不同使用者的方法。因此所有的使用者在執行程式之前必須先"登入
"系統以取得系統內程式的存取權限。每個使用者都有一組獨一無二的使用者名稱 ("username") 及個人密碼 ("password")。
要登入系統 Console 需輸入在系統安裝時設定的使用者名稱,請參考 新增使用者,並按下 Enter。 接著輸入該使用者名稱的密碼按下 Enter。 輸入的密碼為了安全起見不會顯示在畫面上。
如果您輸入了正確的密碼,您應該會看到今日訊息 (Message of the day, MOTD),後面接著顯示指令提示字元,依使用者建立時所選擇的 Shell 會有不同的提示字元可能為 #
, $
或者 %
。 看到指令提示代表使用者現在已經登入 FreeBSD 系統 Console 且已經準備好可以下指令。
3.2.1. 虛擬 Console
雖然系統 Console 已經可以用來與系統互動,但使用鍵盤來下指令使用 FreeBSD 系統的使用者通常會使用虛擬 Console 登入。 因為系統訊息預設會顯示在系統 Console,這些訊些會在使用者作業的過程中不斷出現,讓使用者難以專心作業。
FreeBSD 預設提供多個虛擬 Console 可輸入指令,每個虛擬 Console 都有自己的登入提示及 Shell 並且可以輕易的在虛擬 Console 間切換。 這實際上讓指令輸入有了類似於圖型化環境中可以同時開啟多個視窗的功能。
組合鍵 Alt+F1 至 Alt+F8 被 FreeBSD 保留用來切換虛擬 Console,使用 Alt+F1 可切換至系統 Console (ttyv0),Alt+F2 可存取第一個虛擬 Console (ttyv1),Alt+F3 可存取第二個虛擬 Console (ttyv2),以此類推。當使用 Xorg 作為圖型化 Console 時,組合鍵則改使用 Ctrl+Alt+F1 來切換回文字介面的虛擬 Console。
當您從一個 Console 切換到下一個的時候,FreeBSD 會切換畫面顯示的內容, 這就好像有很多虛擬的螢幕和鍵盤可以讓您輸入指令到 FreeBSD 執行。 在某一個虛擬 Console 上執行的程式並不會因為使用者切到別的 Console 而停止執行。
請參考 kbdcontrol(1), vidcontrol(1), atkbd:(4), syscons(4) 以及 vt(4) 來取得更多有關 FreeBSD Console 及鍵盤驅動程式的技術說明。
FreeBSD 中虛擬 Console 的數量設定在 /etc/ttys 檔案中的下列章節:
# name getty type status comments # ttyv0 "/usr/libexec/getty Pc" xterm on secure # Virtual terminals ttyv1 "/usr/libexec/getty Pc" xterm on secure ttyv2 "/usr/libexec/getty Pc" xterm on secure ttyv3 "/usr/libexec/getty Pc" xterm on secure ttyv4 "/usr/libexec/getty Pc" xterm on secure ttyv5 "/usr/libexec/getty Pc" xterm on secure ttyv6 "/usr/libexec/getty Pc" xterm on secure ttyv7 "/usr/libexec/getty Pc" xterm on secure ttyv8 "/usr/X11R6/bin/xdm -nodaemon" xterm off secure
要關閉虛擬 Console 只要在指定的虛擬 Console 該行設定的一開始加上註解符號 ()。 例如要將虛擬 Console 的數量由 8 個改為 4 個,則可將
加在代表虛擬 Console 的 ttyv5 到 ttyv8 的最後四行一開始。 請勿將系統 Console ttyv0 加上註解符號。 注意,若有依照 X Window 系統 安裝並設定 Xorg 時,會用到最後一個虛擬 Console (ttyv8)。
有關各欄位的設定以及其他選項,請參閱 ttys(5) 說明。
3.2.2. 單使用者模式
FreeBSD 開機選單會提供一個選項為 "Boot Single User",若選擇該項目,系統將會進入所謂 "單使用者模式" 的特殊模式。 此模式通常用在修復系統無法開機或重設已忘掉的 root
密碼。 在當使用者模式中無法使用網路及其他虛擬 Console,但有完整 root
對系統的存取權限,而且預設是不須要輸入 root
密碼。 也因此,要能透過實體鍵盤操作才能進入此模式,在考量 FreeBSD 系統安全時須要限制可操作實體鍵盤的人員。
有關單使用者模式的設定可在 /etc/ttys 中的以下章節中找到:
# name getty type status comments # # If console is marked "insecure", then init will ask for the root password # when going to single-user mode. console none unknown off secure
預設狀態為安全 (secure
),這代表誰能夠操作實體鍵盤不是不重要就是已受到實體安全規範管制。 若設定更該為不安全 (insecure
) 則代表主機所在的環境不安全,因為任何人皆可接觸鍵盤。 當此行設定更改為不安全 (insecure
) 時,當使用擇選擇單使用者模式時,FreeBSD 將會要求輸入 root
的密碼。
請審慎考慮是否要改為 |
3.2.3. 更改 Console 影像模式
FreeBSD Console 預設顯示大小可以調整為 1024x768、1280x1024 或其他顯示卡與螢幕有支援的解析度大小。 要使用不同的影像模式需載入 VESA
模組:
# kldload vesa
要偵測硬體支援的影像模式,可使用 vidcontrol(1)。 要取得支援的影像模式清單可輸入以下指令:
# vidcontrol -i mode
該指令會顯示硬體所支援的影像模式清單,要採用新的影像模式需以 root
使用者執行 vidcontrol(1) 指令:
# vidcontrol MODE_279
若可接受新的影像模式,可以在 /etc/rc.conf 加入設定,讓每次重開機後會自動生效:
allscreens_flags="MODE_279"
3.3. 使用者與基礎帳號管理
FreeBSD 允許多使用者同時使用電腦,在一次只能有一位使用者坐在電腦螢幕前使用鍵盤操作的同時,可讓任何數量的使用者透過網路登入到系統。每一位要使用該系統的使用者應有自己的帳號。
本章介紹:
FreeBSD 系統中各種類型的使用者帳號。
如何加入、移除與修改使用者帳號。
如何設定用來控制使用者與群組允許存取的資源的限制。
如何建立群組與加入使用者作為群組成員。
3.3.1. 帳號類型
由於所有對 FreeBSD 系統的存取是透過使用者帳號來達成,且所有的程序需要經由使用者來執行,因此使用者帳號管理非常重要。
有三種主要類型的帳號:系統帳號、使用者帳號以及超級使用者帳號。
3.3.1.1. 系統帳號
系統帳號用來執行服務,例如 DNS、郵件及網頁伺服器,要這麼作是因為安全性考量,若所有的服務均以超級使用者來執行,那麼這些服務的運作將不會受到限制。
系統帳號的例子有 daemon
, operator
, bind
, news
, and www
。
nobody
是通用的無權限系統帳號。雖然如此,只有要越多的服務使用 nobody
,就會有更多的檔案與程式與該使用者相關聯,會讓該使用者擁有更多的權限。
3.3.1.2. 使用者帳號
使用者帳號會分配給實際人員,用來登入及使用系統。每位要存取系統的人員需要擁有一組唯一的使用者帳號,這可讓管理者辨識誰在做什麼以及避免使用者覆蓋其他使用者的設定。
每位使用者可以設定自己的環境來配合自己使用系統的習慣,透過設定預設的 Shell、編輯器、組合鍵 (Key Binding) 及語言設定。
每個在 FreeBSD 系統的使用者帳號都會有一些相關的資訊:
- 使用者名稱 (User name)
在
login:
提示出現時便要輸入使用者名稱,每位使用者必須要有一個唯一的使用者名稱。要建立有效的使用者名稱要遵守數條規則,在 passwd(5) 中有說明。建議使用者名稱由 8 個或更少的字母組成,全部採用小寫字元以向下相容應用程式。- 密碼 (Password)
每個帳號都會有密碼。
- 使用者 ID (UID)
使用者 ID (User ID, UID) 是一組數字用來獨一無二的辨識 FreeBSD 系統的使用者,用到使用者名稱的指令會先將使用者名稱轉換為 UID。建議使用小於 65535 的 UID,超過這個值可能會造成部份軟體的相容性問題。
- 群組 ID (GID)
群組 ID (Group ID, GID) 是一組數字用來獨一無二的辨識使用者所屬的主要群組。群組是一個除了使用 UID 之外根據使用者的 GID 來控制資源存取權的機制。這可以顯著的降低某些設定檔的大小且可讓使用者成為一個以上群組的成員。建議使用 65535 或以下的 GID,因超過此值的 GID 可能會讓部份軟體無法運作。
- 登入類別 (Login class)
登入類別 (Login class) 擴充了群組機制,當在對不同使用者客製化系統時可提供額外的彈性。在 設定登入類別 有對登入類別更進一步的討論。
- 密碼更改時間 (Password change time)
預設情況下密碼並不會過期,雖然如此,密碼期限可在各別使用者上開啟,可強制部份或所有使用者在某段期間過後更改他們的密碼。
- 帳號到期時間 (Account expiration time)
預設情況下 FreeBSD 的帳號不會有期限。當建立需要有限壽命的帳號時,例如,學校的學生帳號,可使用 pw(8) 指定帳號的到期日期。到期日期過後,便無法使用該帳號登入到系統,儘管該帳號的目錄及檔案仍存在。
- 使用者的全名 (User’s full name)
使用者名稱用來獨一無二的辦識 FreeBSD 的帳號,但並不一定反映了使用者的真實姓名。類似註解,這個資訊可以含有空白、大寫字元並可超過 8 個字母的長度。
- 家目錄 (Home directory)
家目錄是系統中某個目錄的完整路徑,這個目錄是使用者登入後的起點目錄。習慣上會將所有使用者目錄放置在 /home/username 或 /usr/home/username。每位使用者可以儲存他們的個人檔案及子目錄於他們自己的家目錄。
- 使用者 Shell (User shell)
Shell 提供了使用者預設的環境來與系統互動。有數種不同類型的 Shell,有經驗的使用者會有自己偏好的選擇,可儲存在自己的帳號設定。
3.3.1.3. 超級使用者帳號
超級使用者帳號,通常稱作 root
,用來管理系統,沒有權限的限制,也因這個原因,該帳號不應該用來做每日的例行作業,如:寄信與收信、系統的一般探索或程式設計。
超級使用者並不像其他使用者帳號,可以沒有限制的操作,不正確的使用超級使用者帳號可能會造成可觀的災害。一般使用者帳號不會因為失誤而法摧毀作業系統,所以建議登入一般使用者帳號,只有在指令需要額外權限時切換為超級使用者。
使用超級使用者下指令時永遠要再三檢查,由於一個多餘的空白或缺少的字元可能意味著無法挽回的資料遺失。
有數種方法可以提升為超級使用者權限,雖然可以直接登入為 root
,但強烈不建議這樣做。
改使用 su(1) 切換為超級使用者。執行此指令時若指定 -
參數,該使用者會繼承 root 的使用者環境。執行此指令的使用者必須在 wheel
群組中,否則指令會失敗。使用者也必須要知道 root
使用者帳號的密碼。
在此例當中,該使用者只在要執行 make install
時切換為超級使用者,因為這個步驟需要超級使用者權限。指令完成之後,該使用者輸入 exit
離開超級使用者帳號並返回他的使用者帳號權限。
% configure
% make
% su -
Password:
# make install
# exit
%
內建的 su(1) 框架在單人系統或只有一位系統管理者的小型網路可以運作的很好。另一種方式是安裝 security/sudo 套件或 Port。此軟體提供了活動記錄且允許管理者設定那個使用者可以用超級使用者執行那個指令。
3.3.2. 管理帳號
FreeBSD 提供了各種不同指令來管理使用者帳號,最常用的指令已摘要於 管理使用者帳號的工具,接著有一些用法的範例。請參考每個工具的操作手冊來取得更多詳細的資訊與用法範例。
指令 | 摘要 |
---|---|
建議用來新增新使用者的指令列應用程式。 | |
建議用來移除使用者的指令列應用程式。 | |
用來更改使用者資料庫資訊的工具。 | |
用來更改使用者密碼的指令列工具。 | |
用來修改使用者帳號各方面資訊強大且靈活的工具。 |
3.3.2.1. adduser
建議用來新增新使用者的程式為 adduser(8)。當新使用者新增之後,此程式會自動更新 /etc/passwd 以及 /etc/group,這同時也會建立新使用者的家目錄 (複製 /usr/shared/skel 中的預設設定檔),並且可以選擇是否要寄送歡迎訊息通知新使用者。這個工具必須使用超級使用者執行。
adduser(8) 工具採用互動的方式,只需幾個步驟便可建立新使用者帳號。如 在 FreeBSD 新增使用者 所示,可輸入必填的資訊或按 Return 鍵採用方括中的預設值。在此例當中,使用者被邀請加入 wheel
群組,這讓使用者可使用 su(1) 變成超級使用者。完成之後,此工具會詢問是否要建立其他的使用者或離開。
# adduser
Username: jru
Full name: J. Random User
Uid (Leave empty for default):
Login group [jru]:
Login group is jru. Invite jru into other groups? []: wheel
Login class [default]:
Shell (sh csh tcsh zsh nologin) [sh]: zsh
Home directory [/home/jru]:
Home directory permissions (Leave empty for default):
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]:
Enter password:
Enter password again:
Lock out the account after creation? [no]:
Username : jru
Password : ****
Full Name : J. Random User
Uid : 1001
Class :
Groups : jru wheel
Home : /home/jru
Shell : /usr/local/bin/zsh
Locked : no
OK? (yes/no): yes
adduser: INFO: Successfully added (jru) to the user database.
Add another user? (yes/no): no
Goodbye!
#
由於密碼在輸入時並不會顯示,在建立使用者帳號時要小心密碼不要輸入錯誤。 |
3.3.2.2. rmuser
要自系統完全移除一個使用者可使用超級使用者執行 rmuser(8)。這個指令會執行以下步驟:
移除使用者的 crontab(1) 項目,若項目存在。
移除任何屬於該使用者的 at(1) 工作。
中止所有該使用者擁有的程序。
自系統本地密碼檔移除該使用者。
選擇性移除該使用者的家目錄,若使用者擁有該目錄。
自 /var/mail 移除屬於該使用者的收件郵件檔。
自暫存檔儲存區域 (如 /tmp) 移除所有使用者擁有的檔案。
最後,自 /etc/group 中該使用者所屬的所有群組移除該使用者。若群組無任何成員且群組名稱與該使用者名稱相同,則該群組也會一併移除。這是為了輔助
adduser(8) 替每位使用者建立獨一無二的群組。
rmuser(8) 無法用來移除超級使用者帳號,因為這幾乎代表著大規模破壞。
預設會使用互動式模式,如下範例所示。
rmuser
互動式帳號移除# rmuser jru
Matching password entry:
jru:*:1001:1001::0:0:J. Random User:/home/jru:/usr/local/bin/zsh
Is this the entry you wish to remove? y
Remove user's home directory (/home/jru)? y
Removing user (jru): mailspool home passwd.
#
3.3.2.3. chpass
任何使用者都可以使用 chpass(1) 來變更自己的預設 Shell 以及與自己的使用者帳號關聯的個人資訊。超級使用者可以使用這個工具更改任何使用者的其他帳號資訊。
除了選填的使用者名稱外,未傳入任何選項時,chpass(1) 會開啟含有使用者資訊的編輯器。當使用者自編輯器離開,便會更新新的資訊到使用者資料庫。
離開編輯器時,此工具會提示使用者輸入密碼,除非使用超級使用者執行此工具。 |
在 以超級使用者的身份使用 chpass
中,超級使用者輸入了 chpass jru
並正在檢視這個使用者可以更改的欄位。若改以 jru
執行這個指令,只會顯示最後六個欄位供編輯,如 以一般使用者的身份使用 chpass
所示。
chpass
#Changing user database information for jru.
Login: jru
Password: *
Uid [#]: 1001
Gid [# or name]: 1001
Change [month day year]:
Expire [month day year]:
Class:
Home directory: /home/jru
Shell: /usr/local/bin/zsh
Full Name: J. Random User
Office Location:
Office Phone:
Home Phone:
Other information:
chpass
#Changing user database information for jru.
Shell: /usr/local/bin/zsh
Full Name: J. Random User
Office Location:
Office Phone:
Home Phone:
Other information:
3.3.2.4. passwd
任何使用者皆可簡單的使用 passwd(1) 更改自己的密碼。要避免意外或未授權的變更,這個指令在設定新密碼之前會提示使用者輸入原來的密碼:
% passwd
Changing local password for jru.
Old password:
New password:
Retype new password:
passwd: updating the database...
passwd: done
超級使用者可以更改任何使用者的密碼透過在執行 passwd(1) 時指定使用者名稱。當此工具以超級使用者執行時,將不會提示輸入使用者目前的密碼,這可在使用者忘記原來的密碼時更改密碼。
# passwd jru
Changing local password for jru.
New password:
Retype new password:
passwd: updating the database...
passwd: done
如同 chpass(1),yppasswd(1) 連結到 passwd(1),因此 NIS 在兩個指令上皆可運作。 |
3.3.3. 管理群組
群組代表一群使用者,群組可以由其群組名稱及 GID 來辨識。在 FreeBSD,核心會使用程序的 UID 以及其所屬的群組清單來決定程序可以做那些事。大多數情況使用者或程序的 GID 通常指的是清單中的第一個群組。
群組名稱與 GID 的對應表列在 /etc/group。這個純文字檔案使用了四個以冒號分隔的欄位,第一個欄位為群組名稱,第二個欄位為加密後的密碼,第二個欄位為 GID 以及第四個欄位為以逗號分隔的成員清單。要取得更完整的語法說明,請參考 group(5)。
超級使用者可以使用文字編輯器修改 /etc/group,或者可使用 pw(8) 加入與編輯群組。例如,要加入一個叫做 teamtwo
的群組然後確認該群組已新增:
# pw groupadd teamtwo
# pw groupshow teamtwo
teamtwo:*:1100:
在本例中,1100
是 teamtwo
的 GID。目前 teamtwo
沒有任何成員,這個指令會加入 jru
作為 teamtwo
的成員。
# pw groupmod teamtwo -M jru
# pw groupshow teamtwo
teamtwo:*:1100:jru
給 -M
的參數是以逗號分隔的使用者清單,用來加入成員到新的 (空的) 群組或取代既有群組中的成員。對使用者來說這裡的群組成員與使用者列於密碼檔的主要群組不同 (額外的),這代表在 pw(8) 使用 groupshow
時不會顯示做為使用者主要群組的成員,但會顯示在使用 id(1) 或同類工具所查詢的資訊當中。當使用 pw(8) 來加入使用者到某個群組,該指令只會處理 /etc/group 且不會嘗試自 /etc/passwd 讀取其他的資料。
# pw groupmod teamtwo -m db
# pw groupshow teamtwo
teamtwo:*:1100:jru,db
在本例當中,給 -m
的參數是以逗號分隔的使用者清單,用來加入使用者到群組。不像前面的例子,這些使用者會加入到群組,而非取代既有群組中的使用者。
% id jru
uid=1001(jru) gid=1001(jru) groups=1001(jru), 1100(teamtwo)
在本例中,jru
是群組 jru
以及 teamtwo
的成員。
3.4. 權限
在 FreeBSD 中,每個檔案與目都有相關聯的數個權限,且有許多工具可以檢視與修改這些權限。了解權限如何運作是必須的,這可確保使用者能夠存存取它們所需的檔案以及無法不正確的存取供作業系統或其他使用者擁有的檔案。
本節會探討在 FreeBSD 中所用到的傳統 UNIX™ 權限。要做檔案系統存取控制的微調,請參考 存取控制清單。
在 UNIX™,基礎權限透過三種類型的存取來分配:讀取、寫入與執行。這些存取類型用來決定檔案擁有者、群組以及其他人 (其他任何人) 的檔案存取權。讀取、寫入及執行權限可使用 r
, w
, and x
字母來表示。這些權限也可以使用二進位數字來表示每種權限的開或關 (0
)。當以二進位數字來表示時,閱讀的順序為 rwx
,其中 r
開啟的值為 4
,w
開啟的值為 2
以及 x
開啟的值為 1
。
表格 4.1 摘要了可用的數字及可用的字母。當閱讀 "目錄清單標示" 欄位時,-
用來代表該權限設為關閉。
數值 | 權限 | 目錄清單標示 |
---|---|---|
0 | 不可讀取, 不可寫入, 不可執行 |
|
1 | 不可讀取, 不可寫入, 可執行 |
|
2 | 不可讀取, 可寫入, 不可執行 |
|
3 | 不可讀取, 可寫入, 可執行 |
|
4 | 可讀取, 不可寫入, 不可執行 |
|
5 | 可讀取, 不可寫入, 可執行 |
|
6 | 可讀取, 可寫入, 不可執行 |
|
7 | 可讀取, 可寫入, 可執行 |
|
使用 ls(1) 指令時,可以加上 -l
參數, 來檢視詳細的目錄清單。 清單中欄位的資訊包含檔案對所有者、群組及其他人的權限。 在任一個目錄底下執行 ls -l
,會顯示如下的結果:
% ls -l
total 530
-rw-r--r-- 1 root wheel 512 Sep 5 12:31 myfile
-rw-r--r-- 1 root wheel 512 Sep 5 12:31 otherfile
-rw-r--r-- 1 root wheel 7680 Sep 5 12:31 email.txt
第一個 (最左邊) 的字元用來表示這個檔案的類型為何,除標準檔案以外,尚有目錄、特殊字元裝置、Socket 及其他特殊虛擬檔案裝置, 在此例當中,-
表示該檔案為一個標準的檔案。 範例中接下來的三個字元中,rw-
代表所有者對檔案擁有的權限。 再接下來的三個字元, r--
則代表群組對檔案擁有的權限, 最後三個字元,r--
則代表其他人對檔案擁有的權限。 破折號 (-) 表示沒有權限,範例中的這個檔案的權限, 只允許所有者讀取、寫入檔案,群組以及其他人僅能讀取檔案。 根據以上的表格,此種權限的檔案可以使用 644
來表示, 每組數字分別代表檔案的三種權限。
那系統如何控制裝置的權限? 實際上 FreeBSD 對大多的硬碟裝置就如同檔案,程式可以開啟、讀取以及寫入資料如一般檔案。 這些特殊裝置檔案都儲存於 /dev/ 目錄中。
目錄也同如檔案,擁有讀取、寫入及執行的權限, 但在執行權限上與檔案有明顯的差異。 當目錄被標示為可執行時,代表可以使用 cd(1) 指令切換進入該目錄。 也代表能夠存取在此目錄之中的已知檔名的檔案,但仍會受限於檔案本身所設定的權限。
要能夠列出目錄內容,必須擁有目錄的讀取權限。 要刪除已知檔名的檔案,必須擁有檔案所在目錄的寫入 以及 執行的權限。
還有一些權限位元,但這些權限主要在特殊情況使用,如 setuid 執行檔及 sticky 目錄。 如果您還想知道更多檔案權限的資訊及使用方法,請務必參閱 chmod(1)。
3.4.1. 權限符號
權限符號可稱做符號表示,使用字元的方式來取代使用數值來設定檔案或目錄的權限。 符號表示的格式依序為 (某人)(動作)(權限),可使用的符號如下:
項目 | 字母 | 代表意義 |
---|---|---|
(某人) | u | 使用者 |
(某人) | g | 群組所有者 |
(某人) | o | 其他 |
(某人) | a | 全部 ("world") |
(動作) | + | 增加權限 |
(動作) | - | 移除權限 |
(動作) | = | 指定權限 |
(權限) | r | 讀取 |
(權限) | w | 寫入 |
(權限) | x | 執行 |
(權限) | t | Sticky 位元 |
(權限) | s | 設定 UID 或 GID |
如先前同樣使用 chmod(1) 指令來設定,但使用的參數為這些字元。 例如,您可以使用下列指令禁止其他使用者存取檔案 FILE:
% chmod go= FILE
若有兩個以上的權限更改可以使用逗號 (,) 區隔。 例如,下列指令將會移除群組及全部人 ("world") 對檔案 FILE 的寫入權限, 並使全部人對該檔有執行權限:
% chmod go-w,a+x FILE
3.4.2. FreeBSD 檔案旗標
除了前面提到的檔案權限外,FreeBSD 支援使用 "檔案旗標"。 這些旗標增加了檔案的安全性及管理性,但不包含目錄。有了檔案旗標可確保在某些時候 root
不會意外將檔案修改或移除。
修改的檔案 flag 僅需要使用擁有簡易的介面的 chflags(1) 工具。 例如,標示系統禁止刪除的旗標於檔案 file1,使用下列指令:
# chflags sunlink file1
若要移除系統禁止刪除的旗標,只需要簡單在 sunlink
前加上 "no",例如:
# chflags nosunlink file1
使用 ls(1) 及參數 -lo
可檢視檔案目前的旗標:
# ls -lo file1
-rw-r--r-- 1 trhodes trhodes sunlnk 0 Mar 1 05:54 file1
多數的旗標僅能由 root
使用者來標示或移除,而部份旗標可由檔案所有者設定。 我們建議系統管理者可閱讀 chflags(1) 及 chflags(2) 說明以瞭解相關細節。
3.4.3. setuid
、setgid
與 sticky
權限
除了已經探討過的權限外,這裡尚有另外三種特別的設定所有管理者都應該知道,這些設定為 setuid
, setgid
以及 sticky
權限。
這些設定對某些一般不會授權給一般使用者的 UNIX™ 操作非常重要,它讓這些功能可運作。要了解這些權限,就必須說明真實使用者 ID (Real user ID) 與有效使用者 ID (Effective user ID) 的差異。
真實使用者 ID 即是擁有者或啟動程序者的 UID,而有效 UID 是執行程序所使用的使用者 ID。例如,passwd(1) 在使用者更改自己的密碼時會以真實使用者 ID 執行,然而,為了要更新密碼資料庫,該指令必須以 root
使用者做為有效 ID 來執行,這讓使用者可以更改自己的密碼而不會遇到權限不足 (Permission Denied
) 的錯誤。
setuid 權限可以透過在權限集前加上數字 (4) 來設定,如下範例所示:
# chmod 4755 suidexample.sh
現在 suidexample.sh 的權限會如下所示:
-rwsr-xr-x 1 trhodes trhodes 63 Aug 29 06:36 suidexample.sh
注意,s
現在取代了原來的執行位元成為指定檔案擁有者權限集的一部份,這會允許須要提升權限的工具,如 passwd(1) 可正常使用。
mount(8) 的 |
實際來看這個範例,先開啟兩個終端機,其中一個用一般使用者輸入 passwd
。在等待輸入新密碼的同時,檢查程序表並查看 passwd(1) 程序的使用者資訊:
於終端機 A:
Changing local password for trhodes
Old Password:
於終端機 B:
# ps aux | grep passwd
trhodes 5232 0.0 0.2 3420 1608 0 R+ 2:10AM 0:00.00 grep passwd
root 5211 0.0 0.2 3620 1724 2 I+ 2:09AM 0:00.01 passwd
雖然使用一般使用者來執行 passwd(1),但該程序使用了 root
的有效 UID。
setgid
權限的功能與 setuid
相似,當應用程式或工具使用此設定執行時,將會以擁有該檔案的群組來執行,而非執行行該程序的使用者。
要在檔案設定 setgid
權限,需在 chmod(1) 的參數前加上 (2):
# chmod 2755 sgidexample.sh
注意以下清單中,s
現在位於指定群組權限設定的欄位:
-rwxr-sr-x 1 trhodes trhodes 44 Aug 31 01:49 sgidexample.sh
在以上這些範例中,雖然在例子中的 Shell script 是可執行的檔案,但並不會以其他的 EUID 或有效使用者 ID 執行,這是因為 Shell script 並不會存取 setuid(2) 系統呼叫 (System call)。 |
setuid
及 setgid
權限位元可能會因允許提升權限而降低系統的安全性,因此有了第三個特殊的權限:sticky bit
,可以加強系統的安全性。
當在目錄上設定 sticky bit
,將只允許由檔案擁有者刪除檔案。這對避免公開目錄,如 /tmp 中的檔案被不擁有該檔案的人刪除非常有用。要使用這個權限,可在權限集前加上 (1):
# chmod 1777 /tmp
sticky bit
權限會以 t
顯示於權限集的最後:
# ls -al / | grep tmp
drwxrwxrwt 10 root wheel 512 Aug 31 01:49 tmp
3.5. 目錄結構
認識 FreeBSD 的目錄架構,就可對系統有概略的基礎理解。 最重要的莫過於整個目錄的根目錄,就是 "/" 目錄, 該目錄會在開機時最先掛載 (mount),裡面會有開機所會用到必備檔案。 此外,根目錄還有紀錄其他檔案系統的掛載點相關設定。
「掛載點」就是讓新增的檔案系統,能接到上層的檔案系統 (通常就是「根目錄」檔案系統) 的目錄。 在 磁碟組織 這邊對此有更詳細介紹。 標準的掛載點包括了 /usr/, /var/, /tmp/, /mnt/ 以及 /cdrom/。 這些目錄通常會記錄在 /etc/fstab 設定檔內。 /etc/fstab 是記錄各檔案系統及相關掛載點的表格。 大部分在 /etc/fstab 有記錄的檔案系統,會在開機時由 rc(8) Script 來自動掛載,除非它們有設定 noauto
選項。 其中細節說明可參閱 fstab 檔。
有關檔案系統架構的完整說明可參閱 hier(7)。 現在呢,讓我們大致先一窺常見的目錄有哪些吧。
目錄 | 說明 |
---|---|
/ | 檔案系統的根目錄。 |
/bin/ | 單使用者 (Single-user)、多使用者 (Multi-user) 兩種模式皆可使用的基本工具 。 |
/boot/ | 作業系統開機過程會用到的程式、設定檔。 |
/boot/defaults/ | 預設的開機啟動設定檔,詳情請參閱 loader.conf(5)。 |
/dev/ | 裝置節點 (Device node),詳情請參閱 intro(4)。 |
/etc/ | 系統設定檔及一些 Script 檔。 |
/etc/defaults/ | 預設的系統設定檔,詳情請參閱 rc(8)。 |
/etc/mail/ | 郵件傳輸代理程式,像是 sendmail(8) 的相關設定檔。 |
/etc/periodic/ | 每日、每週、每月透過 cron(8),執行的定期排程 Script,詳情請參閱 periodic(8)。 |
/etc/ppp/ | ppp(8) 設定檔。 |
/mnt/ | 系統管理者慣用充當臨時掛載點的空目錄。 |
/proc/ | 程序 (Process) 檔案系統,詳情請參閱 procfs(5) 及 mount_procfs(8)。 |
/rescue/ | 緊急救援用途的一些靜態連結 (Statically linked) 的程式,詳情請參閱 rescue(8)。 |
/root/ |
|
/sbin/ | 供單使用者 (Single-user) 及多使用者 (Multi-user) 環境使用的系統程式及管理工具 。 |
/tmp/ | 臨時檔案。 一般而言,重開機之後 /tmp 內的東西會被清除掉。 而通常會將以記憶體為基礎 (Memory-based) 的檔案系統掛載在 /tmp 上。 這些瑣事可透過 tmpmfs 相關的 rc.conf(5) 環境變數來自動完成 。(或是在 /etc/fstab 內做設定, 詳情請參閱 mdmfs(8))。 |
/usr/ | 主要是使用者所安裝的工具程式、應用程式存放處。 |
/usr/bin/ | 常用工具、開發工具、應用軟體。 |
/usr/include/ | 標準 C include 檔案。 |
/usr/lib/ | 程式庫存放處。 |
/usr/libdata/ | 其他各式工具的資料檔。 |
/usr/libexec/ | 系統 Daemon 及系統工具程式 (透過其他程式來執行)。 |
/usr/local/ | 存放一些自行安裝的執行檔、程式庫等等。 同時,也是 FreeBSD Port 架構的預設安裝目錄。 /usr/local 內的目錄架構大致與 /usr 相同,詳情請參閱 hier(7) 說明。 但 man 目錄例外,它們是直接放在 /usr/local 底下,而非 /usr/local/share,而 Port 所安裝的說明文件則在 share/doc/port。 |
/usr/obj/ | 在編譯 /usr/src 目錄時所產生的相關架構目地檔。 |
/usr/ports/ | FreeBSD Port 套件集 (選用)。 |
/usr/sbin/ | 由使用者執行的系統 Daemon 及系統工具。 |
/usr/shared/ | 各架構皆共通的檔案。 |
/usr/src/ | BSD 原始碼 (或自行新增的)。 |
/var/ | 存放各種用途的日誌 (Log) 檔、臨時或暫時存放、列印或郵件的緩衝 (Spool) 檔案。有時候,以記憶體為基礎 (Memory-based) 的檔案系統也會掛載在 /var。 這些瑣事可透過 varmfs 相關的 rc.conf(5) 環境變數來自動完成。(或是在 /etc/fstab 內做設定,相關細節請參閱 mdmfs(8))。 |
/var/log/ | 各項系統記錄的日誌 (Log) 檔。 |
/var/mail/ | 各使用者的郵件 (Mailbox) 檔案。 |
/var/spool/ | 各種印表機、郵件系統的緩衝 (Spool) 目錄。 |
/var/tmp/ | 臨時檔案。 這些檔案在重開機後通常仍會保留,除非 /var 是屬於以記憶體為基礎 (Memory-based) 的檔案系統。 |
/var/yp/ | NIS 對應表。 |
3.6. 磁碟組織
FreeBSD 用來尋找檔案的最小單位就是檔案的名稱了。 檔案的名稱有大小寫之分,所以說 readme.txt 和 README.TXT 是兩個不同的檔案。 FreeBSD 並不使用副檔名 (.txt) 來判別這是一個程式檔、文件檔或是其他類型的檔案。
檔案存在目錄裡面。 一個目錄中可能沒有任何檔案,也可能有好幾百個檔案。 目錄之中也可以包含其他的目錄; 您可以建立階層式的目錄以便資料的管理。
檔案或目錄的對應是藉由給定的檔案或目錄名稱,然後加上正斜線符號 (/
);之後再視需要加上其他的目錄名稱。 如果您有一個目錄 foo ,裡面有一個目錄叫作 bar,這個目錄中又包含了一個叫 readme.txt 的檔案,那麼這個檔案的全名,或者說檔案的路徑 (Path)就是 foo/bar/readme.txt。注意這與 Windows™ 用來分隔檔案與目錄名稱所使用的 \
不同,且 FreeBSD 在路徑上並不使用磁碟機代號或其他磁碟機名稱,意思是,在 FreeBSD 上不會有人輸入 c:\foo\bar\readme.txt 這種路徑。
目錄及檔案儲存在檔案系統 (File system) 之中。 每個檔案系統都有唯一一個最上層的目錄,叫做根目錄 (Root directory)。 然後在這個根目錄下面才能有其他的目錄。其中一個檔案系統會被指定成為根檔案系統 (Root file system) 或 /
,其他的檔案系統均會掛載 (Mount) 在該根檔案系統之下,不論在 FreeBSD 有多少個磁碟,所有目錄都會成為該磁碟的一部份。
假設您有三個檔案系統,分別叫作 A
, B
及 C
。 每個檔案系統都包含兩個目錄,叫做 A1
, A2
(以此類推得 B1
, B2
及 C1
, C2
)。
稱 A
為主要的檔案系統;如果您用 ls(1) 指令查看此目錄的內容,您會看到兩個子目錄: A1
及 A2
,如下所示:

一個檔案系統必須以目錄形式掛載於另一個檔案系統上。 因此,假設您將 B
掛載於 A1
之上,則 B
的根目錄就變成了 A1
,而在 B
之下的任何目錄的路徑也隨之改變:

在 B1
或 B2
目錄中的任何檔案必須經由路徑 /A1/B1 或 /A1/B2 才能達到。 所有原來在 /A1 中的檔案會暫時被隱藏起來,直到 B
被卸載 (Unmount) 後才會再顯現出來。
如果 B
掛載在 A2
之上,則會變成:

上面的路徑分別為 /A2/B1 及 /A2/B2。
檔案系統可以掛在其他檔案系統的目錄之上。 延續之前的例子,C
檔案系統可以掛在檔案系統 B
的 B1
目錄之上,如圖所示:

或者 C
直接掛載於 A
的 A1
目錄之上:

您可以使用單一的一個大的根檔案系統而不建立其他的檔案系統。 這樣有好處也有有壞處。
不同的檔案系統在掛上的時候可以有不同的 掛載參數 (Mount option)。 舉例來說,為求謹慎您可以將根檔案系統設成唯讀, 以避免不小心刪除或修改掉重要的檔案。 將使用者可寫入的檔案系統 (例如 /home) 獨立出來也可以讓他們用 nosuid 的參數掛載,此選項可以讓在這個檔案系統中執行檔的 suid/guid 位元失效,可讓系統更安全。
FreeBSD 會自動根據您檔案系統的使用方式來做最佳的檔案配置方式。 因此,一個有很多小檔案、 常常寫入的檔案系統跟只有幾個較大的檔案的檔案系統配置是不一樣的。 如果您只有單一個大的檔案系統,這部分就沒用了。
FreeBSD 的檔案系統在停電的時候很穩固。 然而,在某些重要的時候停電仍然會對檔案系統結構造成損害。 分割成許多個檔案系統的話在系統在停電後比較能夠正常啟動, 以便您在需要的時候將備份資料回存回來。
檔案系統的大小是固定的。 若您在當初安裝 FreeBSD 的時指定了一個大小,可是後來您想把空間加大,在沒有備份的情況下很難達成,您必須將檔案系統重新建立為您需要的大小,然後將備份回存回來。
FreeBSD 的 growfs(8) 指令可以突破此限制直接變更檔案系統的大小。
檔案系統放在分區 (Partition) 中。 因為 FreeBSD 承襲 UNIX™ 架構,這邊講的分區和一般提到的分割區 (例如 MS-DOS™ 分割區) 不同。每一個分區由一個代號 (字母) 表示,從 a
到 h
。 每個分區只能含有一個檔案系統,因此在表示檔案系統時,除了用該檔案系統的常用的掛載點表示外,也可以使用該檔案系統所在的分區來表示。
FreeBSD 也會使用磁碟空間作為交換空間 (Swap space) 來提供虛擬記憶體 (Virtual memory)。 這讓您的電腦好像擁有比實際更多的記憶體。 當 FreeBSD 的記憶體用完的時候,它會把一些目前沒用到的資料移到交換空間,然後在用到的時候移回去 (同時移出部份沒用到的)。
有些分割區有特定的使用慣例。
分區 | 慣例 |
---|---|
| 通常含有根檔案系統。 |
| 通常含有交換空間。 |
| 通常用來代表整個切割區 (Slice),因此大小會與其所在的切割區一樣。這可讓需要對整個切割區處理的工具 (例如硬碟壞軌檢查工具) 可在 |
| 分區 |
在 FreeBSD 的磁碟會分割成數個切割區 (Slice),如同 Windows™ 中由編號 1 到 4 表示的分割區。這些切割區會再分成數個分區,每個分區內含檔案系統,且會使用字母來標示。
切割區的編號在裝置名稱後面,會先以 s
為字首,然後從 1 開始編號。 因此 "da0s1" 是指第一個 SCSI 硬碟的第一個切割區。 一個磁碟上只能有四個實體切割區,但是在實體切割區中放進適當類型的邏輯切割區。這些延伸的切割區編號會從 5 開始,所以 "ada0s5" 是第一個 SATA 硬碟上的第一個延伸切割區。因此可以預期這些由檔案系統使用的裝置 (Device) 上均會各別佔據一個切割區。
切割區、"危險專用 (Dangerously dedicated)" 的實體磁碟機以及其他內含分割區 (Partition) 的磁碟都是以字母 a
到 h
來表示。 字母會接在裝置名稱的後面,因此 "da0a" 是第一顆 "dangerously dedicated" 磁碟機 da
上的 a
分割區。 而 "ada1s3e" 則是第二顆 SATA 硬碟上第三個切割區的第五個分區。
終於,我們可以辨識系統上的每個磁碟了,一個磁碟的名稱會有一個代碼來表示這個磁碟的類型,接著是一個表示這是那一個磁碟的編號。不像切割區,磁碟的編號從 0 開始。常見的代碼可以參考 磁碟裝置名稱。
當要參照一個分區的時候,需包含磁碟機名稱、s
、切割區編號以及分區字母。範例可以參考 磁碟、切割區及分區命名範例。
磁碟的概念模型 示範了一個基本的磁碟配置,相信對您有些幫助。
要安裝 FreeBSD,您必須先建置磁碟的切割區,接著於切割區中建立要給 FreeBSD 用的分區。 最後在這些分區中建立檔案系統 (或交換空間) 並決定要將這些檔案系統掛載於哪裡。
磁碟機類型 | 磁碟機裝置稱 |
---|---|
SATA 及 IDE 硬碟 |
|
SCSI 硬碟與 USB 儲存裝置 |
|
SATA 與 IDECD-ROM 光碟機 |
|
SCSICD-ROM 光碟機 |
|
軟碟機 |
|
各種非標準 CD-ROM 光碟機 |
|
SCSI 磁帶機 |
|
IDE 磁帶機 |
|
RAID 磁碟機 | 範例包含 |
名稱 | 意義 |
---|---|
| 第一個 SATA 硬碟 ( |
| 第二個 SCSI 硬碟 ( |
此圖顯示 FreeBSD 中連接到系統的第一個 SATA 磁碟機內部配置圖。 假設這個磁碟的容量是 250 GB,並且包含了一個 80 GB 的切割區及一個 170 GB 的切割區 (MS-DOS™ 的分割區)。 第一個切割區是 Windows™NTFS 檔案系統的 C: 磁碟機,第二個則安裝了 FreeBSD。 本範例中安裝的 FreeBSD 有四個資料分區及一個交換分區。
這四個分區中各有一個檔案系統。 分區 a
是根檔案系統、分區 d
是 /var/、分區 e
是 /tmp/,而分區 f
是 /usr/。分區字母 c
用來代表整個切割區,因此並不作為一般分區使用。

3.7. 掛載與卸載檔案系統
檔案系統就像一顆樹。/ 就像是樹根,而 /dev,/usr 以及其他在根目錄下的目錄就像是樹枝,而這些樹枝上面又還有分支,像是 /usr/local 等。
因為某些原因,我們會將一些目錄分別放在不同的檔案系統上。 如 /var 包含了可能會滿出來的 log/,spool/ 等目錄以及各式各樣的暫存檔。 把根檔案系統塞到滿出來顯然不是個好主意,所以我們往往會比較傾向把 /var 從 / 中拉出來。
另一個常見到把某些目錄放在不同檔案系統上的理由是: 這些檔案在不同的實體或虛擬磁碟機上。 像是網路檔案系統 (Network File System) 詳情可參考 網路檔案系統 (NFS) 或是光碟機。
3.7.1. fstab 檔
在 /etc/fstab 裡面有設定的檔案系統會在開機 (FreeBSD 開機程序) 的過程中自動地被掛載 (除非該檔案系統有被加上 noauto
參數)。檔案內容的格式如下:
device /mount-point fstype options dumpfreq passno
device
已存在的裝置名稱,詳情請參閱 磁碟裝置名稱。
mount-point
檔案系統要掛載到的目錄 (該目錄必須存在)。
fstype
檔案系統類型,這是要傳給 mount(8) 的參數。 FreeBSD 預設的檔案系統是
ufs
。options
可讀可寫 (Read-Write) 的檔案系統用
rw
,而唯讀 (Read-Only) 的檔案系統則是用ro
,後面視需要還可以加其他選項。 常見的選項如noauto
是用在不要於開機過程中自動的掛載的檔案系統。 其他選項可參閱 mount(8) 說明。dumpfreq
dump(8) 由此項目決定那些檔案系統需要傾印。 如果這格空白則以零為預設值。
passno
這個項目決定檔案系統檢查的順序。 對於要跳過檢查的檔案系統,它們的
passno
值要設為零。 根檔案系統的passno
值應設為一 (因為需要比所有其他的還要先檢查),而其他的檔案系統的passno
值應該要設得比一大。 若有多個檔案系統具有相同的passno
值,則 fsck(8) 會試著平行地 (如果可能的話) 檢查這些檔案系統。
更多關於 /etc/fstab 檔案格式及選項的資訊請參閱 fstab(5) 說明文件。
3.7.2. 使用 mount(8)
mount(8) 指令是拿來掛載檔案系統用的。基本的操作指令格式如下:
# mount device mountpoint
在 mount(8) 裡面有提到一大堆的選項,不過最常用的就是這些:
-a
把 /etc/fstab 裡面所有還沒有被掛載、沒有被標記成 /etc/fstab 而且沒有用
-t
排除的檔案系統掛載起來。-d
執行所有的動作,但是不真的去呼叫掛載的系統呼叫 (System call)。 這個選項和
-v
搭配拿來推測 mount(8) 將要做什麼動作時很好用。-f
強迫掛載不乾淨的檔案系統 (危險),或是用來強制取消寫入權限 (把檔案系統的掛載狀態從可存取變成唯讀)。
-r
用唯讀的方式掛載檔案系統。 這個選項和在 -o 選項中指定 ro 參數是一樣的。
-t
fstype用指定的檔案系統型態來掛載指定的檔案系統,或是在有
-a
選項時只掛載指定型態的檔案系統。預設的檔案系統類型為 "ufs"。-u
更新檔案系統的掛載選項。
-v
顯示詳細資訊。
-w
以可讀寫的模式掛載檔案系統。
-o
選項後面會接著以逗號分隔的參數:
- nosuid
不解析檔案系統上的 setuid 或 setgid 旗標, 這也是一個蠻有用的安全選項。
3.8. 程序與 Daemon
FreeBSD 是一個多工的作業系統,也就是說在同一時間內可以跑超過一個程式。 每一個正在花時間跑的程式就叫做程序 (Process)。 您下的每個指令都至少會開啟一個新的程序, 而有些系統程序是一直在跑以維持系統正常運作的。
每一個程序都有一個獨一無二的數字叫做 程序代號 (Process ID, PID),而且就像檔案一樣,每一個程序也有擁有者及群組。 擁有者及群組的資訊是用來決定什麼檔案或裝置是這個程序可以開啟的 (前面有提到過檔案權限)。 大部份的程序都有父程序。 父程序是開啟這個程序的程序,例如:您對 Shell 輸入指令,Shell 本身就是一個程序,而您執行的指令也是程序。 每一個您用這種方式跑的程序的父程序都是 Shell。 有一個特別的程序叫做 init(8) 是個例外,在 FreeBSD 開機的時候 init 會自動地被開啟,init 永遠是第一個程序,所以他的 PID 一直都會是 1
。
有些程式並不是設計成一直在接收使用者的輸入的, 而是在開始執行的時候就從中斷與終端機的連線。 例如說, 網頁伺服器整天都在回應網頁方面的要求,它通常不需要您輸入任何東西。 另外,像是把信從一個站傳送到另一個站的程式,也是這種類型的應用程式。我們把這種程式稱作 Daemon。 Daemon 一詞是來自是希臘神話中的角色:祂們既不屬於善良陣營或邪惡陣營,祂們在背地裡做一些有用的事情。這也就是為何 BSD 的吉祥物,是一隻穿著帆布鞋拿著三叉耙的快樂小惡魔的原因。
通常來說做為 Deamon 執行的程式名字後面都會加一個字母 "d"。 BIND 是 Berkeley Internet Name Domain 的縮寫,但實際上執行的程式名稱是 named
、Apache 網頁伺服器的程式名稱是 httpd
、行列式印表機緩衝服務 (Line Printer Spooling) Daemon 是 lpd
,依此類推。 但這是習慣用法,並沒有硬性規定,例如 Sendmail 主要的寄信 Daemon 是叫做 sendmail
而不是 maild
。
3.8.1. 檢視程序
要看系統執行中的程序,有兩個相當有用的指令可用: ps(1) 以及 top(1)。ps(1) 指令是用來列出正在執行之程序,而且可以顯示它們的 PID、用了多少記憶體、執行的指令名稱及其後之參數是什麼等等。 top(1) 指令則是顯示所有正在執行的程序, 並且數秒鐘更新一次。因此您可以互動式的觀看您的電腦正在做什麼。
在預設的情況下,ps(1) 指令只會顯示使用者所擁有的的程序。 例如:
% ps
PID TT STAT TIME COMMAND
8203 0 Ss 0:00.59 /bin/csh
8895 0 R+ 0:00.00 ps
在這個範例裡可以看到 ps(1) 的輸出分成好幾個欄位。 PID
就是前面有提到的程序代號。 PID
的分配是從 1 開始一直到 99999,如果用完的話又會繞回來重頭開始分配 (若該 PID 已經在用了,則 PID 不會重新分配)。 TT
欄位是指這個程式在哪個 Console (tty) 上執行,在這裡可以先忽略不管。STAT
是程式的狀態,也可以先不要管。TIME
是這個程式在 CPU 上執行的時間—這通常不是程式總共花的時間, 因為當您開始執行程式後,大部份的程式在 CPU 上執行前會先花上不少時間等待 。 最後,COMMAND
是執行這個程式的指令。
有幾個不同的選項組合可以用來變更顯示出來的資訊,其中一個最有用的組合是 auxww
。 a
可以顯示所有正在跑的程序的指令,不只是您自已的。 u
則是顯示程序的擁有者名稱以及記憶體使用情況。 x
可以把 daemon 程序顯示出來, 而 ww
可讓 ps(1) 顯示出每個程序完整的內容, 而不致因過長而被螢幕截掉了。
top(1) 也有類似的輸出。 一般的情況看像是這樣:
% top
last pid: 9609; load averages: 0.56, 0.45, 0.36 up 0+00:20:03 10:21:46
107 processes: 2 running, 104 sleeping, 1 zombie
CPU: 6.2% user, 0.1% nice, 8.2% system, 0.4% interrupt, 85.1% idle
Mem: 541M Active, 450M Inact, 1333M Wired, 4064K Cache, 1498M Free
ARC: 992M Total, 377M MFU, 589M MRU, 250K Anon, 5280K Header, 21M Other
Swap: 2048M Total, 2048M Free
PID USERNAME THR PRI NICE SIZE RES STATE C TIME WCPU COMMAND
557 root 1 -21 r31 136M 42296K select 0 2:20 9.96% Xorg
8198 dru 2 52 0 449M 82736K select 3 0:08 5.96% kdeinit4
8311 dru 27 30 0 1150M 187M uwait 1 1:37 0.98% firefox
431 root 1 20 0 14268K 1728K select 0 0:06 0.98% moused
9551 dru 1 21 0 16600K 2660K CPU3 3 0:01 0.98% top
2357 dru 4 37 0 718M 141M select 0 0:21 0.00% kdeinit4
8705 dru 4 35 0 480M 98M select 2 0:20 0.00% kdeinit4
8076 dru 6 20 0 552M 113M uwait 0 0:12 0.00% soffice.bin
2623 root 1 30 10 12088K 1636K select 3 0:09 0.00% powerd
2338 dru 1 20 0 440M 84532K select 1 0:06 0.00% kwin
1427 dru 5 22 0 605M 86412K select 1 0:05 0.00% kdeinit4
輸出的資訊分成兩個部份。開頭 (前五行或六行) 顯示出最近一個程序的 PID、系統平均負載 (系統忙磁程度評估方式)、系統的開機時間 (自上次重新開機) 以及現在的時間等。 在開頭裡面的其他數字分別是在講有多少程序正在執行、有多少記憶體及交換空間被占用了,還有就是系統分別花了多少時間在不同的 CPU 狀態上。若有載入 ZFS 檔案系統模組,會有一行 ARC
標示有多少資料從磁碟改由記憶體快取中取得。
接下來的部份是由好幾個欄位所構成,和 ps(1) 輸出的資訊類似。 就如同前例,您可以看到 PID、使用者名稱、CPU 花費的時間以及正在執行的指令。 top(1) 在預設的情況下還會告訴您程序用掉了多少的記憶體空間。 在這邊會分成兩欄,一個是總用量 (Total size),另一個是實際用量 (Resident size)----總用量是指這個應用程式需要的記憶體空間,而實際用量則是指目前實際上該程式的記憶體使用量。
top(1) 每隔 2 秒鐘會自動更新顯示內容,可用 -s
選項來改變間隔的時間。
3.8.2. 終止程序
要與執行中的程序或 Daemon 溝通唯一的方法是透過 kill(1) 指令傳送信號 (Signal)。 信號有很多種,有些有特定的意義,有些則是會由應用程式來解讀,應用程式的說明文件會告訴您該程式是如何解讀信號。 使用者只能送信號給自己所擁有的程序,送信號給其他人的程序會出現權限不足的錯誤。 唯一的例外是 root
使用者,他可以送信號給任何人的程序。
作業系統在某些情況也會送信號給應用程式。 假設有個應用程式寫得不好,企圖要存取它不該碰的記憶體的時候,FreeBSD 會送一個 "Segmentation Violation" 信號 (SIGSEGV
) 給這個程序。 如果有一個應用程式用了 alarm(3) 的系統呼叫 (System call) 要求系統在過一段時間之後發出通知,時間到了的時候系統就會發出"通知"信號 (SIGALRM
) 給該程式。
SIGTERM
與 SIGKILL
這兩個信號可以拿來終止程序。 用 SIGTERM
結束程序是比較有禮貌的方式,該程序收到信號後可以把自已所使用的日誌檔關閉及其他要在結束前要做的事完成, 然後在關掉程序之前結束掉手邊的工作。 在某些情況下程序有可能會忽略 SIGTERM
,如它正在做一些不能中斷的工作的話。
SIGKILL
就沒有辦法被程序忽略。 傳送 SIGKILL
信號給程序通常會將程序直接中止。
其他常用的信號有:SIGHUP
, SIGUSR1
及 SIGUSR2
。 這些是通用的信號,對不同的應用程式會有不同的反應。
舉例來說,當您更動了網頁伺服器的設定檔,您想要叫網頁伺服器去重新讀取設定。 重新啟動 httpd
會造成網頁伺服器暫停服務一段時間,我們可以傳送 SIGHUP
信號來取代關掉重開。 不同的 Daemon 會有不同的行為,所以使用前請先參考 Deamon 的說明文件查看是否可以達到想要的結果。
Procedure: 送信號給程序
使用 pgrep(1) 來查詢要傳送信號的目標程序。 在這個例子中 inetd(8) 的 PID 為 198:
% pgrep -l inetd 198 inetd -wW
使用 kill(1) 來發送信號。因為 inetd(8) 是
root
所有,因此必須先用 su(1) 切換成root
先。% su Password: # /bin/kill -s HUP 198
對大多數 UNIX™ 指令來講,kill(1) 執行成功時並不會輸出任何訊息。 假設您送一個信號給某個不是使用者所擁有的程序, 那麼就會顯示這個錯誤訊息:
kill: PID: Operation not permitted
。 若打錯 PID 的話,那就會把信號送給錯誤的程序,並把該程序關閉,或者是把信號送給一個非使用中的 PID,那您就會看到錯誤:kill: PID: No such process
。為何要使用/bin/kill
?多數 Shell 都有提供內建的
kill
指令。 也就是說這種 shell 會直接發送信號,而不是執行 /bin/kill。 但要小心不同的 shell 會有不同的語法來指定信號的名稱等。 與其嘗試去把它們通通學會,不如就單純的直接用/bin/kill
。
要送其他的信號的話也是非常類似,就視需要把指令中的 TERM
或 KILL
替換成其他信號的名稱即可。
3.9. Shell
Shell 提供了指令列介面可用來與作業系統互動,Shell 負責從輸入的頻道接收指令並執行它們。 多數 Shell 也內建一些有助於日常工作的功能,像是檔案管理、檔案搜尋、指令列編輯、指令巨集以及環境變數等。 FreeBSD 有內附了幾個 Shell,包含 Bourne Shell (sh(1)),與改良版的 C-shell (tcsh(1))。 還有許多其他的 Shell 可以從 FreeBSD Port 套件集中取得,像是 zsh
以及 bash
等。
要用哪個 Shell 牽涉到每個人的喜好。 如果您是一個 C 程式設計師,那對於使用像是 tcsh(1) 這種 C-like 的 shell 可能會感到較容易上手。 如果是 Linux™ 的使用者,那您也許會想要用 bash
。 每一個 Shell 都有自已獨特之處,至於這些特點能不能符合使用者的喜好,就是您選擇 shell 的重點了。
常見的 Shell 功能之一就是檔名自動補齊。 首先輸入指令或檔案的前幾個字母,然後按下 Tab 鍵,Shell 就會自動把指令或是檔案名稱剩餘的部份補齊。 假設您有兩個檔案分別叫作 foobar 及 football。 要刪掉 foobar,那麼可以輸入 rm foo
然後按下 Tab 來補齊檔名。
但 Shell 只顯示了 rm foo
,這代表它沒有辦法完全自動補齊檔名,因為有不只一個檔名符合條件。 foobar 和 football 都是 foo
開頭的檔名。 有一些 Shell 會有嗶的音效或者顯示所有符符條件的檔名。 使用者只需要多打幾個字元來分辦想要的檔名。 輸入 t
然後再按 Tab 一次,那 Shell 就能夠替您把剩下的檔名填滿了。
Shell 的另一項特點是使用了環境變數。 環境變數是以變數與鍵值 (Variable/Key) 的對應關係儲存於 Shell 的環境,任何由該 Shell 所產生的程序都可以讀取此環境變數, 因此環境變數儲存了許多程序的設定。 常用環境變數 提供了常見的環境變數與其涵義的清單。 請注意環境變數的名稱永遠以大寫表示。
變數 | 說明 |
---|---|
| 目前登入的使用者名稱。 |
| 以冒號 (:) 隔開的目錄列表,用以搜尋執行檔的路徑。 |
| 若存在這個環境變數,則代表 Xorg 顯示器的網路名稱。 |
| 目前使用的 Shell。 |
| 使用者終端機類型的名稱,用來判斷終端機有那些功能。 |
| 用來執行各種終端機功能的終端機跳脫碼 (Terminal escape code) 的資料庫項目。 |
| 作業系統的類型。 |
| 系統的 CPU 架構。 |
| 使用者偏好的文字編輯器。 |
| 使用者偏好的文字分頁檢視工具。 |
| 以冒號 (:) 隔開的目錄列表,用以搜尋使用手冊的路徑。 |
在不同的 Shell 底下設定環境變數的方式也有所不同。 在 tcsh(1) 和 csh(1),使用 setenv
來設定環境變數。 在 sh(1) 和 bash
則使用 export
來設定目前環境的變數。 以下範例將 tcsh(1) Shell 下的 EDITOR
環境變數從預設值更改為 /usr/local/bin/emacs:
% setenv EDITOR /usr/local/bin/emacs
相同功能的指令在 bash
下則是:
% export EDITOR="/usr/local/bin/emacs"
要展開以顯示目前環境變數中的值,只要在指令列輸入環境變數之前加上 $
字元。 舉例來說,echo $TERM
會顯示出目前 $TERM
的設定值。
Shell 中有特殊字元用來表示特殊資料,我們將其稱作 Meta-character。 其中最常見的 Meta-character 是 *
字元,它代表了檔名中的任意字元。 Meta-character 可以用在搜尋檔名,舉例來說,輸入 echo *
會和輸入 ls
得到幾乎相同的結果,這是因為 shell 會將所有符合 *
字元的檔案由 echo
顯示出來。
為了避免 Shell 轉譯這些特殊字元,我們可以在這些特殊字元前放一個反斜線 (\
) 字元使他們跳脫 (Escape) Shell 的轉譯。舉例來說,echo $TERM
會印出你目前終端機的設定, echo \$TERM
則會直接印出 $TERM
這幾個字。
3.9.1. 變更 Shell
永久變更 Shell 最簡單的方法就是透過 chsh
指令。 執行 chsh
將會使用環境變數中 EDITOR
指定的文字編輯器,如果沒有設定,則預設是 vi(1)。 請修改 Shell:
為新的 Shell 的完整路徑。
或者,使用 chsh -s
, 來直接設定 Shell 而不開啟文字編輯器。 例如, 假設想把 Shell 更改為 bash
:
% chsh -s /usr/local/bin/bash
新的 Shell 必須已列於 /etc/shells 裡頭。 若是依 安裝應用程式:套件與 Port 說明由 Port 套件集來裝的 Shell, 那就會自動列入至該檔案裡。 若仍缺少,請使用以下指令加入檔案 (請將路徑替換為新的 Shell 的路徑):
然後重新執行 chsh(1)。 |
3.9.2. 進階 Shell 技巧
UNIX™ Shell 不只是指令的直譯器,它是一個強大的工具可讓使用者執行指令、重新導向指令的輸出、重新導向指令的輸入並將指令串連在一起來改進最終指令的輸出結果。當這個功能與內建的指令混合使用時,可提供一個可以最佳化效率的環境給使用者。
Shell 重新導向是將一個指令的輸出或輸入傳送給另一個指令或檔案。例如,要擷取 ls(1) 指令的輸出到一個檔案,可以重新導向輸出:
% ls > directory_listing.txt
目錄的內容現在會列到 directory_listing.txt 中,部份指令可以讀取輸入,例如 sort(1)。要排序這個清單,可重新導向輸入:
% sort < directory_listing.txt
輸入的內容會被排序後呈現在畫面上,要重新導向該輸入到另一個檔案,可以重新導向 sort(1) 的出輸:
% sort < directory_listing.txt > sorted.txt
於上述所有的範例中,指令會透過檔案描述符 (File descriptor) 來執行重新導向。每個 UNIX™ 系統都有檔案描述符,其中包含了標準輸入 (stdin)、標準輸出 (stdout) 以及標準錯誤 (stderr)。每一種檔案描述符都有特定的用途,輸入可能來自鍵盤或滑鼠、任何可能提供輸入的來源,輸出則可能是螢幕或印表機中的紙張,而錯誤則為任何可能用來診斷的資訊或錯誤訊息。這三種皆被認為是以 I/O 為基礎的檔案描述符,有些也會被當做串流。
透過使用這些檔案描述符,Shell 能夠讓輸出與輸入在各種指令間傳遞與重新導向到或自檔案。另一種重新導向的方式是使用管線運算子 (Pipe operator)。
UNIX™ 的管線運算子,即 "|",可允許指令的輸出可直接傳遞或導向到另一個程式。基本上,管線運算子允許指令的標準輸出以標準輸入傳遞給另一個指令,例如:
% cat directory_listing.txt | sort | less
在這個例子中,directory_listing.txt 的內容會被排序然後輸出傳遞給 less(1),這可讓使用者依自己的閱讀步調捲動輸出的結果,避免結果直接捲動出畫面。
3.10. 文字編輯器
在 FreeBSD 中有許多設定必須透過編輯文字檔完成。 因此,若能熟悉文字編輯器是再好不過的。 FreeBSD 本身就內建幾種文字編輯器, 您也可以透過 Port 套件集來安裝其他的文字編輯器。
最簡單易學的文字編輯器叫做 ee(1),意為簡易的編輯器 (Easy Editor)。 要開始使用這個編輯器, 只需輸入 ee filename
,其中 filename 代表你想要編輯的檔案名稱。 在編輯器中, 所有編輯器的功能與操作都顯示在螢幕的上方。 其中的插入符號 (^
) 代表鍵盤上的 Ctrl 鍵,所以 ^e
代表的是 Ctrl+e。 若要結束 ee(1),請按下 Esc 鍵,接著選擇 "leave editor" 即可。 此時如果該檔案有修改過,編輯器會提醒你是否要存檔。
FreeBSD 同時也內建功能強大的文字編輯器,像是vi(1)。 其他編輯器如 editors/emacs 及 editors/vim 則由 FreeBSD Port 套件集提供。 這些編輯器提供更強的功能,但是也比較難學習。 長期來看學習 vim 或 Emacs 會在日後為您省下更多的時間。
有許多應用程式在修改檔案或需要輸入時會自動開啟文字編輯器,要更改預設的編輯器可設定 EDITOR
環境變數如 Shell 所說明。
3.11. 裝置及裝置節點
裝置 (Device) 一詞大多是跟硬體比較有關的術語,包括磁碟、印表機、顯示卡和鍵盤。 FreeBSD 開機過程當中,開機訊息 (Boot Message) 中主要是會列出偵測到的硬體裝置,開機訊息的複本也會存放在 /var/run/dmesg.boot。
每一個裝置都有一個裝置名稱及編號,舉例來說 ada0 是第一台 SATA 硬碟,而 kbd0 則代表鍵盤。
在 FreeBSD 中大多數的裝置必須透過裝置節點 (Device Node) 的特殊檔案來存取,這些檔案會放置在 /dev。
3.12. 操作手冊
在 FreeBSD 中,最詳細的文件莫過於操作手冊。 幾乎在系統上所有程式都會有簡短的操作手冊來介紹該程式的基本操作以及可用的參數。 這些操作手冊可以使用 man
指令來檢視:
% man command
其中 command 想要瞭解指令的名稱。 舉例,要知道 ls(1) 的詳細用法,就可以打:
% man ls
操作手冊被分成很多個章節,每個章節有不同的主題。 在 FreeBSD 中操作手冊有以下章節:
使用者指令。
系統呼叫 (System call) 與錯誤編號。
C 程式庫函數。
裝置驅動程式。
檔案格式。
遊戲及其他程式。
其他資訊。
系統維護與操作指令。
系統核心介面。
有些情況會有同樣主題會同時出現在不同章節。 舉個例子,系統內會有 chmod
使用者指令,但同時也有 chmod()
系統呼叫。 在這種情況,要告訴 man(1) 要查詢的章節編號:
% man 1 chmod
若不曉得操作手冊的名稱,可以使用 man -k
來以關鍵字查詢所有操作手冊的描述:
% man -k mail
這個指令會顯示所有描述中有使用到關鍵字 "mail" 的指令。 這等同使用 apropos(1)。
想要閱讀所有在 /usr/bin 底下的指令說明則可輸入:
% cd /usr/bin
% man -f * | more
或
% cd /usr/bin
% whatis * |more
3.12.1. GNU Info 檔
FreeBSD 有許多應用程式與工具來自自由軟體基金會 (Free Software Foundation, FSF)。 除了操作手冊之外,這些程式提供了另外一種更具有彈性的超文字文件叫做 info
檔。 這些檔案可以使用 info(1) 指令來閱讀,或者若有裝 editors/emacs 亦可透過 emacs 的 info 模式閱讀。
要使用 info(1) 指令,只需輸入:
% info
要查詢簡單說明請按 h
鍵,若要查訊快速指令參考請按 ?
鍵。
Chapter 4. 安裝應用程式:套件與 Port
4.1. 概述
FreeBSD 內建豐富的系統工具集,此外 FreeBSD 提供了兩種安裝第三方軟體的套件管理技術︰由原始碼安裝的 FreeBSD Port 套件集,以及由預先編譯好的 Binary 安裝的 Binary 套件集。兩種方法都可使用本地的媒體或網路來安裝軟體。
讀完這章,您將了解:
Binary 套件集與 Port 的差別。
如何找到已移植到 FreeBSD 的第三方軟體。
如何使用 pkg 管理 Binary 套件。
如何編譯來自 Port 套件集的第三方軟體原始碼。
如何找到應用程式已安裝的檔案來完成安裝後的設定。
若軟體安裝失敗要如何處理。
4.2. 安裝軟體的概要
通常要在 UNIX™ 系統上安裝第三方軟體時,有幾個步驟要作:
找到並且下載軟體,該軟體有可能以原始碼或 Binary 格式發佈。
自發佈的格式解壓縮軟體。 發佈的格式通常為 tarball 並以程式壓縮,如 compress(1), gzip(1), bzip2(1) 或 xz(1)。
找到位於 INSTALL, README 或者 doc/ 子目錄底下的檔案閱讀如何安裝該軟體。
若軟體是以原始碼的格式發佈則需要編譯該軟體。 這可能會需要修改 Makefile 或執行
configure
Script。測試並安裝該軟體。
FreeBSD Port 是指設計用來自動化從原始碼編譯應用程式整個程序的一系列檔案,組成 Port 的檔案包含了自動下載、解壓縮、修補、編譯與安裝應用程式的必要資訊。
若軟體尚未被 FreeBSD 採用並測試,可能會需要經過一些修正才能正常安裝並執行。
雖然如此,目前已有超過 24,000 個第三方應用程式已經被移植到 FreeBSD。當可行時,這些應用程式也會做成預先編譯好的 套件 (Package) 供下載。
這些 Binary 套件可使用 FreeBSD 套件管理指令來管理。
不論是 Binary 套件或者 Port 都有相依性,若用 Binary 套件或 Port 來安裝應用程式,且該應用程式若有相依的程式庫尚未被安裝,則會自動先安裝該程式庫。
FreeBSD Binary 套件中含有一個應用程式中所有預先編譯好的指令、設定檔以及文件,Binary 套件可以使用 pkg(8) 指令來管理,如 pkg install
。
雖然兩種技術非常相似,但 Binary 套件及 Port 有各自的優點。 要視您要安裝的應用程式需求來選擇。
應用程式壓縮 Binary 套件的 tarball 會比壓縮原始碼的 tarball 還要小。
安裝 Binary 套件不需要編譯的時間,對於較慢的電腦要安裝大型的應用程式如 Mozilla, KDE 或 GNOME 這點顯的相當重要。
Binary 套件不需要了解在 FreeBSD 上編譯軟體的流程。
由於 Binary 套件必須盡可能在大多數系統上執行,通常會採用較通用的編譯選項來編譯,由 Port 來編輯可更改編譯選項。
部份應用程式編譯期選項會與要安裝的功能有關,舉例來說 Apache 便有大量不同的內建選項可以設定。
在某些情況,同樣的應用程式會存在多個不同的 Binary 套件,如 Ghostscript 有 ghostscript 及 ghostscript-nox11 兩種 Binary 套件,用來區別是否有安裝 Xorg。 若應用程式有一個以上的編譯期選項便無法用這個方式來區別 Binary 套件。
部份軟體的授權條款中禁止以 Binary 格式發佈。 這種軟體必須以原始碼發佈並由終端使用者編譯。
部份人並不相信 Binary 發佈版本,寧願閱讀原始碼來查看是否潛藏的問題。
原始碼可套用自訂的修補。
要持續追蹤 Port 的更新可以訂閱 FreeBSD Port 郵遞論壇 與 FreeBSD Port 問題郵遞論壇。
在安裝任何應用程式之前,請先查看 https://vuxml.freebsd.org/ 是否有與該應用程式相關的安全性問題或輸入 |
本章接下來的部份將說明如何在 FreeBSD 使用 Binary 套件及 Port 套件安裝與管理第三方軟體。
4.3. 搜尋軟體
FreeBSD 上可安裝的軟體清單不斷在增加, 有幾種方式可以來找你想安裝的軟體:
FreeBSD 網站有維護一份可搜尋的最新應用程式清單,在 https://www.FreeBSD.org/ports/。 可以依應用程式名稱或軟體分類來搜尋 Port。 *
由 Dan Langille 維護的 FreshPorts.org,提供完整的搜尋工具並且可追蹤在 Port 套件集中的應用程式變更。註冊的使用者可以建立自訂的監視清單會自動寄發電子郵件通知 Port 的更新資訊。 *
若找不到指定的應用程式,可以先到網站 SourceForge.net 或 GitHub.com 搜尋,後然再回到 FreeBSD 網站 檢查該應用程式是否已被移植。 *
要搜尋 Binary 套件檔案庫中的應用程式可:
# pkg search subversion git-subversion-1.9.2 java-subversion-1.8.8_2 p5-subversion-1.8.8_2 py27-hgsubversion-1.6 py27-subversion-1.8.8_2 ruby-subversion-1.8.8_2 subversion-1.8.8_2 subversion-book-4515 subversion-static-1.8.8_2 subversion16-1.6.23_4 subversion17-1.7.16_2
套件名稱包含版本編號,且若 Port 使用 Python 為基礎,也會包含用來編譯該套件的 Python 版本。有些 Port 會有多個版本可使用,如 Subversion ,因編譯選項不同,有多個版本可用,這個例子中即指靜態連結版本的 Subversion。在指定要安裝的套件時,最好使用 Port 來源來指定該應用程式,Port 來源是指應用程式在 Port 樹中的路徑。再輸入一次
pkg search
並加上-o
來列出每個套件來源:# pkg search -o subversion devel/git-subversion java/java-subversion devel/p5-subversion devel/py-hgsubversion devel/py-subversion devel/ruby-subversion devel/subversion16 devel/subversion17 devel/subversion devel/subversion-book devel/subversion-static
pkg search
支援使用 Shell 萬手字元 (globs)、正規表示法、描述或檔案庫中的其他其他內容。在安裝 ports-mgmt/pkg 或 ports-mgmt/pkg-devel 之後,可參考 pkg-search(8) 以取得更多詳細資訊。若 Port 套件集已安裝,有數個方法可以查詢 Port 樹中的本地版本。要找到 Port 所在的分類,可輸入
whereis file
,其中 file 是要安裝的程式:# whereis lsof lsof: /usr/ports/sysutils/lsof
或者,也可使用 echo(1):
# echo /usr/ports/*/*lsof* /usr/ports/sysutils/lsof
請注意,這也會顯示已下載至 /usr/ports/distfiles 目錄中任何已符合條件的檔案。
另一個方法是使用 Port 套件集內建的搜尋機制來找軟體。要使用搜尋的功能需先 cd 到 /usr/ports 然後執行
make search name=program-name
,其中 program-name 代表軟體的名稱。舉例搜尋lsof
:# cd /usr/ports # make search name=lsof Port: lsof-4.88.d,8 Path: /usr/ports/sysutils/lsof Info: Lists information about open files (similar to fstat(1)) Maint: ler@lerctr.org Index: sysutils B-deps: R-deps:
內建的搜尋機制會使用索引檔內的資訊。若出現訊息指出需要 INDEX 檔,可執行
make fetchindex
來下載最新的索引檔。當 INDEX 檔存在時,make search
方可執行請求的搜尋動作。"Path:" 此行代表 Port 的所在位置。
若不要接受這麼多資訊,可使用
quicksearch
功能:# cd /usr/ports # make quicksearch name=lsof Port: lsof-4.88.d,8 Path: /usr/ports/sysutils/lsof Info: Lists information about open files (similar to fstat(1))
若要進行更有深度的搜尋,使用
make search key=string
或make quicksearch key=string
其中 string 是要搜尋的文字。該文字可以是一部份的註解、描述或相依套件,當不清楚程式的名稱時可以找到與特定主題相關的 Port。當使用
search
或quicksearch
時,搜尋的字串不分大小寫。 搜尋 "LSOF" 會與搜尋 "lsof" 產生相同的結果。
4.4. 使用 pkg 管理 Binary 套件
pkg 是新一代套件管理工具用來取代舊版工具,提供許多功能讓處理 Binary 套件更快更簡單。
對於只想要使用在 FreeBSD 鏡像站上預先編譯 Binary 套件的站台,使用 pkg 管理套件便已足夠。
但是,對於那些想要從原始碼或使用自己的檔案庫編譯的站台,則會需要 Port 管理工具。
因為 pkg 僅能管理 Binary 套件,所以不能當做為替代 Port 管理工具,這些工具可用來安裝來自 Binary 與 Port 套件集的軟體,而 pkg 僅能安裝 Binary 套件。
4.4.1. 開始使用 pkg
FreeBSD 內建啟動 (Bootstrap) 工具可用來下載並安裝 pkg 及其操作手冊。這個工具是設計在 FreeBSD 版本 10.X 之後使用。
不是所有 FreeBSD 版本及架構支援此啟動程序,目前支援的清單列於 https://pkg.freebsd.org/,對不支援的版本,必須改透過 Port 套件集或者 Binary 套件來安裝 pkg。 |
要啟動 (Bootstrap) 系統請執行:
# /usr/sbin/pkg
您必須有可用的網際網路連線供啟動程式使用方可成功。
否則,要安裝 Port 套件,則須執行:
# cd /usr/ports/ports-mgmt/pkg
# make
# make install clean
當升級原使用舊版 pkg_* 工具的既有系統時,必須將資料庫轉換成新的格式,如此新的工具才會知道有那些已安裝過的套件。pkg 安裝完後,必須執行以下指令將套件資料庫從舊版格式轉換到新版格式:
# pkg2ng
新安裝的版本因尚未安裝任何第三方軟體因此不須做這個步驟。 |
這個步驟無法還原。一旦套件資料庫轉為成 pkg 的格式,舊版 |
套件資料庫轉換的過程可能會因內容轉換為新版本產生錯誤。通常,這些錯誤皆可安全忽略,即使如此,仍然有在執行 |
為了確保 FreeBSD Port 套件集會將新軟體的資訊註冊到 pkg 而非舊版套件資料庫,FreeBSD 版本 10.X 之前需要在 /etc/make.conf 加入此行:
WITH_PKGNG= yes
預設 pkg 會使用 FreeBSD 套件鏡像站 (Repository) 的 Binary 套件。若要取得有關編譯自訂套件檔案庫的資訊,請參考 使用 Poudriere 編譯套件。
其他 pkg 設定選項說明請參考 pkg.conf(5)。
pkg 的用法資訊可在 pkg(8) 操作手冊或不加任何參數執行 pkg
來取得。
每個 pkg 指令參數皆記庫在指令操件手冊。要閱讀 pkg install
的操作手冊,可執行以下指令:
# pkg help install
# man pkg-install
本章節剩餘的部份將會示範使用 pkg 執行常用的 Binary 套件管理工作。每個示範的指令皆會提供多個參數可使用,請參考指令的說明或操作手冊以取得詳細資訊或更多範例。
4.4.2. 取得有關已安裝套件的資訊
有關已安裝在系統的套件資訊可透過執行 pkg info
來檢視,若執行時未指定任何參數,將會列出所有已安裝或指定的套件版本。
例如,要查看已安裝的 pkg 版本可執行:
# pkg info pkg
pkg-1.1.4_1
4.4.3. 安裝與移除套件
要安裝 Binary 套件可使用以下指令,其中 packagename 為要安裝的套件名稱:
# pkg install packagename
這個指令會使用檔案庫的資料來決定要安裝的軟體版本以及是否有任何未安裝的相依。例如,要安裝 curl:
# pkg install curl
Updating repository catalogue
/usr/local/tmp/All/curl-7.31.0_1.txz 100% of 1181 kB 1380 kBps 00m01s
/usr/local/tmp/All/ca_root_nss-3.15.1_1.txz 100% of 288 kB 1700 kBps 00m00s
Updating repository catalogue
The following 2 packages will be installed:
Installing ca_root_nss: 3.15.1_1
Installing curl: 7.31.0_1
The installation will require 3 MB more space
0 B to be downloaded
Proceed with installing packages [y/N]: y
Checking integrity... done
[1/2] Installing ca_root_nss-3.15.1_1... done
[2/2] Installing curl-7.31.0_1... done
Cleaning up cache files...Done
新的套件以及任何做為相依安裝的額外套件可在已安裝的套件清單中看到:
# pkg info
ca_root_nss-3.15.1_1 The root certificate bundle from the Mozilla Project
curl-7.31.0_1 Non-interactive tool to get files from FTP, GOPHER, HTTP(S) servers
pkg-1.1.4_6 New generation package manager
不再需要的套件可以使用 pkg delete
來移除,例如:
# pkg delete curl
The following packages will be deleted:
curl-7.31.0_1
The deletion will free 3 MB
Proceed with deleting packages [y/N]: y
[1/1] Deleting curl-7.31.0_1... done
4.4.5. 稽查已安裝套件
在第三方的應用程式中偶爾可能會發現軟體漏洞,要找出這些程式,可使用 pkg 內建的稽查機制。要查詢已安裝在系統上的軟體是否有任何已知的漏洞可執行:
# pkg audit -F
4.4.6. 自動移除未使用的套件
移除一個套件可能會留下不再需要使用的相依套件。不再需要的相依套件是當初隨著其套件所安裝的套件 (枝葉套件),可以使用以下指令自動偵測並移除:
# pkg autoremove
Packages to be autoremoved:
ca_root_nss-3.15.1_1
The autoremoval will free 723 kB
Proceed with autoremoval of packages [y/N]: y
Deinstalling ca_root_nss-3.15.1_1... done
因為相依所安裝的套件稱作 自動 (Automatic) 套件,而非自動套件即套件被安裝的原因不是因為其他套件所相依,可以使用以下方式查詢:
# pkg prime-list
nginx
openvpn
sudo
pkg prime-list
是一個別名指令,定義在 /usr/local/etc/pkg.conf,尚還有許多其他相關指令可以用來查詢系統的套件資料庫,例如,指令 pkg prime-origins
可用來取得上述清單的來源 Port 目錄:
# pkg prime-origins
www/nginx
security/openvpn
security/sudo
這份清單可以用來重新編譯所有安裝在系統中的套件,使用 ports-mgmt/poudriere 或 ports-mgmt/synth 這類的編譯工具。
要將一個安裝好的套件註記成為 "自動" 可以用:
# pkg set -A 1 devel/cmake
當套件為末端套件 (Leaf Package) 且被註記為 "自動",則會被 pkg autoremove
挑選出來。
要註記一個安裝好的套件為 "非自動" 可以用:
# pkg set -A 0 devel/cmake
4.4.7. 還原套件資料庫
不如傳統的套件管理系統,pkg 有自己的套件資料庫備份機制,此功能預設是開啟的。
要停止週期的 Script 備份套件資料庫可在 periodic.conf(5) 設定 |
要還原先前套件資料庫的備份,可執行以下指令並將 /path/to/pkg.sql 替換為備份的位置:
# pkg backup -r /path/to/pkg.sql
若要還原有週期 Script 所產生的備份必須在還原前先解壓縮。 |
要手動備份 pkg 資料庫,可執行以下指令,並替換 /path/to/pkg.sql 為適當的檔案名稱與位置:
# pkg backup -d /path/to/pkg.sql
4.4.8. 移除過時的套件
預設 pkg 會儲存 Binary 套件在快取目錄定義在 pkg.conf(5) 中的 PKG_CACHEDIR
,只會保留最後安裝的套件複本。較舊版的 pkg 會保留所有先前的套件,若要移除這些過時的 Binary 套件,可執行:
# pkg clean
使用以下指令可清空全部的快取:
# pkg clean -a
4.4.9. 修改套件 Metadata
在 FreeBSD Port 套件集中的軟體可能會經歷主要版號的修改,要解決這個問題可使用 pkg 內建的指令來更新套件來源。這非常有用,例如 lang/php5 重新命名為 lang/php53 因此 lang/php5 從此之後代表版本 5.4
。
要更改上述例子中的套件來源,可執行:
# pkg set -o lang/php5:lang/php53
再一個例子,要更新 lang/ruby18 為 lang/ruby19,可執行:
# pkg set -o lang/ruby18:lang/ruby19
最後一個例子,要更改 libglut 共用程式庫的來源從 graphics/libglut 改成 graphics/freeglut 可執行:
# pkg set -o graphics/libglut:graphics/freeglut
在更改套件來源之後,很重要的一件事是要重新安裝套件,來讓相依的套件也同時使用修改後的來源。要強制重新安裝相依套件,可執行:
|
4.5. 使用 Port 套件集
Port 套件集是指一數個 Makefiles、修補及描述檔案,每一組這些檔案可用來編譯與安裝在 FreeBSD 上的一個應用程式,即稱為一個 Port。
預設,Port 套件集儲存在 /usr/ports 的子目錄下。
在應用程式可以使用 Port 編譯之前,必須先安裝 Port 套件集。若在安裝 FreeBSD 時沒有安裝,可以使用以下其中一種方式安裝:
Procedure: Portsnap 方法
FreeBSD 的基礎系統內含 Portsnap,這是一個可用來取得 Port 套件集簡單又快速的工具,較建議多數使用者使用這個方式。此工具會連線到 FreeBSD 的網站,驗証密鑰,然後下載 Port 套件集的新複本。該金鑰是要用來檢驗所有已下載檔案的完整性。
要下載壓縮後的 Port 套件集快照 (Snapshot) 到 /var/db/portsnap:
# portsnap fetch
當第一次執行 Portsnap 時,要先解壓縮快照到 /usr/ports:
# portsnap extract
在完成上述第一次使用 Portsnap 的動作之後,往後可隨需要執行以下指令來更新 /usr/ports :
# portsnap fetch # portsnap update
當使用
fetch
時也可同時執行extract
或update
如:# portsnap fetch update
Procedure: Subversion 方法
若要取得更多對 Port 樹的控制,或若有本地的變更需要維護,可以使用 Subversion 來取得 Port 套件集。請參考 Subversion Primer 來取得 Subversion 的詳細說明。
必須安裝 Subversion 才可用來取出 (Check out) Port 樹。若已存在 Port 樹的複本,可使用此方式安裝 Subversion:
# cd /usr/ports/devel/subversion # make install clean
若尚無法使用 Port 樹,或已經使用 pkg 來管理套件,可使用套件來安裝 Subversion:
# pkg install subversion
取出 Port 樹的複本:
# svn checkout https://svn.FreeBSD.org/ports/head /usr/ports
若需要,在第一次 Subversion 取出後可使用以下指令更新 /usr/ports:
# svn update /usr/ports
Port 套件集中含有代表不同軟體分類的目錄,每個分類底下的子目錄代表每個應用程式,每個內含數個用來告訴 FreeBSD 如何編譯與安裝該程式檔案的應用程式子目錄即稱作 Port Skeleton,每個 Port Skeleton 會含有以下檔案及目錄:
Makefile:內含用來說明應用程式要如何編譯、要安裝該程式到那的敘述句。
distinfo:內含編譯 Port 必須下載的檔案名稱以及校驗碼 (Checksum)。
files/:此目錄含有編譯與安裝程式到 FreeBSD 時所需的修補檔。此目錄也可能含有其他用來編譯 Port 的檔案。
pkg-descr:提供程式更詳細的說明。
pkg-plist:Port 安裝的所有檔案清單,也同時會告訴 Port 系統解除安裝時要移除那一些檔案。
部份 Port 含有 pkg-message 或其他檔案用來處理特殊情況。要取得有關這些檔案的詳細資訊,以及 Port 的概要可參考 FreeBSD Porter’s Handbook。
Port 中並不含實際的原始碼,即為 distfile,在編譯 Port 解壓縮時會自動下載的原始碼到 /usr/ports/distfiles。
4.5.1. 安裝 Port
下面我們會介紹如何使用 Port 套件集來安裝、移除軟體的基本用法。 make
可用的目標及環境變數詳細說明可參閱 ports(7)。
在編譯任何 Port 套件前,請先確認已經如前章節所敘述之方法更新 Port 套件集。安裝任何第三方軟體皆可能會導致安全性漏洞,建議在安裝前先閱讀 https://vuxml.freebsd.org/ 了解 Port 已知的安全性問題。或者在每次安裝新 Port 前執行 |
使用 Port 套件集會假設您擁有可正常連線的網路,同時也會需要超級使用者的權限。
要編譯並安裝 Port,需切換目錄到要安裝的 Port 底下,然後輸入 make install
,訊息中會顯示安裝的進度:
# cd /usr/ports/sysutils/lsof
# make install
>> lsof_4.88D.freebsd.tar.gz doesn't seem to exist in /usr/ports/distfiles/.
>> Attempting to fetch from ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/.
===> Extracting for lsof-4.88
...
[extraction output snipped]
...
>> Checksum OK for lsof_4.88D.freebsd.tar.gz.
===> Patching for lsof-4.88.d,8
===> Applying FreeBSD patches for lsof-4.88.d,8
===> Configuring for lsof-4.88.d,8
...
[configure output snipped]
...
===> Building for lsof-4.88.d,8
...
[compilation output snipped]
...
===> Installing for lsof-4.88.d,8
...
[installation output snipped]
...
===> Generating temporary packing list
===> Compressing manual pages for lsof-4.88.d,8
===> Registering installation for lsof-4.88.d,8
===> SECURITY NOTE:
This port has installed the following binaries which execute with
increased privileges.
/usr/local/sbin/lsof
#
lsof
是需要進階權限才有辦法執行的程式,因此當該程式安裝完成時會顯示安全性警告。一旦安裝完成便會顯示指令提示。
有些 Shell 會將 PATH
環境變數中所列目錄中可用的指令做快取,來增加在執行指這些指令時的查詢速度。tcsh
Shell 的使用者應輸入 rehash
來讓新安裝的指令不須指定完整路徑便可使用。若在 sh
Shell 則使用 hash -r
。請參考 Shell 的說明文件以取得更多資訊。
安裝過程中會建立工作用的子目錄用來儲存編譯時暫存的檔案。可移除此目錄來節省磁碟空間並漸少往後升級新版 Port 時造成問題:
# make clean
===> Cleaning for lsof-88.d,8
#
若想要少做這個額外的步驟,可以編譯 Port 時使用 |
4.5.1.1. 自訂 Port 安裝
部份 Port 提供編譯選項,可用來開啟或關閉應用程式中的元件、安全選項、或其他允許自訂的項目。這類的應用程式例子包括 www/firefox, security/gpgme 以及 mail/sylpheed-claws。若 Port 相依的其他 Port 有可設定的選項時,預設的模式會提示使用者選擇選單中的選項,這可能會讓安裝的過程暫停讓使用者操作數次。要避免這個情況,可一次設定所有選項,只要在 Port skeleton 中執行 make config-recursive
,然後再執行 make install [clean]
編譯與安裝該 Port。
使用 |
有許多方式可以重新進入 Port 的編譯選項清單,以便在編譯 Port 之後加入、移除或更改這些選項。方法之一是 cd
進入含有 Port 的目錄並輸入 make config
。還有另一個方法是使用 make showconfig
。最後一個方法是執行 make rmconfig
來移除所有曾選擇過的選項,讓您能夠重新設定。這些方法在 ports(7) 中都有詳細的說明。
Port 系統使用 fetch(1) 來下載檔案,它支援許多的環境變數可設定。若 FreeBSD 系統在防火牆或 FTP/HTTP 代理伺服器後面,可以設定 FTP_PASSIVE_MODE
, FTP_PROXY
以及 FTP_PASSWORD
變數。請參考 fetch(3) 取得完整支援的變數清單。
對於那些無法一直連線到網際網路的使用者,可在 /usr/ports 下執行 make fetch
來下載所有的 distfiles,或是可在某個分類的目錄中,例如 /usr/ports/net,或指定的 Port Skeleton 中執行。要注意的是,若 Port 有任何的相依,在分類或 Port Skeleton 中執行此指令並 不會 下載相依在其他分類的 Port distfiles。可使用 make fetch-recursive
來下載所有相依 Port 的 distfiles。
在部份少數情況,例如當公司或組織有自己的本地 distfiles 檔案庫,可使用 MASTER_SITES
變數來覆蓋在 Makefile 中指定的下載位址。當要指定替代的位址時可:
# cd /usr/ports/directory
# make MASTER_SITE_OVERRIDE= \
ftp://ftp.organization.org/pub/FreeBSD/ports/distfiles/ fetch
也可使用 WRKDIRPREFIX
及 PREFIX
變數來覆蓋預設的工作及目標目錄。例如:
# make WRKDIRPREFIX=/usr/home/example/ports install
會編譯在 /usr/home/example/ports 的 Port 並安裝所有東西到 /usr/local 下。
# make PREFIX=/usr/home/example/local install
會編譯在 /usr/ports Port 並安裝到 /usr/home/example/local。然後:
# make WRKDIRPREFIX=../ports PREFIX=../local install
來同時設定工作及目標目錄。
這些變數也可做為環境變數設定,請參考您使用的 Shell 操作手冊來取得如何設定環境變數的說明。
4.5.2. 移除已安裝的 Port
安裝的 Port 可以使用 pkg delete
解除安裝。 使用這個指令的範例可以在 pkg-delete(8) 操作手冊找到。
或者,可在 Port 的目錄下執行 make deinstall
:
# cd /usr/ports/sysutils/lsof
make deinstall
===> Deinstalling for sysutils/lsof
===> Deinstalling
Deinstallation has been requested for the following 1 packages:
lsof-4.88.d,8
The deinstallation will free 229 kB
[1/1] Deleting lsof-4.88.d,8... done
建議閱讀 Port 解除安裝後的訊息,若有任何相依該 Port 的應用程式,這些資訊會被顯示出來,但解除安裝的程序仍會繼續。在這種情況下最好重新安裝應用程式來避免破壞相依性。
4.5.3. 升級 Port
隨著時間推移,Port 套件集中會有新版的軟體可用。本節將說明如何檢查是否有可以升級的軟體及如何升級。
要檢查已安裝 Port 是否有新版可用,請先確定已安裝最新版本的 Port 樹,使用 Procedure: Portsnap 方法 或 Procedure: Subversion 方法 中說明的指令來更新。在 FreeBSD 10 與更新的版本,或若套件系統已轉換為 pkg,可以使用下列指令列出已經安裝的 Port 中有那些已過時:
# pkg version -l "<"
在 FreeBSD 9.X 與較舊的版本,可以使用下列指令列出已經安裝的 Port 中有那些已過時:
# pkg_version -l "<"
在嘗試升級之前,請先從檔首閱讀 /usr/ports/UPDATING 來取得最近有那些 Port 已升級或系統已安裝。這個檔案中會說明各種問題及在升級 Port 時可能會需要使用者執行的額外步驟,例如檔案格式更改、設定檔位置更改、或任何與先前版本不相容的問題。留意那些與您要升級 Port 相關的指示,並依照這些指示執行升級。 |
4.5.3.1. 升級與管理 Port 的工具
Port 套件集含有數個工具可以進行升級,每一種工具都有其優點及缺點。
以往大多 Port 安裝會使用 Portmaster 或 Portupgrade,現在有較新的 Synth 可使用。
那一種工具對特定系統是最佳的選擇取決於系統管理員。建議在使用任何這些工具之前先備份資料。 |
4.5.3.2. 使用 Portmaster 升級 Port
ports-mgmt/portmaster 是可用來升級已安裝 Port 的小巧工具,它只使用了隨 FreeBSD 基礎系統安裝的工具,不需要相依其他 Port 或資料庫便可在 FreeBSD 使用,要使用 Port 安裝此工具可:
# cd /usr/ports/ports-mgmt/portmaster
# make install clean
Portmaster 將 Port 定義成四種類型:
根 Port:沒有相依且也不被任何其他 Port 相依。
主幹 Port:沒有相依,但被其他 Port 相依。
分支 Port:有相依,且其被其他 Port 相依。
枝 Port:有相依,但沒有被其他 Port 相依。
要列出這幾個分類並搜尋是否有新版:
# portmaster -L
===>>> Root ports (No dependencies, not depended on)
===>>> ispell-3.2.06_18
===>>> screen-4.0.3
===>>> New version available: screen-4.0.3_1
===>>> tcpflow-0.21_1
===>>> 7 root ports
...
===>>> Branch ports (Have dependencies, are depended on)
===>>> apache22-2.2.3
===>>> New version available: apache22-2.2.8
...
===>>> Leaf ports (Have dependencies, not depended on)
===>>> automake-1.9.6_2
===>>> bash-3.1.17
===>>> New version available: bash-3.2.33
...
===>>> 32 leaf ports
===>>> 137 total installed ports
===>>> 83 have new versions available
此指令用來升級所有過時的 Port:
# portmaster -a
預設 Portmaster 會在刪除已存在的 Port 前備份套件,若成功安裝新版 Portmaster 會刪除該備份。使用 |
若升級的過程發生錯誤,可加入 -f
來升級並重新編譯所有 Port:
# portmaster -af
Portmaster 也可用來安裝新的 Port 到系統,在編譯及安裝新 Port 前升級所有相依模組。要使用這個功能,要指定 Port 位於 Port 套件集中的位置:
# portmaster shells/bash
更多有關 ports-mgmt/portmaster 的資訊可至其 pkg-descr 取得。
4.5.3.3. 使用 Portupgrade 升級 Port
ports-mgmt/portupgrade 是另一個可以用來升級 Port 的工具,此工具會安裝一套可以用來管理 Port 的應用程式,它需要相依 Ruby。要安裝該 Port:
# cd /usr/ports/ports-mgmt/portupgrade
# make install clean
在執行升級之前使用此工具,建議使用 pkgdb -F
掃描已安裝的 Port 並修正該指令回報的所有資訊不一致的套件。
要升級所有安裝在系統上過時的 Port,可使用 portupgrade -a
,或者加上 -i
會在每個套件升級時詢問確認:
# portupgrade -ai
要升級指定的應用程式而非所有可用 Port 可使用 portupgrade pkgname
,非常重要的是,要加上 -R
來先升級指定應用程式所有相依的 Port:
# portupgrade -R firefox
若使用 -P
,Portupgrade 會先在 PKG_PATH
清單中的本地目錄中搜尋可用的套件。若本地沒有可用的套件,則會從遠端下載。若套件無法在本地或遠端找到,Portupgrade 則會使用 Port 來安裝。要避免完全使用 Port 安裝,可使用 -PP
,這個選項會告訴 Portupgrade 若沒有套件可用時放棄安裝:
# portupgrade -PP gnome3
若只想要下載 Port distfiles 或套件,使用 -P
參數。若不要編譯或安裝任何東西,使用 -F
。請參考 portupgrade
的操作手冊來取得所有可用選項的更多資訊。
更多有關 ports-mgmt/portupgrade 的資訊可至其 pkg-descr 取得。
4.5.4. Port 與磁碟空間
使用 Port 套件集會隨著時間消耗磁碟空間。在編譯與安裝 Port 完之後,在 Port Skeleton 中執行 make clean
可清除暫存的 work 目錄。若使用 Portmaster 來安裝 Port,則會自動移除該目錄,除非使用 -K
。若有安裝 Portupgrade,此指令將會移除所有在 Port 套件集的本地複本中找到的 work 目錄:
# portsclean -C
除此之外,許多過時的原始碼發行檔案會儲存在 /usr/ports/distfiles。使用 Portupgrade 刪除所有不再被任何 Port 所引用的 distfiles:
# portsclean -D
Portupgrade 可以移除所有未被任何安裝在系統上的 Port 所引用的 distfiles:
# portsclean -DD
若有安裝 Portmaster,則可使用:
# portmaster --clean-distfiles
預設,若 distfile 應要被刪除,這個指令會以互動的方式向使用者確認。
除了以上指令外,ports-mgmt/pkg_cutleaves 可自動移除不再需要使用的 Port。
4.6. 使用 Poudriere 編譯套件
Poudriere 是一個使用 BSD 授權條款用來建立與測試 FreeBSD 套件的工具。它使用 FreeBSD Jail 來建置獨立的編譯環境,這些 Jail 可以用來編譯與目前所在系統不同 FreeBSD 版本的套件,也同樣可以在主機為 amd64 的系統上編譯供 i386 使用的套件。套件編譯完成後的目錄配置會與官方鏡像站完全相同。這些套件可由 pkg(8) 及其他套件管理工具使用。
Poudriere 可使用 ports-mgmt/poudriere 套件或 Port 安裝。安裝完成後會有一個範例的設定檔 /usr/local/etc/poudriere.conf.sample。複製此檔案到 /usr/local/etc/poudriere.conf,編輯複製的檔案來配合本地的設定。
雖然在系統上執行 poudriere 並不一定要使用 ZFS,但使用了是有幫助的。當使用了 ZFS,則必須在 /usr/local/etc/poudriere.conf 指定 ZPOOL
以及 FREEBSD_HOST
應設定到一個最近的鏡像站。定義 CCACHE_DIR
可開啟使用 devel/ccache 快取的功能來快取編譯結果並減少那些需時常編譯的程式碼的編譯次數。將 poudriere 資料集放到一個獨立的目錄並掛載到 /poudriere 可能會比較方便,其他設定項目採用預設值便足夠。
偵測到的處理器數量可用來定義要同時執行多少個編譯。並給予足夠的虛擬記憶體,不論是 RAM 或交換空間,若虛擬記憶體不足,編譯 Jail 的動作將會停止並被清除,會造成奇怪的錯誤訊息。
4.6.1. 初始化 Jail 與 Port 樹
在設定之後,初始化 poudriere 來安裝 Jail 及其所需的 FreeBSD 樹與 Port 樹。使用 -j
來指定 Jail 的名稱以及 -v
來指定 FreeBSD 的版本。在執行 FreeBSD/amd64 的系統上可使用 -a
來設定要使用的架構為 i386
或 amd64
,預設會採用使用 uname
所顯示的架構。
# poudriere jail -c -j 10amd64 -v 10.0-RELEASE
====>> Creating 10amd64 fs... done
====>> Fetching base.txz for FreeBSD 10.0-RELEASE amd64
/poudriere/jails/10amd64/fromftp/base.txz 100% of 59 MB 1470 kBps 00m42s
====>> Extracting base.txz... done
====>> Fetching src.txz for FreeBSD 10.0-RELEASE amd64
/poudriere/jails/10amd64/fromftp/src.txz 100% of 107 MB 1476 kBps 01m14s
====>> Extracting src.txz... done
====>> Fetching games.txz for FreeBSD 10.0-RELEASE amd64
/poudriere/jails/10amd64/fromftp/games.txz 100% of 865 kB 734 kBps 00m01s
====>> Extracting games.txz... done
====>> Fetching lib32.txz for FreeBSD 10.0-RELEASE amd64
/poudriere/jails/10amd64/fromftp/lib32.txz 100% of 14 MB 1316 kBps 00m12s
====>> Extracting lib32.txz... done
====>> Cleaning up... done
====>> Jail 10amd64 10.0-RELEASE amd64 is ready to be used
# poudriere ports -c -p local
====>> Creating local fs... done
====>> Extracting portstree "local"...
Looking up portsnap.FreeBSD.org mirrors... 7 mirrors found.
Fetching public key from ec2-eu-west-1.portsnap.freebsd.org... done.
Fetching snapshot tag from ec2-eu-west-1.portsnap.freebsd.org... done.
Fetching snapshot metadata... done.
Fetching snapshot generated at Tue Feb 11 01:07:15 CET 2014:
94a3431f0ce567f6452ffde4fd3d7d3c6e1da143efec76100% of 69 MB 1246 kBps 00m57s
Extracting snapshot... done.
Verifying snapshot integrity... done.
Fetching snapshot tag from ec2-eu-west-1.portsnap.freebsd.org... done.
Fetching snapshot metadata... done.
Updating from Tue Feb 11 01:07:15 CET 2014 to Tue Feb 11 16:05:20 CET 2014.
Fetching 4 metadata patches... done.
Applying metadata patches... done.
Fetching 0 metadata files... done.
Fetching 48 patches.
(48/48) 100.00% done.
done.
Applying patches...
done.
Fetching 1 new ports or files... done.
/poudriere/ports/tester/CHANGES
/poudriere/ports/tester/COPYRIGHT
[...]
Building new INDEX files... done.
在一台電腦,poudriere 可使用多組設定在多個 Jail 編譯來自不同 Port 樹的 Port。用來定義這些組合的自訂設定稱作 sets,可在安裝 ports-mgmt/poudriere 或 ports-mgmt/poudriere-devel 後參考 poudriere(8) 中的 CUSTOMIZATION 章節來取得詳細的資訊。
在此處示範的基本設定放了單一個 jail-, port- 以及 set- 特定的 make.conf 在 /usr/local/etc/poudriere.d。在此範例使用的檔案名稱由 Jail 名稱、Port 名稱以及 set 名稱所組成:10amd64-local-workstation-make.conf。系統 make.conf 與這個新的檔案在編譯時期會被合併為編譯 Jail 要使用的 make.conf。
要編譯的套件會輸入到 10amd64-local-workstation-pkglist:
editors/emacs devel/git ports-mgmt/pkg ...
可使用以下方式設定選項及相依:
# poudriere options -j 10amd64 -p local -z workstation -f 10amd64-local-workstation-pkglist
最後,編譯套件並建立套件檔案庫:
# poudriere bulk -j 10amd64 -p local -z workstation -f 10amd64-local-workstation-pkglist
在執行時,按下 Ctrl+t 可以顯示目前編譯的狀態,Poudriere 也會編譯在 /poudriere/logs/bulk/jailname 中的檔案,可用在網頁伺服器來顯示編譯資訊。
完成之後,新套件現在可以從 poudriere 檔案庫來安裝。
要取得更多使用 poudriere 的資訊,請參考 poudriere(8) 及主網站 https://github.com/freebsd/poudriere/wiki。
4.6.2. 設定 pkg 客戶端使用 Poudriere 檔案庫
雖然可以同時使用自訂的檔案庫與官方檔案庫,但有時關閉官方檔案庫會有幫助。這可以透過建立一個設定檔覆蓋並關閉官方的設定檔來完成。建立 /usr/local/etc/pkg/repos/FreeBSD.conf 包含以下內容:
FreeBSD: { enabled: no }
通常最簡單要提供 poudriere 檔案庫給客戶端的方式是透過 HTTP。安裝一個網頁伺服器來提供套件目錄,通常會像:/usr/local/poudriere/data/packages/10amd64,其中 10amd64 是編譯的名稱。
若要連往套件檔案庫的 URL 是:http://pkg.example.com/10amd64
,則在 /usr/local/etc/pkg/repos/custom.conf 的檔案庫設定檔為:
custom: { url: "http://pkg.example.com/10amd64", enabled: yes, }
4.7. 安裝後的注意事項
不論軟體是從套件或 Port 安裝,大部份的第三方應用程式安裝完後需要做某種程度的設定,下列指令與位置可以用來協助找到應用程式安裝了什麼。
大部份應用程式安裝會在 /usr/local/etc 安裝至少一個預設的設定檔,若應用程式有大量設定檔的時則會建立一個子目錄來存放這些設定檔。範例的設定檔案名稱通常使用 .sample 結尾,設定檔應要仔細查看並可能要做一些編輯讓設定檔符合系統的需求,要編輯設定檔範本前需先複製該檔案並去除 .sample 副檔名。
應用程式提供的文件會安裝到 /usr/local/shared/doc,且許多應用程式也同時會安裝操作手冊,在繼續使用應用程式前應先查看這些文件。
部份應用程式會以服務的方式執行,在啟動應用程式前前需要加入設定到 /etc/rc.conf。這些應用程式通常會安裝啟動 Script 到 /usr/local/etc/rc.d,請參考 啟動服務 來取得更多資訊。
依設計,應用程式不會在安裝時執行其啟動 Script,也不會在解除安裝或升級時執行其中止 Script,這留給各系統的管理者去做決定。
csh(1) 的使用者應要執行
rehash
來更新已知 Binary 清單到 Shell 的PATH
。使用
pkg info
來了解應用程式安裝了那些檔案、操作手冊以及 Binary。
4.8. 處理損壞的 Port
當發現某個 Port 無法順利編譯或安裝,可以嘗試以下幾種方法解決:
搜尋 問題回報資料庫 看該 Port 有沒有待審核的修正,若有的話可以使用該修正來修正問題。
尋求維護人員的協助,在 Port Skeleton 目錄中輸入
make maintainer
或閱讀 Port 的 Makefile 來取得維護人員的電子郵件位址。寄給維護人員的郵件內容請記得要包含 Port 的 Makefile 中的$FreeBSD:
一整行及輸出的錯誤訊息。有一些 Port 並非由個人維護,而是由 郵遞論壇 維護,有許多,但並非全部,只要郵件地址長的像 freebsd-listname@FreeBSD.org 都是,寄信時記得代入實際的論壇名稱。
尤其是由 ports@FreeBSD.org 所維護的 Port 都不是由特定個人維護,而該 Port 的修正與支援都是來自訂閱該郵遞論壇的一般社群所提供,我們隨時歡迎志工參與!
若寄信後沒有取得任何回應,可以依照 撰寫 FreeBSD 問題回報 的說明使用 Bugzilla 提出問題回報。
自行修正看看!Porter’s Handbook 中含有 Port 基礎架構的詳細資訊,可提供資訊讓您可修正偶然損壞的 Port 或甚至您可以提交之自己的 Port!
依照 使用 pkg 管理 Binary 套件 中的說明安裝 Binary 套件,替代使用 Port 安裝。
Chapter 5. X Window 系統
5.1. 概述
使用 bsdinstall 安裝 FreeBSD 並不會自動安裝圖型化使用者介面。本章將說明如何安裝並設定 Xorg,該應用程式提供開放源碼的 X Window 系統來提供圖型化環境。接著會說明如何找到並安裝桌面環境或視窗管理程式。
偏好安裝時會自動設定 Xorg 並且在安裝過程提供視窗管理程式選項的使用者請參考 http://www.trueos.org/ 網站。 |
更多有關 Xorg 支援影像硬體資訊,請參考 x.org 網站。
讀完這章,您將了解:
組成 X Window 系統的各種元件以及它們是如何相互運作。
如何安裝並設定 Xorg。
如何安裝並設定各種視窗管理程式與桌面環境。
如何在 Xorg 上使用 TrueType™ 字型。
如何設定系統以使用圖形化登入 (XDM)。
在開始閱讀這章之前,您需要:
了解如何依照 安裝應用程式:套件與 Port 說明安裝其他第三方軟體。
5.2. 術語
雖然 X 各元件的所有細節及運作方式,並不是必須要知道的。 但對它們有些基本概念會更容易上手。
- X 伺服器 (X Server)
X 最初設計是以網路為中心,採用 "client-server" 架構。在此架構下 "X 伺服器" 在有鍵盤、螢幕、滑鼠的電腦上運作。該伺服器負責的工作包含管理顯示、處理來自鍵盤、滑鼠的輸入及來自其他設備 (如平板或或影像投影機) 的輸入或輸出。這點可能會讓人感到困惑,因為 X 使用的術語與一般的認知剛好相反。 一般認知會以為 "X 伺服器" 是要在最強悍的主機上執行,而 "X 客戶端" 才是在桌機上面執行,實際上卻是相反。
- X 客戶端 (X Client)
每個 X 應用程式,如 XTerm、Firefox 都是 "客戶端"。 客戶端會傳訊息到伺服器,例如:"請在這些座標畫一個視窗",接著伺服器會傳回訊息,如:"使用者剛點選了確定按鈕"。
在家庭或小型辦公室環境,通常 X 伺服器跟 X 客戶端都是在同一台電腦上執行。也可以在比較慢的電腦上執行 X 伺服器, 並在比較強、比較貴的系統上執行 X 應用程式。 在這種情景,X 客戶端與伺服器之間的溝通就需透過網路來進行。
- 視窗管理程式 (Window Manager)
X 並不規定螢幕上的視窗該長什麼樣、要如何移動滑鼠指標、 要用什麼鍵來在視窗切換、每個視窗的標題列長相,及是否該有關閉按鈕,等等。事實上,X 把這部分交給所謂的視窗管理程式來管理。可用的視窗管理程式有很多種,每一種視窗管理程式都提供不同的使用介面風格:有些支援虛擬桌面,有些允許自訂組合鍵來管理桌面,有些有 "開始" 鈕,有些則是可更換佈景主題,可自行安裝新的佈景主題以更換外觀。 視窗管理程式可在 Port 套件集的 x11-wm 分類找到。
每個視窗管理程式也各有其不同的設定機制,有些需要手動修改設定檔, 而有的則可透過圖型化工具來完成大部分的設定工作。
- 桌面環境 (Desktop Environment)
KDE 與 GNOME 會被稱作桌面環境是因為包含了完整常用桌面作業的應用程式,這些應用程式可能包含文書軟體、網頁瀏覽器及遊戲。
- 聚焦政策 (Focus Policy)
視窗管理程式負責滑鼠指標的聚焦政策。 聚焦政策指的是如何決定使用中及接收鍵盤輸入的視窗。
通常較為人熟悉的聚焦政策叫做 "click-to-focus",這個模式中,滑鼠點選到的視窗便會處於作用中 (Active) 的狀態。在 "focus-follows-mouse" 模式滑鼠指標所在的視窗便是作用中的視窗,只要把滑鼠移到其他視窗就可以改變作用中的視窗,若滑鼠移到根視窗 (Root Window),則會聚焦在根視窗。在 "sloppy-focus" 模式,既使滑鼠移到根視窗,仍然會聚焦在最後聚焦的視窗上,此模式只有當滑鼠進入新的視窗時才會聚焦於該視窗,而非離開目前視窗時。"click-to-focus" 模式用滑鼠點擊來決定作用中的視窗,且該視窗會被置頂到所有其他視窗之前,即使滑鼠移到其他視窗,所有的鍵盤輸入仍會由該視窗所接收。
不同的視窗管理程式支援不同的聚焦模式,全部都支援 click-to-focus 且其中大部份支援其他模式,請查看視窗管理程式的說明文件來了解可用的聚焦模式。
- 視窗元件 (Widget)
視窗元件指的是在所有在使用者介面上可被點選或操作的項目,這包括按鈕、核選方塊、單選按鈕、圖示及清單。 視窗元件工具包 (Widget toolkit) 是指用來建立圖型化應用程式的一系列的視窗元件。目前有數個有名的視窗元件工具包,包含 KDE 所使用的 Qt、GNOME 所使用的 GTK+。 因此應用程式會依其開發時所選用的視窗元件工具包而有不同的外觀。
5.3. 安裝 Xorg
在 FreeBSD,Xorg 可透過套件或 Port 來安裝。
使用 Binary 套件的安裝速度較快,但可用的自訂選項較少:
# pkg install xorg
要從 Port 套件集編譯與安裝:
# cd /usr/ports/x11/xorg
# make install clean
兩種安裝方式皆可完整安裝 Xorg 系統,對大多數使用者較建議使用 Binary 套件安裝。
較精簡版本的 X 系統適合給有經驗的使用者使用,可至 x11/xorg-minimal 取得。這個版本就不會安裝大多數的文件、函數庫以及應用程式,而部份應用程式會需要這些額外的元件才能運作。
5.4. Xorg 設定
5.4.1. 快速開始
Xorg 支援大多數常見的顯示卡、鍵盤以及指標裝置。
顯示卡、顯示器以及輸入裝置會自動偵測,無須任何手動設置。除非自動設置失敗,否則請勿建立 xorg.conf 或執行 |
若 Xorg 曾經在電腦使用過,可先將現有的設定檔重新命名或移除:
# mv /etc/X11/xorg.conf ~/xorg.conf.etc # mv /usr/local/etc/X11/xorg.conf ~/xorg.conf.localetc
加入要執行 Xorg 的使用者到
video
或wheel
群組,以便在可用時能開啟 3D 加速。要加入使用者 jru 到任一個可用的群組:# pw groupmod video -m jru || pw groupmod wheel -m jru
預設內含 TWM 視窗管理程式,啟動 Xorg 時便會啟動該視窗管理程式:
% startx
在部份較舊版的 FreeBSD,在切換回文字 Console 前系統 Console 必須設為 vt(4) 才可正常運作,請參考 核心模式設定 (Kernel Mode Setting, KMS)。
5.4.2. 可加速影像處理的使用者群組
要存取 /dev/dri 需要允許顯示卡的 3D 加速功能,這通常只需要將要執行 X 的使用者加入 video
或 wheel
群組。此處使用 pw(8) 來將使用者 slurms 加入 video
群組,若沒有 video
則會加入 wheel
群組:
# pw groupmod video -m slurms || pw groupmod wheel -m slurms
5.4.3. 核心模式設定 (Kernel Mode Setting, KMS)
當電腦顯示從 Console 切換到高螢幕解析度供 X 使用時,必須設定影像輸出模式。最近版本的 Xorg 使用了核心內部的系統來讓切換模式更有效率。較舊版的 FreeBSD 使用的 sc(4) 並不知到 KMS 系統的存在,這會導致關閉 X 之後即始仍在運作但系統 Console 卻呈現空白。較新版的 vt(4) Console 可避免這個問題。
加入此行到 /boot/loader.conf 來開啟 vt(4):
kern.vty=vt
5.4.4. 設定檔
通常不需要做手動設置,除非自動設置無法運作,否則請不要手動建立設定檔。
5.4.5. 顯示卡
由於最近 FreeBSD 版本所做的變更,現在可以使用由 Port 或套件所提供的繪圖驅動程式,所以使用者可以使用下列來自 graphics/drm-kmod 的驅動程式。
- Intel KMS 驅動程式
大多數使用 Intel KMS 驅動程式的 Intel 顯示卡支援 2D 與 3D 加速。
驅動程式名稱:
i915kms
大多數使用 Radeon KMS 驅動程式的舊 AMD 顯示卡支援 2D 與 3D 加速。
驅動程式名稱:
radeonkms
大多數使用 AMD KMS 驅動程式的新 AMD 顯示卡支援 2D 與 3D 加速。
驅動程式名稱:
amdgpu
- Intel™
3D 加速在大多數 Intel™ 顯示晶片都有支援,最新到 Ivy Bridge (HD Graphics 2500, 4000, 及 P4000) 包含 Iron Lake (HD Graphics) 與 Sandy Bridge (HD Graphics 2000)。
驅動程式名稱:
intel
- AMD™ Radeon
Radeon 顯示卡支援 2D 及 3D 加速,最新到 HD6000 系列。
驅動程式名稱:
radeon
- NVIDIA
有數個 NVIDIA 驅動程式可於 Port 套件集中的 x11 分類取得,請安裝其中與顯示卡相符的驅動程式。
- 混合組合繪圖晶片
部份筆記型電腦加入了額外繪圖處理單元到那些內建晶片組或處理。Optimus 結合了 Intel™ 及 NVIDIA 的硬體,Switchable Graphics 或 Hybrid Graphics 則是結合了 Intel™ 或 AMD™ 處理器與 AMD™ Radeon GPU。
這些混合繪圖系統的實作方式均不同,FreeBSD 的 Xorg 尚無法驅動所有的混合繪圖系統版本。
部份電腦提供了 BIOS 的選項可以關閉其中一個繪圖介面卡或選擇 discrete 模式,可用使用其中一種標準顯示卡驅動程式來驅動。例如,有時關閉 Optimus 系統中的 NVIDIA GPU 是可能讓 Intel™ 顯示晶片可用 Intel™ 驅動程式驅動。
BIOS 設定會依電腦的型號有所不同,在某些情況下,可以同時開啟兩個 GPU,而在建立的設定檔中的
Device
節只使用主要的 GPU 便能讓系統運作。
- 其他顯示卡
較不常見的顯示卡驅動程式可在 Port 套件集的 x11-drivers 目錄找到。
若沒有特定的驅動程式可以支援顯示卡,仍可能可用 x11-drivers/xf86-video-vesa 驅動程式來驅動。該驅動程式可使用 x11/xorg 安裝,也可使用 x11-drivers/xf86-video-vesa 手動安裝。當沒有指定驅動程式時 Xorg 會嘗試使用這個驅動程式來驅動顯示卡。
x11-drivers/xf86-video-scfb 也是不特定顯示卡的驅動程式,可在許多 UEFI 及 ARM™ 的電腦上運作。
- 在檔案中設定影像驅動程式
要在設定檔設定使用 Intel™ 驅動程式:
例 15. 在單檔中選擇 Intel™ 影像驅動程式/usr/local/etc/X11/xorg.conf.d/driver-intel.conf
Section "Device" Identifier "Card0" Driver "intel" # BusID "PCI:1:0:0" EndSection
若有多張顯示卡,可取消註解
BusID
identifier 然後設定為想要的顯示卡,顯示卡的 Bus ID 清單可以使用pciconf -lv | grep -B3 display
取得。要在設定檔設定使用 Radeon 驅動程式:
例 16. 在單檔中選擇 Radeon 影像驅動程式/usr/local/etc/X11/xorg.conf.d/driver-radeon.conf
Section "Device" Identifier "Card0" Driver "radeon" EndSection
要在設定檔設定使用 VESA 驅動程式:
例 17. 在單檔中選擇 VESA 影像驅動程式/usr/local/etc/X11/xorg.conf.d/driver-vesa.conf
Section "Device" Identifier "Card0" Driver "vesa" EndSection
要設定 UEFI 或 ARM™ 電腦使用
scfb
驅動程式:例 18. 在單檔中選擇scfb
影像驅動程式/usr/local/etc/X11/xorg.conf.d/driver-scfb.conf
Section "Device" Identifier "Card0" Driver "scfb" EndSection
5.4.6. 顯示器
幾乎所有顯示器都支援延伸顯示辨識資料標準 (Extended Display Identification Data, EDID),Xorg 會使用 EDID 與顯示器通訊並偵測支援的解析度與更新頻率,然後選擇最適合的設定組合使用該顯示器。
其他顯示器支援的解析度可透過在設定檔中設定想要的解析度來選擇,或者在 X 伺服器啟動之後使用 xrandr(1)。
- 使用 xrandr(1)
執行 xrandr(1) 不加任何參數可檢查影像輸出及已偵測到的顯示器模式清單:
% xrandr Screen 0: minimum 320 x 200, current 3000 x 1920, maximum 8192 x 8192 DVI-0 connected primary 1920x1200+1080+0 (normal left inverted right x axis y axis) 495mm x 310mm 1920x1200 59.95*+ 1600x1200 60.00 1280x1024 85.02 75.02 60.02 1280x960 60.00 1152x864 75.00 1024x768 85.00 75.08 70.07 60.00 832x624 74.55 800x600 75.00 60.32 640x480 75.00 60.00 720x400 70.08 DisplayPort-0 disconnected (normal left inverted right x axis y axis) HDMI-0 disconnected (normal left inverted right x axis y axis)
這個結果顯示
DVI-0
輸出被用來顯示解析度為 1920x1200 像素於更新頻率約 60 Hz 的畫面,未有顯示器連接到DisplayPort-0
與HDMI-0
接頭。可使用 xrandr(1) 來選擇任何其他的顯示模式。例如要切換為 1280x1024 於 60 Hz:
% xrandr --mode 1280x1024 --rate 60
在筆記型電腦使用外部顯示輸出到投影機是常見的作業。
不同裝置間輸出接頭的類型與數量也不同,給每個輸出的名稱在不同驅動程式間也不同。在某些驅動程式稱為
HDMI-1
的輸出在其他驅動程式則可能稱為HDMI1
。因此第一個步驟是執行 xrandr(1) 列出所有可用的輸出:% xrandr Screen 0: minimum 320 x 200, current 1366 x 768, maximum 8192 x 8192 LVDS1 connected 1366x768+0+0 (normal left inverted right x axis y axis) 344mm x 193mm 1366x768 60.04*+ 1024x768 60.00 800x600 60.32 56.25 640x480 59.94 VGA1 connected (normal left inverted right x axis y axis) 1280x1024 60.02 + 75.02 1280x960 60.00 1152x864 75.00 1024x768 75.08 70.07 60.00 832x624 74.55 800x600 72.19 75.00 60.32 56.25 640x480 75.00 72.81 66.67 60.00 720x400 70.08 HDMI1 disconnected (normal left inverted right x axis y axis) DP1 disconnected (normal left inverted right x axis y axis)
已找到四個輸出:內建面板的
LVDS1
,外接的VGA1
,HDMI1
以及DP1
接頭。投影機已連接至
VGA1
輸出,現在使用 xrandr(1) 來設定該輸出到投影機 (原始解析度) 並加入額外的空間到桌面的右側:% xrandr --output VGA1 --auto --right-of LVDS1
--auto
會選擇使用 EDID 偵測到的解析度與更新頻率。若未正確偵測解析度,可替換--auto
為--mode
然後給予固定值。例如大部份的投影機可使用 1024x768 解析度為,則可設定--mode 1024x768
。xrandr(1) 通常會在 .xinitrc 執行以在 X 啟動時設定適合的模式。
- 在檔案中設定螢幕解析度
在設定檔設定螢幕解析度為 1024x768:
例 19. 在單檔中設定螢幕解析度/usr/local/etc/X11/xorg.conf.d/screen-resolution.conf
Section "Screen" Identifier "Screen0" Device "Card0" SubSection "Display" Modes "1024x768" EndSubSection EndSection
少數顯示器沒有 EDID,可設定
HorizSync
及VertRefresh
為顯示器支援的頻率範圍。例 20. 手動設定顯示器頻率/usr/local/etc/X11/xorg.conf.d/monitor0-freq.conf
Section "Monitor" Identifier "Monitor0" HorizSync 30-83 # kHz VertRefresh 50-76 # Hz EndSection
5.4.7. 輸入裝置
5.4.7.1. 鍵盤
- 鍵盤配置
鍵盤上標準按鍵的位置稱做 配置 (Layout)。配置與其他可調整的參數列於 xkeyboard-config(7)。
預設為 United States 配置,要選擇其他的配置可在
InputClass
設定XkbLayout
與XkbVariant
選項。這會套用所有符合該類別的輸入裝置。這個例子選擇 French 鍵盤配置使用
oss
變體。例 21. 設定鍵盤配置/usr/local/etc/X11/xorg.conf.d/keyboard-fr-oss.conf
Section "InputClass" Identifier "KeyboardDefaults" Driver "keyboard" MatchIsKeyboard "on" Option "XkbLayout" "fr" Option "XkbVariant" "oss" EndSection
- 從鍵盤關閉 Xorg
X 可以使用組合鍵來關閉,預設並未設定組合鍵,因為該組合鍵與部份應用程式的鍵盤指令衝突。要開啟這個選項需要更改鍵盤
InputDevice
節:例 23. 開啟鍵盤離開 X 功能/usr/local/etc/X11/xorg.conf.d/keyboard-zap.conf
Section "InputClass" Identifier "KeyboardDefaults" Driver "keyboard" MatchIsKeyboard "on" Option "XkbOptions" "terminate:ctrl_alt_bksp" EndSection
5.4.7.2. 滑鼠與指標裝置
有許多滑鼠參數可使用設定選項來調整,請參考 mousedrv(4) 來取得完整清單。
5.4.8. 手動設定
在某些情況 Xorg 的自動設定無法在特定硬體上運作,或需要使用不同的設定。針對這些情況會建立自訂的設定檔。
非必要請勿手動建立設定檔,非必要的手動設置會造成運作不正常。 |
設定檔可由 Xorg 根據偵測到的硬體產生,這個檔案對一開始自訂設定很有幫助。
產生 xorg.conf:
# Xorg -configure
設定檔會儲存至 /root/xorg.conf.new,做任何需要的更改,然後使用以下指令測試該檔案:
# Xorg -config /root/xorg.conf.new
在新設定檔調整與測試過後,便可分開成較小的檔案放置到正常的位置 /usr/local/etc/X11/xorg.conf.d/。
5.5. 在 Xorg 使用字型
5.5.1. Type1 字型
由於 Xorg 內建的預設字型用在典型的桌面出版應用程式並不是很理想,大字型會呈現鋸齒狀邊緣,看起來很不專業,小字型幾乎完全看不清楚。不過,這裡有幾個免費高品質的 Type1 (PostScript™) 字型可用,且能容易的在 Xorg 使用。例如,URW 字型集 (Times Roman™, Helvetica™, Palatino™ 及其他)。 Freefont 字型集 (x11-fonts/freefonts) 包含了更多的字型,但其中大部分是給圖形軟體如 GIMP 所使用的字型,並不能完全作為螢幕字型使用。此外,Xorg 可以簡單的設定使用 TrueType™ 字型。更多有關本主題的詳細資訊,請參考 X(7) 操作手冊或 TrueType™ 字型。
要由 Binary 套件安裝上述的 Type1 字型集可執行以下指令:
# pkg install urwfonts
或由 Port 套件集編譯,可執行以下指令:
# cd /usr/ports/x11-fonts/urwfonts
# make install clean
同樣的安裝方式也適用 Freefont 或其他字型集。要讓 X 伺服器偵測到這些新安裝的字型,可加入適當的設定到 X 伺服器設定檔 (/etc/X11/xorg.conf),內容為:
FontPath "/usr/local/shared/fonts/urwfonts/"
或者在 X session 的指令列執行:
% xset fp+ /usr/local/shared/fonts/urwfonts
% xset fp rehash
這樣便可,但在 X session 關閉時將會失效,除非將該設定加入啟動檔 (一般的 startx
session 可在 ~/.xinitrc 設定,若透過圖型化登入管理程式如 XDM 登入時則在 ~/.xsession 設定)。第三種方式是使用新 /usr/local/etc/fonts/local.conf,如 反鋸齒字型 的示範。
5.5.2. TrueType™ 字型
Xorg 內建支援繪製 TrueType™ 字型,目前有兩個模組可以支援這項功能。在本例中使用 freetype 模組,由於此模組與其他字型繪製後端較為一致。要開啟 freetype 模組只需要將下行加入到 /etc/X11/xorg.conf 中的 "Module"
section。
Load "freetype"
現在要建立一個儲存 TrueType™ 字型的目錄 (例如,/usr/local/shared/fonts/TrueType) 然後複製所有 TrueType™ 字型到這個目錄。要注意 TrueType™ 字型並無法直接取自 Apple™Mac™,Xorg 使用的字型必須為 UNIX™/MS-DOS™/Windows™ 的格式。檔案複製到讓目錄之後,使用 mkfontscale 來建立 fonts.dir 來讓 X 字型繪製程式知道安裝了新的檔案。mkfontscale
可用套件的方式安裝:
# pkg install mkfontscale
然後在目錄中建立 X 字型檔的索引:
# cd /usr/local/shared/fonts/TrueType
# mkfontscale
接著加入 TrueType™ 目錄到字型路徑。這個動作與 Type1 字型 中所介紹的方式相同:
% xset fp+ /usr/local/shared/fonts/TrueType
% xset fp rehash
或直接加入 FontPath
一行到 xorg.conf。
現在 Gimp, Apache OpenOffice 以及其他 X 應用程式應可以辨識到已安裝的 TrueType™ 字型。極小的字型 (以高解析度在網頁中顯示的文字) 與極大的字型 (在 StarOffice™ 中) 現在會看起來比較像樣了。
5.5.3. 反鋸齒字型
所有可在 /usr/local/shared/fonts/ 及 ~/.fonts/ 找到的 Xorg 字型均可在 Xft-aware 的應用程式使用反鋸齒的效果。大多最近的應用程式均為 Xft-aware 的,包括 KDE, GNOME 以及 Firefox。
要控制那一些字型要做反鋸齒或設定反鋸齒的屬性,需建立 /usr/local/etc/fonts/local.conf 檔案 (若檔案存在則編輯)。在這個檔案中可以調整 Xft 字型系統的數項進階功能,本章節僅介紹部份簡單的項目,要取得進一步資訊,請參考 fonts-conf(5)。
這個檔案必須使用 XML 格式,小心文字大小寫,且要確定所有標籤均有正常結尾。檔案的開頭使用常見的 XML 檔首,接著為 DOCTYPE 定義,然後是 <fontconfig>
標籤:
<?xml version="1.0"?> <!DOCTYPE fontconfig SYSTEM "fonts.dtd"> <fontconfig>
如同前面所提到的,所有在 /usr/local/shared/fonts/ 與 ~/.fonts/ 的字型均可在 Xft-aware 的應用程式做反鋸齒效果,若您想要加入除了上兩者以外的目錄,可加入如下行設定到 /usr/local/etc/fonts/local.conf:
<dir>/path/to/my/fonts</dir>
加入新字型及額外的新字型目錄之後,需重新建立字型快取:
# fc-cache -f
反鋸齒效果會讓文字的邊緣變模糊,這會讓非常小的文字更能閱讀且去除大型文字的 "鋸齒",但套用在一般的文字可能會造成眼睛的疲勞。要排除小於 14 點的字型大小使用反鋸齒效果,可加入這些行:
<match target="font"> <test name="size" compare="less"> <double>14</double> </test> <edit name="antialias" mode="assign"> <bool>false</bool> </edit> </match> <match target="font"> <test name="pixelsize" compare="less" qual="any"> <double>14</double> </test> <edit mode="assign" name="antialias"> <bool>false</bool> </edit> </match>
反鋸齒所產生的間距對於部份等寬字型並不合適,尤其是在使用 KDE 時會成為一個問題。可能的修正方式是強制這類字型的間距為 100,可加入以下行:
<match target="pattern" name="family"> <test qual="any" name="family"> <string>fixed</string> </test> <edit name="family" mode="assign"> <string>mono</string> </edit> </match> <match target="pattern" name="family"> <test qual="any" name="family"> <string>console</string> </test> <edit name="family" mode="assign"> <string>mono</string> </edit> </match>
(這會設定等寬字型的其他常用名稱為 "mono"
),然後加入:
<match target="pattern" name="family"> <test qual="any" name="family"> <string>mono</string> </test> <edit name="spacing" mode="assign"> <int>100</int> </edit> </match>
部份字型,如 Helvetica,在使用反鋸齒時可能會發生問題,通常會呈現像垂直切成兩半的字型,最差還可能會導致應用程式當掉。要避免這個問題,可考慮加入以下設定到 local.conf:
<match target="pattern" name="family"> <test qual="any" name="family"> <string>Helvetica</string> </test> <edit name="family" mode="assign"> <string>sans-serif</string> </edit> </match>
編輯 local.conf 完之後,請確認有使用 </fontconfig>
標籤結尾,若沒有使用會讓所做的更改被忽略。
使用者可透過建立自己的 ~/.config/fontconfig/fonts.conf 來加入個人化的設定,此檔案使用與上述說明相同的 XML 格式。
最後一點:若有使用 LCD 螢幕,可能會想要使用子像素取樣 (Sub-pixel sampling),這基本上會分開處理 (水平分隔) 紅、綠、藍色彩組成來提高垂直解析度,結果可能是無法預料的。要開啟這個功能,加入下行到 local.conf 的任一處:
<match target="font"> <test qual="all" name="rgba"> <const>unknown</const> </test> <edit name="rgba" mode="assign"> <const>rgb</const> </edit> </match>
依據不同的顯示器類型可能會需要將 |
5.6. X 顯示管理程式
Xorg 提供了 X 顯示管理程式 (X Display Manager, XDM),可用來做登入階段的管理。XDM 提供了一個圖型化的介面來選擇要連結的顯示伺服器以及輸入認証資訊 (登入與密碼)。
本節將示範如何設定 FreeBSD 的 X 顯示管理程式。部份桌面環境會提供自己的圖型化登入管理程式,請參考 GNOME 取得如何設定 GNOME 顯示管理程式 (GNOME Display Manager) 的操作方式以及 KDE 取得如何設定 KDE 顯示管理程式 (KDE Display Manager) 的操作方式。
5.6.1. 設定 XDM
要安裝 XDM 可使用 x11/xdm 套件或 Port。安裝完成之後,可設定 XDM 在開機時執行,只需編輯 /etc/ttys 中的此項目:
ttyv8 "/usr/local/bin/xdm -nodaemon" xterm off secure
更改關 (off
) 為開 (on
) 然後儲存編輯。在此項目中的 ttyv8
代表 XDM 會在第 9 個虛擬終端機執行。
XDM 的設定目錄位於 /usr/local/etc/X11/xdm。此目錄中包含數個可用來更改 XDM 行為與外觀的檔案以及在 XDM 執行時用來設定桌面的一些 Script 及程式,XDM 設定檔 摘要了每個檔案的功能。這些檔案正確的語法與用法在 xdm(1) 有說明。
檔案 | 說明 |
---|---|
Xaccess | 連線到 XDM 所需的通訊協定稱做 X 顯示管理程式連線通訊協定 (X Display Manager Connection Protocol, XDMCP),此檔案為客戶端認証規則,用來控制來自遠端機器的 XDMCP 連線。預設此檔案並不允許任何遠端的客戶端連線。 |
Xresources | 此檔案控制 XDM 顯示選擇器及登入畫面的外觀。預設的設定簡單的矩形登入視窗,上方用較大的字型顯示機器的主機名稱,並在下方顯示 "Login:" 與 "Password:" 提示。此檔案的格式與 Xorg 說明文件中說明的 app-defaults 檔相同。 |
Xservers | 登入選擇時在選擇器上要提供的本地及遠端顯示清單。 |
Xsession | 預設的登入階段 Script,使用者登入之後由 XDM 執行。這會指向使用者自訂的登入階段 Script 於 ~/.xsession。 |
Xsetup_* | 用來在顯示選擇器與登入介面之前自動執行應用程式的 Script。每一個顯示各有一個 Script,名稱為 Xsetup_*,其中 |
xdm-config | 用來設定所有在此機器上執行的顯示的全域設定檔。 |
xdm-errors | 內含由伺服器程式產生的錯誤訊息,若 XDM 嘗試啟動的顯示沒有回應,可查看此檔案來取得錯誤訊息。以登入階段為基礎,這些訊息也同樣會寫入至使用者的 ~/.xsession-errors。 |
xdm-pid | XDM 的執行程序 ID。 |
5.6.2. 設定遠端存取
預設只有同系統的使用者可以使用 XDM 登入。要開啟讓其他系統的使用者可連線到顯示伺服器,需編輯存取控制規則及開啟連線傾聽程式。
要設定 XDM 傾聽任何遠端的連線,在 /usr/local/etc/X11/xdm/xdm-config 中的 DisplayManager.requestPort
行前加上 !
來註解該行:
! SECURITY: do not listen for XDMCP or Chooser requests
! Comment out this line if you want to manage X terminals with xdm
DisplayManager.requestPort: 0
儲存編輯並重新啟動 XDM,要限制遠端存取,請看 /usr/local/etc/X11/xdm/Xaccess 中的範例項目,並參考 xdm(1) 取得進一步資訊。
5.7. 桌面環境
本節將介紹如何在 FreeBSD 系統安裝三種熱門的桌面環境。一套桌面環境的範圍可從簡單的視窗管理程式到完整的桌面應用程式集。有上百套的桌面環境可在 Port 套件集的 x11-wm 分類取得。
5.7.1. GNOME
GNOME 是一個擁有友善使用者介面的的桌面環境,它包括用於啟動應用程式和顯示狀態的面板、一系列工具與應用程序及一套可讓應用程式更容易進行合作、相互一致的協定。更多有關 FreeBSD GNOME 的訊息可在 https://www.FreeBSD.org/gnome 取得,該網站包含了有關在 FreeBSD 安裝、設定和管理 GNOME 的額外文件。
這套桌面環境可以從套件安裝:
# pkg install gnome3
也可使用以下指令從 Port 編譯 GNOME,GNOME 是一套大型的應用程式,即使在速度較快的電腦上,也會需要花費一些時間編譯。
# cd /usr/ports/x11/gnome3
# make install clean
GNOME 需要掛載 /proc。加入下行到 /etc/fstab 讓系統啟動時會自動掛載這個檔案系統:
proc /proc procfs rw 0 0
GNOME 使用了 D-Bus 以及 HAL 的 Message bus 與 Hardware abstraction。這兩個應用程式會隨著 GNOME 的相依一併自動安裝,但需要在 /etc/rc.conf 開啟,這樣在系統開機時才會啟動:
dbus_enable="YES" hald_enable="YES"
安裝完之後,需設定讓 Xorg 啟動 GNOME。最簡單的方法是開啟 GNOME Display Manager, GDM,該程式已做為 GNOME 套件或 Port 的一部份安裝了,可加入下行到 /etc/rc.conf 來開啟:
gdm_enable="YES"
通常也會需要啟動所有的 GNOME 服務,可加入下行到 /etc/rc.conf:
gnome_enable="YES"
GDM 則會在系統開機時自動啟動。
第二種啟動 GNOME 的方法是在設定完 ~/.xinitrc 後在指令列輸入 startx
。若這個檔案已經存在,替換啟動目前視窗管理程式的那一行,改為啟動 /usr/local/bin/gnome-session。若檔案不存在,則使用以下指令建立一個:
% echo "exec /usr/local/bin/gnome-session" > ~/.xinitrc
第三種方法是使用 XDM 做為顯示管理程式,在這個方法需要建立一個可執行的 ~/.xsession:
% echo "exec /usr/local/bin/gnome-session" > ~/.xsession
5.7.2. KDE
KDE 是另一套易於使用的桌面環境。這個桌面環境提供了一致外觀的應用程式、標準化的選單和工具列、組合鍵、配色方案、國際化與集中、對話框導向的桌面設定。更多有關 KDE 可在 http://www.kde.org/ 取得。要取得 FreeBSD 特定的資訊,則可參考 http://freebsd.kde.org。
要安裝 KDE 套件,請輸入:
# pkg install x11/kde5
或者要使用 KDE Port 編譯,可使用以下指令,採用 Port 方式安裝會有選單可以選擇要安裝的元件。KDE 是一個大型的應用程式,即使在較快的電腦上仍需要花費一段時間來編譯。
# cd /usr/ports/x11/kde5
# make install clean
KDE 需要掛載 /proc。加入下行到 /etc/fstab 讓系統啟動時會自動掛載這個檔案系統:
proc /proc procfs rw 0 0
KDE 使用了 D-Bus 以及 HAL 的 Message bus 與 Hardware abstraction。這兩個應用程式會隨著 KDE 的相依一併自動安裝,但需要在 /etc/rc.conf 開啟,這樣在系統開機時才會啟動:
dbus_enable="YES" hald_enable="YES"
自 KDE Plasma 5 開始,KDE Display Manager, KDM 便停止開發,可能的替代方案為 SDDM,要安裝該套件可輸入:
# pkg install x11/sddm
加入下行到 /etc/rc.conf:
sddm_enable="YES"
第二種執行 KDE 的方法是在在指令列輸入 startx
。要採用這個方式,需要加入下行到 ~/.xinitrc:
exec ck-launch-session startkde
第三種啟動 KDE 的方式是透過 XDM,要使用這個方法需要建立一個可執行的 ~/.xsession 如下:
% echo "exec ck-launch-session startkde" > ~/.xsession
啟動 KDE 之後,請參考內建的說明系統來取得更多有關如何使用各種選單及應用程式的資訊。
5.7.3. Xfce
Xfce 是以 GNOME 使用的 GTK +工具包做為基礎所開發的桌面環境,但是它更輕巧且提供了一種簡單、高效、易於使用的桌面。它可完全自訂設定、附有選單、Applet 及應用程式啟動器的主面板、提供檔案管理程式和音效管理程式並且可設定主題。由於它是快速、輕巧、高效的桌面環境,因此它非常適合有記憶體限制的較舊或較慢機器。更多有關 Xfce 的資訊可至 http://www.xfce.org 取得。
要安裝 Xfce 套件:
# pkg install xfce
或者使用 Port 編譯:
# cd /usr/ports/x11-wm/xfce4
# make install clean
Xfce 使用了 D-Bus 作為 Message bus,由於是 Xfce 的相依,因此會自動安裝,但仍要在 /etc/rc.conf 中開啟該程式才會在系統開機時啟動:
dbus_enable="YES"
不像 GNOME 或 KDE,Xfce 並沒有自己的登入管理程式,要能用 startx
指令列啟動 Xfce 之前需先加入其項目到 ~/.xinitrc:
% echo ". /usr/local/etc/xdg/xfce4/xinitrc" > ~/.xinitrc
另一種方式是使用 XDM,要設定這個方式需建立一個可執行的 ~/.xsession:
% echo ". /usr/local/etc/xdg/xfce4/xinitrc" > ~/.xsession
5.8. 安裝 Compiz Fusion
要令使用桌面電腦更令人愉快的方法是用炫麗的 3D 效果。
安裝 Compiz Fusion 套件非常簡單,但設定該套件需要一些未在 Port 說明文件中說明的步驟。
5.8.1. 設定 FreeBSD nVidia 驅動程式
桌面特效需要使用相當程度的顯示卡,對於以 nVidia 為基礎的顯示卡,需要使用專用的驅動程序來取得較佳的性能。其他顯示卡的使用可以跳過這一節,並繼續 xorg.conf 設定。
要知道需要那一種 nVidia 驅動程式可以查看 FAQ 中與此主題相關的問題。
知道您的顯示卡要使用那種驅動程式才是正確的之後,接下來的安裝程序跟安裝其他套件一樣簡單。
例如,要安裝最新的驅動程式:
# pkg install x11/nvidia-driver
驅動程式會建立一個需要在系統啟動時載入的核心模組,加入下行到 /boot/loader.conf:
nvidia_load="YES"
要立即載入核心模組到執行中的核心可以下 |
核心模組載入之後,您只需要更改 xorg.conf 的其中一行來開啟專用的驅動程式:
找到 /etc/X11/xorg.conf 中的下行:
Driver "nv"
然後更改該行為:
Driver "nvidia"
如往常般啟動 GUI,您應該會看到 nVidia 的啟動畫面,其他東西應如往常般運作。
5.8.2. 設定 xorg.conf 來啟動桌面特效
要開啟 Compiz Fusion 需要修改 /etc/X11/xorg.conf:
加入以下 Section 來開啟合成特效:
Section "Extensions" Option "Composite" "Enable" EndSection
找到 "Screen" section,長的應該如下所示:
Section "Screen" Identifier "Screen0" Device "Card0" Monitor "Monitor0" ...
然後加入以下兩行 (在"Monitor" 之後):
DefaultDepth 24 Option "AddARGBGLXVisuals" "True"
找到您欲使用的螢幕解析度所在的 "Subsection",例如,您想要使用 1280x1024,則找到如下所示的 Section。若想要使用的解析度不在任何 Subsection 之中,您可以手動加入對應的項目:
SubSection "Display" Viewport 0 0 Modes "1280x1024" EndSubSection
桌面合成需要 24 bit 的色彩深度,更改上述 Subsection 為:
SubSection "Display" Viewport 0 0 Depth 24 Modes "1280x1024" EndSubSection
最後確認在 "Module" section 中已經載入 "glx" 與 "extmod" 模組:
Section "Module" Load "extmod" Load "glx" ...
前面所述的動作可以執行 x11/nvidia-xconfig 來自動完成 (使用 root):
# nvidia-xconfig --add-argb-glx-visuals
# nvidia-xconfig --composite
# nvidia-xconfig --depth=24
5.8.3. 安裝與設定 Compiz Fusion
安裝 Compiz Fusion 如同安裝其他套件一樣簡單:
# pkg install x11-wm/compiz-fusion
安裝完成之後,開啟您的圖型化桌面,然後在終端機的畫面輸入以下指令 (使用一般使用者):
% compiz --replace --sm-disable --ignore-desktop-hints ccp &
% emerald --replace &
由於您的視窗管理程式 (例如:Metacity,若您使用 GNOME) 會被替換成 Compiz Fusion,您的螢幕會閃爍幾秒。而 Emerald 會處理視窗的裝飾 (例如:關閉、最小化、最大化按鈕、標題列及其他相關)。
您或許可以將這些指令改寫成較小的 Script 然後在啟動時自動執行 (加到 GNOME 桌面的 "Sessions" 中):
#! /bin/sh compiz --replace --sm-disable --ignore-desktop-hints ccp & emerald --replace &
儲存這個 Script 到您的家目錄所在位置,例如 start-compiz,然後讓該檔案可以執行:
% chmod +x ~/start-compiz
接著使用 GUI 將該檔案加入啟動程式
(位於 GNOME 桌面的系統 , 偏好設定 , 工作階段 )。要選擇所想使用的特效與相關設定,可執行 (一樣使用一般使用者) Compiz Config 設定管理程式 Compiz Config Settings Manager:
% ccsm
在 GNOME 中,也可在系統 , 偏好設定 選單中找到。 |
若您在編譯時選擇了 "gconf support",您便可使用 gconf-editor
在 apps/compiz
下查看設定。
5.9. 疑難排解
若滑鼠無法使用,您將需要做第一次設定方可繼續。在最近的 Xorg 版本,使用自動偵測裝置會忽略在 xorg.conf 中的 InputDevice
section。要採用舊的方式,需在此檔案加入下行到 ServerLayout
或 ServerFlags
section:
Option "AutoAddDevices" "false"
輸入裝置便可如先前版本一樣設定,連同其他所需的選項 (如:切換鍵盤配置)。
如同前面有說明過,hald Daemon 預設會自動偵測您的鍵盤,因此您的鍵盤配置或型號可能不正確,桌面環境如 GNOME, KDE 或 Xfce 會提供設定鍵盤的工具。即使如此,還是有可能透過 setxkbmap(1) 工具或 hald 的設定規則的協助來直接設定鍵盤屬性。 舉例來說,若有人想要使用 PC 102 鍵的鍵盤,採用法語 (French) 配置,我們便需要建立一個給 hald 的鍵盤設定檔,名稱為 x11-input.fdi,然後儲存到 /usr/local/etc/hal/fdi/policy 目錄。這個檔案中應要有以下幾行: <?xml version="1.0" encoding="utf-8"?> <deviceinfo version="0.2"> <device> <match key="info.capabilities" contains="input.keyboard"> <merge key="input.x11_options.XkbModel" type="string">pc102</merge> <merge key="input.x11_options.XkbLayout" type="string">fr</merge> </match> </device> </deviceinfo> 若這個檔案已經存在,只需要複製並貼上您的檔案中有關鍵盤設定的那幾行。 您會需要重新啟動您的機器來讓 hald 讀取這個檔案。 也是可以從 X 終端機或 Script 下指令來做同樣的設定:
/usr/local/shared/X11/xkb/rules/base.lst 中列出了各種可用的鍵盤、配置與設定。 |
現在可以開始調整 xorg.conf.new 設定檔,在文字編輯器如 emacs(1) 或 ee(1) 開啟該設定檔。若顯示器是不支援自動偵測同步頻率 (Sync frequency) 的舊或特殊的型號,同步頻率的設定可以手動加到 xorg.conf.new 的 "Monitor"
section:
Section "Monitor" Identifier "Monitor0" VendorName "Monitor Vendor" ModelName "Monitor Model" HorizSync 30-107 VertRefresh 48-120 EndSection
多數顯示器都支援自動偵測同步頻率,並不需要手動設定這些數值。對於那些不支援自動偵測的顯示器,請輸入由製造商提供的數值來避免損壞顯示器。
X 允許在支援的顯示器使用 DPMS (Energy Star) 功能,xset(1) 程式可以控制逾時並可強制待機 (Standby)、暫停 (Suspend) 或關閉 (Off) 模式。若您想要為您的顯示器開啟 DPMS 功能,您需要加入下行到顯示器 (Monitor) 的 Section:
Option "DPMS"
在編輯器還未關閉 xorg.conf.new 設定檔前,選擇想要使用的預設解析度及色彩深度。這些項目可在 "Screen"
section 定義:
Section "Screen" Identifier "Screen0" Device "Card0" Monitor "Monitor0" DefaultDepth 24 SubSection "Display" Viewport 0 0 Depth 24 Modes "1024x768" EndSubSection EndSection
DefaultDepth
關鍵字代表預設執行要使用的色彩深度,這個設定可以被 Xorg(1) 的指令列參數 -depth
覆蓋。Modes
關鍵字代表執行要使用的解析度,注意,只有 VESA 標準模式才支援目標系統的繪圖硬體來定義解析度。在上述的例子中,預設使用的色彩深度為每像素 24 bit,這個色彩深度可用的解析度為 1024 x 768 像素。
最後,儲存設定檔並使用測試模式來測試上述的設定。
有一個工具可以協助您診斷問題,那就是 Xorg 日誌檔。該日誌檔中記錄了 Xorg 連接的每個裝置的資訊。Xorg 記錄檔名稱的格式為 /var/log/Xorg.0.log,確切的記錄檔名會可能從 Xorg.0.log 到 Xorg.8.log 以此類推。 |
若一且運作正常,設定檔需要安裝到 Xorg(1) 會尋找的常用設定檔位置,通常是 /etc/X11/xorg.conf 或 /usr/local/etc/X11/xorg.conf。
# cp xorg.conf.new /etc/X11/xorg.conf
5.9.1. 設定 Intel™i810
繪圖晶片組
要設定 Intel™ i810 整合晶片組需要使用 agpgart AGP 程式介面來控制 Xorg 驅動該顯示卡。請參考 agp(4) 驅動程式操作手冊來取得更多詳細資訊。
這也可讓您可以設定任何其他繪圖卡的硬體。注意,在未編譯 agp(4) 到核心的系統,並無法使用 kldload(8) 來載入該模組,因此驅動程式必須在開機時便在核心啟動,所以需要透過編譯或使用 /boot/loader.conf 來載入。
5.9.2. 加入寬螢幕平板顯示器到設定檔
此章節會需要有一些進階的設定知識,若嘗試使用上述的標準設定工具仍無法產生可運作的設定,在日誌檔中應有足夠的資訊可運用來讓顯示卡運作。在此會需要使用文字編輯器。
目前使用寬螢幕 (WSXGA, WSXGA+, WUXGA, WXGA, WXGA+, et.al.) 格式支援的 16:10 及 10:9 格式或其他的寬高比可會有問題。例如一些 16:10 寬高比常見的螢幕解析度:
2560x1600
1920x1200
1680x1050
1440x900
1280x800
在某些時候,可以簡單的將這些要使用的解析度以 Mode
加入到 Section "Screen":
Section "Screen" Identifier "Screen0" Device "Card0" Monitor "Monitor0" DefaultDepth 24 SubSection "Display" Viewport 0 0 Depth 24 Modes "1680x1050" EndSubSection EndSection
Xorg 能夠從寬螢幕設定取得解析度資訊 (透過 I2C/DDC),因此能夠知道螢幕能處理的頻率及解析度。
若驅動程式中不存在那些螢幕能處理的 ModeLines
,則需要給 Xorg 一點提示。透過 /var/log/Xorg.0.log 可以取得足夠的資訊來手動建立可運作的 ModeLine
。只需要在日誌檔中找到類似以下的訊息:
(II) MGA(0): Supported additional Video Mode: (II) MGA(0): clock: 146.2 MHz Image Size: 433 x 271 mm (II) MGA(0): h_active: 1680 h_sync: 1784 h_sync_end 1960 h_blank_end 2240 h_border: 0 (II) MGA(0): v_active: 1050 v_sync: 1053 v_sync_end 1059 v_blanking: 1089 v_border: 0 (II) MGA(0): Ranges: V min: 48 V max: 85 Hz, H min: 30 H max: 94 kHz, PixClock max 170 MHz
這些資訊稱作 EDID 資訊,使用 EDIT 資訊建立 ModeLine
只需要將數據使用正確的順序放入:
ModeLine <name> <clock> <4 horiz. timings> <4 vert. timings>
將資訊放入之後,本例中 Section "Monitor"
中的 ModeLine
會看起來像這樣:
Section "Monitor" Identifier "Monitor1" VendorName "Bigname" ModelName "BestModel" ModeLine "1680x1050" 146.2 1680 1784 1960 2240 1050 1053 1059 1089 Option "DPMS" EndSection
便完成編輯的步驟,接著需要在您的寬螢幕顯示器啟動 X。
5.9.3. Compiz Fusion 疑難排解
5.9.3.1. 我已經安裝了 Compiz Fusion,但在執行了您所提到的指令後,我的視窗的標題列與按鈕便消失了。是那裡有問題?
您可能忘記在 /etc/X11/xorg.conf 中的設定。請重新檢查這個檔案,特別是 DefaultDepth
及 AddARGBGLXVisuals
指令項。
5.9.3.2. 當我執行指令來啟動 Compiz Fusion,X 伺服器便當掉了,然後我又返回 Console。是那裡有問題?
若您檢查 /var/log/Xorg.0.log,您可能可以找到當 X 啟動時所發生的錯誤訊息。最常發生的錯誤會是:
(EE) NVIDIA(0): Failed to initialize the GLX module; please check in your X
(EE) NVIDIA(0): log file that the GLX module has been loaded in your X
(EE) NVIDIA(0): server, and that the module is the NVIDIA GLX module. If
(EE) NVIDIA(0): you continue to encounter problems, Please try
(EE) NVIDIA(0): reinstalling the NVIDIA driver.
會發生這個情形通常是因為您升級了 Xorg,您需要重新安裝 x11/nvidia-driver 套件來重新編譯 glx。
Part II: 一般作業
既然基礎的部分已經提過了,接下來的這個部分將會討論一些常會用到的 FreeBSD 的特色,這些章節包括:
介紹給您常見且實用的桌面應用軟體:瀏覽器、辦工工具、文件閱覽程式等。
介紹給您眾多 FreeBSD 上可用的多媒體工具。
解釋如何編譯量身訂做的 FreeBSD 核心以增加額外系統功能的流程。
詳細描述列印系統,包含桌上型印表機及網路印表機的設定。
展示給您看如何在您的 FreeBSD 系統中執行 Linux 應用軟體。
這些章節中有些需要您預先閱讀些相關文件,在各章節開頭的概要內會提及。
Chapter 6. 桌面應用程式
6.1. 概述
隨著 FreeBSD 優越的效能及穩定性越來越熱門,它同時適合作為每日使用的桌面系統。FreeBSD 套件或 Port 有超過 24,000 個可用的應用程式,可以簡單的建立一個自訂的桌面環境來執行各種不同的桌面應用程式。本章將示範如何安裝數個桌面應用程式,包含網頁瀏覽器、辦工軟體、文件閱覽程式以及財務軟體。
比起重頭設定與編譯,較偏好使用 FreeBSD 桌面環境已預先編譯好版本的使用者可參考 trueos.org 網站。 |
在閱讀這章之前,你必須了解如何:
使用套件或 Port 安裝其他軟體如 安裝應用程式:套件與 Port 所敘述。
安狀 X 與視窗管理程式如 X Window 系統 所敘述。
要取得有關如何設定多媒體環境的資訊,請參考 多媒體。
6.2. 瀏覽器
在 FreeBSD 中並未預先安裝好網頁瀏覽器。 但在 Port 套件集中的 www 分類中有許多瀏覽器可以採 Binary 套件安裝或自 Port 套件集編譯的方式安裝。
KDE 和 GNOME 桌面環境都有提供自有的 HTML 瀏覽器。請參考 桌面環境 來了解更多有關如何設定完整桌面環境的資訊。
有一些輕量化的瀏覽器可使用,包含 www/dillo2, www/links 以及 www/w3m。
本章節將示範如何安裝下列常見的網頁瀏覽器並說明該應用程式是否需要用到大量資源、花費大量時間自 Port 編譯或何主要的相依套件。
應用程式名稱 | 所需資源 | 自 Port 安裝時間 | 說明 |
---|---|---|---|
Firefox | 中 | 多 | 有 FreeBSD 、 Linux™ 及在地化版本 |
Opera | 少 | 少 | 有 FreeBSD 、 Linux™ 版本 |
Konqueror | 中 | 多 | 需要 KDE 程式庫 |
Chromium | 中 | 多 | 需要 Gtk+ 程式庫 |
6.2.1. Firefox
Firefox 是一套開放源始碼的瀏覽器,它具備符合 HTML 標準的顯示引擎、頁籤瀏覽、彈出視窗封鎖、擴充套件、強化安全性及其他更多功能。Firefox 的基礎使用了 Mozilla 的程式庫。
要安裝最新釋出版本的 Firefox 套件可輸入:
# pkg install firefox
要安裝延長支援發佈 (Extended Support Release, ESR) 版本的 Firefox,可使用:
# pkg install firefox-esr
在地化的版本可在 www/firefox-i18n 及 www/firefox-esr-i18n 取得。
使用 Port 套件地可以用原始碼編譯成您想要的 Firefox 版本。此範例編譯 www/firefox,其中 firefox
可替換為 ESR 或在地化版本來安裝。
# cd /usr/ports/www/firefox
# make install clean
6.2.2. Opera
Opera 是個具備完整功能、符合標準且輕量、執行速度快的瀏覽器。 它同時也具備了內建的郵件、新聞閱讀器、IRC 客戶端、RSS/Atom 來源閱讀器等。 可用的版本有兩種原生的 FreeBSD 版本及 Linux™ 模擬模式下執行的版本。
以下指令可安裝 FreeBSD Binary 套件版本的 Opera,替換 opera
為 linux-opera
則可改安裝 Linux™ 版本。
# pkg install opera
或者,可安裝 Port 套件集中的版本,以下範例會編譯原生的版本:
# cd /usr/ports/www/opera
# make install clean
要安裝 Linux™ 則替換 opera
為 linux-opera
。
要安裝 Adobe™Flash™ 附加元件,需先編譯 www/linux-flashplayer Port,因受到授權條款限制無法事先編譯為 Binary 套件。然後再安裝 www/opera-linuxplugins。以下範例示範如何編譯 Port 中的這兩個應用程式:
# cd /usr/ports/www/linux-flashplayer
# make install clean
# cd /usr/ports/www/opera-linuxplugins
# make install clean
安裝完成後,開啟瀏覽器檢查附加元件是否存在,在網址列輸入 opera:plugins
並按下 Enter 鍵,便會有清單顯示目前可用的附加元件。
若要安裝 Java™ 附加元件請接著安裝 java/icedtea-web。
6.2.3. Konqueror
Konqueror 不只是個網頁瀏覽器, 它同時也是檔案管理器和多媒體瀏覽器。它包含在 x11/kde4-baseapps 套件或 Port 中。
Konqueror 使用支援 WebKit 以及它自有的 KTHML。WebKit 是一套被許多現代瀏覽器所使用的繪圖引擎,包含 Chromium。要在 FreeBSD 的 Konqueror 使用 WebKit 需安裝 www/kwebkitpart 套件或 Port。此範例示範使用 Binary 套件安裝:
# pkg install kwebkitpart
從 Port 套件集安裝:
# cd /usr/ports/www/kwebkitpart
# make install clean
要啟動 Konqueror 中的 WebKit 點選 "Settings"、"Configure Konqueror"。在 "General" 設定頁面內點選 "Default web browser engine" 旁的下拉示選單並變更 "KHTML" 為 "WebKit"。
Konqueror 也支援 Flash™,"如何"在 Konqueror 上安裝 Flash™ 的說明可參考 http://freebsd.kde.org/howtos/konqueror-flash.php。
6.3. 辦工工具
當開始進行辦公,使用者通常會找好用的辦公軟體或是好上手的文書處理程式。 雖然有些 桌面環境 像是 KDE 已經提供了辦公軟體,但並沒有預設的辦公軟體,FreeBSD 提供多套辦公軟體以及圖型化文書處理程式,不論您用那種的視窗管理程式都能使用。
本章節元範如何安裝以下熱門的辦公軟體以及說明該應用程式所需的資源、自 Port 編譯的時間或者是否有其他主要相依套件。
應用程式名稱 | 所需資源 | 自 Port 安裝時間 | 主要相依套件 |
---|---|---|---|
Calligra | 少 | 多 | KDE |
AbiWord | 少 | 少 | Gtk+ 或 GNOME |
The Gimp | 少 | 多 | Gtk+ |
Apache OpenOffice | 多 | 非常多 | JDK™ 及 Mozilla |
LibreOffice | 有點多 | 非常多 | Gtk+ 或 KDE/ GNOME 或 JDK™ |
6.3.1. Calligra
KDE 桌面環境中內含辦公軟體可以與 KDE 分開安裝。Calligra 中也有可在其他辦公軟體中找到的標準元件,如 Words 是文件處理程式、Sheets 是試算表程式、Stage 可管理投影片以及 Karbon 用來繪製圖型文件。
在 FreeBSD 中 editors/calligra 可以使用套件或 Port 的方式安裝,要使用套件安裝:
# pkg install calligra
若沒有可用的套件,可改使用 Port 套件集安裝:
# cd /usr/ports/editors/calligra
# make install clean
6.3.2. AbiWord
AbiWord 是一個免費的文件處理軟體,外觀和感覺都近似於 Microsoft™ Word。 它非常快速,包含了許多功能而且非常容易上手。
AbiWord 可以輸入或輸出許多檔案格式, 包括一些有專用的格式,例如 Microsoft™ .rtf 格式。
要安裝 AbiWord Binary 套件,可使用下列指令:
# pkg install abiword
若沒有 Binary 套件版本,也可以從 Port 套件集中編譯安裝:
# cd /usr/ports/editors/abiword
# make install clean
6.3.3. The GIMP
對於影像的編輯及修改來說,The GIMP 是非常精緻的影像處理軟體。 它可以當作簡單的繪圖軟體或是高品質的相片處理軟體。 它支援為數眾多的外掛程式及指令稿 (script-fu) 介面。 The GIMP 可以讀寫許多檔案格式。 它也支援掃描器和手寫板。
要安裝套件可:
# pkg install gimp
或使用 Port 套件集安裝:
# cd /usr/ports/graphics/gimp
# make install clean
在 Port 套件集的 graphics 分類 (freebsd.org/ports/) 下也包含了許多 GIMP 相關的附加元件,說明檔及使用手冊。
6.3.4. Apache OpenOffice
Apache OpenOffice 是開放原始碼的辦工室軟體,由 Apache Software Foundation’s Incubator 底下的團隊所開發。 它包含了所有完整的辦公軟體組合: 文字處理器、試算表、簡報軟體還有繪圖軟體。 除了它的使用者介面非常類似其他的辦公軟體, 他還能夠輸入和輸出許多熱門的檔案格式。 它也包含了不同語言的使用者介面、拼字檢查和字典。
Apache OpenOffice 的文字處理器使用原生的 XML 檔案格式來增加移植性及彈性。 試算表程式支援巨集 (Macro) 功能而且能夠使用外來的資料庫介面。 Apache OpenOffice 已經十分穩定, 並且能夠在 Windows™, Solaris™, Linux™, FreeBSD 及 Mac OS™ X 等作業系統上面執行。 想知道更多關於 Apache OpenOffice 的資訊可以在 openoffice.org 網頁上查詢。在 FreeBSD 特定的資訊可參考 porting.openoffice.org/freebsd/。
要安裝 Apache OpenOffice 套件:
# pkg install apache-openoffice
當套件安裝完成之後,只要輸入下面的指令就能執行 Apache OpenOffice:
% openoffice-X.Y.Z
其中 X.Y.Z 是已安裝的 Apache OpenOffice 的版本編號。第一次執行 Apache OpenOffice 會詢問一些問題且會在使用者的家目錄建立一個 .openoffice.org 資料夾。
若無法由套件取得想要的 Apache OpenOffice,仍可選擇從 Port 編譯。 不過必須注意:編譯的過程會需要大量的磁碟空間與時間:
# cd /usr/ports/editors/openoffice-4
# make install clean
如果想要編譯在地化的版本,將前面的指令替換成為:
替換 your_language 為正確的語言 ISO 編碼。支援的語言編碼清單在 files/Makefile.localized,位於該 Port 的目錄。 |
6.3.5. LibreOffice
LibreOffice 是一套自由的辦公軟體由 documentfoundation.org 所開發。它可相容其他主流的辦公軟體以及可在各種平台上使用。它是 Apache OpenOffice 品牌重塑後的分支,含有可在完整辦公生產力軟體中找到的應用程式:文件處理程式、試算表、簡報管理程式、繪圖程式、資料庫管理程式以及建立與編輯數學公式的工具。它也支援數種語言與國際化一直延伸到介面、拼字檢查程式與字典。
LibreOffice 的文件處理程式使用了原生的 XML 檔案格式來增加可攜性與彈性,試算表程式支援可與外部資料庫連接的巨集語言。LibreOffice 非常穩定且可直接在 Windows™, Linux™, FreeBSD 以及 Mac OS™ X 上執行。更多有關 LibreOffice 的資訊可在 libreoffice.org 找到。
要安裝英文版本的 LibreOffice 套件:
# pkg install libreoffice
Port 套件集的編輯器分類 (freebsd.org/ports/) 中含有數個 LibreOffice 的語系。安裝在地化套件時,請替換 libreoffice
為在地化套件的名稱。
套件安裝之後,輸入以下指令來執行 LibreOffice:
% libreoffice
第一次啟動的過程中會詢問一些問題並在使用者的家目錄建立 .libreoffice 資料夾。
若找不到想使用的 LibreOffice 套件,也可從 Port 編譯,但這會要大量的磁碟空間及漫長的時間編譯。以下例子示範編譯英文版本:
# cd /usr/ports/editors/libreoffice
# make install clean
要編譯在地化版本,則需 |
6.4. 文件閱覽程式
UNIX™ 出現之後,有一些新的文件格式才越來越熱門,這些文件所需的檢視程式可能並不在基礎系統中。本節將示範如何安裝以下文件檢視程式:
應用程式名稱 | 所需資源 | 自 Port 安裝時間 | 主要相依套件 |
---|---|---|---|
Xpdf | 少 | 少 | FreeType |
gv | 少 | 少 | Xaw3d |
Geeqie | 少 | 少 | Gtk+ 或 GNOME |
ePDFView | 少 | 少 | Gtk+ |
Okular | 少 | 多 | KDE |
6.4.1. Xpdf
如果你想要一個小型的 FreeBSD PDF 閱覽軟體, Xpdf 是個輕量級而且有效率的閱覽器。 它只需要非常少的資源而且十分穩定。 它只使用標準的 X 字型且不需要額外的工具包(Toolkit)。
安裝 Xpdf 套件:
# pkg install xpdf
若沒有可用的套件版本,可使用 Port 套件集安裝:
# cd /usr/ports/graphics/xpdf
# make install clean
完成安裝後,執行 xpdf
並使用滑鼠右鍵開啟選單。
6.4.2. gv
gv 是 PostScript™ 和 PDF 的閱覽器。 它建構於 ghostview 的基礎上,不過因為使用 Xaw3d 視窗元件工具包,所以外觀看起來比較漂亮。 gv 有許多可設定的功能,比如說紙張方向、紙張大小、縮放比例、和反鋸齒(Anti-aliasing)等。 而且幾乎所有的使用都可以從鍵盤或滑鼠來完成。
安裝 gv 套件:
# pkg install gv
若沒有可用的套件版本,可使用 Port 套件集安裝:
# cd /usr/ports/print/gv
# make install clean
6.4.3. Geeqie
Geeqie 是由已經停止維護的 GQView 專案所衍伸出來的分支,並致力開發新功能並整合已有的修補。Geeqie 是一套影像管理軟體,支援單鍵閱覽檔案、啟動外部編輯器、縮圖預覽等功能。 它也有幻燈片模式及一些基本的檔案操作的功能,能輕鬆的管理大量影像並找出重複的檔案。 Geeqie 也支援使用全螢幕閱覽以及國際化。
安裝 Geeqie 套件:
# pkg install geeqie
若沒有可用的套件版本,可使用 Port 套件集安裝:
# cd /usr/ports/graphics/geeqie
# make install clean
6.5. 財務
如果有任何理由你想要在你的 FreeBSD 桌面環境上管理你的個人財務, 這裡有一些功能強大、使用簡單的應用程式可供安裝。 這些財務管理軟體之中有些是相容於流行的 Quicken 或 Excel 文件。
這節涵蓋了下面這些軟體:
應用程式名稱 | 所需資源 | 自 Port 安裝時間 | 主要相依套件 |
---|---|---|---|
GnuCash | 少 | 多 | GNOME |
Gnumeric | 少 | 多 | GNOME |
KMyMoney | 少 | 多 | KDE |
6.5.1. GnuCash
GnuCash 是 GNOME 團隊努力成果中的一部分, GNOME 團隊主要提供親切而強大的桌面應用程式給終端使用者。使用 GnuCash 可以持續追蹤收入與花費、銀行帳戶以及股票證券等。 它的特性是介面直覺但功能仍非常專業。
GnuCash 提供了智慧的計數器、多階層帳戶系統以及快速鍵及自動完成功能。 它也能分開單一的報表至數個詳細的部份。 GnuCash 也能夠匯入及合併 Quicken QIF 檔案。 它也能處理大部分國際的日期及通用貨幣之格式。
安裝 GnuCash 套件:
# pkg install gnucash
若沒有可用的套件版本,可使用 Port 套件集安裝:
# cd /usr/ports/finance/gnucash
# make install clean
Chapter 7. 多媒體
7.1. 概述
FreeBSD 廣泛地支援各種音效卡, 讓使用者可以享受來自電腦上的高傳真音質(Hi-Fi), 此外還包括了錄製和播放 MPEG Audio Layer 3 (MP3)、 Waveform Audio File (WAV)、Ogg Vorbis 以及其他許多種格式聲音的能力。同時 FreeBSD Port 套件集也包含了許多可讓您可以錄音、編修音效以及控制 MIDI 配備的應用程式。
FreeBSD 也能播放一般的視訊檔和 DVD。 FreeBSD Port 套件集中含有可編碼、轉換以及播放格種影像媒體的應用程式。
本章會說明如何設定 FreeBSD 上的音效卡、影像播放器、電視卡及掃描器。同時會說明有那些應用程式可以使用這些裝置。
讀完這章,您將了解:
設定 FreeBSD 上的音效卡。
音效設定疑難排解。
播放、錄製 MP3 及其他聲音檔案格式。
FreeBSD 系統播放影像的準備工具。
播放 DVD 的 .mpg 及 .avi 檔。
擷取(Rip) CD 和 DVD的內容至檔案。
設定電視卡。
在 FreeBSD 安裝 MythTV
設定影像掃描機。
設定藍芽耳機。
在開始閱讀這章之前,您需要:
知道如何安裝應用程式如 安裝應用程式:套件與 Port 所敘述。
7.2. 設定音效卡
開始設定之前,必須先知道你的音效卡型號、晶片為何。 FreeBSD 支援許多種音效卡,請檢查支援的音效硬體表 Hardware Notes,以確認你的音效卡是否支援以及如何在 FreeBSD 上驅動。
要使用音效裝置,必須要載入正確的驅動程式才行。最簡單方式就是以 kldload(8) 來載入核心模組。以下範例示範載入 Intel 規格內建的音效晶片驅動程式:
# kldload snd_hda
要開機時自動載入驅動程式,需將驅動程式加到 /boot/loader.conf 檔,以此驅動程式為例:
snd_hda_load="YES"
其他可用的音效卡模組清單列於 /boot/defaults/loader.conf。當不確認要使用何種驅動程式時,可載入 snd_driver 模組:
# kldload snd_driver
它是 metadriver 會載入所有最通用的音效驅動程式並且用來加速尋找正確的驅動程式。也可以把 metadriver 加入 /boot/loader.conf 檔來載入所有音效驅動程式。
要知道載入 snd_driver metadriver 後使用了那個音效卡驅動程式,請輸入 cat /dev/sndstat
。
7.2.1. 設定自訂核心支援音效
This section is for users who prefer to statically compile in support for the sound card in a custom kernel. For more information about recompiling a kernel, refer to 設定 FreeBSD 核心.
When using a custom kernel to provide sound support, make sure that the audio framework driver exists in the custom kernel configuration file:
device sound
Next, add support for the sound card. To continue the example of the built-in audio chipset based on the Intel specification from the previous section, use the following line in the custom kernel configuration file:
device snd_hda
Be sure to read the manual page of the driver for the device name to use for the driver.
Non-PnP ISA sound cards may require the IRQ and I/O port settings of the card to be added to /boot/device.hints. During the boot process, loader(8) reads this file and passes the settings to the kernel. For example, an old Creative SoundBlaster™ 16 ISA non-PnP card will use the snd_sbc(4) driver in conjunction with snd_sb16
. For this card, the following lines must be added to the kernel configuration file:
device snd_sbc device snd_sb16
If the card uses the 0x220
I/O port and IRQ 5
, these lines must also be added to /boot/device.hints:
hint.sbc.0.at="isa" hint.sbc.0.port="0x220" hint.sbc.0.irq="5" hint.sbc.0.drq="1" hint.sbc.0.flags="0x15"
The syntax used in /boot/device.hints is described in sound(4) and the manual page for the driver of the sound card.
The settings shown above are the defaults. In some cases, the IRQ or other settings may need to be changed to match the card. Refer to snd_sbc(4) for more information about this card.
7.2.2. 測試音效
After loading the required module or rebooting into the custom kernel, the sound card should be detected. To confirm, run dmesg | grep pcm
. This example is from a system with a built-in Conexant CX20590 chipset:
pcm0: <NVIDIA (0x001c) (HDMI/DP 8ch)> at nid 5 on hdaa0
pcm1: <NVIDIA (0x001c) (HDMI/DP 8ch)> at nid 6 on hdaa0
pcm2: <Conexant CX20590 (Analog 2.0+HP/2.0)> at nid 31,25 and 35,27 on hdaa1
The status of the sound card may also be checked using this command:
# cat /dev/sndstat
FreeBSD Audio Driver (newpcm: 64bit 2009061500/amd64)
Installed devices:
pcm0: <NVIDIA (0x001c) (HDMI/DP 8ch)> (play)
pcm1: <NVIDIA (0x001c) (HDMI/DP 8ch)> (play)
pcm2: <Conexant CX20590 (Analog 2.0+HP/2.0)> (play/rec) default
The output will vary depending upon the sound card. If no pcm devices are listed, double-check that the correct device driver was loaded or compiled into the kernel. The next section lists some common problems and their solutions.
If all goes well, the sound card should now work in FreeBSD. If the CD or DVD drive is properly connected to the sound card, one can insert an audio CD in the drive and play it with cdcontrol(1):
% cdcontrol -f /dev/acd0 play 1
Audio CDs have specialized encodings which means that they should not be mounted using mount(8). |
Various applications, such as audio/workman, provide a friendlier interface. The audio/mpg123 port can be installed to listen to MP3 audio files.
Another quick way to test the card is to send data to /dev/dsp:
% cat filename > /dev/dsp
where filename can be any type of file. This command should produce some noise, confirming that the sound card is working.
The /dev/dsp* device nodes will be created automatically as needed. When not in use, they do not exist and will not appear in the output of ls(1). |
7.2.3. 設定藍芽音效裝置
Connecting to a Bluetooth device is out of scope for this chapter. Refer to 藍牙 for more information.
To get Bluetooth sound sink working with FreeBSD’s sound system, users have to install audio/virtual_oss first:
# pkg install virtual_oss
audio/virtual_oss requires cuse
to be loaded into the kernel:
# kldload cuse
To load cuse
during system startup, run this command:
# sysrc -f /boot/loader.conf cuse_load=yes
To use headphones as a sound sink with audio/virtual_oss, users need to create a virtual device after connecting to a Bluetooth audio device:
# virtual_oss -C 2 -c 2 -r 48000 -b 16 -s 768 -R /dev/null -P /dev/bluetooth/headphones -d dsp
headphones in this example is a hostname from /etc/bluetooth/hosts. |
請參考 virtual_oss(8) 取得更多資訊。
7.2.4. 疑難排解音效
常見錯誤訊息 lists some common error messages and their solutions:
錯誤 | 解決方式 |
---|---|
| The I/O port is not set correctly. |
| The IRQ is set incorrectly. Make sure that the set IRQ and the sound IRQ are the same. |
| There is not enough available memory to use the device. |
| Type |
Modern graphics cards often come with their own sound driver for use with HDMI. This sound device is sometimes enumerated before the sound card meaning that the sound card will not be used as the default playback device. To check if this is the case, run dmesg and look for pcm
. The output looks something like this:
... hdac0: HDA Driver Revision: 20100226_0142 hdac1: HDA Driver Revision: 20100226_0142 hdac0: HDA Codec #0: NVidia (Unknown) hdac0: HDA Codec #1: NVidia (Unknown) hdac0: HDA Codec #2: NVidia (Unknown) hdac0: HDA Codec #3: NVidia (Unknown) pcm0: <HDA NVidia (Unknown) PCM #0 DisplayPort> at cad 0 nid 1 on hdac0 pcm1: <HDA NVidia (Unknown) PCM #0 DisplayPort> at cad 1 nid 1 on hdac0 pcm2: <HDA NVidia (Unknown) PCM #0 DisplayPort> at cad 2 nid 1 on hdac0 pcm3: <HDA NVidia (Unknown) PCM #0 DisplayPort> at cad 3 nid 1 on hdac0 hdac1: HDA Codec #2: Realtek ALC889 pcm4: <HDA Realtek ALC889 PCM #0 Analog> at cad 2 nid 1 on hdac1 pcm5: <HDA Realtek ALC889 PCM #1 Analog> at cad 2 nid 1 on hdac1 pcm6: <HDA Realtek ALC889 PCM #2 Digital> at cad 2 nid 1 on hdac1 pcm7: <HDA Realtek ALC889 PCM #3 Digital> at cad 2 nid 1 on hdac1 ...
In this example, the graphics card (NVidia
) has been enumerated before the sound card (Realtek ALC889
). To use the sound card as the default playback device, change hw.snd.default_unit
to the unit that should be used for playback:
# sysctl hw.snd.default_unit=n
where n
is the number of the sound device to use. In this example, it should be 4
. Make this change permanent by adding the following line to /etc/sysctl.conf:
hw.snd.default_unit=4
7.2.5. 使用多個音效來源
It is often desirable to have multiple sources of sound that are able to play simultaneously. FreeBSD uses "Virtual Sound Channels" to multiplex the sound card’s playback by mixing sound in the kernel.
Three sysctl(8) knobs are available for configuring virtual channels:
# sysctl dev.pcm.0.play.vchans=4
# sysctl dev.pcm.0.rec.vchans=4
# sysctl hw.snd.maxautovchans=4
This example allocates four virtual channels, which is a practical number for everyday use. Both dev.pcm.0.play.vchans=4
and dev.pcm.0.rec.vchans=4
are configurable after a device has been attached and represent the number of virtual channels pcm0 has for playback and recording. Since the pcm module can be loaded independently of the hardware drivers, hw.snd.maxautovchans
indicates how many virtual channels will be given to an audio device when it is attached. Refer to pcm(4) for more information.
The number of virtual channels for a device cannot be changed while it is in use. First, close any programs using the device, such as music players or sound daemons. |
The correct pcm device will automatically be allocated transparently to a program that requests /dev/dsp0.
7.2.6. 設定混音器頻道的預設值
The default values for the different mixer channels are hardcoded in the source code of the pcm(4) driver. While sound card mixer levels can be changed using mixer(8) or third-party applications and daemons, this is not a permanent solution. To instead set default mixer values at the driver level, define the appropriate values in /boot/device.hints, as seen in this example:
hint.pcm.0.vol="50"
This will set the volume channel to a default value of 50
when the pcm(4) module is loaded.
7.3. MP3 音樂
This section describes some MP3 players available for FreeBSD, how to rip audio CD tracks, and how to encode and decode MP3s.
7.3.1. MP3 播放器
A popular graphical MP3 player is Audacious. It supports Winamp skins and additional plugins. The interface is intuitive, with a playlist, graphic equalizer, and more. Those familiar with Winamp will find Audacious simple to use. On FreeBSD, Audacious can be installed from the multimedia/audacious port or package. Audacious is a descendant of XMMS.
The audio/mpg123 package or port provides an alternative, command-line MP3 player. Once installed, specify the MP3 file to play on the command line. If the system has multiple audio devices, the sound device can also be specified:
# mpg123 -a /dev/dsp1.0 Foobar-GreatestHits.mp3
High Performance MPEG 1.0/2.0/2.5 Audio Player for Layers 1, 2 and 3
version 1.18.1; written and copyright by Michael Hipp and others
free software (LGPL) without any warranty but with best wishes
Playing MPEG stream from Foobar-GreatestHits.mp3 ...
MPEG 1.0 layer III, 128 kbit/s, 44100 Hz joint-stereo
Additional MP3 players are available in the FreeBSD Ports Collection.
7.3.2. 擷取 CD 音軌
Before encoding a CD or CD track to MP3, the audio data on the CD must be ripped to the hard drive. This is done by copying the raw CD Digital Audio (CDDA) data to WAV files.
The cdda2wav
tool, which is installed with the sysutils/cdrtools suite, can be used to rip audio information from CDs.
With the audio CD in the drive, the following command can be issued as root
to rip an entire CD into individual, per track, WAV files:
# cdda2wav -D 0,1,0 -B
In this example, the -D 0,1,0
indicates the SCSI device 0,1,0 containing the CD to rip. Use cdrecord -scanbus
to determine the correct device parameters for the system.
To rip individual tracks, use -t
to specify the track:
# cdda2wav -D 0,1,0 -t 7
To rip a range of tracks, such as track one to seven, specify a range:
# cdda2wav -D 0,1,0 -t 1+7
To rip from an ATAPI (IDE) CDROM drive, specify the device name in place of the SCSI unit numbers. For example, to rip track 7 from an IDE drive:
# cdda2wav -D /dev/acd0 -t 7
Alternately, dd
can be used to extract audio tracks on ATAPI drives, as described in 複製音樂 CD.
7.3.3. MP3 編碼與解碼
Lame is a popular MP3 encoder which can be installed from the audio/lame port. Due to patent issues, a package is not available.
The following command will convert the ripped WAV file audio01.wav to audio01.mp3:
# lame -h -b 128 --tt "Foo Song Title" --ta "FooBar Artist" --tl "FooBar Album" \
--ty "2014" --tc "Ripped and encoded by Foo" --tg "Genre" audio01.wav audio01.mp3
The specified 128 kbits is a standard MP3 bitrate while the 160 and 192 bitrates provide higher quality. The higher the bitrate, the larger the size of the resulting MP3. The -h
turns on the "higher quality but a little slower" mode. The options beginning with --t
indicate ID3 tags, which usually contain song information, to be embedded within the MP3 file. Additional encoding options can be found in the lame manual page.
In order to burn an audio CD from MP3s, they must first be converted to a non-compressed file format. XMMS can be used to convert to the WAV format, while mpg123 can be used to convert to the raw Pulse-Code Modulation (PCM) audio data format.
To convert audio01.mp3 using mpg123, specify the name of the PCM file:
# mpg123 -s audio01.mp3 > audio01.pcm
To use XMMS to convert a MP3 to WAV format, use these steps:
Procedure: Converting to WAV Format in XMMS
. Launch XMMS.
. Right-click the window to bring up the XMMS menu.
. Select Preferences
under Options
.
. Change the Output Plugin to "Disk Writer Plugin".
. Press Configure
.
. Enter or browse to a directory to write the uncompressed files to.
. Load the MP3 file into XMMS as usual, with volume at 100% and EQ settings turned off.
. Press Play
. The XMMS will appear as if it is playing the MP3, but no music will be heard. It is actually playing the MP3 to a file.
. When finished, be sure to set the default Output Plugin back to what it was before in order to listen to MP3s again.
Both the WAV and PCM formats can be used with cdrecord. When using WAV files, there will be a small tick sound at the beginning of each track. This sound is the header of the WAV file. The audio/sox port or package can be used to remove the header:
% sox -t wav -r 44100 -s -w -c 2 track.wav track.raw
Refer to 建立與使用 CD 媒體 for more information on using a CD burner in FreeBSD.
7.4. 影片播放
Before configuring video playback, determine the model and chipset of the video card. While Xorg supports a wide variety of video cards, not all provide good playback performance. To obtain a list of extensions supported by the Xorg server using the card, run xdpyinfo
while Xorg is running.
It is a good idea to have a short MPEG test file for evaluating various players and options. Since some DVD applications look for DVD media in /dev/dvd by default, or have this device name hardcoded in them, it might be useful to make a symbolic link to the proper device:
# ln -sf /dev/cd0 /dev/dvd
Due to the nature of devfs(5), manually created links will not persist after a system reboot. In order to recreate the symbolic link automatically when the system boots, add the following line to /etc/devfs.conf:
link cd0 dvd
DVD decryption invokes certain functions that require write permission to the DVD device.
To enhance the shared memory Xorg interface, it is recommended to increase the values of these sysctl(8) variables:
kern.ipc.shmmax=67108864 kern.ipc.shmall=32768
7.4.1. 偵測影像處理能力
There are several possible ways to display video under Xorg and what works is largely hardware dependent. Each method described below will have varying quality across different hardware.
Common video interfaces include:
Xorg: normal output using shared memory.
XVideo: an extension to the Xorg interface which allows video to be directly displayed in drawable objects through a special acceleration. This extension provides good quality playback even on low-end machines. The next section describes how to determine if this extension is running.
SDL: the Simple Directmedia Layer is a porting layer for many operating systems, allowing cross-platform applications to be developed which make efficient use of sound and graphics. SDL provides a low-level abstraction to the hardware which can sometimes be more efficient than the Xorg interface. On FreeBSD, SDL can be installed using the devel/sdl20 package or port.
DGA: the Direct Graphics Access is an Xorg extension which allows a program to bypass the Xorg server and directly alter the framebuffer. Because it relies on a low level memory mapping, programs using it must be run as
root
. The DGA extension can be tested and benchmarked using dga(1). Whendga
is running, it changes the colors of the display whenever a key is pressed. To quit, press q.SVGAlib: a low level console graphics layer.
7.4.1.1. XVideo
To check whether this extension is running, use xvinfo
:
% xvinfo
XVideo is supported for the card if the result is similar to:
X-Video Extension version 2.2
screen #0
Adaptor #0: "Savage Streams Engine"
number of ports: 1
port base: 43
operations supported: PutImage
supported visuals:
depth 16, visualID 0x22
depth 16, visualID 0x23
number of attributes: 5
"XV_COLORKEY" (range 0 to 16777215)
client settable attribute
client gettable attribute (current value is 2110)
"XV_BRIGHTNESS" (range -128 to 127)
client settable attribute
client gettable attribute (current value is 0)
"XV_CONTRAST" (range 0 to 255)
client settable attribute
client gettable attribute (current value is 128)
"XV_SATURATION" (range 0 to 255)
client settable attribute
client gettable attribute (current value is 128)
"XV_HUE" (range -180 to 180)
client settable attribute
client gettable attribute (current value is 0)
maximum XvImage size: 1024 x 1024
Number of image formats: 7
id: 0x32595559 (YUY2)
guid: 59555932-0000-0010-8000-00aa00389b71
bits per pixel: 16
number of planes: 1
type: YUV (packed)
id: 0x32315659 (YV12)
guid: 59563132-0000-0010-8000-00aa00389b71
bits per pixel: 12
number of planes: 3
type: YUV (planar)
id: 0x30323449 (I420)
guid: 49343230-0000-0010-8000-00aa00389b71
bits per pixel: 12
number of planes: 3
type: YUV (planar)
id: 0x36315652 (RV16)
guid: 52563135-0000-0000-0000-000000000000
bits per pixel: 16
number of planes: 1
type: RGB (packed)
depth: 0
red, green, blue masks: 0x1f, 0x3e0, 0x7c00
id: 0x35315652 (RV15)
guid: 52563136-0000-0000-0000-000000000000
bits per pixel: 16
number of planes: 1
type: RGB (packed)
depth: 0
red, green, blue masks: 0x1f, 0x7e0, 0xf800
id: 0x31313259 (Y211)
guid: 59323131-0000-0010-8000-00aa00389b71
bits per pixel: 6
number of planes: 3
type: YUV (packed)
id: 0x0
guid: 00000000-0000-0000-0000-000000000000
bits per pixel: 0
number of planes: 0
type: RGB (packed)
depth: 1
red, green, blue masks: 0x0, 0x0, 0x0
The formats listed, such as YUV2 and YUV12, are not present with every implementation of XVideo and their absence may hinder some players.
If the result instead looks like:
X-Video Extension version 2.2
screen #0
no adaptors present
XVideo is probably not supported for the card. This means that it will be more difficult for the display to meet the computational demands of rendering video, depending on the video card and processor.
7.4.2. 可處理影像的 Port 與套件
This section introduces some of the software available from the FreeBSD Ports Collection which can be used for video playback.
7.4.2.1. MPlayer 與 MEncoder
MPlayer is a command-line video player with an optional graphical interface which aims to provide speed and flexibility. Other graphical front-ends to MPlayer are available from the FreeBSD Ports Collection.
MPlayer can be installed using the multimedia/mplayer package or port. Several compile options are available and a variety of hardware checks occur during the build process. For these reasons, some users prefer to build the port rather than install the package.
When compiling the port, the menu options should be reviewed to determine the type of support to compile into the port. If an option is not selected, MPlayer will not be able to display that type of video format. Use the arrow keys and spacebar to select the required formats. When finished, press Enter to continue the port compile and installation.
By default, the package or port will build the mplayer
command line utility and the gmplayer
graphical utility. To encode videos, compile the multimedia/mencoder port. Due to licensing restrictions, a package is not available for MEncoder.
The first time MPlayer is run, it will create ~/.mplayer in the user’s home directory. This subdirectory contains default versions of the user-specific configuration files.
This section describes only a few common uses. Refer to mplayer(1) for a complete description of its numerous options.
To play the file testfile.avi, specify the video interfaces with -vo
, as seen in the following examples:
% mplayer -vo xv testfile.avi
% mplayer -vo sdl testfile.avi
% mplayer -vo x11 testfile.avi
# mplayer -vo dga testfile.avi
# mplayer -vo 'sdl:dga' testfile.avi
It is worth trying all of these options, as their relative performance depends on many factors and will vary significantly with hardware.
To play a DVD, replace testfile.avi with dvd://N -dvd-device DEVICE
, where N is the title number to play and DEVICE is the device node for the DVD. For example, to play title 3 from /dev/dvd:
# mplayer -vo xv dvd://3 -dvd-device /dev/dvd
The default DVD device can be defined during the build of the MPlayer port by including the |
To stop, pause, advance, and so on, use a keybinding. To see the list of keybindings, run mplayer -h
or read mplayer(1).
Additional playback options include -fs -zoom
, which engages fullscreen mode, and -framedrop
, which helps performance.
Each user can add commonly used options to their ~/.mplayer/config like so:
vo=xv fs=yes zoom=yes
mplayer
can be used to rip a DVD title to a .vob. To dump the second title from a DVD:
# mplayer -dumpstream -dumpfile out.vob dvd://2 -dvd-device /dev/dvd
The output file, out.vob, will be in MPEG format.
Anyone wishing to obtain a high level of expertise with UNIX™ video should consult mplayerhq.hu/DOCS as it is technically informative. This documentation should be considered as required reading before submitting any bug reports.
Before using mencoder
, it is a good idea to become familiar with the options described at mplayerhq.hu/DOCS/HTML/en/mencoder.html. There are innumerable ways to improve quality, lower bitrate, and change formats, and some of these options may make the difference between good or bad performance. Improper combinations of command line options can yield output files that are unplayable even by mplayer
.
Here is an example of a simple copy:
% mencoder input.avi -oac copy -ovc copy -o output.avi
To rip to a file, use -dumpfile
with mplayer
.
To convert input.avi to the MPEG4 codec with MPEG3 audio encoding, first install the audio/lame port. Due to licensing restrictions, a package is not available. Once installed, type:
% mencoder input.avi -oac mp3lame -lameopts br=192 \
-ovc lavc -lavcopts vcodec=mpeg4:vhq -o output.avi
This will produce output playable by applications such as mplayer
and xine
.
input.avi can be replaced with dvd://1 -dvd-device /dev/dvd
and run as root
to re-encode a DVD title directly. Since it may take a few tries to get the desired result, it is recommended to instead dump the title to a file and to work on the file.
7.4.2.2. xine 影像播放器
xine is a video player with a reusable base library and a modular executable which can be extended with plugins. It can be installed using the multimedia/xine package or port.
In practice, xine requires either a fast CPU with a fast video card, or support for the XVideo extension. The xine video player performs best on XVideo interfaces.
By default, the xine player starts a graphical user interface. The menus can then be used to open a specific file.
Alternatively, xine may be invoked from the command line by specifying the name of the file to play:
% xine -g -p mymovie.avi
Refer to xine-project.org/faq for more information and troubleshooting tips.
7.4.2.3. Transcode 工具
Transcode provides a suite of tools for re-encoding video and audio files. Transcode can be used to merge video files or repair broken files using command line tools with stdin/stdout stream interfaces.
In FreeBSD, Transcode can be installed using the multimedia/transcode package or port. Many users prefer to compile the port as it provides a menu of compile options for specifying the support and codecs to compile in. If an option is not selected, Transcode will not be able to encode that format. Use the arrow keys and spacebar to select the required formats. When finished, press Enter to continue the port compile and installation.
This example demonstrates how to convert a DivX file into a PAL MPEG-1 file (PAL VCD):
% transcode -i input.avi -V --export_prof vcd-pal -o output_vcd
% mplex -f 1 -o output_vcd.mpg output_vcd.m1v output_vcd.mpa
The resulting MPEG file, output_vcd.mpg, is ready to be played with MPlayer. The file can be burned on a CD media to create a video CD using a utility such as multimedia/vcdimager or sysutils/cdrdao.
In addition to the manual page for transcode
, refer to transcoding.org/cgi-bin/transcode for further information and examples.
7.5. 電視卡
電視卡 (TV card) 可以讓您用電腦來看無線、有線電視節目。許多卡都是透過 RCA 或 S-video 輸入端子來接收視訊,而且有些卡還可接收 FM 廣播的功能。
FreeBSD 可透過 bktr(4) 驅動程式,來支援 PCI 介面的電視卡,只要這些卡使用的是 Brooktree Bt848/849/878/879 或 Conexant CN-878/Fusion 878a 視訊擷取晶片。此外,要再確認哪些卡上所附的選台功能是否有支援,可以參考 bktr(4) 說明,以查看所支援的硬體清單。
7.5.1. 載入驅動程式
要用電視卡的話,就要載入 bktr(4) 驅動程式,這個可以透過在 /boot/loader.conf 檔加上下面這一行就可以了:
bktr_load="YES"
或者可以將電視卡支援靜態編譯到自訂的核心當中,若要這麼做則可在自訂核心設定檔加入以下行:
device bktr device iicbus device iicbb device smbus
之所以要加上這些額外的驅動程式,是因為卡的各組成部分都是透過 I2C 匯流排而相互連接的。接下來,請編譯、安裝新的核心 。
要測試調諧器 (Tuner) 是否被正確的偵測,請先重新啟動系統。電視卡應該會出現在開機訊息檔中,如同此範例:
bktr0: <BrookTree 848A> mem 0xd7000000-0xd7000fff irq 10 at device 10.0 on pci0 iicbb0: <I2C bit-banging driver> on bti2c0 iicbus0: <Philips I2C bus> on iicbb0 master-only iicbus1: <Philips I2C bus> on iicbb0 master-only smbus0: <System Management Bus> on bti2c0 bktr0: Pinnacle/Miro TV, Philips SECAM tuner.
該訊息會依硬體不同而有所不同。若必要,可以使用 sysctl(8) 系統偵測的參數或者自訂核心設定選項。例如要強制使用 Philips SECAM 調諧器則可加入下列行至自訂核心設定檔:
options OVERRIDE_TUNER=6
或使用 sysctl(8):
# sysctl hw.bt848.tuner=6
7.5.2. 好用的應用程式
To use the TV card, install one of the following applications:
multimedia/fxtv provides TV-in-a-window and image/audio/video capture capabilities.
multimedia/xawtv is another TV application with similar features.
audio/xmradio provides an application for using the FM radio tuner of a TV card.
More applications are available in the FreeBSD Ports Collection.
7.5.3. 疑難排解
If any problems are encountered with the TV card, check that the video capture chip and the tuner are supported by bktr(4) and that the right configuration options were used. For more support or to ask questions about supported TV cards, refer to the freebsd-multimedia mailing list.
7.6. MythTV
MythTV is a popular, open source Personal Video Recorder (PVR) application. This section demonstrates how to install and setup MythTV on FreeBSD. Refer to mythtv.org/wiki for more information on how to use MythTV.
MythTV requires a frontend and a backend. These components can either be installed on the same system or on different machines.
The frontend can be installed on FreeBSD using the multimedia/mythtv-frontend package or port. Xorg must also be installed and configured as described in X Window 系統. Ideally, this system has a video card that supports X-Video Motion Compensation (XvMC) and, optionally, a Linux Infrared Remote Control (LIRC)-compatible remote.
To install both the backend and the frontend on FreeBSD, use the multimedia/mythtv package or port. A MySQL™ database server is also required and should automatically be installed as a dependency. Optionally, this system should have a tuner card and sufficient storage to hold recorded data.
7.6.1. 硬體
MythTV uses Video for Linux (V4L) to access video input devices such as encoders and tuners. In FreeBSD, MythTV works best with USB DVB-S/C/T cards as they are well supported by the multimedia/webcamd package or port which provides a V4L userland application. Any Digital Video Broadcasting (DVB) card supported by webcamd should work with MythTV. A list of known working cards can be found at wiki.freebsd.org/WebcamCompat. Drivers are also available for Hauppauge cards in the multimedia/pvr250 and multimedia/pvrxxx ports, but they provide a non-standard driver interface that does not work with versions of MythTV greater than 0.23. Due to licensing restrictions, no packages are available and these two ports must be compiled.
The wiki.freebsd.org/HTPC page contains a list of all available DVB drivers.
7.6.2. 設定 MythTV 後端
要使用 Binary 套件安裝 MythTV 可:
# pkg install mythtv
或從 Port 套件集安裝:
# cd /usr/ports/multimedia/mythtv
# make install
Once installed, set up the MythTV database:
# mysql -uroot -p < /usr/local/shared/mythtv/database/mc.sql
Then, configure the backend:
# mythtv-setup
Finally, start the backend:
# sysrc mythbackend_enable=yes
# service mythbackend start
7.7. 影像掃描器
In FreeBSD, access to image scanners is provided by SANE (Scanner Access Now Easy), which is available in the FreeBSD Ports Collection. SANE will also use some FreeBSD device drivers to provide access to the scanner hardware.
FreeBSD supports both SCSI and USB scanners. Depending upon the scanner interface, different device drivers are required. Be sure the scanner is supported by SANE prior to performing any configuration. Refer to http://www.sane-project.org/sane-supported-devices.html for more information about supported scanners.
This chapter describes how to determine if the scanner has been detected by FreeBSD. It then provides an overview of how to configure and use SANE on a FreeBSD system.
7.7.1. 檢查掃描器
The GENERIC kernel includes the device drivers needed to support USB scanners. Users with a custom kernel should ensure that the following lines are present in the custom kernel configuration file:
device usb device uhci device ohci device ehci
To determine if the USB scanner is detected, plug it in and use dmesg
to determine whether the scanner appears in the system message buffer. If it does, it should display a message similar to this:
ugen0.2: <EPSON> at usbus0
In this example, an EPSON Perfection™ 1650 USB scanner was detected on /dev/ugen0.2.
If the scanner uses a SCSI interface, it is important to know which SCSI controller board it will use. Depending upon the SCSI chipset, a custom kernel configuration file may be needed. The GENERIC kernel supports the most common SCSI controllers. Refer to /usr/src/sys/conf/NOTES to determine the correct line to add to a custom kernel configuration file. In addition to the SCSI adapter driver, the following lines are needed in a custom kernel configuration file:
device scbus device pass
Verify that the device is displayed in the system message buffer:
pass2 at aic0 bus 0 target 2 lun 0
pass2: <AGFA SNAPSCAN 600 1.10> Fixed Scanner SCSI-2 device
pass2: 3.300MB/s transfers
If the scanner was not powered-on at system boot, it is still possible to manually force detection by performing a SCSI bus scan with camcontrol
:
# camcontrol rescan all
Re-scan of bus 0 was successful
Re-scan of bus 1 was successful
Re-scan of bus 2 was successful
Re-scan of bus 3 was successful
The scanner should now appear in the SCSI devices list:
# camcontrol devlist
<IBM DDRS-34560 S97B> at scbus0 target 5 lun 0 (pass0,da0)
<IBM DDRS-34560 S97B> at scbus0 target 6 lun 0 (pass1,da1)
<AGFA SNAPSCAN 600 1.10> at scbus1 target 2 lun 0 (pass3)
<PHILIPS CDD3610 CD-R/RW 1.00> at scbus2 target 0 lun 0 (pass2,cd0)
Refer to scsi(4) and camcontrol(8) for more details about SCSI devices on FreeBSD.
7.7.2. SANE 設定
The SANE system is split in two parts: the backends (graphics/sane-backends) and the frontends (graphics/sane-frontends or graphics/xsane). The backends provide access to the scanner. Refer to http://www.sane-project.org/sane-supported-devices.html to determine which backend supports the scanner. The frontends provide the graphical scanning interface. graphics/sane-frontends installs xscanimage while graphics/xsane installs xsane.
要由 Binary 套件安裝這兩個部份可:
# pkg install xsane sane-frontends
或由 Port 套件集安裝
# cd /usr/ports/graphics/sane-frontends
# make install clean
# cd /usr/ports/graphics/xsane
# make install clean
After installing the graphics/sane-backends port or package, use sane-find-scanner
to check the scanner detection by the SANE system:
# sane-find-scanner -q
found SCSI scanner "AGFA SNAPSCAN 600 1.10" at /dev/pass3
The output should show the interface type of the scanner and the device node used to attach the scanner to the system. The vendor and the product model may or may not appear.
Some USB scanners require firmware to be loaded. Refer to sane-find-scanner(1) and sane(7) for details. |
Next, check if the scanner will be identified by a scanning frontend. The SANE backends include scanimage
which can be used to list the devices and perform an image acquisition. Use -L
to list the scanner devices. The first example is for a SCSI scanner and the second is for a USB scanner:
# scanimage -L
device `snapscan:/dev/pass3' is a AGFA SNAPSCAN 600 flatbed scanner
# scanimage -L
device 'epson2:libusb:/dev/usb:/dev/ugen0.2' is a Epson GT-8200 flatbed scanner
In this second example, 'epson2:libusb:/dev/usb:/dev/ugen0.2'
is the backend name (epson2
) and /dev/ugen0.2
is the device node used by the scanner.
If scanimage
is unable to identify the scanner, this message will appear:
# scanimage -L
No scanners were identified. If you were expecting something different,
check that the scanner is plugged in, turned on and detected by the
sane-find-scanner tool (if appropriate). Please read the documentation
which came with this software (README, FAQ, manpages).
If this happens, edit the backend configuration file in /usr/local/etc/sane.d/ and define the scanner device used. For example, if the undetected scanner model is an EPSON Perfection™ 1650 and it uses the epson2
backend, edit /usr/local/etc/sane.d/epson2.conf. When editing, add a line specifying the interface and the device node used. In this case, add the following line:
usb /dev/ugen0.2
Save the edits and verify that the scanner is identified with the right backend name and the device node:
# scanimage -L
device 'epson2:libusb:/dev/usb:/dev/ugen0.2' is a Epson GT-8200 flatbed scanner
Once scanimage -L
sees the scanner, the configuration is complete and the scanner is now ready to use.
While scanimage
can be used to perform an image acquisition from the command line, it is often preferable to use a graphical interface to perform image scanning. The graphics/sane-frontends package or port installs a simple but efficient graphical interface, xscanimage.
Alternately, xsane, which is installed with the graphics/xsane package or port, is another popular graphical scanning frontend. It offers advanced features such as various scanning modes, color correction, and batch scans. Both of these applications are usable as a GIMP plugin.
7.7.3. 掃描器權限
In order to have access to the scanner, a user needs read and write permissions to the device node used by the scanner. In the previous example, the USB scanner uses the device node /dev/ugen0.2 which is really a symlink to the real device node /dev/usb/0.2.0. The symlink and the device node are owned, respectively, by the wheel
and operator
groups. While adding the user to these groups will allow access to the scanner, it is considered insecure to add a user to wheel
. A better solution is to create a group and make the scanner device accessible to members of this group.
This example creates a group called usb
:
# pw groupadd usb
Then, make the /dev/ugen0.2 symlink and the /dev/usb/0.2.0 device node accessible to the usb
group with write permissions of 0660
or 0664
by adding the following lines to /etc/devfs.rules:
[system=5] add path ugen0.2 mode 0660 group usb add path usb/0.2.0 mode 0666 group usb
Finally, add the users to usb
in order to allow access to the scanner:
# pw groupmod usb -m joe
For more details refer to pw(8).
Chapter 8. 設定 FreeBSD 核心
8.1. 概述
核心 (Kernel) 是 FreeBSD 作業系統最重要的部份之一。它負責記憶體管理、安全控管、網路、硬碟存取等等。 儘管目前 FreeBSD 大多可以用動態設定, 但有時仍需要設定並編譯自訂的核心。
讀完這章,您將了解:
何時需要編譯自訂核心。
如何取得硬體資訊。
如何量身訂做核心設定檔。
如何使用核心設定檔來建立並編譯新的核心。
如何安裝新的核心。
發生錯誤時如何排除問題。
所有在本章所列出的指令均應以 root
來執行。
8.2. 為何要編譯自訂的核心?
早期的 FreeBSD 的核心 (Kernel) 被戲稱為 “巨石”。因為當時的核心是一個非常大的程式,且只支援固定的硬體裝置,如果您想改變核心的設定,就必須編譯一個新核心並重新開機,才能使用。
現今,大多數在 FreeBSD 核心的功能已採用模組 (Module) 的方式包裝,並可依需求動態從核心載入或卸載。 這使得執行中的核心能夠快速適應新硬體環境並在核心開啟新的功能,這就是所謂模組化核心 (Modular Kernel)。
儘管如此,還是有一些功能因使用到靜態的核心設定須要編譯,因為這些功能與核心緊密結合,無法將做成可動態載入的模組。且部份強調安全性的環境會盡量避免載入與卸載核心模組,且只要將需要的功能靜態的編譯到核心當中。
編譯自訂的核心幾乎是每位進階的 BSD 使用者所必須經歷的過程。儘管這項工作可能比較耗時,但在 FreeBSD 的使用上會有許多好處。 跟必須支援大多數各式硬體的 GENERIC 核心相比的話, 自訂的核心可以更『體貼』,只支援『自己硬體』的部分就好。 自訂核心有許多項優點,如:
加速開機,因為自訂的核心只需要偵測您系統上存在的硬體,所以讓啟動所花的過程更流暢快速。
減少記憶體使用,自訂的核心通常會比 GENERIC 核心使用更少的記憶體,這很重要,因為核心必須一直存放在實體記憶體內,會讓其他應用程式無法使用。因此,自訂核心對於記憶體較小的系統來說,發揮很大的作用。
支援額外的硬體,自訂的核心可以增加一些 GENERIC 核心沒有提供的硬體支援。
在編譯自訂核心之前,請思考要這麼做的原因,若是因為需要特定硬體的支援,很可能已有既有的模組可以使用。
核心模組會放在 /boot/kernel 並且可使用 kldload(8) 動態載入到執行中的核心。大部份的核心驅動程式都有可載入的模組與操作手冊。例如 ath(4) 無線乙太網路驅動程式在其操作手冊有以下資訊:
Alternatively, to load the driver as a module at boot time, place the
following line in loader.conf(5):
if_ath_load="YES"
加入 if_ath_load="YES"
到 /boot/loader.conf 會於開機期間自動載入這個模組。
部份情況在 /boot/kernel 會沒有相關的模組,這對於某些子系統大多是真的。
8.3. 偵測系統硬體
在編輯核心設定檔之前,建議先調查清楚機器各項硬體資訊。在雙作業系統的環境,也可透過其他作業系統來了解目前機器上的硬體資訊。 舉例來說,Microsoft™ 的 裝置管理員 (Device Manager) 內會有目前已安裝的硬體資訊。
某些版本的 Microsoft™ Windows™ 會有系統 (System) 圖示可用來進入 裝置管理員。 |
若 FreeBSD 是唯一安裝的作業系統,則可使用 dmesg(8) 來查看開時時系統偵測到的硬體資訊 。FreeBSD 上大多硬體驅動程式都有操作手冊會列出支援的硬體。例如,以下幾行是說 psm(4) 驅動程式偵測到了一隻滑鼠:
psm0: <PS/2 Mouse> irq 12 on atkbdc0
psm0: [GIANT-LOCKED]
psm0: [ITHREAD]
psm0: model Generic PS/2 mouse, device ID 0
因為該硬體存在,此驅動程式便不應該從自訂核心設定檔中移除。
若 dmesg
輸出的結果未顯示開機偵測硬體的部份,則可改閱讀 /var/run/dmesg.boot 檔案的內容。
另外,也可以透過 pciconf(8) 工具可用來查詢硬體資訊,該工具會列出更詳細的硬體資訊如:
% pciconf -lv
ath0@pci0:3:0:0: class=0x020000 card=0x058a1014 chip=0x1014168c rev=0x01 hdr=0x00
vendor = 'Atheros Communications Inc.'
device = 'AR5212 Atheros AR5212 802.11abg wireless'
class = network
subclass = ethernet
以上輸出資訊說明 ath 驅動程式已經找到一個無線乙太網路裝置。
在 man(1) 指令加上 -k
旗標可提供有用的資訊,例如,這可列出有包含指定裝置品牌或名稱的手冊頁面清單:
# man -k Atheros
ath(4) - Atheros IEEE 802.11 wireless network driver
ath_hal(4) - Atheros Hardware Access Layer (HAL)
準備好硬體清單之後,參考該清單來確認已安裝的硬體驅動程式在編輯自訂核心設定時沒有被移除。
8.4. 設定檔
為了要建立自訂核心設定檔並編譯自訂核心,必須先安裝完整的 FreeBSD 原始碼樹。
若 /usr/src/ 目錄不存在或者是空的,代表尚未安裝。原始碼可以使用 Subversion 並依據 使用 Subversion 中的操作說明來安裝。
完成原始碼安裝完成後,需檢查 /usr/src/sys 內的檔案。該目錄內包含數個子目錄,這些子目錄代表著支援的硬體架構 (Architecture) 如下:amd64, i386, ia64, powerpc 以及 sparc64。在指定架構目錄中的內容只對該架構有效,其餘部份的程式碼與硬體架構無關,可通用所有平台。每個支援的硬體架構中會有 conf 子目錄,裡面含有供該架構使用的 GENERIC 核心設定檔。
請不要直接對 GENERIC 檔案做編輯。複製該檔案為另一個名稱,並對複製出來的檔案做編輯,習慣上檔名會全部使用大寫字元。當維護多台安裝不同的硬體的 FreeBSD 機器時,將檔名後方加上機器的主機名稱 (Host name) 是個不錯的方法。以下範例使用 amd64
架構的 GENERIC 設定檔建立了一個複本名稱為 MYKERNEL:
# cd /usr/src/sys/amd64/conf
# cp GENERIC MYKERNEL
現在可以使用任何 ASCII 文字編輯器來自訂 MYKERNEL。預設的編輯器為 vi,在 FreeBSD 也內建一個易於初學者使用的編輯器叫做 ee。
核心設定檔的格式很簡單,每一行會含有代表裝置 (Device) 或子系統 (Subsystem) 的關鍵字、參數以及簡短的說明。任何在 符號之後的文字會被當做註解並且略過。要移除核心對某個裝置或子系統的支援,僅需要在代表該裝置或子系統的行前加上
符號。請不要在您還不了解用途的行前加上或移除
#
符號。
移除對裝置或選項的支援很容易會造成核心損壞。例如,若從核心設定檔 ata(4) 驅動程式,那麼使用 ATA 磁碟驅動程式的系統便會無法開機。因此當您不確定時,請在核心保留該項目的支援。 |
除了在設定檔中提供的簡短說明之外,尚有其他的說明在 NOTES 檔案中,可在與該架構 GENERIC 相同的目錄底下找到。要查看所有架構通用的選項,請參考 /usr/src/sys/conf/NOTES。
當完成自訂的核心設定檔,請備份到 /usr/src 位置之外。 或者,將核心設定檔放在其他地方,然後建立一個符號連結 (Symbolic link) 至該檔案:
|
設定檔中可以使用 include
指令 (Directive)。該指令可以引用其他設定檔到目前的設定檔,這讓只需根據現有檔案設定做些微調整時更簡單。若只有少量的額外選項或驅動程式需要設定,該指令可引用 GENERIC 並設定額外增加的選項,如範例所示:
include GENERIC ident MYKERNEL options IPFIREWALL options DUMMYNET options IPFIREWALL_DEFAULT_TO_ACCEPT options IPDIVERT
使用此方法,設定檔只含有與 GENERIC 核心不同的部份。當升級有新功能加入 GENERIC 時,也可一併引用,除非特別使用 nooptions
或 nodevice
選項來排除設定。更詳細的設定檔指令及其說明可在 config(5) 找到。
要產生含有所有可用選項的設定檔,可以
|
8.5. 編譯與安裝自訂核心
完成自訂設定檔的編輯並儲存之後,便可依據以下步驟編譯核心的原始碼:
Procedure: 編譯核心
切換至此目錄:
# cd /usr/src
指定自訂核心設定檔的名稱來編譯新的核心:
# make buildkernel KERNCONF=MYKERNEL
安裝使用指定核心設定檔所編譯的新核心。此指令將會複製新核心到 /boot/kernel/kernel 並將舊核心備份到 /boot/kernel.old/kernel:
# make installkernel KERNCONF=MYKERNEL
關機並重新開機載入新的核心,若發生錯誤請參考 無法使用核心開機。
預設在自訂核心編譯完成後,所有核心模組也同被重新編譯。要快速更新核心或只編譯自訂的模組,需在開始編譯之前先編輯 /etc/make.conf。
例如,使用以下變數可指定要編譯的模組清單來替代預設編譯所有模組的設定:
MODULES_OVERRIDE = linux acpi
或者,可使用以下變數來從編譯程序中排除要編譯的模組:
WITHOUT_MODULES = linux acpi sound
尚有其他可用的變數,請參考 make.conf(5) 取得詳細資訊。
8.6. 如果發生錯誤
當編譯自訂核心時可能發生以下四種類型的問題:
config
失敗若
config
失敗,會列出不正確的行號。使用以下訊息為例子,需要與 GENERIC 或 NOTES 比對來確認第 17 行輸入的內容正確:config: line 17: syntax error
make
失敗若
make
失敗,通常是因為核心設定檔未提供足夠的資訊讓config
找到問題。請仔細檢查設定檔,若仍不清楚問題,請寄發電子郵件給 FreeBSD general questions mailing list 並附上核心設定檔。
- 無法使用核心開機
若新核心無法開機或無法辨識裝置並不要恐慌!幸好,FreeBSD 有良好的機制可以從不相容的核心復原。只需要在 FreeBSD 開機載入程式 (Boot loader) 選擇要用來開機的核心便可,當系統開機選單出現時選擇 "Escape to a loader prompt" 選項,並在指令提示後輸入
boot kernel.old
或替換為任何其他已經知道可以正常開機的核心名稱。使用好的核心開機之後,檢查設定檔並嘗試再編譯一次。/var/log/messages 是有用的資源,它在每次成功開機時會記錄核心訊息。同樣的,dmesg(8) 也會印出自本次開機後的核心訊息。
在排除核心問題時,請確定留有 GENERIC 的複本,或者其他已知可以運作的核心,並使用不同的名稱來確保下次編譯時不會被刪除,這很重要,因此每當新的核心被安裝之後,kernel.old 都會被最後安裝的核心覆寫,有可能會無法開機。盡快,透過重新命名將可運作的核心目錄移動到目前運作的核心目錄:
# mv /boot/kernel /boot/kernel.bad # mv /boot/kernel.good /boot/kernel
- 核心可運作,但 ps(1) 無法運作
若核心版本與系統工具所編譯的版本不同,例如,有一個核心使用 -CURRENT 的原始碼編譯並安裝在 -RELEASE 的系統上,許多系統狀態指令如 ps(1) 及 vmstat(8) 將會無法運作。要修正此問題,請使用與核心相同版本的原始碼樹 (Source tree) 重新編譯並安裝 World。使用與作業系統其他部份版本不同的核心永遠不會是個好主意。
Chapter 9. 列印
儘管很多人試圖淘汰列印功能,但列印資訊到紙上仍是一個重要的功能。列印由兩個基本元件組成,包含了資料傳送到印表機的方式以及印表機可以理解的資料形式。
9.1. 快速開始
基本的列印功能可以快速設定完成,列印機必須能夠列印純 ASCII 文字。若要列印其他類型的檔案,請參考 過濾器。
建立一個目錄來儲存要被列印的檔案:
# mkdir -p /var/spool/lpd/lp # chown daemon:daemon /var/spool/lpd/lp # chmod 770 /var/spool/lpd/lp
以
root
建立 /etc/printcap 內容如下:lp:\ :lp=/dev/unlpt0:\ (1) :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :lf=/var/log/lpd-errs:
1 此行是針對連接到 USB 埠的印表機。連接到並列或 "印表器 (Printer)" 埠的印表機要使用:直接連接到網路的印表機要使用:替換 network-printer-name 為網路印表機的 DNS 主機名稱。 編輯 /etc/rc.conf 加入下行來開啟
lpd
:lpd_enable="YES"
啟動服務:
# service lpd start Starting lpd.
測試列印:
# printf "1. This printer can print.\n2. This is the second line.\n" | lpr
若列印的兩行未從左邊界開始,而是呈現 "階梯狀 (Stairstep)",請參考 避免在純文字印表機階梯狀列印。
現在可以使用
lpr
來列印文字檔,只要在指令列給序檔案名稱,或者將輸出使用管線符號 (Pipe) 傳送給lpr
。% lpr textfile.txt % ls -lh | lpr
9.2. 印表機連線
印表機有許多方式可以連接到電腦,小型的桌面印表機會直接連接到電腦的 USB 埠,舊式的印表機會連接到並列 (Parallel) 或 "印表機 (Printer)" 埠,而有一部份印表機則是直接連接網路,讓印表機能夠給多台電腦共享使用,還有少部分印表機則是連接到較罕見的序列 (Serial) 埠。
FreeBSD 可以與這些類型的印表機溝通。
- USB
USB 印表機可以連接到電腦上任何可用的 USB 埠。
當 FreeBSD 偵測到 USB 印表機,會建立兩個裝置項目:/dev/ulpt0 以及 /dev/unlpt0,傳送到兩者任一裝置的資料都會被轉發到印表機。在每個列印工作完成後 ulpt0 便會重設 USB 埠,重設 USB 埠可能會在部份印表機造成問題,因此通常可以改使用 unlpt0 裝置。unlpt0 不會重設 USB 埠。
- 並列 (IEEE-1284)
並列埠裝置使用 /dev/lpt0,此裝置不論印表機是否連接上都會存在,它並不會自動偵測。
供應商已不再採用這種 "舊式" 連接埠,且有許多電腦甚至已沒有這種連接埠。可以用轉接器來連接並列印表機到 USB 埠,有了轉接器,並列印表機可以被當作 USB 印表機使用。有另一種稱作 列印伺服器 (Print server) 的裝置也可用來連接並列印表機到網路。
- 序列 (RS-232)
序列埠也是另一種舊式連接埠,已很少用在印表機上,除了某些特殊的應用外,纜線、接頭與需要的佈線方式依需求變化性很大。
內建在主機板的序列埠的序列裝置名稱為 /dev/cuau0 或 /dev/cuau1。也有序列 USB 轉接器可使用,而裝置的的名稱則會是 /dev/cuaU0。
要與序列印表機通訊必須知道數個通訊參數,其中最重要的是 傳輸速率 (Baud rate) 或 BPS (Bits Per Second) 以及 同位檢查 (Parity)。數值有數種,但一般序列印表機會使用 的傳輸速率是 9600 且無同位檢查。
- 網路
網路印表機可直接連接到區域網路。
若印表機透過 DHCP 分配動態位址,則必須要知道 DNS 主機名稱,DNS 應動態更新來讓主機名稱能夠對應到正確的 IP 位址。指定網路印表機一個靜態的 IP 位址可避免這個問題。
大多數網路印表機可以認得使用 LPD 通訊協定所送出的列印工作,列印佇列 (Print queue) 的名稱也會在這時指定。部份印表機會依據使用的佇列來決定處理資料的方式,例如
raw
佇列會列印原始資料,而text
佇列則會在純文字上增加換行符號 (Carriage return)。大部份網路印表機也可列印直接傳送到埠號 9100 的資料。
9.3. 常見的頁面描述語言
傳送給印表機的資料必須使用印表機能夠理解的語言,這些語言稱為頁面描述語言 (Page Description Languages) 或 PDL。
- ASCII
純 ASCII 文字是傳送資料到印表機最簡單的方式,一個字元對應一個要列印的文字:資料中的
A
會列印一個A
在頁面。可以使用的格式非常少,沒有辦法選擇字型或者比例間距。強迫使用簡單的純 ASCII 為的是讓文字可以直接從電腦列印只需一點或甚至不需要編碼或轉譯,列印的結果可直接對應傳送的內容。部份便宜印表機無法列印純 ASCII 文字,這讓這些印表機較難設定。
- PostScript™
PostScript™ 與 ASCII 幾乎相反,與簡單的文字不同,PostScript™ 程式語言有一套指令可以繪出最終所要的文件,可以使用不同的字型與圖形,但是,這樣強大的功能是有代價的,繪製頁面需要搛寫程式語言,通常這個程式語言會由應用程式產生,所以使用者是看不到的。
便宜的印表機有時會移除 PostScript™ 的相容性來節省成本。
- PCL (Printer Command Language)
PCL 由 ASCII 延伸而來,加入了跳脫序列 (Escape sequence) 來標示格式、選擇字型以及列印圖型。大部份印表機都支援 PCL5,少數支援較新的 PCL6 或 PCLXL,這些後來的版本是 PCL5 的超集合 (Superset),並可以提供更快的列印速度。
- 以主機為基礎 (Host-Based)
製造商可能會使用簡單的處理器和較小的記憶體來降低印表機的成本,這些印表機無法列印純文字,相反的,文字與圖形會先在機器上的驅動程式畫完後傳送到印表機。這些稱為以主機為基礎 (Host-based) 的印表機。
驅動程式與以主機為基礎的印表機通訊通常會透過專用或無文件的通訊協定,這讓這些印表機只能在最常用的作業系統上運作。
9.3.1. 轉換 PostScript™ 至其他 PDL
Port 套件集與 FreeBSD 工具集有許多可以處理 PostScript™ 輸出的應用程式,此表整理出了可轉換 PostScript™ 成其他常用 PDL 的工具:
輸出 PDL | 產生由 | 說明 |
---|---|---|
PCL 或 PCL5 | 單色使用 | |
PCLXL 或 PCL6 | 單色使用 | |
ESC/P2 |
| |
XQX |
9.3.2. 摘要
要可以列印最簡單的方式就是選擇支援 PostScript™ 的印表機,再來是支援 PCL 的印表機,有了 print/ghostscript9-base 這些印表機也可像原生支援 PostScript™ 的印表機一般使用。有直接支援 PostScript™ 或 PCL 的印表機通常也會直接支援純 ASCII 文字檔案。
行列式印表機如同典型的噴墨式印表機通常不支援 PostScript™ 或 PCL,這種印表機通常可以列印純 ASCII 文字檔案。print/ghostscript9-base 支援部份這種印表機使用的 PDL,不過要在這種印表機上列印完全以圖型為基礎的頁面通常會非常緩慢,由於需要傳送大量的資料並列印。
以主機為基礎的印表機通常較難設定,有些會因為用了專用的 PDL 而無法使用,盡可能避免使用這類的印表機。
有關各種 PDL 的介紹可至 http://www.undocprint.org/formats/page_description_languages。各種型號印表機所使用的特定 PDL 可至 http://www.openprinting.org/printers 查詢。
9.4. 直接列印
對於偶爾列印,檔案可以直接傳送到印表機裝置,無需做任何設定。例如,要傳送一個名稱為 sample.txt 的檔案到 USB 印表機:
# cp sample.txt /dev/unlpt0
要直接使用網路印表機列印需看該印表機支援的功能,但大多數會接受埠號 9100 的列印作業,可使用 nc(1) 來完成。要使用 DNS 主機名稱為 netlaser 的印表機列印與上述相同的檔案可:
# nc netlaser 9100 < sample.txt
9.5. LPD (行列式印表機 Daemon)
在背景列印一個檔案稱作 Spooling,緩衝程式 (Spooler) 讓使用者能夠繼續執行電腦的其他程式而不需要等候印表機緩慢的完成列印工作。
9.5.1. 初始設定
建立要用來儲存列印工作的目錄、設定擁有關係以及權限來避免其他使用者可以檢視這些檔案的內容:
# mkdir -p /var/spool/lpd/lp
# chown daemon:daemon /var/spool/lpd/lp
# chmod 770 /var/spool/lpd/lp
印表機會定義在 /etc/printcap,每台印表機項目所包含的詳細資料有名稱、連接的接頭以及各種其他設定。建立 /etc/printcap 使用以下內容:
lp:\ (1) :lp=/dev/unlpt0:\ (2) :sh:\ (3) :mx#0:\ (4) :sd=/var/spool/lpd/lp:\ (5) :lf=/var/log/lpd-errs: (6)
1 | 印表機的名稱。 lpr(1) 會傳送列印工作到 lp 印表機,除非有使用 -P 來指定其他印表機,所以預的印表機名稱應使用 lp 。 |
2 | 印表機所連接到裝置。替換此行為正確的連線類型,如此處所示。 |
3 | 在列印工作開始時不列印首頁。 |
4 | 不限制列印工作的最大尺寸。 |
5 | 此印表機的緩衝 (Spooling) 目錄路徑,每台印表機會自己使用一個獨立的緩衝 (Spooling) 目錄。 |
6 | 回報此印表機的錯誤的日誌檔。 |
在建立 /etc/printcap 之後,使用 chkprintcap(8) 測試印表機是否有錯誤:
# chkprintcap
在繼續之前修正任何回報的問題。
開啟 /etc/rc.conf 中的 lpd(8):
lpd_enable="YES"
啟動服務:
# service lpd start
9.5.2. 使用 lpr(1) 列印
Documents are sent to the printer with lpr
. A file to be printed can be named on the command line or piped into lpr
. These two commands are equivalent, sending the contents of doc.txt to the default printer:
% lpr doc.txt
% cat doc.txt | lpr
Printers can be selected with -P
. To print to a printer called laser:
% lpr -Plaser doc.txt
9.5.3. 過濾器
The examples shown so far have sent the contents of a text file directly to the printer. As long as the printer understands the content of those files, output will be printed correctly.
Some printers are not capable of printing plain text, and the input file might not even be plain text.
Filters allow files to be translated or processed. The typical use is to translate one type of input, like plain text, into a form that the printer can understand, like PostScript™ or PCL. Filters can also be used to provide additional features, like adding page numbers or highlighting source code to make it easier to read.
The filters discussed here are input filters or text filters. These filters convert the incoming file into different forms. Use su(1) to become root
before creating the files.
Filters are specified in /etc/printcap with the if=
identifier. To use /usr/local/libexec/lf2crlf as a filter, modify /etc/printcap like this:
lp:\ :lp=/dev/unlpt0:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :if=/usr/local/libexec/lf2crlf:\ (1) :lf=/var/log/lpd-errs:
1 | if= identifies the input filter that will be used on incoming text. |
The backslash line continuation characters at the end of the lines in printcap entries reveal that an entry for a printer is really just one long line with entries delimited by colon characters. An earlier example can be rewritten as a single less-readable line: lp:lp=/dev/unlpt0:sh:mx#0:sd=/var/spool/lpd/lp:if=/usr/local/libexec/lf2crlf:lf=/var/log/lpd-errs: |
9.5.3.1. 避免在純文字印表機階梯狀列印
Typical FreeBSD text files contain only a single line feed character at the end of each line. These lines will "stairstep" on a standard printer:
A printed file looks like the steps of a staircase scattered by the wind
A filter can convert the newline characters into carriage returns and newlines. The carriage returns make the printer return to the left after each line. Create /usr/local/libexec/lf2crlf with these contents:
#!/bin/sh CR=$'\r' /usr/bin/sed -e "s/$/${CR}/g"
Set the permissions and make it executable:
# chmod 555 /usr/local/libexec/lf2crlf
Modify /etc/printcap to use the new filter:
:if=/usr/local/libexec/lf2crlf:\
Test the filter by printing the same plain text file. The carriage returns will cause each line to start at the left side of the page.
9.5.3.2. 使用 print/enscript 在 PostScript™ 印表機美化純文字內容
GNUEnscript converts plain text files into nicely-formatted PostScript™ for printing on PostScript™ printers. It adds page numbers, wraps long lines, and provides numerous other features to make printed text files easier to read. Depending on the local paper size, install either print/enscript-letter or print/enscript-a4 from the Ports Collection.
Create /usr/local/libexec/enscript with these contents:
#!/bin/sh /usr/local/bin/enscript -o -
Set the permissions and make it executable:
# chmod 555 /usr/local/libexec/enscript
Modify /etc/printcap to use the new filter:
:if=/usr/local/libexec/enscript:\
Test the filter by printing a plain text file.
9.5.3.3. 列印 PostScript™ 到 PCL 印表機
Many programs produce PostScript™ documents. However, inexpensive printers often only understand plain text or PCL. This filter converts PostScript™ files to PCL before sending them to the printer.
由 Port 套件集安裝 Ghostscript PostScript™ 直譯器,print/ghostscript9-base。
Create /usr/local/libexec/ps2pcl with these contents:
#!/bin/sh /usr/local/bin/gs -dSAFER -dNOPAUSE -dBATCH -q -sDEVICE=ljet4 -sOutputFile=- -
Set the permissions and make it executable:
# chmod 555 /usr/local/libexec/ps2pcl
PostScript™ input sent to this script will be rendered and converted to PCL before being sent on to the printer.
Modify /etc/printcap to use this new input filter:
:if=/usr/local/libexec/ps2pcl:\
Test the filter by sending a small PostScript™ program to it:
% printf "%%\!PS \n /Helvetica findfont 18 scalefont setfont \
72 432 moveto (PostScript printing successful.) show showpage \004" | lpr
9.5.3.4. 智慧過濾器
A filter that detects the type of input and automatically converts it to the correct format for the printer can be very convenient. The first two characters of a PostScript™ file are usually %!
. A filter can detect those two characters. PostScript™ files can be sent on to a PostScript™ printer unchanged. Text files can be converted to PostScript™ with Enscript as shown earlier. Create /usr/local/libexec/psif with these contents:
#!/bin/sh # # psif - Print PostScript or plain text on a PostScript printer # IFS="" read -r first_line first_two_chars=`expr "$first_line" : '\(..\)'` case "$first_two_chars" in %!) # %! : PostScript job, print it. echo "$first_line" && cat && exit 0 exit 2 ;; *) # otherwise, format with enscript ( echo "$first_line"; cat ) | /usr/local/bin/enscript -o - && exit 0 exit 2 ;; esac
Set the permissions and make it executable:
# chmod 555 /usr/local/libexec/psif
Modify /etc/printcap to use this new input filter:
:if=/usr/local/libexec/psif:\
Test the filter by printing PostScript™ and plain text files.
9.5.3.5. 其他智慧過濾器
Writing a filter that detects many different types of input and formats them correctly is challenging. print/apsfilter from the Ports Collection is a smart "magic" filter that detects dozens of file types and automatically converts them to the PDL understood by the printer. See http://www.apsfilter.org for more details.
9.5.4. 多序列
The entries in /etc/printcap are really definitions of queues. There can be more than one queue for a single printer. When combined with filters, multiple queues provide users more control over how their jobs are printed.
As an example, consider a networked PostScript™ laser printer in an office. Most users want to print plain text, but a few advanced users want to be able to print PostScript™ files directly. Two entries can be created for the same printer in /etc/printcap:
textprinter:\ :lp=9100@officelaser:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/textprinter:\ :if=/usr/local/libexec/enscript:\ :lf=/var/log/lpd-errs: psprinter:\ :lp=9100@officelaser:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/psprinter:\ :lf=/var/log/lpd-errs:
Documents sent to textprinter
will be formatted by the /usr/local/libexec/enscript filter shown in an earlier example. Advanced users can print PostScript™ files on psprinter
, where no filtering is done.
This multiple queue technique can be used to provide direct access to all kinds of printer features. A printer with a duplexer could use two queues, one for ordinary single-sided printing, and one with a filter that sends the command sequence to enable double-sided printing and then sends the incoming file.
9.5.5. 監視與控制列印
Several utilities are available to monitor print jobs and check and control printer operation.
9.5.5.1. lpq(1)
lpq(1) shows the status of a user’s print jobs. Print jobs from other users are not shown.
Show the current user’s pending jobs on a single printer:
% lpq -Plp
Rank Owner Job Files Total Size
1st jsmith 0 (standard input) 12792 bytes
Show the current user’s pending jobs on all printers:
% lpq -a
lp:
Rank Owner Job Files Total Size
1st jsmith 1 (standard input) 27320 bytes
laser:
Rank Owner Job Files Total Size
1st jsmith 287 (standard input) 22443 bytes
9.5.5.2. lprm(1)
lprm(1) is used to remove print jobs. Normal users are only allowed to remove their own jobs. root
can remove any or all jobs.
Remove all pending jobs from a printer:
# lprm -Plp -
dfA002smithy dequeued
cfA002smithy dequeued
dfA003smithy dequeued
cfA003smithy dequeued
dfA004smithy dequeued
cfA004smithy dequeued
Remove a single job from a printer. lpq(1) is used to find the job number.
% lpq
Rank Owner Job Files Total Size
1st jsmith 5 (standard input) 12188 bytes
% lprm -Plp 5
dfA005smithy dequeued
cfA005smithy dequeued
9.5.5.3. lpc(8)
lpc(8) is used to check and modify printer status. lpc
is followed by a command and an optional printer name. all
can be used instead of a specific printer name, and the command will be applied to all printers. Normal users can view status with lpc(8). Only root
can use commands which modify printer status.
Show the status of all printers:
% lpc status all
lp:
queuing is enabled
printing is enabled
1 entry in spool area
printer idle
laser:
queuing is enabled
printing is enabled
1 entry in spool area
waiting for laser to come up
Prevent a printer from accepting new jobs, then begin accepting new jobs again:
# lpc disable lp
lp:
queuing disabled
# lpc enable lp
lp:
queuing enabled
Stop printing, but continue to accept new jobs. Then begin printing again:
# lpc stop lp
lp:
printing disabled
# lpc start lp
lp:
printing enabled
daemon started
Restart a printer after some error condition:
# lpc restart lp
lp:
no daemon to abort
printing enabled
daemon restarted
Turn the print queue off and disable printing, with a message to explain the problem to users:
# lpc down lp Repair parts will arrive on Monday
lp:
printer and queuing disabled
status message is now: Repair parts will arrive on Monday
Re-enable a printer that is down:
# lpc up lp
lp:
printing enabled
daemon started
See lpc(8) for more commands and options.
9.5.6. 分享印表機
Printers are often shared by multiple users in businesses and schools. Additional features are provided to make sharing printers more convenient.
9.5.6.1. 別名
The printer name is set in the first line of the entry in /etc/printcap. Additional names, or aliases, can be added after that name. Aliases are separated from the name and each other by vertical bars:
lp|repairsprinter|salesprinter:\
Aliases can be used in place of the printer name. For example, users in the Sales department print to their printer with
% lpr -Psalesprinter sales-report.txt
Users in the Repairs department print to their printer with
% lpr -Prepairsprinter repairs-report.txt
All of the documents print on that single printer. When the Sales department grows enough to need their own printer, the alias can be removed from the shared printer entry and used as the name of a new printer. Users in both departments continue to use the same commands, but the Sales documents are sent to the new printer.
9.5.6.2. 頁首
It can be difficult for users to locate their documents in the stack of pages produced by a busy shared printer. Header pages were created to solve this problem. A header page with the user name and document name is printed before each print job. These pages are also sometimes called banner or separator pages.
Enabling header pages differs depending on whether the printer is connected directly to the computer with a USB, parallel, or serial cable, or is connected remotely over a network.
Header pages on directly-connected printers are enabled by removing the :sh:\
(Suppress Header) line from the entry in /etc/printcap. These header pages only use line feed characters for new lines. Some printers will need the /usr/shared/examples/printing/hpif filter to prevent stairstepped text. The filter configures PCL printers to print both carriage returns and line feeds when a line feed is received.
Header pages for network printers must be configured on the printer itself. Header page entries in /etc/printcap are ignored. Settings are usually available from the printer front panel or a configuration web page accessible with a web browser.
9.6. 其他列印系統
Several other printing systems are available in addition to the built-in lpd(8). These systems offer support for other protocols or additional features.
9.6.1. CUPS (Common UNIX™ Printing System)
CUPS is a popular printing system available on many operating systems. Using CUPS on FreeBSD is documented in a separate article: CUPS
9.6.2. HPLIP
Hewlett Packard provides a printing system that supports many of their inkjet and laser printers. The port is print/hplip. The main web page is at http://hplipopensource.com/hplip-web/index.html. The port handles all the installation details on FreeBSD. Configuration information is shown at http://hplipopensource.com/hplip-web/install/manual/hp_setup.html.
9.6.3. LPRng
LPRng was developed as an enhanced alternative to lpd(8). The port is sysutils/LPRng. For details and documentation, see http://www.lprng.com/.
Chapter 10. Linux® Binary 相容性
10.1. 概述
FreeBSD 提供 Linux™ Binary 的相容性,允許使用者在 FreeBSD 系統上不需要修改就可以安裝和執行大部份的 Linux™ Binary。 曾經有報告指出,在某些情況下,Linux™ Binary 在 FreeBSD 的表現比在 Linux™ 好。
然而,部份特定在 Linux™ 作業系統上的功能在 FreeBSD 並沒有支援。例如,若 Linux™ Binary 過度的使用 i386™ 特定的呼叫,如啟動虛擬 8086 模式,會無法在 FreeBSD 執行。
FreeBSD 10.3 後支援 64 位元的 Linux™ Binary 相容性。 |
讀完這章,您將了解:
如何在 FreeBSD 系統啟用 Linux™ Binary 相容模式。
如何安裝其他的 Linux™ 共用程式庫。
如何在 FreeBSD 系統安裝 Linux™ 應用程式。
在 FreeBSD 中 Linux™ 相容性的實作細節。
在開始閱讀這章之前,您需要:
知道如何安裝 其他的第三方軟體。
10.2. 設定 Linux™ Binary 相容性
Linux™ 程式庫預設並不會安裝,且並不會開啟 Linux™ Binary 相容性。 Linux™ 程式庫可以手動安裝或是從 FreeBSD Port 套件集安裝。
在嘗試編譯 Port 前,要載入 Linux™ 核心模組,否則編譯會失敗:
# kldload linux
對 64-位元的相容性:
# kldload linux64
確認模組已載入:
% kldstat
Id Refs Address Size Name
1 2 0xc0100000 16bdb8 kernel
7 1 0xc24db000 d000 linux.ko
在 FreeBSD 安裝基本的 Linux™ 程式庫和 Binary 最簡單的方式是安裝 emulators/linux_base-c6 套件或是 Port 。要安裝 Port:
# pkg install emulators/linux_base-c6
要在開機時開啟 Linux™ 相容性,可以加入這行到 /etc/rc.conf:
linux_enable="YES"
在 64-位元的機器上,/etc/rc.d/abi 會自動載入用來做 64-位元模擬的模組。
Since the Linux™ binary compatibility layer has gained support for running both 32- and 64-bit Linux™ binaries (on 64-bit x86 hosts), it is no longer possible to link the emulation functionality statically into a custom kernel.
10.2.1. 手動安裝其他程式庫
若有 Linux™ 應用程式在設定 Linux™ Binary 相容性後出現缺少共用程式庫的情況,確認這個 Linux™ Binary 需要哪個共用程式庫並手動安裝。
在 Linux™ 系統,可使用 ldd
來找出應用程式需要哪個共用程式庫。 例如,檢查 linuxdoom
需要哪個共用程式庫,在有安裝 Doom 的 Linux™ 系統執行這個指令:
% ldd linuxdoom
libXt.so.3 (DLL Jump 3.1) => /usr/X11/lib/libXt.so.3.1.0
libX11.so.3 (DLL Jump 3.1) => /usr/X11/lib/libX11.so.3.1.0
libc.so.4 (DLL Jump 4.5pl26) => /lib/libc.so.4.6.29
然後,複製所有 Linux™ 系統輸出結果中最後一欄的檔案到 FreeBSD 系統的 /compat/linux。 複製完後,建立符號連結 (Symbolic link) 至輸出結果第一欄的名稱。以這個例子會在 FreeBSD 系統產生以下檔案:
/compat/linux/usr/X11/lib/libXt.so.3.1.0
/compat/linux/usr/X11/lib/libXt.so.3 -> libXt.so.3.1.0
/compat/linux/usr/X11/lib/libX11.so.3.1.0
/compat/linux/usr/X11/lib/libX11.so.3 -> libX11.so.3.1.0
/compat/linux/lib/libc.so.4.6.29
/compat/linux/lib/libc.so.4 -> libc.so.4.6.29
若 Linux™ 共用程式庫已經存在,並符合 ldd
輸出結果第一欄的主要修訂版號,則不需要複製該行最後一欄的檔案,使用既有的程式庫應可運作。若有較新的版本建議仍要複製共用程式庫,只要符號連結指向新版的程式庫,舊版便可移除。
例如,以下程式庫已存在 FreeBSD 系統:
/compat/linux/lib/libc.so.4.6.27
/compat/linux/lib/libc.so.4 -> libc.so.4.6.27
且 ldd
顯示 Binary 需要使用較新的版本:
libc.so.4 (DLL Jump 4.5pl26) -> libc.so.4.6.29
雖然既有的程式庫只有在最後一碼過時一或兩個版本,程式應該仍可使用稍微舊的版本執行,雖然如此,保險起見還替換既有的 libc.so 為較新的版本:
/compat/linux/lib/libc.so.4.6.29
/compat/linux/lib/libc.so.4 -> libc.so.4.6.29
一般來說,只有在安裝 Linux™ 程式到 FreeBSD 完的前幾次會需要查看 Linux™ Binary 相依的共用程式庫。之後系統便有足夠的 Linux™ 共用程式庫能夠執行新安裝的 Linux™ Binary,便不再需要額外的動作。
10.2.2. 安裝 Linux™ELF Binary
ELF Binary 有時候需要額外的步驟。當執行無商標 (Unbranded) 的 ELF Binary,會產生錯誤訊息:
% ./my-linux-elf-binary
ELF binary type not known
Abort
要協助 FreeBSD 核心區別是 FreeBSD ELF Binary 還是 Linux™ Binary,可使用 brandelf(1):
% brandelf -t Linux my-linux-elf-binary
由於 GNU 工具鏈會自動放置適當的商標資訊到 ELF Binary,通常不需要這個步驟。
10.2.3. 安裝以 Linux™RPM 為基礎的應用程式
要安裝 Linux™RPM 為基礎的應用程式,需先安裝 archivers/rpm4 套件或 Port。安裝完成之後,root
可以使用這個指令安裝 .rpm:
# cd /compat/linux
# rpm2cpio < /path/to/linux.archive.rpm | cpio -id
如果需要, brandelf
已安裝的 ELF Binary。注意,這將會無法乾淨地解除安裝。
10.2.4. 設定主機名稱解析器
如果 DNS 無法運作或出現這個錯誤:
resolv+: "bind" is an invalid keyword resolv+:
"hosts" is an invalid keyword
將 /compat/linux/etc/host.conf 設定如下:
order hosts, bind multi on
這指定先搜尋 /etc/hosts,其次為 DNS。 當 /compat/linux/etc/host.conf 不存在, Linux™ 應用程式會使用 /etc/host.conf 並會警告不相容的 FreeBSD 語法。如果名稱伺服器未設定使用 /etc/resolv.conf 的話,則可移除 bind
。
10.3. 進階主題
This section describes how Linux™ binary compatibility works and is based on an email written to FreeBSD chat mailing list by Terry Lambert tlambert@primenet.com (Message ID: <199906020108.SAA07001@usr09.primenet.com>
).
FreeBSD has an abstraction called an "execution class loader". This is a wedge into the execve(2) system call.
Historically, the UNIX™ loader examined the magic number (generally the first 4 or 8 bytes of the file) to see if it was a binary known to the system, and if so, invoked the binary loader.
If it was not the binary type for the system, the execve(2) call returned a failure, and the shell attempted to start executing it as shell commands. The assumption was a default of "whatever the current shell is".
Later, a hack was made for sh(1) to examine the first two characters, and if they were :\n
, it invoked the csh(1) shell instead.
FreeBSD has a list of loaders, instead of a single loader, with a fallback to the #!
loader for running shell interpreters or shell scripts.
For the Linux™ABI support, FreeBSD sees the magic number as an ELF binary. The ELF loader looks for a specialized brand, which is a comment section in the ELF image, and which is not present on SVR4/Solaris™ ELF binaries.
For Linux™ binaries to function, they must be branded as type Linux
using brandelf(1):
# brandelf -t Linux file
When the ELF loader sees the Linux
brand, the loader replaces a pointer in the proc
structure. All system calls are indexed through this pointer. In addition, the process is flagged for special handling of the trap vector for the signal trampoline code, and several other (minor) fix-ups that are handled by the Linux™ kernel module.
The Linux™ system call vector contains, among other things, a list of sysent[]
entries whose addresses reside in the kernel module.
When a system call is called by the Linux™ binary, the trap code dereferences the system call function pointer off the proc
structure, and gets the Linux™, not the FreeBSD, system call entry points.
Linux™ mode dynamically reroots lookups. This is, in effect, equivalent to union
to file system mounts. First, an attempt is made to lookup the file in /compat/linux/original-path. If that fails, the lookup is done in /original-path. This makes sure that binaries that require other binaries can run. For example, the Linux™ toolchain can all run under Linux™ABI support. It also means that the Linux™ binaries can load and execute FreeBSD binaries, if there are no corresponding Linux™ binaries present, and that a uname(1) command can be placed in the /compat/linux directory tree to ensure that the Linux™ binaries cannot tell they are not running on Linux™.
In effect, there is a Linux™ kernel in the FreeBSD kernel. The various underlying functions that implement all of the services provided by the kernel are identical to both the FreeBSD system call table entries, and the Linux™ system call table entries: file system operations, virtual memory operations, signal delivery, and System V IPC. The only difference is that FreeBSD binaries get the FreeBSD glue functions, and Linux™ binaries get the Linux™glue functions. The FreeBSD glue functions are statically linked into the kernel, and the Linux™glue functions can be statically linked, or they can be accessed via a kernel module.
Technically, this is not really emulation, it is an ABI implementation. It is sometimes called "Linux™ emulation" because the implementation was done at a time when there was no other word to describe what was going on. Saying that FreeBSD ran Linux™ binaries was not true, since the code was not compiled in.
Part III: 系統管理
FreeBSD 使用手冊剩下的這些章節涵蓋了全方位的 FreeBSD 系統管理。 每個章節的開頭會先描述在該您讀完該章節後您會學到什麼,也會詳述在您在看這些資料時應該要有的一些背景知識。
這些章節是讓您在需要查資料的時候翻閱用的。 您不需要依照特定的順序來讀,也不需要將這些章節全部過讀之後才開始用 FreeBSD。
Chapter 11. 設定與調校
11.1. 概述
在 FreeBSD 使用過程中,相當重要的環節之一就是如何正確設定系統。 本章著重於介紹 FreeBSD 的設定流程,包括一些可以調整 FreeBSD 效能的參數設定。
讀完這章,您將了解:
rc.conf 設定的基礎概念及 /usr/local/etc/rc.d 啟動 Script。
如何設定並測試網路卡。
如何在網路裝置上設定虛擬主機。
如何使用在 /etc 中的各種設定檔。
如何使用 sysctl(8) 變數調校 FreeBSD。
如何調校磁碟效能及修改核心限制。
在開始閱讀這章之前,您需要:
了解 UNIX™ 及 FreeBSD 基礎 (FreeBSD 基礎)。
熟悉核心設定與編譯的基礎 (設定 FreeBSD 核心)。
11.2. 啟動服務
許多使用者會使用 Port 套件集安裝第三方軟體到 FreeBSD 且需要安裝服務在系統初始化時可啟動該軟體。服務,例如 mail/postfix 或 www/apache22 僅只是在眾多需要在系統初始化時啟動的軟體之中的兩個。本章節將說明可用來啟動第三方軟體的程序。
在 FreeBSD 大多數內建的服務,例如 cron(8) 也是透過系統啟動 Script 來執行。
11.2.1. 延伸應用程式設定
現在 FreeBSD 會引用 rc.d,設定應用程式啟動變的更簡單且提供更多的功能。使用於 管理 FreeBSD 中的服務 所提到的關鍵字,可以設定應用程式在其他特定服務之後啟動且可以透過 /etc/rc.conf 來傳遞額外的旗標來取代寫死在啟動 Script 中的旗標。一個基本的 Script 可能會如下例所示:
#!/bin/sh # # PROVIDE: utility # REQUIRE: DAEMON # KEYWORD: shutdown . /etc/rc.subr name=utility rcvar=utility_enable command="/usr/local/sbin/utility" load_rc_config $name # # DO NOT CHANGE THESE DEFAULT VALUES HERE # SET THEM IN THE /etc/rc.conf FILE # utility_enable=${utility_enable-"NO"} pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1"
這個 Script 會確保要執行的 utility
會在虛構的服務 DAEMON
之後啟動,也同時提供設定與追蹤程序 ID (Process ID, PID) 的方法。
接著此應用程式便可將下行放到 /etc/rc.conf 中:
utility_enable="YES"
使用這種方式可以簡單的處理指令列參數、引用 /etc/rc.subr 所提供的預設函數、與 rcorder(8) 相容並可在 rc.conf 簡單的設定。
11.2.2. 使用服務來啟動其他服務
其他的服務可以使用 inetd(8) 來啟動,在 inetd 超級伺服器 有如何使用 inetd(8) 以及其設定的深入說明。
在某些情況更適合使用 cron(8) 來啟動系統服務,由於 cron(8) 會使用 crontab(5) 的擁有者來執行這些程序,所以這個方法有不少優點,這讓一般的使用者也可以啟動與維護自己的應用程式。
11.3. 設定 cron(8)
在 FreeBSD 其中最有用的其中一項工具便是 cron,這個工具會在背景執行並且定期檢查 /etc/crontab 是否有要執行的工作然後搜尋 /var/cron/tabs 是否有自訂的 crontab 檔案,這些檔案用來安排要讓 cron 在指定的時間執行的工作,crontab 中的每一個項目定義了一個要執行的工作,又稱作 cron job。
這裡使用了兩種類型的設定檔:其一是系統 crontab,系統 crontab 不應該被修改,其二為使用者 crontab,使用者 crontab 可以依需要建立與編輯。這兩種檔案的格式在 crontab(5) 有說明。系統 crontab /etc/crontab 的格式含有在使用者 crontab 所沒有的 who
欄位,在系統 crontab,cron 會依據該欄位所指定的使用者來執行指令,而在使用者 crontab,會以建立 crontab 的使用者來執行指令。
使用者 crontab 讓個別使用者可以安排自己的工作,root
使用者也可有自己的使用者 crontab 來安排不在系統 crontab 中的工作。
以下為系統 crontab /etc/crontab 的範例項目:
# /etc/crontab - root's crontab for FreeBSD # # $FreeBSD: head/zh_TW.UTF-8/books/handbook/book.xml 53653 2019-12-03 17:05:41Z rcyu $ #(1) SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin (2) # #minute hour mday month wday who command (3) # */5 * * * * root /usr/libexec/atrun (4)
1 | 以 # 字元為首的行代表註解。可在檔案中放置註解提醒要執行什麼動作及為何要執行。註解不可與指令同行,否則會被當做指令的一部份,註解必須在新的一行,空白行則會被忽略掉。 |
2 | 等號 (= ) 字元用來定義任何環境設定。在這個例子當中,使用了等號來定義 SHELL 及 PATH 。若 SHELL 被省略,cron 則會使用預設的 Bourne shell。若 PATH 被省略,則必須指定指令或 Script 的完整路徑才能執行。 |
3 | 此行定義了在系統 crontab 會使用到的七個欄位:minute , hour , mday , month , wday , who 以及 command 。minute 欄位是指定指令要執行的時間中的分,hour 指定指令要執行的時,mday 是月裡面的日,month 是月,以及 wday 是週裡面的日。這些欄位必須數值代表 24 小時制的時間或 \* 來代表所有可能的值。who 這個欄位只有系統 crontab 才有,用來指定要用那一個使用者來執行指令。最後一個欄位則是要執行的指令。 |
4 | 這個項目定義了該工作所使用的數值,*/5 後接著數個 * 字元指的是每個月的每一週的每一日的每個小時的每 5 分鐘會使用 root 執行 /usr/libexec/atrun 。指令可含任何數量的參數,但若指令要使用多行則需以反斜線 "\" 連線字元換行。 |
11.3.1. 建立使用者的 Crontab
要建立一個使用者 crontab 可使用編輯模式執行 crontab
:
% crontab -e
這樣會使用預設的文字編輯器來開啟使用者的 crontab,使用者第一次執行這個指令會開啟一個空的檔案,使用者建立 crontab 之後這個指令則會開啟已建立的 crontab 供編輯。
加入這些行到 crontab 檔的最上方來設定環境變數以及備忘在 crontab 中欄位的意思非常有用:
SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin # Order of crontab fields # minute hour mday month wday command
然後每一個要執行的指令或 Script 加入一行,指定要執行指令的時間。這個例子會每天在下午 2 點執行指定的自訂 Bourne shell script,由於沒有在 PATH
指定 Script 的路徑,所以必須給予完整的 Script 路徑:
0 14 * * * /usr/home/dru/bin/mycustomscript.sh
在使用自訂的 Script 之前,請先確定該 Script 可以執行並且使用 cron 在有限的環境變數下測試。要複製一個用來執行上述 cron 項目的環境可以使用: env -i SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin HOME=/home/dru LOGNAME=dru /usr/home/dru/bin/mycustomscript.sh 在 crontab(5) 有討論 cron 使用的環境變數,若 Script 中含有任何會使用萬用字元刪除檔案的指令,那麼檢查 Script 可正常在 cron 的環境運作非常重要。 |
編輯完成 crontab 之後儲存檔案,編輯完的 crontab 會被自動安裝且 cron 會讀取該 crontab 並在其指定的時指執行其 cron job。要列出 crontab 中有那一些 cron job 可以使用此指令:
% crontab -l
0 14 * * * /usr/home/dru/bin/mycustomscript.sh
要移除使用在使用者 crontab 中的 cron job 可:
% crontab -r
remove crontab for dru? y
11.4. 管理 FreeBSD 中的服務
FreeBSD 在系統初始化時使用 rc(8) 系統的啟動 Script。列於 /etc/rc.d 的 Script 提供了基本的服務可使用 service(8) 加上 start
, stop
以及 restart
選項來控制。例如,使用以下指令可以重新啟動 sshd(8):
# service sshd restart
這個程序可以用來在執行中的系統上啟動服務,而在 rc.conf(5) 中有指定的服務則會在開機時自動啟動。例如,要在系統啟動時開啟 natd(8),可入下行到 /etc/rc.conf:
natd_enable="YES"
若 natd_enable="NO"
行已存在,則將 NO
更改為 YES
,在下次開機時 rc(8) script 便會自動載入任何相依的服務,詳細如下所述。
由於 rc(8) 系統主要用於在系統開機與關機時啟動與停止服務,只有當有服務的變數設定在 /etc/rc.conf 時 start
, stop
以及 restart
才會有作用。例如 sshd restart
只會在 /etc/rc.conf 中的 sshd_enable
設為 YES
時才會運作,若要不透過 /etc/rc.conf 的設定來 start
, stop
或 restart
一個服務則需要在指令前加上 "one",例如要不透過目前在 /etc/rc.conf 的設定重新啟動 sshd(8) 可執行以下指令:
# service sshd onerestart
# service sshd rcvar
# sshd
#
sshd_enable="YES"
# (default: "")
行 |
要判斷是一個服務是否正在執行,可使用 status
,例如要確認 sshd(8) 是否正常在執行:
# service sshd status
sshd is running as pid 433.
在某些情況,也可以 reload
一個服務。這個動作會嘗試發送一個信號給指定的服務,強制服務重新載入其設定檔,在大多數的情況下,發送給服務的信號是 SIGHUP
。並不是每個服務都有支援此功能。
rc(8) 系統會用在網路服務及也應用在大多數的系統初化 。例如執行 /etc/rc.d/bgfsck Script 會列印出以下訊息:
Starting background file system checks in 60 seconds.
這個 Script 用來在背景做檔案系統檢查,只有在系統初始化時要執行。
許多系統服務會相依其他服務來運作,例如 yp(8) 及其他以 RPC 為基礎的服務在 rpcbind(8) 服務啟動前可能會啟動失敗。要解決這種問題,就必須在啟動 Script 上方的註解中加入相依及其他 meta-data。在系統初始化時會用 rcorder(8) 程式分析這些註解來決定要以什麼順序來執行系統服務以滿足相依。
因 rc.subr(8) 的需要,以下的關鍵字必須加入到所有的啟動 Script 方可 "enable" 啟動 Script:
PROVIDE
: 設定此檔案所提供的服務。
以下關鍵字可能會在每個啟動 Script 的上方引用,雖然非必要,但是對於 rcorder(8) 是非常有用的提示:
REQUIRE
: 列出此服務需要引用的服務。有使用此關鍵字的 Script 會在指定服務啟動 之後 才執行。BEFORE
: 列出相依此服務的服務。有使用此關鍵字的 Script 會在指定的服務啟動 之前 執行。
透過仔細的設定每個啟動 Script 的這些關鍵字,管理者便可對 Script 的啟動順序進行微調,而不需使用到其他 UNIX™ 作業系統所使用的 "runlevels"。
額外的資訊可在 rc(8) 以及 rc.subr(8) 中找到。請參考 此文章 來取得如何建立自訂 rc(8) Script 的操作說明。
11.4.1. 管理系統特定的設定
系統設定資訊的主要位於 /etc/rc.conf,這個檔案的設定資訊範圍非常廣且會在系統啟動時讀取來設定系統,它也提供設定資訊給 rc* 檔案使用。
在 /etc/rc.conf 中的設定項目會覆蓋在 /etc/defaults/rc.conf 的預設設定,不應直接編輯該檔案中的預設設定,所有系統特定的設定應到 /etc/rc.conf 所修改。
在叢集應用時要將系統特定的設定與各站特定的設定分開,藉此減少管理成本有好幾種方法,建議的方法是將系統特定的設定放置在 /etc/rc.conf.local,例如以下將要套用到所有系統的設定項目放在 /etc/rc.conf:
sshd_enable="YES" keyrate="fast" defaultrouter="10.1.1.254"
而只套用到此系統的設定放在 /etc/rc.conf.local:
hostname="node1.example.org" ifconfig_fxp0="inet 10.1.1.1/8"
使用應用程式如 rsync 或 puppet 將 /etc/rc.conf 散布到每個系統,而在各系統保留自己的 /etc/rc.conf.local。
升級系統並不會覆寫 /etc/rc.conf,所以系統設定資訊不會因此遺失。
/etc/rc.conf 以及 /etc/rc.conf.local 兩個檔案都會使用 sh(1) 解析,這讓系統操作者能夠建立較複雜的設定方案。請參考 rc.conf(5) 來取得更多有關此主題的資訊。 |
11.5. 設定網路介面卡
對 FreeBSD 管理者來說加入與設定網路介面卡 (Network Interface Card, NIC) 會是一件常見的工作。
11.5.1. 找到正確的驅動程式
首先,要先確定 NIC 的型號及其使用的晶片。FreeBSD 支援各種 NIC,可檢查該 FreeBSD 發佈版本的硬體相容性清單來查看是否有支援該 NIC。
若有支援該 NIC,接著要確定該 NIC 所要需要的 FreeBSD 驅動程式名稱。請參考 /usr/src/sys/conf/NOTES 及 /usr/src/sys/arch/conf/NOTES 來取得 NIC 驅動程式清單及其支援的晶片組相關資訊。當有疑問是,請閱讀該驅動程式的操作手冊,會有提供更多有關支援硬體及該驅動程式已知問題的資訊。
GENERIC 核心已有內含常見 NIC 的驅動程式 ,意思是在開機時應該會偵測到 NIC。可以輸入 more /var/run/dmesg.boot
來檢視系統的開機訊息並使用空白鍵捲動文字。在此例中,兩個乙太網路 NIC 使用系統已有的 dc(4) 驅動程式:
dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38
000ff irq 15 at device 11.0 on pci0
miibus0: <MII bus> on dc0
bmtphy0: <BCM5201 10/100baseTX PHY> PHY 1 on miibus0
bmtphy0: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto
dc0: Ethernet address: 00:a0:cc:da:da:da
dc0: [ITHREAD]
dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30
000ff irq 11 at device 12.0 on pci0
miibus1: <MII bus> on dc1
bmtphy1: <BCM5201 10/100baseTX PHY> PHY 1 on miibus1
bmtphy1: 10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto
dc1: Ethernet address: 00:a0:cc:da:da:db
dc1: [ITHREAD]
若在 GENERIC 中沒有該 NIC 的驅動程式,但有可用的驅動程式,那麼在設定及使用 NIC 前要先載入該驅動程式,有兩種方式可以完成這件事:
最簡單的方式是使用 kldload(8) 載入 NIC 要使用的核心模組。要在開機時自動載入,可加入適當的設定到 /boot/loader.conf。不是所有 NIC 驅動程式皆可當做模組使用。
或者,靜態編譯對 NIC 的支援到自訂核心,請參考 /usr/src/sys/conf/NOTES, /usr/src/sys/arch/conf/NOTES 及驅動程式的操作手冊來了解要在自訂核心設定檔中要加入那些設定。要取得更多有關重新編譯核心的資訊可參考 設定 FreeBSD 核心。若在開機時有偵測到 NIC,就不需要再重新編譯核心。
11.5.1.1. 使用 Windows™NDIS 驅動程式
很不幸的,仍有很多供應商並沒有提供它們驅動程式的技術文件給開源社群,因為這些文件有涉及商業機密。因此,FreeBSD 及其他作業系統的開發人員只剩下兩種方案可以選擇:透過長期與艱苦的過程做逆向工程來開發驅動程式或是使用現有供 Microsoft™ Windows™ 平台用的驅動程式 Binary。
FreeBSD 對 Network Driver Interface Specification (NDIS) 有提供 "原生" 的支援,這包含了 ndisgen(8) 可用來轉換 Windows™ XP 驅動程式成可在 FreeBSD 上使用的格式。由於 ndis(4) 驅動程式使用的是 Windows™ XP binary,所以只能在 i386™ 及 amd64 系統上執行。PCI, CardBus, PCMCIA 以及 USB 裝置也都有支援。
要使用 ndisgen(8) 需要三樣東西:
FreeBSD 核心原始碼。
一個 .SYS 附檔名的 Windows™ XP 驅動程式 Binary。
一個 .INF 附檔名的 Windows™ XP 驅動程式設定檔。
下載供指定 NIC 使用的 .SYS 及 .INF 檔。通常這些檔案可以在驅動程式 CD 或者供應商的網站上找到。以下範例會使用 W32DRIVER.SYS 及 W32DRIVER.INF。
驅動程式的位元寬度必須與 FreeBSD 的版本相符。例如 FreeBSD/i386 需要使用 Windows™ 32-bit 驅動程式,而 FreeBSD/amd64 則需要使用 Windows™ 64-bit 驅動程式。
下個步驟是編譯驅動程式 Binary 成可載入的核心模組。以 root
身份使用 ndisgen(8):
# ndisgen /path/to/W32DRIVER.INF /path/to/W32DRIVER.SYS
這個指令是互動式的,會提示輸入任何所需的額外資訊,新的核心模組會被產生在目前的目錄,使用 kldload(8) 來載入新的模組:
# kldload ./W32DRIVER_SYS.ko
除了產生的核心模組之外,ndis.ko 以及 if_ndis.ko 也必須載入,會在任何有相依 ndis(4) 的模組被載入時一併自動載入。若沒有自動載入,則需使用以下指令手動載入:
# kldload ndis
# kldload if_ndis
第一個指令會載入 ndis(4) miniport 驅動程式包裝程式,而第二個指令會載入產生的 NIC 驅動程式。
檢查 dmesg(8) 查看是否有任何載入錯誤,若一切正常,輸出結果應會如下所示:
ndis0: <Wireless-G PCI Adapter> mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1
ndis0: NDIS API version: 5.0
ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5
ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps
ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps
到此之後 ndis0 可以像任何其他 NIC 設定使用。
要設定系統於開機時載入 ndis(4) 模組,可複製產生的模組 W32DRIVER_SYS.ko 到 /boot/modules。然後加入下行到 /boot/loader.conf:
W32DRIVER_SYS_load="YES"
11.5.2. 設定網路卡
載入正確的 NIC 驅動程式之後,接著需要設定介面卡,這個動作可能在安裝時已經使用 bsdinstall(8) 設定過了。
要查看 NIC 設定可輸入以下指令:
% ifconfig
dc0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
options=80008<VLAN_MTU,LINKSTATE>
ether 00:a0:cc:da:da:da
inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255
media: Ethernet autoselect (100baseTX <full-duplex>)
status: active
dc1: flags=8802<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
options=80008<VLAN_MTU,LINKSTATE>
ether 00:a0:cc:da:da:db
inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255
media: Ethernet 10baseT/UTP
status: no carrier
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> metric 0 mtu 16384
options=3<RXCSUM,TXCSUM>
inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4
inet6 ::1 prefixlen 128
inet 127.0.0.1 netmask 0xff000000
nd6 options=3<PERFORMNUD,ACCEPT_RTADV>
在這個例子中列出了以下裝置:
dc0: 第一個乙太網路介面。
dc1: 第二個乙太網路介面。
lo0: Loopback 裝置。
FreeBSD 會使用驅動程式名稱接著開機時所偵測到的介面卡順序來命名 NIC。例如 sis2 是指在系統上使用 sis(4) 驅動程式的第三個 NIC。
在此例中,dc0 已經上線並且執行中。主要的依據有:
UP
代表介面卡已設定好並且準備就緒。介面卡有網際網路 (
inet
) 位址,192.168.1.3
。介面卡有一個有效的子網路遮罩 (
netmask
),其中0xffffff00
等同於255.255.255.0
。介面卡有一個有效的廣播位址,
192.168.1.255
。介面卡 (
ether
) 的 MAC 位址是00:a0:cc:da:da:da
。實體媒介選擇為自動選擇模式 (
media: Ethernet autoselect (100baseTX <full-duplex>)
)。在本例中 dc1 被設定使用10baseT/UTP
媒介。要取得更多有關可用的驅動程式媒介類型請參考操作手冊。連結的狀態 (
status
) 為使用中 (active
),代表有偵測到載波信號 (Carrier Signal)。若 dc1 所代表的介面卡未插入乙太網路線則狀態為status: no carrier
是正常的。
若 ifconfig(8) 的輸出結果如下:
dc0: flags=8843<BROADCAST,SIMPLEX,MULTICAST> metric 0 mtu 1500
options=80008<VLAN_MTU,LINKSTATE>
ether 00:a0:cc:da:da:da
media: Ethernet autoselect (100baseTX <full-duplex>)
status: active
則代表尚未設定介面卡。
介面卡必須以 root
來設定。NIC 的設定可在指令列執行 ifconfig(8) 來完成,但重新開機之後變會消失,除非將設定也加到 /etc/rc.conf。若在 LAN 中有 DHCP 伺服器,則只需加入此行:
ifconfig_dc0="DHCP"
替換 dc0 為該系統的正確值。
加入這行之後,接著依據 測試與疑難排解 指示操作。
若網路在安裝時已設定,可能會已經有 NIC 的設定項目。在加入任何設定前請再次檢查 /etc/rc.conf。 |
在這個例中,沒有 DHCP 伺服器,必須手動設定 NIC。提每一個在系統上的 NIC 加入一行設定,如此例:
ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP"
替換 dc0 及 dc1 以及 IP 位址資訊為系統的正確值。請參考驅動程式的操作手冊、ifconfig(8) 以及 rc.conf(5) 取得更多有關可用的選項及 /etc/rc.conf 的語法。
若網路沒有使用 DNS,則編輯 /etc/hosts 加入 LAN 上主機的名稱與 IP 位址。要取得更多資訊請參考 hosts(5) 及 /usr/shared/examples/etc/hosts。
若沒有 DHCP 伺服器且需要存取網際網路,那麼需要手動設定預設閘道及名稱伺服器:
|
11.5.3. 測試與疑難排解
必要的變更儲存到 /etc/rc.conf 之後,需要重新啟動系統來測試網路設定並檢查系統重新啟動是否沒有任何設定錯誤。或者使用這個指令將設定套用到網路系統:
# service netif restart
若預設的通訊閘已設定於 /etc/rc.conf 也同樣要下這個指令:
|
網路系統重新啟動後,便可接著測試 NIC。
11.5.3.1. 測試乙太網路卡
% ping -c5 192.168.1.3
PING 192.168.1.3 (192.168.1.3): 56 data bytes
64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms
64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms
64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms
64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms
64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms
--- 192.168.1.3 ping statistics ---
5 packets transmitted, 5 packets received, 0% packet loss
round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms
% ping -c5 192.168.1.2
PING 192.168.1.2 (192.168.1.2): 56 data bytes
64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms
64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms
64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms
64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms
64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms
--- 192.168.1.2 ping statistics ---
5 packets transmitted, 5 packets received, 0% packet loss
round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms
要測試網路解析,可使用主機名稱來替代 IP 位址。若在網路上沒有 DNS 伺服器則必須先設定 /etc/hosts,若主機尚未設定到 /etc/hosts 中,則需編輯 /etc/hosts 加入 LAN 上主機的名稱及 IP 位址,要取得更多資訊請參考 hosts(5) 及 /usr/shared/examples/etc/hosts。
11.5.3.2. 疑難排解
在排除硬體及軟體設定問題時,要先檢查幾件簡單的事。網路線插上了沒?網路的服務都正確設定了嗎?防火牆設定是否正確?FreeBSD 是否支援該 NIC?在回報問題之前,永遠要先檢查 Hardware Notes、更新 FreeBSD 到最新的 STABLE 版本、檢查郵遞論壇封存記錄以及上網查詢。
若介面卡可以運作,但是效能很差,請閱讀 tuning(7),同時也要檢查網路設定,因為不正確的網路設定會造成連線速度緩慢。
部份使用者會遇到一次或兩次 device timeout
的訊息,在對某些介面卡是正常的。若訊息持續發生或很煩的,請確認是否有與其他的裝置衝突,再次檢查網路線,或考慮使用其他介面卡。
要解決 watchdog timeout
錯誤,先檢查網路線。許多介面卡需要使用支援 Bus Mastering 的 PCI 插槽,在一些舊型的主機板,只會有一個 PCI 插槽支援,通常是插槽 0。檢查 NIC 以及主機板說明文件來確定是否為此問題。
若系統無法路由傳送封包到目標主機則會出現 No route to host
訊息,這可能是因為沒有指定預設的路由或未插上網路線。請檢查 netstat -rn
的輸出並確認有一個有效的路由可連線至主機,若沒有,請閱讀 通訊閘與路由。
造成 ping: sendto: Permission denied
錯誤訊息的原因通常是防火牆設定錯誤。若在 FreeBSD 上有開啟防火牆,但卻未定義任何的規則,預設的原則是拒絕所有傳輸,即使是用 ping(8)。請參考 防火牆 取得更多資訊。
有時介面卡的效能很差或低於平均值,在這種情況可嘗試設定媒介選擇模式由 autoselect
更改為正確的媒介選項,雖然這在大部份硬體可運作,但可能無法解決問題,同樣的,檢查所有網路設定並參考 tuning(7)。
11.6. 虛擬主機
FreeBSD 最常見的用途之一就是虛擬網站代管,即以一台伺服器在網路上扮演多台伺服器,這可以透過指定多個網路位置到一個網路介面來做到。
一個網路介面會有一個 "真實 (Real)" 位址且可以有許多個 "別名 (Alias)" 位址。一般會在 /etc/rc.conf 中放置別名項目來增加別名,如下例:
ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx"
別名項目必須以 alias0
開頭,使用連續數字例如 alias0
, alias1
以此類推,設定程序會在第一個遇到缺號的地方中止。
要注意別名網路遮罩 (Netmask) 的計算,使用的介面必須至少有一個正確的填寫網路遮罩的位址,而其他所有在此網路中的位址則必須使用全部 1
的網路遮罩,可用 255.255.255.255
或 0xffffffff
來表示。
舉例來說,有一個 fxp0 介面連結到兩個網路:10.1.1.0
使用網路遮罩 255.255.255.0
以及 202.0.75.16
使用網路遮罩 255.255.255.240
。而系統將要設定使用範圍 10.1.1.1
到 10.1.1.5
以及 202.0.75.17
到 202.0.75.20
。在指定的網路範圍中只有第一個位址應使用真實的網路遮罩,其餘 (10.1.1.2
到 10.1.1.5
及 202.0.75.18
到 202.0.75.20
) 則必須設定使用 255.255.255.255
的遮罩。
在此情境下正確設定網路介面的方式如下 /etc/rc.conf 中的項目:
ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0" ifconfig_fxp0_alias0="inet 10.1.1.2 netmask 255.255.255.255" ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255" ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255" ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255" ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240" ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255" ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255" ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255"
有一種更簡單的方式可以表達這些設定,便是使用以空白分隔的 IP 位址清單。只有第一個位址會使用指定的子網路遮罩,其他的位址則會使用 255.255.255.255
的子網路遮罩。
ifconfig_fxp0_aliases="inet 10.1.1.1-5/24 inet 202.0.75.17-20/28"
11.7. 設定系統日誌
產生與讀取系統日誌對系統管理來說是一件非常重要的事,在系統日誌中的資訊可以用來偵測硬體與軟體的問題,同樣也可以偵測應用程式與系統設定的錯誤。這些資訊在安全性稽查與事件回應也同樣扮演了重要的角色,大多數系統 Daemon 與應用程式都會產生日誌項目。
FreeBSD 提供了一個系統日誌程式 syslogd 用來管理日誌。預設 syslogd 會與系統開機時啟動。這可使用在 /etc/rc.conf 中的變數 syslogd_enable
來控制。而且有數個應用程式參數可在 /etc/rc.conf 使用 syslogd_flags
來設定。請參考 syslogd(8) 來取得更多可用參數的資訊。
此章節會介紹如何設定 FreeBSD 系統日誌程式來做本地與遠端日誌並且介紹如何執行日誌翻轉 (Log rotation) 與日誌管理。
11.7.1. 設定本地日誌
設定檔 /etc/syslog.conf 控制 syslogd 收到日誌項目時要做的事情,有數個參數可以用來控制接收到事件時的處理方式。設施 (facility) 用來描述記錄產生訊息的子系統 (subsystem),如核心或者 Daemon,而 層級 (level) 用來描述所發生的事件嚴重性。也可以依據應用程式所發出的訊息及產生日誌事件機器的主機名稱來決定後續處置的動作。
此設定檔中一行代表一個動作,每一行的格式皆為一個選擇器欄位 (Selector field) 接著一個動作欄位 (Action field)。選擇器欄位的格式為 facility.level 可以用來比對來自 facility 於層級 level 或更高層的日誌訊息,也可以在層級前加入選擇性的比對旗標來更確切的指定記錄的內容。同樣一個動作可以使用多個選擇器欄位並使用分號 (;
) 來分隔。用 *
可以比對任何東西。動作欄位可用來指定傳送日誌訊息的目標,如一個檔案或遠端日誌主機。範例為以下為 FreeBSD 預設的 syslog.conf:
# $FreeBSD: head/zh_TW.UTF-8/books/handbook/book.xml 53653 2019-12-03 17:05:41Z rcyu $ # # Spaces ARE valid field separators in this file. However, # other *nix-like systems still insist on using tabs as field # separators. If you are sharing this file between systems, you # may want to use only tabs as field separators here. # Consult the syslog.conf(5) manpage. *.err;kern.warning;auth.notice;mail.crit /dev/console *.notice;authpriv.none;kern.debug;lpr.info;mail.crit;news.err /var/log/messages security.* /var/log/security auth.info;authpriv.info /var/log/auth.log mail.info /var/log/maillog lpr.info /var/log/lpd-errs ftp.info /var/log/xferlog cron.* /var/log/cron !-devd *.=debug /var/log/debug.log *.emerg * # uncomment this to log all writes to /dev/console to /var/log/console.log #console.info /var/log/console.log # uncomment this to enable logging of all log messages to /var/log/all.log # touch /var/log/all.log and chmod it to mode 600 before it will work #*.* /var/log/all.log # uncomment this to enable logging to a remote loghost named loghost #*.* @loghost # uncomment these if you're running inn # news.crit /var/log/news/news.crit # news.err /var/log/news/news.err # news.notice /var/log/news/news.notice # Uncomment this if you wish to see messages produced by devd # !devd # *.>=info !ppp *.* /var/log/ppp.log !*
在這個範例中:
第 8 行會找出所有符合
err
或以上層級的訊息,還有kern.warning
,auth.notice
與mail.crit
的訊息,然後將這些日誌訊息傳送到 Console (/dev/console)。第 12 行會找出所有符合
mail
設施中於info
或以上層級的訊息,並記錄訊息至 /var/log/maillog。第 17 行使用了比較旗標 (
=
) 來只找出符合debug
層級的訊息,並將訊息記錄至 /var/log/debug.log。第 33 行是指定程式的範例用法。這可以讓在該行以下的規則只對指定的程式生效。在此例中,只有由 ppp 產生的訊息會被記錄到 /var/log/ppp.log。
所以可用層級從最嚴重到最不嚴重的順序為 emerg
, alert
, crit
, err
, warning
, notice
, info
以及 debug
。
設施 (facility) 則無特定順序,可用的有 auth
, authpriv
, console
, cron
, daemon
, ftp
, kern
, lpr
, mail
, mark
, news
, security
, syslog
, user
, uucp
及 local0
到 local7
。要注意在其他作業系統的設施可能會不同。
要記錄所有所有 notice
與以上層級的訊息到 /var/log/daemon.log 可加入以下項目:
daemon.notice /var/log/daemon.log
要取得更多有關不同的層級與設施的資訊請參考 syslog(3) 及 syslogd(8)。要取得更多有關 /etc/syslog.conf、語法以及更多進階用法範例的資訊請參考 syslog.conf(5)。
11.7.2. 日誌管理與翻轉
日誌檔案會成長的非常快速,這會消耗磁碟空間並且會更難在日誌中找到有用的資訊,日誌管理便是為了嘗試減緩這種問題。在 FreeBSD 可以使用 newsyslog 來管理日誌檔案,這個內建的程式會定期翻轉 (Rotate) 與壓縮日誌檔案,並且可選擇性的建立遺失的日誌檔案並在日誌檔案被移動位置時通知程式。日誌檔案可能會由 syslogd 產生或由其他任何會產生日誌檔案的程式。newsyslog 正常會由 cron(8) 來執行,它並非一個系統 Daemon,預設會每個小時執行一次。
newsyslog 會讀取其設定檔 /etc/newsyslog.conf 來決定其要採取的動作,每個要由 newsyslog 所管理的日誌檔案會在此設定檔中設定一行,每一行要說明檔案的擁有者、權限、何時要翻轉該檔案、選用的日誌翻轉旗標,如:壓縮,以及日誌翻轉時要通知的程式。以下為 FreeBSD 的預設設定:
# configuration file for newsyslog # $FreeBSD: head/zh_TW.UTF-8/books/handbook/book.xml 53653 2019-12-03 17:05:41Z rcyu $ # # Entries which do not specify the '/pid_file' field will cause the # syslogd process to be signalled when that log file is rotated. This # action is only appropriate for log files which are written to by the # syslogd process (ie, files listed in /etc/syslog.conf). If there # is no process which needs to be signalled when a given log file is # rotated, then the entry for that file should include the 'N' flag. # # The 'flags' field is one or more of the letters: BCDGJNUXZ or a '-'. # # Note: some sites will want to select more restrictive protections than the # defaults. In particular, it may be desirable to switch many of the 644 # entries to 640 or 600. For example, some sites will consider the # contents of maillog, messages, and lpd-errs to be confidential. In the # future, these defaults may change to more conservative ones. # # logfilename [owner:group] mode count size when flags [/pid_file] [sig_num] /var/log/all.log 600 7 * @T00 J /var/log/amd.log 644 7 100 * J /var/log/auth.log 600 7 100 @0101T JC /var/log/console.log 600 5 100 * J /var/log/cron 600 3 100 * JC /var/log/daily.log 640 7 * @T00 JN /var/log/debug.log 600 7 100 * JC /var/log/kerberos.log 600 7 100 * J /var/log/lpd-errs 644 7 100 * JC /var/log/maillog 640 7 * @T00 JC /var/log/messages 644 5 100 @0101T JC /var/log/monthly.log 640 12 * $M1D0 JN /var/log/pflog 600 3 100 * JB /var/run/pflogd.pid /var/log/ppp.log root:network 640 3 100 * JC /var/log/devd.log 644 3 100 * JC /var/log/security 600 10 100 * JC /var/log/sendmail.st 640 10 * 168 B /var/log/utx.log 644 3 * @01T05 B /var/log/weekly.log 640 5 1 $W6D0 JN /var/log/xferlog 600 7 100 * JC
每一行的開始為要翻轉的日誌名稱、接著是供翻轉與新建檔案使用的擁有者及群組 (選填)。mode
欄位可設定日誌檔案的權限,count
代表要保留多少個翻轉過的日誌檔案,而 size
與 when
欄位會告訴 newsyslog 何時要翻轉該檔案。日誌檔案會在當其檔案超過 size
欄位的大小或已超過 when
欄位指定的時間時翻轉,可使用星號 (*
) 忽略該欄位。flags 欄位可以給予進階的參數,例如:如何壓縮翻轉後檔案或建立遺失的日誌檔案。最後兩個欄位皆為選填,可指定程序的程序 ID (PID) 檔名稱以及檔案翻轉後要傳送給該程序的信號 (Signal) 編號。
要取的更多有關所有欄位、可用的旗標及如何指定翻轉時間,請參考 newsyslog.conf(5)。由於 newsyslog 是由 cron(8) 執行,因此無法比其在 cron(8) 中所排定的時間間距內更頻繁的執行翻轉檔案。
11.7.3. 設定遠端日誌
Monitoring the log files of multiple hosts can become unwieldy as the number of systems increases. Configuring centralized logging can reduce some of the administrative burden of log file administration.
In FreeBSD, centralized log file aggregation, merging, and rotation can be configured using syslogd and newsyslog. This section demonstrates an example configuration, where host A
, named logserv.example.com
, will collect logging information for the local network. Host B
, named logclient.example.com
, will be configured to pass logging information to the logging server.
11.7.3.1. 日誌伺服器設定
A log server is a system that has been configured to accept logging information from other hosts. Before configuring a log server, check the following:
If there is a firewall between the logging server and any logging clients, ensure that the firewall ruleset allows UDP port 514 for both the clients and the server.
The logging server and all client machines must have forward and reverse entries in the local DNS. If the network does not have a DNS server, create entries in each system’s /etc/hosts. Proper name resolution is required so that log entries are not rejected by the logging server.
On the log server, edit /etc/syslog.conf to specify the name of the client to receive log entries from, the logging facility to be used, and the name of the log to store the host’s log entries. This example adds the hostname of B
, logs all facilities, and stores the log entries in /var/log/logclient.log.
+logclient.example.com *.* /var/log/logclient.log
When adding multiple log clients, add a similar two-line entry for each client. More information about the available facilities may be found in syslog.conf(5).
Next, configure /etc/rc.conf:
syslogd_enable="YES" syslogd_flags="-a logclient.example.com -v -v"
The first entry starts syslogd at system boot. The second entry allows log entries from the specified client. The -v -v
increases the verbosity of logged messages. This is useful for tweaking facilities as administrators are able to see what type of messages are being logged under each facility.
Multiple -a
options may be specified to allow logging from multiple clients. IP addresses and whole netblocks may also be specified. Refer to syslogd(8) for a full list of possible options.
Finally, create the log file:
# touch /var/log/logclient.log
At this point, syslogd should be restarted and verified:
# service syslogd restart
# pgrep syslog
If a PID is returned, the server restarted successfully, and client configuration can begin. If the server did not restart, consult /var/log/messages for the error.
11.7.3.2. 日誌客戶端設定
A logging client sends log entries to a logging server on the network. The client also keeps a local copy of its own logs.
Once a logging server has been configured, edit /etc/rc.conf on the logging client:
syslogd_enable="YES" syslogd_flags="-s -v -v"
The first entry enables syslogd on boot up. The second entry prevents logs from being accepted by this client from other hosts (-s
) and increases the verbosity of logged messages.
Next, define the logging server in the client’s /etc/syslog.conf. In this example, all logged facilities are sent to a remote system, denoted by the @
symbol, with the specified hostname:
*.* @logserv.example.com
After saving the edit, restart syslogd for the changes to take effect:
# service syslogd restart
To test that log messages are being sent across the network, use logger(1) on the client to send a message to syslogd:
# logger "Test message from logclient"
This message should now exist both in /var/log/messages on the client and /var/log/logclient.log on the log server.
11.7.3.3. 日誌伺服器除錯
If no messages are being received on the log server, the cause is most likely a network connectivity issue, a hostname resolution issue, or a typo in a configuration file. To isolate the cause, ensure that both the logging server and the logging client are able to ping
each other using the hostname specified in their /etc/rc.conf. If this fails, check the network cabling, the firewall ruleset, and the hostname entries in the DNS server or /etc/hosts on both the logging server and clients. Repeat until the ping
is successful from both hosts.
If the ping
succeeds on both hosts but log messages are still not being received, temporarily increase logging verbosity to narrow down the configuration issue. In the following example, /var/log/logclient.log on the logging server is empty and /var/log/messages on the logging client does not indicate a reason for the failure. To increase debugging output, edit the syslogd_flags
entry on the logging server and issue a restart:
syslogd_flags="-d -a logclient.example.com -v -v"
# service syslogd restart
Debugging data similar to the following will flash on the console immediately after the restart:
logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart
syslogd: restarted
logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel
Logging to FILE /var/log/messages
syslogd: kernel boot file is /boot/kernel/kernel
cvthname(192.168.1.10)
validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com;
rejected in rule 0 due to name mismatch.
In this example, the log messages are being rejected due to a typo which results in a hostname mismatch. The client’s hostname should be logclient
, not logclien
. Fix the typo, issue a restart, and verify the results:
# service syslogd restart
logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart
syslogd: restarted
logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel
syslogd: kernel boot file is /boot/kernel/kernel
logmsg: pri 166, flags 17, from logserv.example.com,
msg Dec 10 20:55:02 <syslog.err> logserv.example.com syslogd: exiting on signal 2
cvthname(192.168.1.10)
validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com;
accepted in rule 0.
logmsg: pri 15, flags 0, from logclient.example.com, msg Dec 11 02:01:28 trhodes: Test message 2
Logging to FILE /var/log/logclient.log
Logging to FILE /var/log/messages
At this point, the messages are being properly received and placed in the correct file.
11.7.3.4. 安全注意事項
As with any network service, security requirements should be considered before implementing a logging server. Log files may contain sensitive data about services enabled on the local host, user accounts, and configuration data. Network data sent from the client to the server will not be encrypted or password protected. If a need for encryption exists, consider using security/stunnel, which will transmit the logging data over an encrypted tunnel.
Local security is also an issue. Log files are not encrypted during use or after log rotation. Local users may access log files to gain additional insight into system configuration. Setting proper permissions on log files is critical. The built-in log rotator, newsyslog, supports setting permissions on newly created and rotated log files. Setting log files to mode 600
should prevent unwanted access by local users. Refer to newsyslog.conf(5) for additional information.
11.8. 設定檔
11.8.1. /etc 配置
有數個目錄中儲存著設定資訊,這些目錄有:
/etc | 通用系統特定的設定資訊。 |
/etc/defaults | 系統設定檔的預設版本。 |
/etc/mail | sendmail(8) 額外的設定以及其他 MTA 設定檔。 |
/etc/ppp | user- 及 kernel-ppp 程式的設定。 |
/usr/local/etc | 已安裝應用程式的設定檔,可能會有以應用程式區分的子目錄。 |
/usr/local/etc/rc.d | 已安裝應用程式的 rc(8) Script。 |
/var/db | 自動產生的系統特定資料庫檔案,例如套件資料庫以及 locate(1) 資料庫。 |
11.8.2. 主機名稱
11.8.2.1. /etc/resolv.conf
FreeBSD 要如何存取網際網路網域名稱系統 (Internet Domain Name System, DNS) 是由 resolv.conf(5) 來控制。
/etc/resolv.conf 中最常用的項目為:
| 解析程式 (Resolver) 要查詢的名稱伺服器 IP 位置,這些伺服器會依所列的順序來查詢,最多可以有三個。 |
| 主機名稱查詢使用的搜尋清單。這通常會使用本機主機名稱所在的網域。 |
| 本地網域名稱。 |
典型的 /etc/resolv.conf 會如下:
search example.com nameserver 147.11.1.11 nameserver 147.11.100.30
|
當使用 DHCP 時,dhclient(8) 通常會使用從 DHCP 伺服器所接收到的資訊覆寫 /etc/resolv.conf。
11.8.2.2. /etc/hosts
/etc/hosts 是簡單的文字資料庫,會與 DNS 及 NIS 一併使用來提供主機名稱與 IP 位址的對應。可將透過 LAN 所連結的在地電腦項目加入到這個檔案做最簡單的命名,來替代設定一個 named(8) 伺服器。除此之外 /etc/hosts 可以用來提供本地的網際網路名稱記錄,來減少常用名稱向外部 DNS 伺服器查詢的需求。
# $FreeBSD: head/zh_TW.UTF-8/books/handbook/book.xml 53653 2019-12-03 17:05:41Z rcyu $ # # # Host Database # # This file should contain the addresses and aliases for local hosts that # share this file. Replace 'my.domain' below with the domainname of your # machine. # # In the presence of the domain name service or NIS, this file may # not be consulted at all; see /etc/nsswitch.conf for the resolution order. # # ::1 localhost localhost.my.domain 127.0.0.1 localhost localhost.my.domain # # Imaginary network. #10.0.0.2 myname.my.domain myname #10.0.0.3 myfriend.my.domain myfriend # # According to RFC 1918, you can use the following IP networks for # private nets which will never be connected to the Internet: # # 10.0.0.0 - 10.255.255.255 # 172.16.0.0 - 172.31.255.255 # 192.168.0.0 - 192.168.255.255 # # In case you want to be able to connect to the Internet, you need # real official assigned numbers. Do not try to invent your own network # numbers but instead get one from your network provider (if any) or # from your regional registry (ARIN, APNIC, LACNIC, RIPE NCC, or AfriNIC.) #
/etc/hosts 的格式如下:
[Internet address] [official hostname] [alias1] [alias2] ...
例如:
10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2
請參考 hosts(5) 取得更多資訊。
11.9. 使用 sysctl(8) 調校
sysctl(8) 可用來更改執行中的 FreeBSD 系統,這包含許多 TCP/IP 堆疊及虛擬記憶體系統的進階選項,讓有經驗的系統管理者能夠簡單的提升效能。有超過五百個系統變數可以使用 sysctl(8) 來讀取與設定。
sysctl(8) 主要提供兩個功能:讀取與修改系統設定。
檢視所有可讀取的變數:
% sysctl -a
要讀取特定變數只要指定其名稱:
% sysctl kern.maxproc
kern.maxproc: 1044
要設定特定變數可使用 variable=value 語法:
# sysctl kern.maxfiles=5000
kern.maxfiles: 2088 -> 5000
sysctl 的設定值通常為字串、數字或布林值,其中布林值的 1
代表是,0
代表否。
要在每次機器開機時自動設定一些變數可將其加入到 /etc/sysctl.conf。要取得更多的資訊請參考 sysctl.conf(5) 及 sysctl.conf。
11.9.1. sysctl.conf
sysctl(8) 的設定檔於 /etc/sysctl.conf,內容很像 /etc/rc.conf,設定數值使用 variable=value
格式。指定的數值會在系統進入多使用者模式時設定,但並非所有變數皆可在此模式設定。
例如,要關閉嚴重信號 (Fatal signal) 中止的記錄並避免使用者看到其他使用者所執行的程序,可加入以下設定到 /etc/sysctl.conf:
# Do not log fatal signal exits (e.g., sig 11) kern.logsigexit=0 # Prevent users from seeing information about processes that # are being run under another UID. security.bsd.see_other_uids=0
11.9.2. 唯讀 sysctl(8)
在有些情況可能會需要修改唯讀的 sysctl(8) 數值,而這會需要重新啟動系統。
例如,某些筆電型號的 cardbus(4) 裝置無法偵測到記憶體範圍而且會失效並有類似以下的錯誤:
cbb0: Could not map register memory
device_probe_and_attach: cbb0 attach returned 12
這個修正需要修改唯讀的 sysctl(8) 設定。加入 hw.pci.allow_unsupported_io_range=1
到 /boot/loader.conf 然後重新啟動。現在 cardbus(4) 應可正常運作。
11.10. 調校磁碟
接下來的章節會討論在磁碟裝置上各種可調校的機制與選項。在大多數案例中,有使用機械元件的硬碟,如 SCSI 磁碟機,會成為導致整體系統效能低下的瓶頸。雖然已經有不使用機械元件的磁碟機解決方案,如,固態硬碟,但使用機械元件的磁碟機短期內並不會消失。在調校磁碟時,建議可以利用 iostat(8) 指令的功能來測試各種對系統的變更,這個指令可讓使用者取得系統 IO 相關的有用資訊。
11.10.1. Sysctl 變數
11.10.1.1. vfs.vmiodirenable
The vfs.vmiodirenable
sysctl(8) variable may be set to either 0
(off) or 1
(on). It is set to 1
by default. This variable controls how directories are cached by the system. Most directories are small, using just a single fragment (typically 1 K) in the file system and typically 512 bytes in the buffer cache. With this variable turned off, the buffer cache will only cache a fixed number of directories, even if the system has a huge amount of memory. When turned on, this sysctl(8) allows the buffer cache to use the VM page cache to cache the directories, making all the memory available for caching directories. However, the minimum in-core memory used to cache a directory is the physical page size (typically 4 K) rather than 512 bytes. Keeping this option enabled is recommended if the system is running any services which manipulate large numbers of files. Such services can include web caches, large mail systems, and news systems. Keeping this option on will generally not reduce performance, even with the wasted memory, but one should experiment to find out.
11.10.1.2. vfs.write_behind
The vfs.write_behind
sysctl(8) variable defaults to 1
(on). This tells the file system to issue media writes as full clusters are collected, which typically occurs when writing large sequential files. This avoids saturating the buffer cache with dirty buffers when it would not benefit I/O performance. However, this may stall processes and under certain circumstances should be turned off.
11.10.1.3. vfs.hirunningspace
The vfs.hirunningspace
sysctl(8) variable determines how much outstanding write I/O may be queued to disk controllers system-wide at any given instance. The default is usually sufficient, but on machines with many disks, try bumping it up to four or five megabytes. Setting too high a value which exceeds the buffer cache’s write threshold can lead to bad clustering performance. Do not set this value arbitrarily high as higher write values may add latency to reads occurring at the same time.
There are various other buffer cache and VM page cache related sysctl(8) values. Modifying these values is not recommended as the VM system does a good job of automatically tuning itself.
11.10.1.4. vm.swap_idle_enabled
The vm.swap_idle_enabled
sysctl(8) variable is useful in large multi-user systems with many active login users and lots of idle processes. Such systems tend to generate continuous pressure on free memory reserves. Turning this feature on and tweaking the swapout hysteresis (in idle seconds) via vm.swap_idle_threshold1
and vm.swap_idle_threshold2
depresses the priority of memory pages associated with idle processes more quickly then the normal pageout algorithm. This gives a helping hand to the pageout daemon. Only turn this option on if needed, because the tradeoff is essentially pre-page memory sooner rather than later which eats more swap and disk bandwidth. In a small system this option will have a determinable effect, but in a large system that is already doing moderate paging, this option allows the VM system to stage whole processes into and out of memory easily.
11.10.1.5. hw.ata.wc
Turning off IDE write caching reduces write bandwidth to IDE disks, but may sometimes be necessary due to data consistency issues introduced by hard drive vendors. The problem is that some IDE drives lie about when a write completes. With IDE write caching turned on, IDE hard drives write data to disk out of order and will sometimes delay writing some blocks indefinitely when under heavy disk load. A crash or power failure may cause serious file system corruption. Check the default on the system by observing the hw.ata.wc
sysctl(8) variable. If IDE write caching is turned off, one can set this read-only variable to 1
in /boot/loader.conf in order to enable it at boot time.
For more information, refer to ata(4).
11.10.1.6. SCSI_DELAY
(kern.cam.scsi_delay
)
The SCSI_DELAY
kernel configuration option may be used to reduce system boot times. The defaults are fairly high and can be responsible for 15
seconds of delay in the boot process. Reducing it to 5
seconds usually works with modern drives. The kern.cam.scsi_delay
boot time tunable should be used. The tunable and kernel configuration option accept values in terms of milliseconds and not seconds.
11.10.2. 軟更新
To fine-tune a file system, use tunefs(8). This program has many different options. To toggle Soft Updates on and off, use:
# tunefs -n enable /filesystem
# tunefs -n disable /filesystem
A file system cannot be modified with tunefs(8) while it is mounted. A good time to enable Soft Updates is before any partitions have been mounted, in single-user mode.
Soft Updates is recommended for UFS file systems as it drastically improves meta-data performance, mainly file creation and deletion, through the use of a memory cache. There are two downsides to Soft Updates to be aware of. First, Soft Updates guarantee file system consistency in the case of a crash, but could easily be several seconds or even a minute behind updating the physical disk. If the system crashes, unwritten data may be lost. Secondly, Soft Updates delay the freeing of file system blocks. If the root file system is almost full, performing a major update, such as make installworld
, can cause the file system to run out of space and the update to fail.
11.10.2.1. 有關軟更新的更多詳細資訊
Meta-data updates are updates to non-content data like inodes or directories. There are two traditional approaches to writing a file system’s meta-data back to disk.
Historically, the default behavior was to write out meta-data updates synchronously. If a directory changed, the system waited until the change was actually written to disk. The file data buffers (file contents) were passed through the buffer cache and backed up to disk later on asynchronously. The advantage of this implementation is that it operates safely. If there is a failure during an update, meta-data is always in a consistent state. A file is either created completely or not at all. If the data blocks of a file did not find their way out of the buffer cache onto the disk by the time of the crash, fsck(8) recognizes this and repairs the file system by setting the file length to 0
. Additionally, the implementation is clear and simple. The disadvantage is that meta-data changes are slow. For example, rm -r
touches all the files in a directory sequentially, but each directory change will be written synchronously to the disk. This includes updates to the directory itself, to the inode table, and possibly to indirect blocks allocated by the file. Similar considerations apply for unrolling large hierarchies using tar -x
.
The second approach is to use asynchronous meta-data updates. This is the default for a UFS file system mounted with mount -o async
. Since all meta-data updates are also passed through the buffer cache, they will be intermixed with the updates of the file content data. The advantage of this implementation is there is no need to wait until each meta-data update has been written to disk, so all operations which cause huge amounts of meta-data updates work much faster than in the synchronous case. This implementation is still clear and simple, so there is a low risk for bugs creeping into the code. The disadvantage is that there is no guarantee for a consistent state of the file system. If there is a failure during an operation that updated large amounts of meta-data, like a power failure or someone pressing the reset button, the file system will be left in an unpredictable state. There is no opportunity to examine the state of the file system when the system comes up again as the data blocks of a file could already have been written to the disk while the updates of the inode table or the associated directory were not. It is impossible to implement a fsck(8) which is able to clean up the resulting chaos because the necessary information is not available on the disk. If the file system has been damaged beyond repair, the only choice is to reformat it and restore from backup.
The usual solution for this problem is to implement dirty region logging, which is also referred to as journaling. Meta-data updates are still written synchronously, but only into a small region of the disk. Later on, they are moved to their proper location. Because the logging area is a small, contiguous region on the disk, there are no long distances for the disk heads to move, even during heavy operations, so these operations are quicker than synchronous updates. Additionally, the complexity of the implementation is limited, so the risk of bugs being present is low. A disadvantage is that all meta-data is written twice, once into the logging region and once to the proper location, so performance "pessimization" might result. On the other hand, in case of a crash, all pending meta-data operations can be either quickly rolled back or completed from the logging area after the system comes up again, resulting in a fast file system startup.
Kirk McKusick, the developer of Berkeley FFS, solved this problem with Soft Updates. All pending meta-data updates are kept in memory and written out to disk in a sorted sequence ("ordered meta-data updates"). This has the effect that, in case of heavy meta-data operations, later updates to an item "catch" the earlier ones which are still in memory and have not already been written to disk. All operations are generally performed in memory before the update is written to disk and the data blocks are sorted according to their position so that they will not be on the disk ahead of their meta-data. If the system crashes, an implicit "log rewind" causes all operations which were not written to the disk appear as if they never happened. A consistent file system state is maintained that appears to be the one of 30 to 60 seconds earlier. The algorithm used guarantees that all resources in use are marked as such in their blocks and inodes. After a crash, the only resource allocation error that occurs is that resources are marked as "used" which are actually "free". fsck(8) recognizes this situation, and frees the resources that are no longer used. It is safe to ignore the dirty state of the file system after a crash by forcibly mounting it with mount -f
. In order to free resources that may be unused, fsck(8) needs to be run at a later time. This is the idea behind the background fsck(8): at system startup time, only a snapshot of the file system is recorded and fsck(8) is run afterwards. All file systems can then be mounted "dirty", so the system startup proceeds in multi-user mode. Then, background fsck(8) is scheduled for all file systems where this is required, to free resources that may be unused. File systems that do not use Soft Updates still need the usual foreground fsck(8).
The advantage is that meta-data operations are nearly as fast as asynchronous updates and are faster than logging, which has to write the meta-data twice. The disadvantages are the complexity of the code, a higher memory consumption, and some idiosyncrasies. After a crash, the state of the file system appears to be somewhat "older". In situations where the standard synchronous approach would have caused some zero-length files to remain after the fsck(8), these files do not exist at all with Soft Updates because neither the meta-data nor the file contents have been written to disk. Disk space is not released until the updates have been written to disk, which may take place some time after running rm(1). This may cause problems when installing large amounts of data on a file system that does not have enough free space to hold all the files twice.
11.11. 調校核心限制
11.11.1. 檔案/程序限制
11.11.1.1. kern.maxfiles
The kern.maxfiles
sysctl(8) variable can be raised or lowered based upon system requirements. This variable indicates the maximum number of file descriptors on the system. When the file descriptor table is full, file: table is full
will show up repeatedly in the system message buffer, which can be viewed using dmesg(8).
Each open file, socket, or fifo uses one file descriptor. A large-scale production server may easily require many thousands of file descriptors, depending on the kind and number of services running concurrently.
In older FreeBSD releases, the default value of kern.maxfiles
is derived from maxusers
in the kernel configuration file. kern.maxfiles
grows proportionally to the value of maxusers
. When compiling a custom kernel, consider setting this kernel configuration option according to the use of the system. From this number, the kernel is given most of its pre-defined limits. Even though a production machine may not have 256 concurrent users, the resources needed may be similar to a high-scale web server.
The read-only sysctl(8) variable kern.maxusers
is automatically sized at boot based on the amount of memory available in the system, and may be determined at run-time by inspecting the value of kern.maxusers
. Some systems require larger or smaller values of kern.maxusers
and values of 64
, 128
, and 256
are not uncommon. Going above 256
is not recommended unless a huge number of file descriptors is needed. Many of the tunable values set to their defaults by kern.maxusers
may be individually overridden at boot-time or run-time in /boot/loader.conf. Refer to loader.conf(5) and /boot/defaults/loader.conf for more details and some hints.
In older releases, the system will auto-tune maxusers
if it is set to 0
. . When setting this option, set maxusers
to at least 4
, especially if the system runs Xorg or is used to compile software. The most important table set by maxusers
is the maximum number of processes, which is set to 20 + 16 * maxusers
. If maxusers
is set to 1
, there can only be 36
simultaneous processes, including the 18
or so that the system starts up at boot time and the 15
or so used by Xorg. Even a simple task like reading a manual page will start up nine processes to filter, decompress, and view it. Setting maxusers
to 64
allows up to 1044
simultaneous processes, which should be enough for nearly all uses. If, however, the error is displayed when trying to start another program, or a server is running with a large number of simultaneous users, increase the number and rebuild.
|
11.11.1.2. kern.ipc.soacceptqueue
The kern.ipc.soacceptqueue
sysctl(8) variable limits the size of the listen queue for accepting new TCP
connections. The default value of 128
is typically too low for robust handling of new connections on a heavily loaded web server. For such environments, it is recommended to increase this value to 1024
or higher. A service such as sendmail(8), or Apache may itself limit the listen queue size, but will often have a directive in its configuration file to adjust the queue size. Large listen queues do a better job of avoiding Denial of Service (DoS) attacks.
11.11.2. 網路限制
The NMBCLUSTERS
kernel configuration option dictates the amount of network Mbufs available to the system. A heavily-trafficked server with a low number of Mbufs will hinder performance. Each cluster represents approximately 2 K of memory, so a value of 1024
represents 2
megabytes of kernel memory reserved for network buffers. A simple calculation can be done to figure out how many are needed. A web server which maxes out at 1000
simultaneous connections where each connection uses a 6 K receive and 16 K send buffer, requires approximately 32 MB worth of network buffers to cover the web server. A good rule of thumb is to multiply by 2
, so 2x32 MB / 2 KB = 64 MB / 2 kB = 32768
. Values between 4096
and 32768
are recommended for machines with greater amounts of memory. Never specify an arbitrarily high value for this parameter as it could lead to a boot time crash. To observe network cluster usage, use -m
with netstat(1).
The kern.ipc.nmbclusters
loader tunable should be used to tune this at boot time. Only older versions of FreeBSD will require the use of the NMBCLUSTERS
kernel config(8) option.
For busy servers that make extensive use of the sendfile(2) system call, it may be necessary to increase the number of sendfile(2) buffers via the NSFBUFS
kernel configuration option or by setting its value in /boot/loader.conf (see loader(8) for details). A common indicator that this parameter needs to be adjusted is when processes are seen in the sfbufa
state. The sysctl(8) variable kern.ipc.nsfbufs
is read-only. This parameter nominally scales with kern.maxusers
, however it may be necessary to tune accordingly.
Even though a socket has been marked as non-blocking, calling sendfile(2) on the non-blocking socket may result in the sendfile(2) call blocking until enough |
11.11.2.1. net.inet.ip.portrange.*
The net.inet.ip.portrange.*
sysctl(8) variables control the port number ranges automatically bound to TCP
and UDP
sockets. There are three ranges: a low range, a default range, and a high range. Most network programs use the default range which is controlled by net.inet.ip.portrange.first
and net.inet.ip.portrange.last
, which default to 1024
and 5000
, respectively. Bound port ranges are used for outgoing connections and it is possible to run the system out of ports under certain circumstances. This most commonly occurs when running a heavily loaded web proxy. The port range is not an issue when running a server which handles mainly incoming connections, such as a web server, or has a limited number of outgoing connections, such as a mail relay. For situations where there is a shortage of ports, it is recommended to increase net.inet.ip.portrange.last
modestly. A value of 10000
, 20000
or 30000
may be reasonable. Consider firewall effects when changing the port range. Some firewalls may block large ranges of ports, usually low-numbered ports, and expect systems to use higher ranges of ports for outgoing connections. For this reason, it is not recommended that the value of net.inet.ip.portrange.first
be lowered.
11.11.2.2. TCP
頻寬延遲乘積
TCP
bandwidth delay product limiting can be enabled by setting the net.inet.tcp.inflight.enable
sysctl(8) variable to 1
. This instructs the system to attempt to calculate the bandwidth delay product for each connection and limit the amount of data queued to the network to just the amount required to maintain optimum throughput.
This feature is useful when serving data over modems, Gigabit Ethernet, high speed WAN
links, or any other link with a high bandwidth delay product, especially when also using window scaling or when a large send window has been configured. When enabling this option, also set net.inet.tcp.inflight.debug
to 0
to disable debugging. For production use, setting net.inet.tcp.inflight.min
to at least 6144
may be beneficial. Setting high minimums may effectively disable bandwidth limiting, depending on the link. The limiting feature reduces the amount of data built up in intermediate route and switch packet queues and reduces the amount of data built up in the local host’s interface queue. With fewer queued packets, interactive connections, especially over slow modems, will operate with lower Round Trip Times. This feature only effects server side data transmission such as uploading. It has no effect on data reception or downloading.
Adjusting net.inet.tcp.inflight.stab
is not recommended. This parameter defaults to 20
, representing 2 maximal packets added to the bandwidth delay product window calculation. The additional window is required to stabilize the algorithm and improve responsiveness to changing conditions, but it can also result in higher ping(8) times over slow links, though still much lower than without the inflight algorithm. In such cases, try reducing this parameter to 15
, 10
, or 5
and reducing net.inet.tcp.inflight.min
to a value such as 3500
to get the desired effect. Reducing these parameters should be done as a last resort only.
11.11.3. 虛擬記憶體
11.11.3.1. kern.maxvnodes
A vnode is the internal representation of a file or directory. Increasing the number of vnodes available to the operating system reduces disk I/O. Normally, this is handled by the operating system and does not need to be changed. In some cases where disk I/O is a bottleneck and the system is running out of vnodes, this setting needs to be increased. The amount of inactive and free RAM will need to be taken into account.
To see the current number of vnodes in use:
# sysctl vfs.numvnodes
vfs.numvnodes: 91349
To see the maximum vnodes:
# sysctl kern.maxvnodes
kern.maxvnodes: 100000
If the current vnode usage is near the maximum, try increasing kern.maxvnodes
by a value of 1000
. Keep an eye on the number of vfs.numvnodes
. If it climbs up to the maximum again, kern.maxvnodes
will need to be increased further. Otherwise, a shift in memory usage as reported by top(1) should be visible and more memory should be active.
11.12. 增加交換空間
有時系統會需要更多的交換 (Swap) 空間,本章節會介紹兩種增加交換空間的方式:一種是在既有的分割區或新的硬碟增加交換空間,另一種則是在既有的分割區中建立一個交換檔。
要取得更多有關如何加密交換空間的資訊、有那些可用的選項以及為何要做加密,可參考 交換空間加密。
11.12.1. 使用新硬碟或既有分割區增加交換空間
使用 swapon
來增加交換分割區到系統,例:
# swapon /dev/ada1s1b
可以使用任何尚未掛載過、甚至已經有內含資料的分割區做為交換空間,但在含有資料的分割區上使用 |
要在開機時自動加入此交換分割區,可加入以下項目到 /etc/fstab:
/dev/ada1s1b none swap sw 0 0
11.12.2. 建立交換檔
以下例子會建立一個 64M 的交換檔於 /usr/swap0 來替代使用分割區建立交換空間。
使用交換檔開啟交換空間前需要在核心編譯或載入 md(4) 所需的模組,請參考 設定 FreeBSD 核心 了解有關編譯自訂核心的資訊。
建立交換檔 /usr/swap0:
# dd if=/dev/zero of=/usr/swap0 bs=1m count=64
設定適當的權限於 /usr/swap0:
# chmod 0600 /usr/swap0
在 /etc/rc.conf 開啟交換檔:
swapfile="/usr/swap0" # Set to name of swap file
交換空間會於系統啟動時增加。若要立即增加交換空間,可指定一個未使用的記憶體裝置。請參考 記憶體磁碟 取得更多有關記憶體裝置的資訊。
# mdconfig -a -t vnode -f /usr/swap0 -u 0 && swapon /dev/md0
11.13. 電源與資源管理
以有效率的方式運用硬體資源是很重要的,電源與資源管理讓作業系統可以監控系統的限制,並且在系統溫度意外升高時能夠發出警報。早期提供電源管理的規範是進階電源管理 (Advanced Power Management, APM),APM 可根據系統的使用狀況來來控制電源用量。然而,使用 APM 要作業系統來管理系統的電源用量和溫度屬性是困難且沒有彈性的,因為硬體是由 BIOS 所管理,使用者對電源管理設定只有有限的設定性與可見性,且 APMBIOS 是由供應商提供且特定於某些硬體平台,而作業系統中必透過 APM 驅動程式做為中介存取 APM 軟體介面才能夠管理電源等級。
在 APM 有四個主要的問題。第一,電源管理是由供應商特定的 BIOS 來完成,與作業系統是分開的。例如,使用者可在 APMBIOS 設定硬碟的閒置時間值,在超過時間時 BIOS 可在未徵得作業系統的同意下降低硬碟的轉速。第二,APM 的邏輯是內嵌在 BIOS 當中的,並且在作業系統範圍之外運作,這代表使用者只能夠透過燒錄新的韌體到 ROM 來修正 APMBIOS 中的問題,而這樣的程序是危險的,若失敗,可能會讓系統進入無法復原的狀態。第三,APM 是供應商特定的技術,這代表有許多重複的工作,在一個供應商的 BIOS 找到的問題在其他的供應商卻沒有解決。最後一點,APMBIOS 並沒有足夠的空間來實作複雜的電源管理政策或可良好適應主機用途的程式。
Plug and Play BIOS (PNPBIOS) 在很多情況下並不可靠,PNPBIOS 是 16 位元的技術,所以作業系統必須模擬 16 位元才能存取 PNPBIOS。FreeBSD 提供了一個 APM 驅動程式來做 APM,應可用在 2000 年之前所製造的系統,該驅動程式的說明於 apm(4)。
APM 的後繼者是進階設置與電源介面 (Advanced Configuration and Power Interface, ACPI)。ACPI 是一套由供應商聯盟所搛寫出的標準,提供了硬體資源與電源管理的介面,它是 作業系統直接設置與電源管理 (Operating System-directed configuration and Power Management) 關鍵的要素,提供了作業系統更多的控制方式與彈性。
本章節將示範如何在 FreeBSD 設定 ACPI,然後提供一些如何對 ACPI 除錯的提示以及如何提交包含除錯資訊的問題回報,讓開發人員能夠診斷並修正 ACPI 的問題。
11.13.1. 設定 ACPI
在 FreeBSD acpi(4) 驅動程式預設會在系統開始時載入,且不應被編譯到核心當中。這個驅動程式在開機之後無法被卸載,因為系統匯流排會使用它做各種硬體互動。雖然如此,若系統遇到問題,ACPI 還是可以被關閉,在 /boot/loader.conf 中設定 hint.acpi.0.disabled="1"
之後重新開機或在載入程式提示時設定這個變數,如 階段三 中的說明。
ACPI 與 APM 不能同時存在且應分開使用,若有偵測到有另一個正在執行,要載入的後者將會中斷。 |
ACPI 可以用來讓系統進入睡眠模式,使用 acpiconf
與 -s
旗標再加上由 1
到 5
的數字。大多數使用者只需使用 1
(快速待命到 RAM) 或 3
(待命到 RAM),選項 5
會執行軟關機 (Soft-off),如同執行 halt -p
一樣。
其他的選項可使用 sysctl
來設定,請參考 acpi(4) 以及 acpiconf(8) 以取得更多資訊。
11.13.2. 常見問題
ACPI is present in all modern computers that conform to the ia32 (x86), ia64 (Itanium), and amd64 (AMD) architectures. The full standard has many features including CPU performance management, power planes control, thermal zones, various battery systems, embedded controllers, and bus enumeration. Most systems implement less than the full standard. For instance, a desktop system usually only implements bus enumeration while a laptop might have cooling and battery management support as well. Laptops also have suspend and resume, with their own associated complexity.
An ACPI-compliant system has various components. The BIOS and chipset vendors provide various fixed tables, such as FADT, in memory that specify things like the APIC map (used for SMP), config registers, and simple configuration values. Additionally, a bytecode table, the Differentiated System Description Table DSDT, specifies a tree-like name space of devices and methods.
The ACPI driver must parse the fixed tables, implement an interpreter for the bytecode, and modify device drivers and the kernel to accept information from the ACPI subsystem. For FreeBSD, Intel™ has provided an interpreter (ACPI-CA) that is shared with Linux™ and NetBSD. The path to the ACPI-CA source code is src/sys/contrib/dev/acpica. The glue code that allows ACPI-CA to work on FreeBSD is in src/sys/dev/acpica/Osd. Finally, drivers that implement various ACPI devices are found in src/sys/dev/acpica.
For ACPI to work correctly, all the parts have to work correctly. Here are some common problems, in order of frequency of appearance, and some possible workarounds or fixes. If a fix does not resolve the issue, refer to 取得與回報除錯資訊 for instructions on how to submit a bug report.
11.13.2.1. 滑鼠問題
In some cases, resuming from a suspend operation will cause the mouse to fail. A known work around is to add hint.psm.0.flags="0x3000"
to /boot/loader.conf.
11.13.2.2. 待機/喚醒
ACPI has three suspend to RAM (STR) states, S1
-S3
, and one suspend to disk state (STD), called S4
. STD can be implemented in two separate ways. The S4
BIOS is a BIOS-assisted suspend to disk and S4
OS is implemented entirely by the operating system. The normal state the system is in when plugged in but not powered up is "soft off" (S5
).
Use sysctl hw.acpi
to check for the suspend-related items. These example results are from a Thinkpad:
hw.acpi.supported_sleep_state: S3 S4 S5
hw.acpi.s4bios: 0
Use acpiconf -s
to test S3
, S4
, and S5
. An s4bios
of one (1
) indicates S4
BIOS support instead of S4
operating system support.
When testing suspend/resume, start with S1
, if supported. This state is most likely to work since it does not require much driver support. No one has implemented S2
, which is similar to S1
. Next, try S3
. This is the deepest STR state and requires a lot of driver support to properly reinitialize the hardware.
A common problem with suspend/resume is that many device drivers do not save, restore, or reinitialize their firmware, registers, or device memory properly. As a first attempt at debugging the problem, try:
# sysctl debug.bootverbose=1
# sysctl debug.acpi.suspend_bounce=1
# acpiconf -s 3
This test emulates the suspend/resume cycle of all device drivers without actually going into S3
state. In some cases, problems such as losing firmware state, device watchdog time out, and retrying forever, can be captured with this method. Note that the system will not really enter S3
state, which means devices may not lose power, and many will work fine even if suspend/resume methods are totally missing, unlike real S3
state.
Harder cases require additional hardware, such as a serial port and cable for debugging through a serial console, a Firewire port and cable for using dcons(4), and kernel debugging skills.
To help isolate the problem, unload as many drivers as possible. If it works, narrow down which driver is the problem by loading drivers until it fails again. Typically, binary drivers like nvidia.ko, display drivers, and USB will have the most problems while Ethernet interfaces usually work fine. If drivers can be properly loaded and unloaded, automate this by putting the appropriate commands in /etc/rc.suspend and /etc/rc.resume. Try setting hw.acpi.reset_video
to 1
if the display is messed up after resume. Try setting longer or shorter values for hw.acpi.sleep_delay
to see if that helps.
Try loading a recent Linux™ distribution to see if suspend/resume works on the same hardware. If it works on Linux™, it is likely a FreeBSD driver problem. Narrowing down which driver causes the problem will assist developers in fixing the problem. Since the ACPI maintainers rarely maintain other drivers, such as sound or ATA, any driver problems should also be posted to the freebsd-current list and mailed to the driver maintainer. Advanced users can include debugging printf(3)s in a problematic driver to track down where in its resume function it hangs.
Finally, try disabling ACPI and enabling APM instead. If suspend/resume works with APM, stick with APM, especially on older hardware (pre-2000). It took vendors a while to get ACPI support correct and older hardware is more likely to have BIOS problems with ACPI.
11.13.2.3. 系統無回應
Most system hangs are a result of lost interrupts or an interrupt storm. Chipsets may have problems based on boot, how the BIOS configures interrupts before correctness of the APIC (MADT) table, and routing of the System Control Interrupt (SCI).
Interrupt storms can be distinguished from lost interrupts by checking the output of vmstat -i
and looking at the line that has acpi0
. If the counter is increasing at more than a couple per second, there is an interrupt storm. If the system appears hung, try breaking to DDB (CTRL+ALT+ESC on console) and type show interrupts
.
When dealing with interrupt problems, try disabling APIC support with hint.apic.0.disabled="1"
in /boot/loader.conf.
11.13.2.4. 當機
Panics are relatively rare for ACPI and are the top priority to be fixed. The first step is to isolate the steps to reproduce the panic, if possible, and get a backtrace. Follow the advice for enabling options DDB
and setting up a serial console in 從序列線路 (Serial Line) 進入 DDB 除錯程式 or setting up a dump partition. To get a backtrace in DDB, use tr
. When handwriting the backtrace, get at least the last five and the top five lines in the trace.
Then, try to isolate the problem by booting with ACPI disabled. If that works, isolate the ACPI subsystem by using various values of debug.acpi.disable
. See acpi(4) for some examples.
11.13.2.5. 系統在待機或關機後仍開機
First, try setting hw.acpi.disable_on_poweroff="0"
in /boot/loader.conf. This keeps ACPI from disabling various events during the shutdown process. Some systems need this value set to 1
(the default) for the same reason. This usually fixes the problem of a system powering up spontaneously after a suspend or poweroff.
11.13.2.6. BIOS 含有有問題的 Bytecode
Some BIOS vendors provide incorrect or buggy bytecode. This is usually manifested by kernel console messages like this:
ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\
(Node 0xc3f6d160), AE_NOT_FOUND
Often, these problems may be resolved by updating the BIOS to the latest revision. Most console messages are harmless, but if there are other problems, like the battery status is not working, these messages are a good place to start looking for problems.
11.13.3. 覆蓋預設的 AML
The BIOS bytecode, known as ACPI Machine Language (AML), is compiled from a source language called ACPI Source Language (ASL). The AML is found in the table known as the Differentiated System Description Table (DSDT).
The goal of FreeBSD is for everyone to have working ACPI without any user intervention. Workarounds are still being developed for common mistakes made by BIOS vendors. The Microsoft™ interpreter (acpi.sys and acpiec.sys) does not strictly check for adherence to the standard, and thus many BIOS vendors who only test ACPI under Windows™ never fix their ASL. FreeBSD developers continue to identify and document which non-standard behavior is allowed by Microsoft™'s interpreter and replicate it so that FreeBSD can work without forcing users to fix the ASL.
To help identify buggy behavior and possibly fix it manually, a copy can be made of the system’s ASL. To copy the system’s ASL to a specified file name, use acpidump
with -t
, to show the contents of the fixed tables, and -d
, to disassemble the AML:
# acpidump -td > my.asl
Some AML versions assume the user is running Windows™. To override this, set hw.acpi.osname="Windows 2009"
in /boot/loader.conf, using the most recent Windows™ version listed in the ASL.
Other workarounds may require my.asl to be customized. If this file is edited, compile the new ASL using the following command. Warnings can usually be ignored, but errors are bugs that will usually prevent ACPI from working correctly.
# iasl -f my.asl
Including -f
forces creation of the AML, even if there are errors during compilation. Some errors, such as missing return statements, are automatically worked around by the FreeBSD interpreter.
The default output filename for iasl
is DSDT.aml. Load this file instead of the BIOS’s buggy copy, which is still present in flash memory, by editing /boot/loader.conf as follows:
acpi_dsdt_load="YES" acpi_dsdt_name="/boot/DSDT.aml"
Be sure to copy DSDT.aml to /boot, then reboot the system. If this fixes the problem, send a diff(1) of the old and new ASL to freebsd-acpi so that developers can work around the buggy behavior in acpica.
11.13.4. 取得與回報除錯資訊
The ACPI driver has a flexible debugging facility. A set of subsystems and the level of verbosity can be specified. The subsystems to debug are specified as layers and are broken down into components (ACPI_ALL_COMPONENTS
) and ACPI hardware support (ACPI_ALL_DRIVERS
). The verbosity of debugging output is specified as the level and ranges from just report errors (ACPI_LV_ERROR
) to everything (ACPI_LV_VERBOSE
). The level is a bitmask so multiple options can be set at once, separated by spaces. In practice, a serial console should be used to log the output so it is not lost as the console message buffer flushes. A full list of the individual layers and levels is found in acpi(4).
Debugging output is not enabled by default. To enable it, add options ACPI_DEBUG
to the custom kernel configuration file if ACPI is compiled into the kernel. Add ACPI_DEBUG=1
to /etc/make.conf to enable it globally. If a module is used instead of a custom kernel, recompile just the acpi.ko module as follows:
# cd /sys/modules/acpi/acpi && make clean && make ACPI_DEBUG=1
Copy the compiled acpi.ko to /boot/kernel and add the desired level and layer to /boot/loader.conf. The entries in this example enable debug messages for all ACPI components and hardware drivers and output error messages at the least verbose level:
debug.acpi.layer="ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS" debug.acpi.level="ACPI_LV_ERROR"
If the required information is triggered by a specific event, such as a suspend and then resume, do not modify /boot/loader.conf. Instead, use sysctl
to specify the layer and level after booting and preparing the system for the specific event. The variables which can be set using sysctl
are named the same as the tunables in /boot/loader.conf.
Once the debugging information is gathered, it can be sent to freebsd-acpi so that it can be used by the FreeBSD ACPI maintainers to identify the root cause of the problem and to develop a solution.
Before submitting debugging information to this mailing list, ensure the latest BIOS version is installed and, if available, the embedded controller firmware version. |
When submitting a problem report, include the following information:
Description of the buggy behavior, including system type, model, and anything that causes the bug to appear. Note as accurately as possible when the bug began occurring if it is new.
The output of
dmesg
after runningboot -v
, including any error messages generated by the bug.The
dmesg
output fromboot -v
with ACPI disabled, if disabling ACPI helps to fix the problem.Output from
sysctl hw.acpi
. This lists which features the system offers.The URL to a pasted version of the system’s ASL. Do not send the ASL directly to the list as it can be very large. Generate a copy of the ASL by running this command:
# acpidump -dt > name-system.asl
Substitute the login name for name and manufacturer/model for system. For example, use njl-FooCo6000.asl.
Most FreeBSD developers watch the FreeBSD-CURRENT mailing list, but one should submit problems to freebsd-acpi to be sure it is seen. Be patient when waiting for a response. If the bug is not immediately apparent, submit a bug report. When entering a PR, include the same information as requested above. This helps developers to track the problem and resolve it. Do not send a PR without emailing freebsd-acpi first as it is likely that the problem has been reported before.
11.13.5. 參考文獻
More information about ACPI may be found in the following locations:
The FreeBSD ACPI Mailing List Archives (https://lists.freebsd.org/pipermail/freebsd-acpi/)
The ACPI 2.0 Specification (http://acpi.info/spec.htm)
acpi(4), acpi_thermal(4), acpidump(8), iasl(8), and acpidb(8)
Chapter 12. FreeBSD 開機程序
12.1. 概述
從開啟電腦到載入作業系統的這段流程稱為 "開機程序" (Bootstrap process) 或 "開機" (Booting)。FreeBSD 的開機程序提供大量的客製化彈性,包含可選擇安裝在同電腦的其他的作業系統、不同版本的作業系統或不同核心的作業系統的功能。
本章會詳細說明可以設定的選項。示範如何自訂 FreeBSD 開機流程,包含其中所有會發生的事,直到啟動 FreeBSD 核心、偵測裝置及啟動 init(8)。這些事會發生在開機訊息的文字顏色會從亮白變成灰色之間。
在閱讀本章之後,您會了解:
FreeBSD 開機系統的元件以及它們如何互動。
FreeBSD 開機程式中各元件可使用的選項,用來控制開機程序。
如何設定自訂的開機啟動畫面 (Splash screen)。
設定 Device Hints 的基礎。
如何開機進入單人及多人模式以及如何正確關閉 FreeBSD 系統。
本章僅說明 FreeBSD 在 x86 及 amd64 系統上執行的開機流程。 |
12.2. FreeBSD 開機程序
打開電腦並啟動作業系統的這個動作呈現了一個有趣的困境。照道理,電腦在啟動作業系統之前並不知道要如何做任何事情,這些事情之中包括從磁碟執行程式。如果電腦無法在沒有作業系統的情況下執行程式,而作業系統的程式本身又在磁碟上,那麼作業系統要如何啟動呢?
這個問題如同 The Adventures of Baron Munchausen 一書中的一個角色掉進了洞裡,他抓住了靴子上的拔靴帶 (Bootstrap) 才把自己拉了出來,因此在早期電腦領域用 bootstrap 一詞來指載入作業系統的機制,後來被縮短為 "booting"。
在 x86 硬體上,基本輸入/輸出系統 (Basic Input/Output System, BIOS) 負責載入作業系統。 BIOS 會找到硬碟上的主開機記錄區 (Master Boot Record, MBR),該記錄區必須位於磁碟上的特定位置。BIOS 有足夠的知識可以載入並執行這個 MBR,並且假設這個 MBR 在 BIOS 的協助下可以完成接下來載入作業系統的工作。
FreeBSD 在較舊的 MBR 標準與較新的 GUID 分割區表 (GUID Partition Table, GPT) 上都能夠開機 (Booting)。GPT 磁碟分割通常會在有支援統一可延伸韌體介面 (Unified Extensible Firmware Interface, UEFI) 的電腦上找到。不論如何,FreeBSD 即使在只有傳統 BIOS 的機器上,也可以使用 gptboot(8) 由 GPT 分割區開機。直接使用 UEFI 開機的開發工作正在進行中。 |
在 MBR 中的程式通常會稱作開機管理程式 (Boot manager),特別是那些會與使用者互動的程式。開機管理程式通常會另一部份的程式會存放於磁碟的第一個磁軌或檔案系統。開機管理程式的例子有標準 FreeBSD 開機管理程式 boot0 又稱 Boot Easy 以及 Grub 常用於各種 Linux™ 發行版。
若只有安裝一個作業系統,MBR 會搜尋磁碟上第一個可開機的 (使用中) 切割區 (Slice),然後執行在該切割區上的程式來載入剩下的作業系統。當有多個作業系統存在時,可以安裝可顯示作業系統清單的開機管理程式,以讓使用者可以選擇要啟動的作業系統。
剩餘的 FreeBSD 開機系統分成三個階段,第一個階段只知道如何讓電腦進入特定狀態並執行第二階段,第二個階段在執行第三階段之前會做的事比較多一點,第三個階段會完成載入作業系統的工作。把工作分成三個階段的原因是 MBR 有限制在階段一與階段二能夠執行程式的大小。將這些工作連結在一起讓 FreeBSD 能夠提供更有彈性的載入程式。
核心會接著開始偵測裝置並初始化這些裝置供使用。核心開機程序完成之後,核心便會傳送控制權給使用者程序 init(8),這個程序會確保磁碟在可以使用的狀態,然後啟動使用者層級的資源設置來掛載檔案系統、設定網路卡以能夠連線網路、啟動那些被設定在開機時要啟動的程序。
本章節將更詳細介紹這些階段並示範如何與 FreeBSD 開機程序互動。
12.2.1. 開機管理程式
有時會稱在 MBR 中的開機管理程式為開機程序的 第零階段 (Stage zero),FreeBSD 預設會使用 boot0 開機管理程式。
由 FreeBSD 安裝程式所安裝的 MBR 便是以 /boot/boot0 為基礎。boot0 的大小與容量被限制在 446 個位元組是由於切割表與 0x55AA
識別碼位於 MBR 的最末端。若安裝多個作業系統使用 boot0 ,則會在開機時顯示如下範例的訊息:
F1 Win
F2 FreeBSD
Default: F2
其作他作業統若在 FreeBSD 之後才安裝則會覆蓋現有的 MBR,若這件事發生了,或者要使用 FreeBSD MBR 取代現有的 MBR 可使用以下指令:
# fdisk -B -b /boot/boot0 device
其中 device 開機磁碟,例如第一個 IDE 磁碟為 ad0,第二個 IDE 控制器的第一個 IDE磁碟為 ad2,第一個 SCSI 磁碟為 da0。要建立自訂的 MBR 設定請參考 boot0cfg(8)。
12.2.2. 階段一與階段二
概念上,第一與第二個階段均為磁碟上同一個區域上同一個程式的一部份,由於空間上的限制,它們被分成兩部份,但是會一併安裝。它們會由 FreeBSD 安裝程式或 bsdlabel
從 /boot/boot 複製而來。
這兩個階段均位於檔案系統之外,在開機切割區的第一個磁軌,從第一個磁碟扇區 (Sector) 開始,這個位置便是 boot0 或其他開機管理程式所會儲存的地方,並會尋找可以執行的程式以繼續開機程序。
第一個階段的 boot1 非常的簡單,因為它只能有 512 位元組的大小。它只能認得儲存切割區資訊的 FreeBSD bsdlabel 以及尋找並執行 boot2。
階段二 boot2 稍微複雜一點,能夠理解 FreeBSD 檔案系統來搜尋檔案。它可以提供一個簡單的介面來選擇要執行的核心或載入程式。它所執行的載入程式 (loader) 更複雜並能讀取開機設定檔。若開機程序在階段二中斷,則會顯示以下的互動畫面:
>> FreeBSD/i386 BOOT
Default: 0:ad(0,a)/boot/loader
boot:
要更換已安裝的 boot1 與 boot2 可使用 bsdlabel
,其中 diskslice 是要開機的磁碟與切割區,例如 ad0s1 代表第一個 IDE 磁碟的第一個切割區:
# bsdlabel -B diskslice
若只使用磁碟名稱,如 ad0, |
12.2.3. 階段三
loader 是三階段開機程多的最後一個階段,載入程式位於檔案系統之中,通常在 /boot/loader。
loader 主要目地是利用擁有更複雜指令集的強大直譯器做為基礎的內建指令集提供一個互動的方式來做設定。
在初始化的過程中,loader 會偵測 Console 與磁碟,並找出可以用來開機的磁碟。在由 Script 或互動輸入使用者指令的地方會設定相對的變數並啟動直譯器。
loader 接著會讀取 /boot/loader.rc,這個程式預設又會讀取 /boot/defaults/loader.conf 來設定合理的變數預設值以及讀取 /boot/loader.conf 來對這些變數做本地的更改。loader.rc 接著會依這些變數來運作,讀取選擇模組與核心。
最後,預設情況下 loader 會待候鍵盤輸入 10 秒鐘,若沒有被中斷的話會接著啟動核心。若被使用者中斷,則會向使用者顯示提示字元,此時使用可以使用指令集來調整變數、卸載所有模組、載入模組,然後最後開機或重新開機。載入程式內建指令 中列出了最常使用的 loader 指令。要完整了解所有可用的指令,請參考 loader(8)。
變數 | 說明 |
---|---|
autoboot seconds | 若在指定時間 (秒) 內沒有中斷,會繼續啟動核心。此指令會顯示倒數,預設的時間為 10 秒鐘。 |
boot | 使用任何指定的選項或核心名稱立即啟動核心,要由指令列指定核心名稱必須先執行 |
boot-conf | 依據指定的變數及最常用的 |
help | 顯示自 /boot/loader.help 取得的說明訊息。若指定的主題為 |
include filename … | 讀取指定的檔案並直譯每一行。若有錯誤則會立即中止 |
load | 由指定的檔案名稱載入核心、核心模組或指定類型的檔案。任何於 filename 之後的參數都會被傳遞到該檔案。若 filename 不是絕對位置則會搜尋 /boot/kernel 及 /boot/modules 底下。 |
ls [-l] | 顯示指定路徑中的檔案,若未指定路徑則會顯示根目錄中的檔案。若有指定 |
lsdev [-v] | 列出所有的裝置,這些裝置可能可以用來載入模組。若有指定 |
lsmod [-v] | 顯示已載入的模組。若有指定 |
more filename | 顯示指定的檔案,並於每 |
reboot | 立即重新啟動系統。 |
set variable, set variable=value | 設定指定的環境變數。 |
unload | 移除所有已載入的模組。 |
這裡有一些 loader 用法的實務範例。要使用一般的核心開機進入單使用者模式 (Single-user mode) 可:
boot -s
要卸載一般的核心與模組,然後載入先前或另一個指定的核心可:
unload
load kernel.old
使用 kernel.GENERIC 來代表安裝程式使用的預設核心,或 kernel.old 來代表在系統升級之前或設定自訂核心前安裝的核心。
使用以下指令來使用另一個核心載入一般的模組:
unload
set kernel="kernel.old"
boot-conf
要載入一個已自動化的核心設置 Script 可:
load -t userconfig_script /boot/kernel.conf
12.2.4. 最終階段
由 loader 或由會繞開 loader 的 boot2 載入核心之後,載入程式便會檢查是不有使用任何開機旗標,並根據需要調整開機的方式。開機時核心互動參數 列出了常用的開機旗標,請參考 boot(8) 取得更多其他開機旗標的資訊。
項目 | 說明 |
---|---|
| 核心初始化時,會詢問要掛載為根檔案系統的裝置。 |
| 由 CDROM 做為根檔案系統開機。 |
| 開機進入單使用者模式。 |
| 核心啟動時提供更多詳細資訊。 |
一旦核心完成開機程序後,便會傳送控制權給使用者程序 init(8),該程序位於 /sbin/init 或在 loader
中的 init_path
變數所指的程式路徑。這是開機程序的最後一個階段。
開機程序會確保系統上的檔案系統的一致性 (Consistency),若 UFS 檔案系統不一致且 fsck
無法修時,init 會讓系統進入單使用者模式,以讓系統管理者能夠直接解決問題,否則系統會開機進入多使用者模式。
12.2.4.1. 單使用者模式
使用者可以在開機時指定 -s
或在 loader 設定 boot_single
變數進入這個模式。也可以透過在多使用者模式執行 shutdown now
進入此模式。進入單使用者模式時會出現此訊息:
Enter full pathname of shell or RETURN for /bin/sh:
若使用者按下 Enter,系統便會進入預設的 Bourne shell。要指定使用其他的 Shell 則輸入該 Shell 的完整路徑。
單使用者模式通常用來修復因檔案系統不一致或開機設定檔發生錯誤造成的無法開機,也可以用來重設遺忘的 root
的密碼,因為在單使用者模式會給予對本地系統及設定檔完整的存取權。在這個模式下沒有網路功能。
雖然單使用者模式對修復系統很有幫助,但若系統放在不安全的場所便會有安全上的風險。預設,開機進入單使用者模式後,任何能夠存取實體主機的使用者便擁有系統的完整控制權。
若在 /etc/ttys 系統 console
更改為 insecure
,系統便會在初始化單使用者模式前先詢問 root
的密碼。這可增加一定程度的安全性,但便無法在忘記 root
密碼時重設密碼。
# name getty type status comments # # If console is marked "insecure", then init will ask for the root password # when going to single-user mode. console none unknown off insecure
不安全 (insecure
) console 代表對 Console 的實體安全性評估為不安全 (insecure),所以只有知道 root
密碼的人可以使用單使用者模式。
12.2.4.2. 多使用者模式
若 init 正常找到檔案系統或在單使用者模式的使用者完成了操作並輸入 exit
離開單使用者模式,系統便會進入多使用者模式,在這個模式便會開始系統的資源設置。
資源設置系統 (Resource configuration system) 會從 /etc/defaults/rc.conf 讀取設定預設值以及從 /etc/rc.conf 讀取系統特定的設定,接著會繼續掛載系統列於 /etc/fstab 的檔案系統,也會啟動網路服務、其他的系統 Daemon,然後執行本地已安裝套件的啟動 Script。
要了解更多有關資源設置系統,請參考 rc(8) 以及查看位於 /etc/rc.d 的 Script。
12.3. 設定開機啟動畫面
正常 FreeBSD 系統開機會在 Console 顯示以一系列訊息來表示開機進度。開機啟動畫面 (Boot splash screen) 是另一種可以把所有開機偵測與服務啟動訊息隱藏的開機畫面,但即使開啟了啟動畫面,仍有有少數的開機載入程式的訊息,如:開機選項選單以及倒數時間的提示,仍會在開機時顯示。在開機程序時可以按下鍵盤上的按鍵來關閉顯示中的啟動畫面。
FreeBSD 有兩種基本的環境可以使用,一種是預設的傳統虛擬 Console 指令列環境,在系統完成開機之後,便會顯示 Console 登入提示。另一種環境則是設定好的圖型化環境,請參考 X Window 系統 以取得更多有關如何安裝與設定圖型化顯示管理程式與圖型化登入管理程式的資訊。
系統開機之後,啟動畫面預設會作為螢幕保護程式,一段時間未使用便會顯示啟動畫面,並且會循環更改影像的亮度,從明亮到非常暗,然後再繼續循環。啟動螢幕保護程式的設定可在 /etc/rc.conf 增加一行 saver=
來更改。有許多內建的螢幕保護程式可用,在 splash(4) 中有說明。saver=
的選項只會套用至虛擬 Console,對圖型化顯示管理程式並不會有任何影響。
透過安裝 sysutils/bsd-splash-changer 套件或 Port,可在開機時顯示隨機挑選的啟動畫面。啟動畫面功能支援 256 色的點陣圖 (.bmp)、ZSoft PCX (.pcx) 或 TheDraw (.bin) 格式。.bmp, .pcx 或 .bin 圖片必須放在根分割區,例如於 /boot。啟動圖片檔必須使用 320x200 像素或更低的解析度以能夠在標準 VGA 介面卡上運作,要在預設 256 色、320x200 像素或更低的解析度設定開機啟動圖片,可加入下行到 /boot/loader.conf,並替換 splash.bmp 為實際要使用的點陣圖檔:
splash_bmp_load="YES" bitmap_load="YES" bitmap_name="/boot/splash.bmp"
要使用 PCX 檔則可替換點陣圖檔:
splash_pcx_load="YES" bitmap_load="YES" bitmap_name="/boot/splash.pcx"
若要改使用 https://en.wikipedia.org/wiki/TheDraw 格式的 ASCII 圖可:
splash_txt="YES" bitmap_load="YES" bitmap_name="/boot/splash.bin"
要使用較大的圖片來填滿整個顯示畫面支援的解析度最大可至 1024x768 像素,VESA 模組也必須在系統開機時載入。若使用自訂的核心,請確定自訂核心設定檔中有含有 VESA
核心設定選項。要載入 VESA 模組來顯示啟動畫面可在 /boot/loader.conf 上述例子中提到的三行之前加入下行:
vesa_load="YES"
其他有用的 loader.conf 選項還有:
beastie_disable="YES"
這個會關閉開機選項選單的顯示,但倒數計時提示仍會在。即使關閉了開機選項選單,在倒數計時提示時輸入選擇的選項還是會啟動對應的開機選項。
loader_logo="beastie"
這個選項會替換預設與上色的小惡魔圖示一起顯示於開機選項選單右側的 "FreeBSD" 文字。
要取得更多資訊,請參考 splash(4), loader.conf(5) 以及 vga(4)。
12.4. 裝置提示
在一開始系統啟動時,開機 loader(8) 會讀取 device.hints(5),這個檔中儲存了核心開機資訊,即變數,有時我們又會稱其為 "裝置提示 (Device hints)"。這些 "裝置提示 (Device hints)" 會傳送給裝置驅動程式做裝置的設置使用。
裝置提示也可在階段 3 開機載入程式提示時指定,如 階段三 中的示範,其變數也可以使用 set
增加、使用 unset
移除、使用 show
檢視,也可覆蓋設定在 /boot/device.hints 的變數,但在開機載入程式輸入的裝置提示並不是永久有效的,在下一次重新開機久後便會失效。
一旦系統開機後,便可使用 kenv(1) 來列出所有的變數。
/boot/device.hints 的語法為一個變數一行,使用井字號 "#" 做為註解符號,每一行的結構如下:
hint.driver.unit.keyword="value"
在階段 3 開機載入程式的語法則為:
set hint.driver.unit.keyword=value
其中 driver
為裝置驅動程式名稱、unit
為裝置驅動程式單位編號及 keyword
為提示關鍵字,關鍵字由以下選項所組成:
at
: 指定裝置所連結的匯流排 (Bus)。port
: 指定要使用的 I/O 開始位置。irq
: 指定要使用的中斷請求編號。drq
: 指定 DMA 頻道編號。maddr
: 指定裝置所使用的實體記憶體位置。flags
: 設定提供給裝置的各種旗標位元。disabled
: 若設為1
則可關閉該裝置。
由於裝置驅動程式可能會接受或請求更多未列於此處的提示,建議先閱讀驅動程式的操作手冊。要取得更多資訊請參考 device.hints(5), kenv(1), loader.conf(5) 以及 loader(8)。
12.5. 關機程序
在使用 shutdown(8) 控制關閉時,init(8) 會嘗試執行 /etc/rc.shutdown Script 接著傳送 TERM
信號給所有的程序,然後傳送 KILL
信號給未在時間內中止的程序。
要在支援電源管理的架構與系統關閉 FreeBSD 主機電源,可使用 shutdown -p now
來立即關閉電源,要重新啟動 FreeBSD 系統可使用 shutdown -r now
。操作人必須為 root
或為 operator
的成員才可執行 shutdown(8),擁有這些身份的人也可使用 halt(8) 與 reboot(8),參考這些指令與 shutdown(8) 的操作手冊來取得更多資訊。
要修改群組成員可參考 使用者與基礎帳號管理。
電源管理需要以載入 acpi(4) 模組或將其靜態編譯至自訂核心中。 |
Chapter 13. 安全性
13.1. 概述
不論實體或虛擬,安全性這個主題大到有整個產業圍繞著它,上百個標準案例已經被用來搛寫如何確保系統與網路的安全性。身為 FreeBSD 必須了解如何避免攻擊與入侵。
在此章會討論幾個基本原理及技術。FreeBSD 系統的安全性有許多層面,且有許多第三方工具可以用來增加安全性。
讀完這章,您將了解:
基礎 FreeBSD 系統安全概念。
FreeBSD 中的幾種加密 (Crypt) 機制。
如何設定一次性密碼認證。
如何設定 inetd(8) 中的 TCP Wrapper。
如何在 FreeBSD 設定 Kerberos。
如何設定 IPsec 並且建立 VPN。
如何在 FreeBSD 設定並使用 OpenSSH。
如何使用檔案系統 ACL。
如何使用 pkg 來稽查從 Port 套件集安裝的第三方軟體套件。
如何利用 FreeBSD 安全報告。
什麼是程序追蹤 (Process Accounting) 以及如何在 FreeBSD 開啟。
如何使用登入類別或資源限制資料庫控制使用者資源。
在開始閱讀這章之前,您需要:
了解 FreeBSD 基礎及網路概念。
其他的安全性議題會在本操作手冊的其他處說明。例如 強制存取控制 (Mandatory Access Control, MAC) 會在 強制存取控制 (MAC) 討論及網路防火牆會在 防火牆 討論。
13.2. 簡介
保安是每個人的責任,任何系統中的弱點都可讓入侵者取得對關鍵資訊的存取權並導致整個網路的浩劫。資訊安全的其中一個核心原則便是 CIA 三字訣,代表著資訊系統的機密性 (Confidentiality)、完整性 (Integrity) 以及可用性 (Availability)。
CIA 三字訣是電腦安全的基石,就如同客戶與使用者期望他們的資料得到保護一樣重要。例如,一個客戶會期望他們的信用卡資訊被安全的保存 (機密性)、他們的訂單不會在私底下被竄改 (完整性) 以及他們隨時可以存取他們的訂單資訊 (可用性)。
要提供 CIA,安全專家會應用防禦深度的策略。防禦深度的概念是增加數個保全階層來避免單一階層失效便導致整個安全系統瓦解。例如,系統管理者不能直接打開防火牆與評估網路或系統的安全性,還要同時稽查帳號、檢查 Binary 的完整性與確保未被安裝惡意工具。要執行有效的保安策略,必須了解威脅以及如何抵禦威脅。
什麼威脅影響到電腦安全性? 威脅並不僅限於在遠端嘗試未經授權存取系統的遠端攻擊者,威脅也包含員工、惡意軟體、未經許可的網路裝置、天然災害、安全性漏洞甚至是公司競爭對手。
系統與網路可以被未經授權存取,有時是因為意外,或是因遠端攻擊者,或在某些案例中,是因商業間諜或者前員工。做為使用者,重要的是做好防範準備以及當有失誤造成安全漏洞能夠承認並回報可能的問題給安全團隊。做為管理者,重要的是了解威脅並準備在發生時能夠減緩威脅。
當要應用保安到系統上時,建議由基本帳號以及系統設定開始保全,接著確保網路層,使其遵守系統政策以及組織的安全程序。許多組織已經有涵蓋科技裝置設置的安全性政策,該政策應包含工作站、桌上型電腦、行動裝置、手機、上線伺服器、開發伺服器的安全設置。在大多數案例中,也都已經有標準操作程序 (SOP),當有疑慮時,請向安全團隊諮詢。
簡介接下來的部份將說明如何在 FreeBSD 系統上執行這些基礎的安全設置。本章接下來的部份將介紹在 FreeBSD 系統執行安全性政策時會用到的特定工具。
13.2.1. 防止登入
要確保一個系統的安全最好的起點便是做好帳號的稽查,確保 root
使用了一個強而有力的密碼,並這個密碼未在其他地方使用過,然後關閉任何無須登入存取權的帳號。
要防止登入存取帳號有兩種方法,第一種是鎖定帳號,以下範例會鎖定 toor
帳號:
# pw lock toor
第二種防止登入存取的方式是狀 Shell 更改為 /usr/sbin/nologin,只有超級使用者可以更改其他使用者的 Shell:
# chsh -s /usr/sbin/nologin toor
/usr/sbin/nologin shell 可以避免系統分配 Shell 給嘗試登入的使用者。
13.2.2. 帳號升級授權
在有一些案例,需要與其他使用者共用系統管理權限,FreeBSD 有兩種方式可以處理這種情況。第一種,也是較不建議的方式,是與 wheel
群組的成員共用 root 的密碼,這種方式使用者可以在需要超級使用者的存取權時輸入 su
然後輸入 wheel
的密碼,在完成需要管理存取權的指令之後,使用應輸入 exit
離開。要加入使用者到這個群組,可編輯 /etc/group 然後加入該使用者到 wheel
項目的最後,使用者必須以逗號字元分隔並不可有空白。
第二種方式,也是較建議的方式,安裝 security/sudo 套件或 Port 來提升權限。這個軟體提供了額外的稽查、更細微的使用者控制,然後可以設定鎖定使用者只能執行特定需權限的指令。
在安裝之後,使用 visudo
來編輯 /usr/local/etc/sudoers。這個範例會建立新 webadmin
群組,並加入 trhodes
帳號到該群組,然後設定該群組可重新啟動 apache24 的存取權:
# pw groupadd webadmin -M trhodes -g 6000
# visudo
%webadmin ALL=(ALL) /usr/sbin/service apache24 *
13.2.3. 密碼編碼方式
密碼是資訊科技的必要之惡,當必須使用密碼時,應要有複雜且強大的雜湊機制來加密儲存在密碼資料庫中的密碼。FreeBSD 支援 DES, MD5, SHA256, SHA512 以及 Blowfish 雜湊演算法於其 crypt()
程式庫。預設使用 SHA512,不建議改成更不安全的雜湊演算法,但可改成更安全的 Blowfish 演算法。
Blowfish 不是 AES 的一部份且不符合任何聯邦資訊處理標準 (Federal Information Processing Standards, FIPS),在某些環境可能不會允許使用這種加密方式。 |
要知道目前用何種雜湊演算法來加密某位使用者密碼,超級使用者可以檢視在 FreeBSD 密碼資料庫中該使用者的雜湊,每個雜湊的一開始便會以符號標示其用來加密密碼所使用的雜湊機制。若使用 DES 則開始不會有任何符號,而 MD5 的符號則是 $
,SHA256 及 SHA512 的符號是 $6$
,Blowfish 的符號是 $2a$
。在以下例子中 dru
的密碼使以預設的 SHA512 演算法加密,因為其雜湊的開始為 $6$
。注意,該加密過的雜湊,不是原來的密碼,會儲存於密碼資料庫中:
# grep dru /etc/master.passwd
dru:$6$pzIjSvCAn.PBYQBA$PXpSeWPx3g5kscj3IMiM7tUEUSPmGexxta.8Lt9TGSi2lNQqYGKszsBPuGME0:1001:1001::0:0:dru:/usr/home/dru:/bin/csh
雜湊機制是設定在該使用者的登入類別 (Login class),以此為例,該使用者屬於 default
登入類別,且雜湊演算法是以下行設定在 /etc/login.conf:
:passwd_format=sha512:\
要更改演算法為 Blowfish,可修改該行如下:
:passwd_format=blf:\
然後依 設定登入類別 中所描述的方式執行 cap_mkdb /etc/login.conf
。注意,這個動作不會影響任何已存在的密碼雜湊,但這代表必須要求所有使用者執行 passwd
來更改其密碼才有辦法重新加密所有密碼。
13.2.4. 強制密碼政策
強制在本地帳號使用高強度密碼的政策是系統安全的基礎之一。在 FreeBSD 密碼長度、密碼強度以及密碼複雜性可使用內建的可插拔認証模組 (Pluggable Authentication Modules, PAM) 來執行。
本節將示範如何設定密碼長度下限與上限以及使用 pam_passwdqc.so 來強制使用混合字元的密碼,此模組可在使用者更改其密碼時強制要求。
要設定此模組,需要先成為超級使用者,然後取消註解在 /etc/pam.d/passwd 中含有 pam_passwdqc.so
的行。然後編輯該行來配合密碼政策:
password requisite pam_passwdqc.so min=disabled,disabled,disabled,12,10 similar=deny retry=3 enforce=users
這個例子會設定新密碼所需符合的需求。min
設定可以控制密碼長度下限,它有五個值因為這個模組根據密碼的複雜度定義了五種類型。而複雜度是由必須在密碼中存在的字元類型來定義,例如:文字、數字、符號以及大小寫,這些密碼類型在 pam_passwdqc(8) 有詳細的說明。在這個例子,密碼類型的前三項為關閉的,代表不會接受只滿足這些複雜度的密碼,不論長度為何。12
設定密碼政策可接受滿足三種字元類型複雜度且至少 12 個字元的密碼,10
設定密碼政策接受滿足四種字元類型複雜度且至少 10 個字元的密碼。
similar
設定則會拒絕以使用者前一次類似的密碼。retry
設定會提供使用者三次輸入新密碼的機會。
一這個檔案儲存之後,更改密碼的使用者將會看到如下的訊息:
% passwd
Changing local password for trhodes
Old Password:
You can now choose the new password.
A valid password should be a mix of upper and lower case letters,
digits and other characters. You can use a 12 character long
password with characters from at least 3 of these 4 classes, or
a 10 character long password containing characters from all the
classes. Characters that form a common pattern are discarded by
the check.
Alternatively, if no one else can see your terminal now, you can
pick this as your password: "trait-useful&knob".
Enter new password:
若輸入了一個不符何密碼政策的密碼,則會被拒絕並顯示警告,然後使用者會有機會再重試,直到超過設定的允許重試次數。
大多數密碼政策會讓密碼在多日過後過期。要在 FreeBSD 設定密碼年齡日期,可在 /etc/login.conf 中該使用者的登入類別設定 passwordtime
。在 default
登入類別已有設定範例:
# :passwordtime=90d:\
因此,要設定此登入類別的密碼在 90 天之後過期只需要移除註解符號 (#
),然後儲存編輯結果並執行 cap_mkdb /etc/login.conf
。
要在個別使用者設定期限,可將有效日期或到期的天數與使用者名稱傳給 pw
:
# pw usermod -p 30-apr-2015 -n trhodes
如這個例子,有效日期的格式為天、月以及年。要取得更多資訊可參考 pw(8)。
13.2.5. 偵測 Root 工具 (Rootkit)
rootkit 指的是嘗試未經授權取得系統 root
存取權的軟體。一旦安裝之後,這個惡意軟體將可以光明正大的開啟給另一個給攻擊者進入的大門。現實上,一但系統已被 rootkit 滲透且執行了搜索動作之後,該系統就應該從頭重新安裝,因為即使非常謹真的資安或系統工程式也可能會遺漏攻擊者留下的動西。
rootkit 對管理者而言唯一有幫助的是:一但偵測到,便代表某處已經被滲透,但這類型的應用程式躲藏的非常好,本節將會示範一個可以用來偵測 rootkit 的工具,security/rkhunter。
安裝此套件或 Port 之後,系統便可使用以下指令檢查。該指令提供許多資訊且會需要手動按下 ENTER 確認:
# rkhunter -c
該程序完成之後,目前狀態的訊息便會顯示在畫面上。這個訊息包含了已檢查過多少檔案、可疑的檔案、可能的 rootkit 以及其他更多資訊。在檢查的過程中,可能會產生一些有關隱藏檔案、OpenSSH 通訊協定選擇及已安裝軟體已知漏洞版本的通用的安全性警告、這些問題可以立即處理或在更詳細的分析之後再處理。
每位管理者應了解在系統上執行了那些程式以及這些程式的用途。第三方工具如 rkhunter 與 sysutils/lsof 以及原生指令如 netstat
與 ps
可以系統上大量的資訊,記錄下那一些是正常的,當有不適當的程式出現時提出疑問,然後找出答案。雖然理想要避免滲透,但也必須偵測是否已被滲透了。
13.2.6. Binary 檢驗
檢驗系統檔案與 Binary 是很重要的,因為它可以提供系統管理者與資安團隊有關系統變更的資訊,能夠監視系統變更的軟體應用程式稱為入侵偵測系統 (Intrusion Detection System, IDS)。
FreeBSD 原生提供了基礎的 IDS 系統,雖然每天晚上會有安全性的信件會通知管理者相關的變更,但這些資訊是儲存在本地的,這讓惡意的使用者有機會能夠修改這些資訊來隱藏其對系統的變更。也因此,會建議建立一個獨立的 Binary 簽名並將這些簽名儲存在唯度、root 擁有的目錄或在可移除的 USB 磁碟或遠端 rsync 伺服器更好。
內建 mtree
工具可以對一個目錄中的內容產生一個規格檔,產生規格檔會用到一個種子碼 (Seed) 或常數,然後在檢查規格是否有更改過時會也會需要使用這個種子碼或常數。這讓檢查一個檔案或 Binary 是否被修改變成可能的一件事。由於攻擊者並不知道種子碼,要仿冒或檢查檔案的校驗碼 (Checksum) 數值是幾乎不可能的。以下例子會產生一組 SHA256 雜湊,每一個在 /bin 的系統 Binary 都會有一個,並姐會將這些值以隱藏黨儲存在 root
的家目錄,/root/.bin_chksum_mtree:
# mtree -s 3483151339707503 -c -K cksum,sha256digest -p /bin > /root/.bin_chksum_mtree
# mtree: /bin checksum: 3427012225
3483151339707503 代表種子碼,這個值應要記錄下來且不可給其它人看。
檢視 /root/.bin_cksum_mtree 應會產生類似以下的輸出結果:
# user: root # machine: dreadnaught # tree: /bin # date: Mon Feb 3 10:19:53 2014 # . /set type=file uid=0 gid=0 mode=0555 nlink=1 flags=none . type=dir mode=0755 nlink=2 size=1024 \ time=1380277977.000000000 \133 nlink=2 size=11704 time=1380277977.000000000 \ cksum=484492447 \ sha256digest=6207490fbdb5ed1904441fbfa941279055c3e24d3a4049aeb45094596400662a cat size=12096 time=1380277975.000000000 cksum=3909216944 \ sha256digest=65ea347b9418760b247ab10244f47a7ca2a569c9836d77f074e7a306900c1e69 chflags size=8168 time=1380277975.000000000 cksum=3949425175 \ sha256digest=c99eb6fc1c92cac335c08be004a0a5b4c24a0c0ef3712017b12c89a978b2dac3 chio size=18520 time=1380277975.000000000 cksum=2208263309 \ sha256digest=ddf7c8cb92a58750a675328345560d8cc7fe14fb3ccd3690c34954cbe69fc964 chmod size=8640 time=1380277975.000000000 cksum=2214429708 \ sha256digest=a435972263bf814ad8df082c0752aa2a7bdd8b74ff01431ccbd52ed1e490bbe7
機器的主機名稱、建立規格檔的日期與時間、以及建立此規格檔的使用者名稱皆會記錄在此報告當中,報告當中還會有在目錄中每個 Binary 的校驗碼、大小、時間以及 SHA256 編碼。
要檢驗 Binary 簽名是否有被變更過,可使用先前產生的規格檔比對目前目錄的內容,然後儲存結果到檔案。這個指令需要當初產生原規格檔所使用的種子碼:
# mtree -s 3483151339707503 -p /bin < /root/.bin_chksum_mtree >> /root/.bin_chksum_output
# mtree: /bin checksum: 3427012225
這個動作應會產生與上次建立 /bin 規格檔時產生的校驗碼相同,若在此目錄的 Binary 沒有被變更過,那麼 /root/.bin_chksum_output 這個輸出檔將會是空的。要模擬變更,可以使用 touch
更改 /root/.bin_chksum_output 的日期然後再執行檢驗指令一次:
# touch /bin/cat
# mtree -s 3483151339707503 -p /bin < /root/.bin_chksum_mtree >> /root/.bin_chksum_output
# more /root/.bin_chksum_output
cat changed
modification time expected Fri Sep 27 06:32:55 2013 found Mon Feb 3 10:28:43 2014
建議對含有 Binary 以及設定檔的目錄建立規格檔,對含有敏感資料的目錄也是。通常會為 /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, /etc 及 /usr/local/etc 建立規格檔。
也有更進階的 IDS 系統,例如 security/aide。大多數情況 mtree
已可提供管理者所需的功能。將種子碼與校驗碼結果保存在惡意使用者無法存取的地方是非常重要的一件事。更多有關 mtree
的資訊可在 mtree(8) 找到。
13.2.7. 系統安全性調校
在 FreeBSD,有許多系統功能可以使用 sysctl
調校,本節會涵蓋少數可以調校來避免阻斷服務 (Denial of Service, DoS) 攻擊的安全性功能。更多有關使用 sysctl
的資訊包含:如何暫時更改數值及如何在測試之後做永久更改可在 使用 sysctl(8) 調校 找到。
任何時間使用 使用 sysctl(8) 調校 做的設定變更都會讓造成不想要的傷害的可能性上升,影響到系統的可用性。因此應要對所有的變更做監視,若可能的話,先在測試系統上實驗,再到上線的系統上使用。 |
預設 FreeBSD 核心會使用安全性層級 -1
來開機,這又稱作"不安全模式",因為不可變 (Immutable) 檔案旗標可以被關閉且可以讀取或寫入所有的裝置。除非有使用 sysctl
或在啟動 Script 設定修改該值,否則安全性層級將會在 -1
。安全性層級可以在系統啟動時透過在 /etc/rc.conf 設定 kern_securelevel_enable
為 YES
以及 設定 kern_securelevel
的值為想要的安全層級來提升。請參考 security(7) 以及 init(8) 以取得更多與這些設定及可用的安全性層級相關的資訊。
提高 |
net.inet.tcp.blackhole
以及 net.inet.udp.blackhole
設定可以用來丟棄在已關閉連接埠 (Port) 收到的 SYN 封包且不會回傳 RST 回應,預設的動作是會回傳 RST 來表示該連接埠已被關閉,更改預設的動作可對連接埠掃描 (用在查看在系統上執行的應用程式) 提供一定程度的保護,要這麼做可設定 net.inet.tcp.blackhole
為 2
及 net.inet.udp.blackhole
為 1
。請參考 blackhole(4) 以取得更多有關這些設定的資訊。
net.inet.icmp.drop_redirect
以及 net.inet.ip.redirect
設定可以幫助避免 重新導向攻擊 (Redirect attacks),重新導向攻擊是 DoS 的一種,會傳送大量 ICMP 類型 5 的封包,由於這些封包並不是必要的,設定 net.inet.icmp.drop_redirect
為 1
以及設定 net.inet.ip.redirect
為 0
可丟棄這些封包。
來源路由 (Source routing) 是一種偵測與存取在內部網路中不可路由位址的方法,由於不可路由位址通常是固故讓它不可路由的,因此可以關閉這個功能。要關閉這個功能可設定 net.inet.ip.sourceroute
以及 net.inet.ip.accept_sourceroute
為 0
。
當一台在網路上的機器需要傳送訊息給所有在子網路上的主機時,會發送 ICMP 回應請求訊息到廣播位址。然而,外部的主機是沒有理由可以執行這個動作的。要拒絕所有來自外部的廣播請求可設定 net.inet.icmp.bmcastecho
為 0
。
還有一些額外的設定在 security(7) 有說明。
13.3. 一次性密碼
預設 FreeBSD 已內建一次性密碼 (One-time Passwords In Everything, OPIE)。OPIE 設計用來避免重送攻擊 (Replay attack),重送攻擊指的是攻擊者發現了某位使用者的密碼,然後使用該密碼來存取系統。由於在 OPIE 的環境下,一組密碼只能被使用一次,被發現的密碼對攻擊者而言便沒有什麼作用。OPIE 使用了安全的加密方式與詰問/回應系統 (Challenge/response system) 來管理密碼。FreeBSD 在實作上預設採用 MD5 加密。
OPIE 使用了三種不同類型的密碼,第一種是一般的 UNIX™ 或 Kerberos 密碼,第二種是由 opiekey
所產生的一次性密碼,第三種是用來生一次性密碼的 "秘密密碼 (Secret password)",秘密密碼與 UNIX™ 密碼無關且不應相同。
對 OPIE 來說還有另外兩個部份的資料很重要。其中一個是"種子碼 (Seed)" 或稱"金鑰 (Key)",由兩個字母與五個數字組成。另一個則是"疊代次數 (Iteration count)",是一個介於 1 到 100 間的數字。OPIE 會將種子碼與秘密密碼串連後,套用 MD5 加密數次後 (根據疊代次數),再將結果轉換成六個簡短的英文單字來產生一次性密碼。認証系統會持續追蹤最後使用的一次性密碼,若使用者提供的密碼加密後與前一次的密碼相同則可通過認証。由於採用了單向的加密方式,若使用過的密碼被成功擷取也無法拿來產生之後的一次性密碼。疊代次數會在每一次登入成功之後減少,來保持使用者與登入程式間的同步。當疊代次數減少至 1
時,OPIE 便要重新初始化。
這個整個程序會牽涉到幾個程式。傳送疊代次數、種子碼與秘密密碼來產生一組一次性密碼或數個一次性密碼的 opiekey(1)。除了初始化 OPIE 之外,用來更改密碼、疊代次數或種子碼的 opiepasswd(1)。會讀取放在 /etc/opiekeys 的相關憑証檔來列出使用者目前的疊代次數與種子碼的 opieinfo(1)。
本章節將介紹四種不同的操作,第一是如何在安全連線下做第一次的一次性密碼設定,第二是如何使用在不安全的連線下使用 opiepasswd
,第三是如何在不安全的連線下登入系統,第四是如何產生數個可以被記錄或列印下來在不安全的場所使的金鑰。
13.3.1. 初始化 OPIE
第一次要初始化 OPIE,要在安全的場所執行以下指令:
% opiepasswd -c
Adding unfurl:
Only use this method from the console; NEVER from remote. If you are using
telnet, xterm, or a dial-in, type ^C now or exit with no password.
Then run opiepasswd without the -c parameter.
Using MD5 to compute responses.
Enter new secret pass phrase:
Again new secret pass phrase:
ID unfurl OTP key is 499 to4268
MOS MALL GOAT ARM AVID COED
-c
會設定採用假設指令在安全場所執行的 Console 模式,如在使用者掌控之中的電腦或者透過 SSH 連線到一台在使用者掌控之中的電腦。
提示出現後,輸入用來產生一次性登入金鑰的秘密密碼,應使用一個不容易被猜出來的密碼,且應與使用者登入帳號所使用的密碼不同,密碼必須介於 10 到 127 個字元長度之間,然後請記住這個密碼。
ID
行會列出登入名稱 (unfurl
)、預設的疊代次數 (499
) 以及預設的種子碼 (to4268
)。在進行登入時,系統會記住這些參數並且顯示出來,這也代表不需要另外記錄這些資訊。最後一行會列出根據這些參數與秘密密碼所產生出來的一次性密碼,在下一次登入時便要使用這個一次性密碼。
13.3.2. 在不安全連線下做初始化
要在不安全的系統上初始化或更改秘密密碼會需要某個可使用安全的連線的地方執行 opiekey
,這可能是在某一台信任的主機上的 Shell。初始化需要設定疊代次數,100 可能是不錯的數字,種子碼可以自行指定或隨機產生,在不安全連線下要被初始化主機須使用 opiepasswd(1):
% opiepasswd
Updating unfurl:
You need the response from an OTP generator.
Old secret pass phrase:
otp-md5 498 to4268 ext
Response: GAME GAG WELT OUT DOWN CHAT
New secret pass phrase:
otp-md5 499 to4269
Response: LINE PAP MILK NELL BUOY TROY
ID mark OTP key is 499 gr4269
LINE PAP MILK NELL BUOY TROY
要採用預設的種子碼,可直接按下 Return 做初始化。接著在輸入回應之前移到安全的連線然後給予相同的加密參數產生密碼:
% opiekey 498 to4268
Using the MD5 algorithm to compute response.
Reminder: Do not use opiekey from telnet or dial-in sessions.
Enter secret pass phrase:
GAME GAG WELT OUT DOWN CHAT
切換回不安全的連線,然後複製產生的一次性密碼貼上。
13.3.3. 產生單組一次性密碼
在初始化 OPIE 之後進行登入會顯示如下的提示訊息:
% telnet example.com
Trying 10.0.0.1...
Connected to example.com
Escape character is '^]'.
FreeBSD/i386 (example.com) (ttypa)
login: <username>
otp-md5 498 gr4269 ext
Password:
OPIE 的提示提供了一個很有用的功能,若在密碼提示時按下 Return,便會開啟回應功能並顯示輸入的內容,這個功能在嘗試手工輸入列印出來的密碼時很有用。
此時,要產生一次性密碼來回應登入時的提示,這必須在受信任且可安全執行 opiekey(1) 的系統上完成。這個指令有提供 Windows™, Mac OS™ 與 FreeBSD 版本,使用時需要疊代次數與種子碼做為在指令列的參數,剪下在要登入主機在登入時所提示的訊息。
在信任的系統上執行:
% opiekey 498 to4268
Using the MD5 algorithm to compute response.
Reminder: Do not use opiekey from telnet or dial-in sessions.
Enter secret pass phrase:
GAME GAG WELT OUT DOWN CHAT
在產生一次性密碼後,回到登入畫面繼續登入。
13.3.4. 產生多組一次性密碼
有時會無法存取信任的主機或沒有安全的連線,在這種情況下,可以使用 opiekey(1) 來預先產生多個一次性密碼,例如:
% opiekey -n 5 30 zz99999
Using the MD5 algorithm to compute response.
Reminder: Do not use opiekey from telnet or dial-in sessions.
Enter secret pass phrase: <secret password>
26: JOAN BORE FOSS DES NAY QUIT
27: LATE BIAS SLAY FOLK MUCH TRIG
28: SALT TIN ANTI LOON NEAL USE
29: RIO ODIN GO BYE FURY TIC
30: GREW JIVE SAN GIRD BOIL PHI
-n 5
會請求產生連續五個金鑰,而 30
則是指定最後一個疊代的編號。注意這些列印出的結果的順序與使用的順序相反。十足的偏執狂可能會想要用手寫下結果,否則就列印出清單。每一行會同時顯示疊代次數及一次性密碼,在密碼使用過後便可劃掉。
13.3.5. 限制使用 UNIX™ 密碼
OPIE 可以根據登入階段的 IP 位置限制使用 UNIX™ 密碼,相關的檔案為 /etc/opieaccess,這個檔案預設便存在。請參考 opieaccess(5) 來取得更多有關此檔案的資訊以及當使用時要考量的安全性問題。
這裡有一個範本 opieaccess:
permit 192.168.0.0 255.255.0.0
這一行允許來源 IP 位址 (容易受到詐騙的位址) 符合指定值與遮罩的使用者在任何時間可使用 UNIX™ 密碼登入。
若在 opieaccess 中沒有符合的規則,預設會拒絕非 OPIE 的登入。
13.4. TCP Wrapper
TCP Wrapper is a host-based access control system which extends the abilities of inetd 超級伺服器. It can be configured to provide logging support, return messages, and connection restrictions for the server daemons under the control of inetd. Refer to tcpd(8) for more information about TCP Wrapper and its features.
TCP Wrapper should not be considered a replacement for a properly configured firewall. Instead, TCP Wrapper should be used in conjunction with a firewall and other security enhancements in order to provide another layer of protection in the implementation of a security policy.
13.4.1. 初始設定
To enable TCP Wrapper in FreeBSD, add the following lines to /etc/rc.conf:
inetd_enable="YES" inetd_flags="-Ww"
Then, properly configure /etc/hosts.allow.
Unlike other implementations of TCP Wrapper, the use of hosts.deny is deprecated in FreeBSD. All configuration options should be placed in /etc/hosts.allow. |
In the simplest configuration, daemon connection policies are set to either permit or block, depending on the options in /etc/hosts.allow. The default configuration in FreeBSD is to allow all connections to the daemons started with inetd.
Basic configuration usually takes the form of daemon : address : action
, where daemon
is the daemon which inetd started, address
is a valid hostname, IP address, or an IPv6 address enclosed in brackets ([ ]), and action
is either allow
or deny
. TCP Wrapper uses a first rule match semantic, meaning that the configuration file is scanned from the beginning for a matching rule. When a match is found, the rule is applied and the search process stops.
For example, to allow POP3 connections via the mail/qpopper daemon, the following lines should be appended to hosts.allow:
# This line is required for POP3 connections: qpopper : ALL : allow
Whenever this file is edited, restart inetd:
# service inetd restart
13.4.2. 進階設定
TCP Wrapper provides advanced options to allow more control over the way connections are handled. In some cases, it may be appropriate to return a comment to certain hosts or daemon connections. In other cases, a log entry should be recorded or an email sent to the administrator. Other situations may require the use of a service for local connections only. This is all possible through the use of configuration options known as wildcards, expansion characters, and external command execution.
Suppose that a situation occurs where a connection should be denied yet a reason should be sent to the host who attempted to establish that connection. That action is possible with twist
. When a connection attempt is made, twist
executes a shell command or script. An example exists in hosts.allow:
# The rest of the daemons are protected. ALL : ALL \ : severity auth.info \ : twist /bin/echo "You are not welcome to use %d from %h."
In this example, the message "You are not allowed to use daemon name from hostname." will be returned for any daemon not configured in hosts.allow. This is useful for sending a reply back to the connection initiator right after the established connection is dropped. Any message returned must be wrapped in quote ("
) characters.
It may be possible to launch a denial of service attack on the server if an attacker floods these daemons with connection requests. |
Another possibility is to use spawn
. Like twist
, spawn
implicitly denies the connection and may be used to run external shell commands or scripts. Unlike twist
, spawn
will not send a reply back to the host who established the connection. For example, consider the following configuration:
# We do not allow connections from example.com: ALL : .example.com \ : spawn (/bin/echo %a from %h attempted to access %d >> \ /var/log/connections.log) \ : deny
This will deny all connection attempts from *.example.com
and log the hostname, IP address, and the daemon to which access was attempted to /var/log/connections.log. This example uses the substitution characters %a
and %h
. Refer to hosts_access(5) for the complete list.
To match every instance of a daemon, domain, or IP address, use ALL
. Another wildcard is PARANOID
which may be used to match any host which provides an IP address that may be forged because the IP address differs from its resolved hostname. In this example, all connection requests to Sendmail which have an IP address that varies from its hostname will be denied:
# Block possibly spoofed requests to sendmail: sendmail : PARANOID : deny
Using the |
To learn more about wildcards and their associated functionality, refer to hosts_access(5).
When adding new configuration lines, make sure that any unneeded entries for that daemon are commented out in hosts.allow. |
13.5. Kerberos
Kerberos is a network authentication protocol which was originally created by the Massachusetts Institute of Technology (MIT) as a way to securely provide authentication across a potentially hostile network. The Kerberos protocol uses strong cryptography so that both a client and server can prove their identity without sending any unencrypted secrets over the network. Kerberos can be described as an identity-verifying proxy system and as a trusted third-party authentication system. After a user authenticates with Kerberos, their communications can be encrypted to assure privacy and data integrity.
The only function of Kerberos is to provide the secure authentication of users and servers on the network. It does not provide authorization or auditing functions. It is recommended that Kerberos be used with other security methods which provide authorization and audit services.
The current version of the protocol is version 5, described in RFC 4120. Several free implementations of this protocol are available, covering a wide range of operating systems. MIT continues to develop their Kerberos package. It is commonly used in the US as a cryptography product, and has historically been subject to US export regulations. In FreeBSD, MITKerberos is available as the security/krb5 package or port. The Heimdal Kerberos implementation was explicitly developed outside of the US to avoid export regulations. The Heimdal Kerberos distribution is included in the base FreeBSD installation, and another distribution with more configurable options is available as security/heimdal in the Ports Collection.
In Kerberos users and services are identified as "principals" which are contained within an administrative grouping, called a "realm". A typical user principal would be of the form user@REALM
(realms are traditionally uppercase).
This section provides a guide on how to set up Kerberos using the Heimdal distribution included in FreeBSD.
For purposes of demonstrating a Kerberos installation, the name spaces will be as follows:
The DNS domain (zone) will be
example.org
.The Kerberos realm will be
EXAMPLE.ORG
.
Use real domain names when setting up Kerberos, even if it will run internally. This avoids DNS problems and assures inter-operation with other Kerberos realms. |
13.5.1. 設定 Heimdal KDC
The Key Distribution Center (KDC) is the centralized authentication service that Kerberos provides, the "trusted third party" of the system. It is the computer that issues Kerberos tickets, which are used for clients to authenticate to servers. Because the KDC is considered trusted by all other computers in the Kerberos realm, it has heightened security concerns. Direct access to the KDC should be limited.
While running a KDC requires few computing resources, a dedicated machine acting only as a KDC is recommended for security reasons.
To begin setting up a KDC, add these lines to /etc/rc.conf:
kdc_enable="YES" kadmind_enable="YES"
Next, edit /etc/krb5.conf as follows:
[libdefaults] default_realm = EXAMPLE.ORG [realms] EXAMPLE.ORG = { kdc = kerberos.example.org admin_server = kerberos.example.org } [domain_realm] .example.org = EXAMPLE.ORG
In this example, the KDC will use the fully-qualified hostname kerberos.example.org
. The hostname of the KDC must be resolvable in the DNS.
Kerberos can also use the DNS to locate KDCs, instead of a [realms]
section in /etc/krb5.conf. For large organizations that have their own DNS servers, the above example could be trimmed to:
[libdefaults] default_realm = EXAMPLE.ORG [domain_realm] .example.org = EXAMPLE.ORG
With the following lines being included in the example.org
zone file:
_kerberos._udp IN SRV 01 00 88 kerberos.example.org. _kerberos._tcp IN SRV 01 00 88 kerberos.example.org. _kpasswd._udp IN SRV 01 00 464 kerberos.example.org. _kerberos-adm._tcp IN SRV 01 00 749 kerberos.example.org. _kerberos IN TXT EXAMPLE.ORG
In order for clients to be able to find the Kerberos services, they must have either a fully configured /etc/krb5.conf or a minimally configured /etc/krb5.confand a properly configured DNS server. |
Next, create the Kerberos database which contains the keys of all principals (users and hosts) encrypted with a master password. It is not required to remember this password as it will be stored in /var/heimdal/m-key; it would be reasonable to use a 45-character random password for this purpose. To create the master key, run kstash
and enter a password:
# kstash
Master key: xxxxxxxxxxxxxxxxxxxxxxx
Verifying password - Master key: xxxxxxxxxxxxxxxxxxxxxxx
Once the master key has been created, the database should be initialized. The Kerberos administrative tool kadmin(8) can be used on the KDC in a mode that operates directly on the database, without using the kadmind(8) network service, as kadmin -l
. This resolves the chicken-and-egg problem of trying to connect to the database before it is created. At the kadmin
prompt, use init
to create the realm’s initial database:
# kadmin -l
kadmin> init EXAMPLE.ORG
Realm max ticket life [unlimited]:
Lastly, while still in kadmin
, create the first principal using add
. Stick to the default options for the principal for now, as these can be changed later with modify
. Type ?
at the prompt to see the available options.
kadmin> add tillman
Max ticket life [unlimited]:
Max renewable life [unlimited]:
Attributes []:
Password: xxxxxxxx
Verifying password - Password: xxxxxxxx
Next, start the KDC services by running service kdc start
and service kadmind start
. While there will not be any kerberized daemons running at this point, it is possible to confirm that the KDC is functioning by obtaining a ticket for the principal that was just created:
% kinit tillman
tillman@EXAMPLE.ORG's Password:
Confirm that a ticket was successfully obtained using klist
:
% klist
Credentials cache: FILE:/tmp/krb5cc_1001
Principal: tillman@EXAMPLE.ORG
Issued Expires Principal
Aug 27 15:37:58 2013 Aug 28 01:37:58 2013 krbtgt/EXAMPLE.ORG@EXAMPLE.ORG
The temporary ticket can be destroyed when the test is finished:
% kdestroy
13.5.2. 設定伺服器使用 Kerberos
The first step in configuring a server to use Kerberos authentication is to ensure that it has the correct configuration in /etc/krb5.conf. The version from the KDC can be used as-is, or it can be regenerated on the new system.
Next, create /etc/krb5.keytab on the server. This is the main part of "Kerberizing" a service — it corresponds to generating a secret shared between the service and the KDC. The secret is a cryptographic key, stored in a "keytab". The keytab contains the server’s host key, which allows it and the KDC to verify each others' identity. It must be transmitted to the server in a secure fashion, as the security of the server can be broken if the key is made public. Typically, the keytab is generated on an administrator’s trusted machine using kadmin
, then securely transferred to the server, e.g., with scp(1); it can also be created directly on the server if that is consistent with the desired security policy. It is very important that the keytab is transmitted to the server in a secure fashion: if the key is known by some other party, that party can impersonate any user to the server! Using kadmin
on the server directly is convenient, because the entry for the host principal in the KDC database is also created using kadmin
.
Of course, kadmin
is a kerberized service; a Kerberos ticket is needed to authenticate to the network service, but to ensure that the user running kadmin
is actually present (and their session has not been hijacked), kadmin
will prompt for the password to get a fresh ticket. The principal authenticating to the kadmin service must be permitted to use the kadmin
interface, as specified in kadmind.acl. See the section titled "Remote administration" in info heimdal
for details on designing access control lists. Instead of enabling remote kadmin
access, the administrator could securely connect to the KDC via the local console or ssh(1), and perform administration locally using kadmin -l
.
After installing /etc/krb5.conf, use add --random-key
in kadmin
. This adds the server’s host principal to the database, but does not extract a copy of the host principal key to a keytab. To generate the keytab, use ext
to extract the server’s host principal key to its own keytab:
# kadmin
kadmin> add --random-key host/myserver.example.org
Max ticket life [unlimited]:
Max renewable life [unlimited]:
Principal expiration time [never]:
Password expiration time [never]:
Attributes []:
kadmin> ext_keytab host/myserver.example.org
kadmin> exit
Note that ext_keytab
stores the extracted key in /etc/krb5.keytab by default. This is good when being run on the server being kerberized, but the --keytab path/to/file
argument should be used when the keytab is being extracted elsewhere:
# kadmin
kadmin> ext_keytab --keytab=/tmp/example.keytab host/myserver.example.org
kadmin> exit
The keytab can then be securely copied to the server using scp(1) or a removable media. Be sure to specify a non-default keytab name to avoid inserting unneeded keys into the system’s keytab.
At this point, the server can read encrypted messages from the KDC using its shared key, stored in krb5.keytab. It is now ready for the Kerberos-using services to be enabled. One of the most common such services is sshd(8), which supports Kerberos via the GSS-API. In /etc/ssh/sshd_config, add the line:
GSSAPIAuthentication yes
做完了這個變更之後,必須重新啟動 sshd(8) 來使新的設定值生效:service sshd restart
。
13.5.3. 設定客戶端使用 Kerberos
As it was for the server, the client requires configuration in /etc/krb5.conf. Copy the file in place (securely) or re-enter it as needed.
Test the client by using kinit
, klist
, and kdestroy
from the client to obtain, show, and then delete a ticket for an existing principal. Kerberos applications should also be able to connect to Kerberos enabled servers. If that does not work but obtaining a ticket does, the problem is likely with the server and not with the client or the KDC. In the case of kerberized ssh(1), GSS-API is disabled by default, so test using ssh -o GSSAPIAuthentication=yes hostname
.
When testing a Kerberized application, try using a packet sniffer such as tcpdump
to confirm that no sensitive information is sent in the clear.
Various Kerberos client applications are available. With the advent of a bridge so that applications using SASL for authentication can use GSS-API mechanisms as well, large classes of client applications can use Kerberos for authentication, from Jabber clients to IMAP clients.
Users within a realm typically have their Kerberos principal mapped to a local user account. Occasionally, one needs to grant access to a local user account to someone who does not have a matching Kerberos principal. For example, tillman@EXAMPLE.ORG
may need access to the local user account webdevelopers
. Other principals may also need access to that local account.
The .k5login and .k5users files, placed in a user’s home directory, can be used to solve this problem. For example, if the following .k5login is placed in the home directory of webdevelopers
, both principals listed will have access to that account without requiring a shared password:
tillman@example.org jdoe@example.org
Refer to ksu(1) for more information about .k5users.
13.5.4. 與 MIT 的差異
The major difference between the MIT and Heimdal implementations is that kadmin
has a different, but equivalent, set of commands and uses a different protocol. If the KDC is MIT, the Heimdal version of kadmin
cannot be used to administer the KDC remotely, and vice versa.
Client applications may also use slightly different command line options to accomplish the same tasks. Following the instructions at http://web.mit.edu/Kerberos/www/ is recommended. Be careful of path issues: the MIT port installs into /usr/local/ by default, and the FreeBSD system applications run instead of the MIT versions if PATH
lists the system directories first.
When using MIT Kerberos as a KDC on FreeBSD, the following edits should also be made to rc.conf:
kerberos5_server="/usr/local/sbin/krb5kdc" kadmind5_server="/usr/local/sbin/kadmind" kerberos5_server_flags="" kerberos5_server_enable="YES" kadmind5_server_enable="YES"
13.5.5. Kerberos 提示、技巧與疑難排解
When configuring and troubleshooting Kerberos, keep the following points in mind:
When using either Heimdal or MITKerberos from ports, ensure that the
PATH
lists the port’s versions of the client applications before the system versions.If all the computers in the realm do not have synchronized time settings, authentication may fail. NTP 時間校對 describes how to synchronize clocks using NTP.
If the hostname is changed, the
host/
principal must be changed and the keytab updated. This also applies to special keytab entries like theHTTP/
principal used for Apache’s www/mod_auth_kerb.All hosts in the realm must be both forward and reverse resolvable in DNS or, at a minimum, exist in /etc/hosts. CNAMEs will work, but the A and PTR records must be correct and in place. The error message for unresolvable hosts is not intuitive:
Kerberos5 refuses authentication because Read req failed: Key table entry not found
.Some operating systems that act as clients to the KDC do not set the permissions for
ksu
to be setuidroot
. This means thatksu
does not work. This is a permissions problem, not a KDC error.With MITKerberos, to allow a principal to have a ticket life longer than the default lifetime of ten hours, use
modify_principal
at the kadmin(8) prompt to change themaxlife
of both the principal in question and thekrbtgt
principal. The principal can then usekinit -l
to request a ticket with a longer lifetime.When running a packet sniffer on the KDC to aid in troubleshooting while running
kinit
from a workstation, the Ticket Granting Ticket (TGT) is sent immediately, even before the password is typed. This is because the Kerberos server freely transmits a TGT to any unauthorized request. However, every TGT is encrypted in a key derived from the user’s password. When a user types their password, it is not sent to the KDC, it is instead used to decrypt the TGT thatkinit
already obtained. If the decryption process results in a valid ticket with a valid time stamp, the user has valid Kerberos credentials. These credentials include a session key for establishing secure communications with the Kerberos server in the future, as well as the actual TGT, which is encrypted with the Kerberos server’s own key. This second layer of encryption allows the Kerberos server to verify the authenticity of each TGT.Host principals can have a longer ticket lifetime. If the user principal has a lifetime of a week but the host being connected to has a lifetime of nine hours, the user cache will have an expired host principal and the ticket cache will not work as expected.
When setting up krb5.dict to prevent specific bad passwords from being used as described in kadmind(8), remember that it only applies to principals that have a password policy assigned to them. The format used in krb5.dict is one string per line. Creating a symbolic link to /usr/shared/dict/words might be useful.
13.5.6. 減輕 Kerberos 的限制
Since Kerberos is an all or nothing approach, every service enabled on the network must either be modified to work with Kerberos or be otherwise secured against network attacks. This is to prevent user credentials from being stolen and re-used. An example is when Kerberos is enabled on all remote shells but the non-Kerberized POP3 mail server sends passwords in plain text.
The KDC is a single point of failure. By design, the KDC must be as secure as its master password database. The KDC should have absolutely no other services running on it and should be physically secure. The danger is high because Kerberos stores all passwords encrypted with the same master key which is stored as a file on the KDC.
A compromised master key is not quite as bad as one might fear. The master key is only used to encrypt the Kerberos database and as a seed for the random number generator. As long as access to the KDC is secure, an attacker cannot do much with the master key.
If the KDC is unavailable, network services are unusable as authentication cannot be performed. This can be alleviated with a single master KDC and one or more slaves, and with careful implementation of secondary or fall-back authentication using PAM.
Kerberos allows users, hosts and services to authenticate between themselves. It does not have a mechanism to authenticate the KDC to the users, hosts, or services. This means that a trojanned kinit
could record all user names and passwords. File system integrity checking tools like security/tripwire can alleviate this.
13.6. OpenSSL
OpenSSL is an open source implementation of the SSL and TLS protocols. It provides an encryption transport layer on top of the normal communications layer, allowing it to be intertwined with many network applications and services.
The version of OpenSSL included in FreeBSD supports the Secure Sockets Layer 3.0 (SSLv3) and Transport Layer Security 1.0/1.1/1.2 (TLSv1/TLSv1.1/TLSv1.2) network security protocols and can be used as a general cryptographic library. In FreeBSD 12.0-RELEASE and above, OpenSSL also supports Transport Layer Security 1.3 (TLSv1.3).
OpenSSL is often used to encrypt authentication of mail clients and to secure web based transactions such as credit card payments. Some ports, such as www/apache24 and databases/postgresql11-server, include a compile option for building with OpenSSL. If selected, the port will add support using OpenSSL from the base system. To instead have the port compile against OpenSSL from the security/openssl port, add the following to /etc/make.conf:
DEFAULT_VERSIONS+= ssl=openssl
Another common use of OpenSSL is to provide certificates for use with software applications. Certificates can be used to verify the credentials of a company or individual. If a certificate has not been signed by an external Certificate Authority (CA), such as http://www.verisign.com, the application that uses the certificate will produce a warning. There is a cost associated with obtaining a signed certificate and using a signed certificate is not mandatory as certificates can be self-signed. However, using an external authority will prevent warnings and can put users at ease.
This section demonstrates how to create and use certificates on a FreeBSD system. Refer to 設定 LDAP 伺服器 for an example of how to create a CA for signing one’s own certificates.
For more information about SSL, read the free OpenSSL Cookbook.
13.6.1. 產生憑証
To generate a certificate that will be signed by an external CA, issue the following command and input the information requested at the prompts. This input information will be written to the certificate. At the Common Name
prompt, input the fully qualified name for the system that will use the certificate. If this name does not match the server, the application verifying the certificate will issue a warning to the user, rendering the verification provided by the certificate as useless.
# openssl req -new -nodes -out req.pem -keyout cert.key -sha256 -newkey rsa:2048
Generating a 2048 bit RSA private key
..................+++
.............................................................+++
writing new private key to 'cert.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:PA
Locality Name (eg, city) []:Pittsburgh
Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Company
Organizational Unit Name (eg, section) []:Systems Administrator
Common Name (eg, YOUR name) []:localhost.example.org
Email Address []:trhodes@FreeBSD.org
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:Another Name
Other options, such as the expire time and alternate encryption algorithms, are available when creating a certificate. A complete list of options is described in openssl(1).
This command will create two files in the current directory. The certificate request, req.pem, can be sent to a CA who will validate the entered credentials, sign the request, and return the signed certificate. The second file, cert.key, is the private key for the certificate and should be stored in a secure location. If this falls in the hands of others, it can be used to impersonate the user or the server.
Alternately, if a signature from a CA is not required, a self-signed certificate can be created. First, generate the RSA key:
# openssl genrsa -rand -genkey -out cert.key 2048
0 semi-random bytes loaded
Generating RSA private key, 2048 bit long modulus
.............................................+++
.................................................................................................................+++
e is 65537 (0x10001)
Use this key to create a self-signed certificate. Follow the usual prompts for creating a certificate:
# openssl req -new -x509 -days 365 -key cert.key -out cert.crt -sha256
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:PA
Locality Name (eg, city) []:Pittsburgh
Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Company
Organizational Unit Name (eg, section) []:Systems Administrator
Common Name (e.g. server FQDN or YOUR name) []:localhost.example.org
Email Address []:trhodes@FreeBSD.org
This will create two new files in the current directory: a private key file cert.key, and the certificate itself, cert.crt. These should be placed in a directory, preferably under /etc/ssl/, which is readable only by root
. Permissions of 0700
are appropriate for these files and can be set using chmod
.
13.6.2. 使用憑證
One use for a certificate is to encrypt connections to the Sendmail mail server in order to prevent the use of clear text authentication.
Some mail clients will display an error if the user has not installed a local copy of the certificate. Refer to the documentation included with the software for more information on certificate installation. |
In FreeBSD 10.0-RELEASE and above, it is possible to create a self-signed certificate for Sendmail automatically. To enable this, add the following lines to /etc/rc.conf:
sendmail_enable="YES" sendmail_cert_create="YES" sendmail_cert_cn="localhost.example.org"
This will automatically create a self-signed certificate, /etc/mail/certs/host.cert, a signing key, /etc/mail/certs/host.key, and a CA certificate, /etc/mail/certs/cacert.pem. The certificate will use the Common Name
specified in sendmail_cert_cn
. After saving the edits, restart Sendmail:
# service sendmail restart
If all went well, there will be no error messages in /var/log/maillog. For a simple test, connect to the mail server’s listening port using telnet
:
# telnet example.com 25
Trying 192.0.34.166...
Connected to example.com.
Escape character is '^]'.
220 example.com ESMTP Sendmail 8.14.7/8.14.7; Fri, 18 Apr 2014 11:50:32 -0400 (EDT)
ehlo example.com
250-example.com Hello example.com [192.0.34.166], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-8BITMIME
250-SIZE
250-DSN
250-ETRN
250-AUTH LOGIN PLAIN
250-STARTTLS
250-DELIVERBY
250 HELP
quit
221 2.0.0 example.com closing connection
Connection closed by foreign host.
If the STARTTLS
line appears in the output, everything is working correctly.
13.7. VPN over IPsec
Internet Protocol Security (IPsec) is a set of protocols which sit on top of the Internet Protocol (IP) layer. It allows two or more hosts to communicate in a secure manner by authenticating and encrypting each IP packet of a communication session. The FreeBSD IPsec network stack is based on the http://www.kame.net/ implementation and supports both IPv4 and IPv6 sessions.
IPsec is comprised of the following sub-protocols:
Encapsulated Security Payload (ESP): this protocol protects the IP packet data from third party interference by encrypting the contents using symmetric cryptography algorithms such as Blowfish and 3DES.
Authentication Header (AH): this protocol protects the IP packet header from third party interference and spoofing by computing a cryptographic checksum and hashing the IP packet header fields with a secure hashing function. This is then followed by an additional header that contains the hash, to allow the information in the packet to be authenticated.
IP Payload Compression Protocol (IPComp): this protocol tries to increase communication performance by compressing the IP payload in order to reduce the amount of data sent.
These protocols can either be used together or separately, depending on the environment.
IPsec supports two modes of operation. The first mode, Transport Mode, protects communications between two hosts. The second mode, Tunnel Mode, is used to build virtual tunnels, commonly known as Virtual Private Networks (VPNs). Consult ipsec(4) for detailed information on the IPsec subsystem in FreeBSD.
在 FreeBSD 11 與之後的版本預設會開啟 IPsec 功能,先前版本的 FreeBSD 可在自訂核心設定檔中加入以下選項然後依 設定 FreeBSD 核心 的指示來重新編譯核心:
options IPSEC #IP security
device crypto
If IPsec debugging support is desired, the following kernel option should also be added:
options IPSEC_DEBUG debug for IP security
This rest of this chapter demonstrates the process of setting up an IPsecVPN between a home network and a corporate network. In the example scenario:
Both sites are connected to the Internet through a gateway that is running FreeBSD.
The gateway on each network has at least one external IP address. In this example, the corporate LAN’s external IP address is
172.16.5.4
and the home LAN’s external IP address is192.168.1.12
.The internal addresses of the two networks can be either public or private IP addresses. However, the address space must not collide. For example, both networks cannot use
192.168.1.x
. In this example, the corporate LAN’s internal IP address is10.246.38.1
and the home LAN’s internal IP address is10.0.0.5
.
13.7.1. 在 FreeBSD 上設定 VPN
To begin, security/ipsec-tools must be installed from the Ports Collection. This software provides a number of applications which support the configuration.
The next requirement is to create two gif(4) pseudo-devices which will be used to tunnel packets and allow both networks to communicate properly. As root
, run the following commands, replacing internal and external with the real IP addresses of the internal and external interfaces of the two gateways:
# ifconfig gif0 create
# ifconfig gif0 internal1 internal2
# ifconfig gif0 tunnel external1 external2
Verify the setup on each gateway, using ifconfig
. Here is the output from Gateway 1:
gif0: flags=8051 mtu 1280 tunnel inet 172.16.5.4 --> 192.168.1.12 inet6 fe80::2e0:81ff:fe02:5881%gif0 prefixlen 64 scopeid 0x6 inet 10.246.38.1 --> 10.0.0.5 netmask 0xffffff00
Here is the output from Gateway 2:
gif0: flags=8051 mtu 1280 tunnel inet 192.168.1.12 --> 172.16.5.4 inet 10.0.0.5 --> 10.246.38.1 netmask 0xffffff00 inet6 fe80::250:bfff:fe3a:c1f%gif0 prefixlen 64 scopeid 0x4
Once complete, both internal IP addresses should be reachable using ping(8):
priv-net# ping 10.0.0.5 PING 10.0.0.5 (10.0.0.5): 56 data bytes 64 bytes from 10.0.0.5: icmp_seq=0 ttl=64 time=42.786 ms 64 bytes from 10.0.0.5: icmp_seq=1 ttl=64 time=19.255 ms 64 bytes from 10.0.0.5: icmp_seq=2 ttl=64 time=20.440 ms 64 bytes from 10.0.0.5: icmp_seq=3 ttl=64 time=21.036 ms --- 10.0.0.5 ping statistics --- 4 packets transmitted, 4 packets received, 0% packet loss round-trip min/avg/max/stddev = 19.255/25.879/42.786/9.782 ms corp-net# ping 10.246.38.1 PING 10.246.38.1 (10.246.38.1): 56 data bytes 64 bytes from 10.246.38.1: icmp_seq=0 ttl=64 time=28.106 ms 64 bytes from 10.246.38.1: icmp_seq=1 ttl=64 time=42.917 ms 64 bytes from 10.246.38.1: icmp_seq=2 ttl=64 time=127.525 ms 64 bytes from 10.246.38.1: icmp_seq=3 ttl=64 time=119.896 ms 64 bytes from 10.246.38.1: icmp_seq=4 ttl=64 time=154.524 ms --- 10.246.38.1 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 28.106/94.594/154.524/49.814 ms
As expected, both sides have the ability to send and receive ICMP packets from the privately configured addresses. Next, both gateways must be told how to route packets in order to correctly send traffic from either network. The following commands will achieve this goal:
corp-net# route add 10.0.0.0 10.0.0.5 255.255.255.0
corp-net# route add net 10.0.0.0: gateway 10.0.0.5
priv-net# route add 10.246.38.0 10.246.38.1 255.255.255.0
priv-net# route add host 10.246.38.0: gateway 10.246.38.1
At this point, internal machines should be reachable from each gateway as well as from machines behind the gateways. Again, use ping(8) to confirm:
corp-net# ping 10.0.0.8 PING 10.0.0.8 (10.0.0.8): 56 data bytes 64 bytes from 10.0.0.8: icmp_seq=0 ttl=63 time=92.391 ms 64 bytes from 10.0.0.8: icmp_seq=1 ttl=63 time=21.870 ms 64 bytes from 10.0.0.8: icmp_seq=2 ttl=63 time=198.022 ms 64 bytes from 10.0.0.8: icmp_seq=3 ttl=63 time=22.241 ms 64 bytes from 10.0.0.8: icmp_seq=4 ttl=63 time=174.705 ms --- 10.0.0.8 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 21.870/101.846/198.022/74.001 ms priv-net# ping 10.246.38.107 PING 10.246.38.1 (10.246.38.107): 56 data bytes 64 bytes from 10.246.38.107: icmp_seq=0 ttl=64 time=53.491 ms 64 bytes from 10.246.38.107: icmp_seq=1 ttl=64 time=23.395 ms 64 bytes from 10.246.38.107: icmp_seq=2 ttl=64 time=23.865 ms 64 bytes from 10.246.38.107: icmp_seq=3 ttl=64 time=21.145 ms 64 bytes from 10.246.38.107: icmp_seq=4 ttl=64 time=36.708 ms --- 10.246.38.107 ping statistics --- 5 packets transmitted, 5 packets received, 0% packet loss round-trip min/avg/max/stddev = 21.145/31.721/53.491/12.179 ms
Setting up the tunnels is the easy part. Configuring a secure link is a more in depth process. The following configuration uses pre-shared (PSK) RSA keys. Other than the IP addresses, the /usr/local/etc/racoon/racoon.conf on both gateways will be identical and look similar to:
path pre_shared_key "/usr/local/etc/racoon/psk.txt"; #location of pre-shared key file log debug; #log verbosity setting: set to 'notify' when testing and debugging is complete padding # options are not to be changed { maximum_length 20; randomize off; strict_check off; exclusive_tail off; } timer # timing options. change as needed { counter 5; interval 20 sec; persend 1; # natt_keepalive 15 sec; phase1 30 sec; phase2 15 sec; } listen # address [port] that racoon will listen on { isakmp 172.16.5.4 [500]; isakmp_natt 172.16.5.4 [4500]; } remote 192.168.1.12 [500] { exchange_mode main,aggressive; doi ipsec_doi; situation identity_only; my_identifier address 172.16.5.4; peers_identifier address 192.168.1.12; lifetime time 8 hour; passive off; proposal_check obey; # nat_traversal off; generate_policy off; proposal { encryption_algorithm blowfish; hash_algorithm md5; authentication_method pre_shared_key; lifetime time 30 sec; dh_group 1; } } sainfo (address 10.246.38.0/24 any address 10.0.0.0/24 any) # address $network/$netmask $type address $network/$netmask $type ( $type being any or esp) { # $network must be the two internal networks you are joining. pfs_group 1; lifetime time 36000 sec; encryption_algorithm blowfish,3des; authentication_algorithm hmac_md5,hmac_sha1; compression_algorithm deflate; }
For descriptions of each available option, refer to the manual page for racoon.conf.
The Security Policy Database (SPD) needs to be configured so that FreeBSD and racoon are able to encrypt and decrypt network traffic between the hosts.
This can be achieved with a shell script, similar to the following, on the corporate gateway. This file will be used during system initialization and should be saved as /usr/local/etc/racoon/setkey.conf.
flush; spdflush; # To the home network spdadd 10.246.38.0/24 10.0.0.0/24 any -P out ipsec esp/tunnel/172.16.5.4-192.168.1.12/use; spdadd 10.0.0.0/24 10.246.38.0/24 any -P in ipsec esp/tunnel/192.168.1.12-172.16.5.4/use;
Once in place, racoon may be started on both gateways using the following command:
# /usr/local/sbin/racoon -F -f /usr/local/etc/racoon/racoon.conf -l /var/log/racoon.log
The output should be similar to the following:
corp-net# /usr/local/sbin/racoon -F -f /usr/local/etc/racoon/racoon.conf Foreground mode. 2006-01-30 01:35:47: INFO: begin Identity Protection mode. 2006-01-30 01:35:48: INFO: received Vendor ID: KAME/racoon 2006-01-30 01:35:55: INFO: received Vendor ID: KAME/racoon 2006-01-30 01:36:04: INFO: ISAKMP-SA established 172.16.5.4[500]-192.168.1.12[500] spi:623b9b3bd2492452:7deab82d54ff704a 2006-01-30 01:36:05: INFO: initiate new phase 2 negotiation: 172.16.5.4[0]192.168.1.12[0] 2006-01-30 01:36:09: INFO: IPsec-SA established: ESP/Tunnel 192.168.1.12[0]->172.16.5.4[0] spi=28496098(0x1b2d0e2) 2006-01-30 01:36:09: INFO: IPsec-SA established: ESP/Tunnel 172.16.5.4[0]->192.168.1.12[0] spi=47784998(0x2d92426) 2006-01-30 01:36:13: INFO: respond new phase 2 negotiation: 172.16.5.4[0]192.168.1.12[0] 2006-01-30 01:36:18: INFO: IPsec-SA established: ESP/Tunnel 192.168.1.12[0]->172.16.5.4[0] spi=124397467(0x76a279b) 2006-01-30 01:36:18: INFO: IPsec-SA established: ESP/Tunnel 172.16.5.4[0]->192.168.1.12[0] spi=175852902(0xa7b4d66)
To ensure the tunnel is working properly, switch to another console and use tcpdump(1) to view network traffic using the following command. Replace em0
with the network interface card as required:
# tcpdump -i em0 host 172.16.5.4 and dst 192.168.1.12
Data similar to the following should appear on the console. If not, there is an issue and debugging the returned data will be required.
01:47:32.021683 IP corporatenetwork.com > 192.168.1.12.privatenetwork.com: ESP(spi=0x02acbf9f,seq=0xa) 01:47:33.022442 IP corporatenetwork.com > 192.168.1.12.privatenetwork.com: ESP(spi=0x02acbf9f,seq=0xb) 01:47:34.024218 IP corporatenetwork.com > 192.168.1.12.privatenetwork.com: ESP(spi=0x02acbf9f,seq=0xc)
At this point, both networks should be available and seem to be part of the same network. Most likely both networks are protected by a firewall. To allow traffic to flow between them, rules need to be added to pass packets. For the ipfw(8) firewall, add the following lines to the firewall configuration file:
ipfw add 00201 allow log esp from any to any ipfw add 00202 allow log ah from any to any ipfw add 00203 allow log ipencap from any to any ipfw add 00204 allow log udp from any 500 to any
The rule numbers may need to be altered depending on the current host configuration. |
pass in quick proto esp from any to any pass in quick proto ah from any to any pass in quick proto ipencap from any to any pass in quick proto udp from any port = 500 to any port = 500 pass in quick on gif0 from any to any pass out quick proto esp from any to any pass out quick proto ah from any to any pass out quick proto ipencap from any to any pass out quick proto udp from any port = 500 to any port = 500 pass out quick on gif0 from any to any
Finally, to allow the machine to start support for the VPN during system initialization, add the following lines to /etc/rc.conf:
ipsec_enable="YES" ipsec_program="/usr/local/sbin/setkey" ipsec_file="/usr/local/etc/racoon/setkey.conf" # allows setting up spd policies on boot racoon_enable="yes"
13.8. OpenSSH
OpenSSH 是一套網路連線工具,可安全的存取遠端的主機,此外,透過 SSH 連線可以建立 TCP/IP 連線通道或安全的轉送 TCP/IP 的封包。OpenSSH 會對所有傳輸的資料做加密,可有效的避免竊聽 (Eavesdropping)、或連線劫持 (Connection hijacking) 與其他網路層的攻擊。
OpenSSH 由 OpenBSD 專案所維護且在 FreeBSD 預設會安裝,它可同時相容 SSH 版本 1 與 2 通訊協定。
當以未加密的方式在網路上傳送資料時,任何在客戶端與伺服器之間的網路竊聽程式 (Network sniffer) 皆可竊取使用者/密碼資訊或者在連線階段傳送的資料,OpenSSH 提供了數種認証與加密方式來避免這種事情發生。更多有關 OpenSSH 的資訊可於 http://www.openssh.com/ 取得。
本節會簡單介紹如何使用內建的客戶端工具安全的存取其他系統及安全的傳輸檔案到 FreeBSD 系統,然後會說明如何設定在 FreeBSD 系統上的 SSH 伺服器。更多的資訊可於本章節所提及的操作手冊 (Man page) 取得。
13.8.1. 使用 SSH 客戶端工具
要登入一台 SSH 伺服器,可使用 ssh
然後指定在伺服器上存在的使用者名稱與 IP 位址或伺服器的主機名稱。若這是第一次連線到指定的伺服器,會提示該使用者伺服器的指紋做第一次檢驗:
# ssh user@example.com
The authenticity of host 'example.com (10.0.0.1)' can't be established.
ECDSA key fingerprint is 25:cc:73:b5:b3:96:75:3d:56:19:49:d2:5c:1f:91:3b.
Are you sure you want to continue connecting (yes/no)? yes
Permanently added 'example.com' (ECDSA) to the list of known hosts.
Password for user@example.com: user_password
SSH 會在客戶端連線時利用金鑰指紋 (Key fingerprint) 系統來驗證伺服器的真偽,當使用者在第一次連線時輸入 yes
接受了這個金鑰指紋,便會將該金鑰的複本儲存到使用者家目錄的 .ssh/known_hosts,未來嘗試登入時便會以這個存好的金鑰來驗證,若伺服器的金鑰與儲存的金鑰不同將會顯示警告訊息。若出現這個警告時,使用者應在繼續連線之前檢查金鑰變動的原因。
最近版本的 OpenSSH 預設只會接受 SSHv2 的連線。客戶端預設會盡可能使用版本 2 的通訊協定,若伺服器不支援版本 2 的通訊協定便會向下相容版本 1 的協定。要強制 ssh
只能使用指定的通訊協定,可使用 -1
或 -2
,其他的選項在 ssh(1) 中有說明。
使用 scp(1) 可從遠端主機安全的複製一個檔案,以下範例會複製在遠端主機的 COPYRIGHT 到本地主機的目前目錄:
# scp user@example.com:/COPYRIGHT COPYRIGHT
Password for user@example.com: *******
COPYRIGHT 100% |*****************************| 4735
00:00
#
由於這個主機的指紋已驗證過,在提示用者輸入密碼之前伺服器的金鑰已自動檢查。
傳給 scp
的參數與傳給 cp
的參數相似。第一個參數是要複製的檔案,第二個參數是目地,由於檔案是透過網路取得,檔案參數需要使用 user@host:<path_to_remote_file>
格式。注意,在 scp
要遞迴複製目錄是使用 -r
,如同 cp
使用 -R
。
要開啟可互動的連線來複製檔案可使用 sftp
,請參考 sftp(1) 來取得在 sftp
連線時可用的指令清單。
13.8.1.1. 以金鑰為基礎的認證
除了使用密碼之外,客戶端可以設定成使用金鑰來連線到遠端的主機。要產生 RSA 認証金鑰可使用 ssh-keygen
。要產生成對的公鑰與私鑰,可指定金鑰的類型並依提示操作。建議使用容易記住但較難猜出的密碼來保護這個金鑰。
% ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa):
Enter passphrase (empty for no passphrase): (1)
Enter same passphrase again: (2)
Your identification has been saved in /home/user/.ssh/id_rsa.
Your public key has been saved in /home/user/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:54Xm9Uvtv6H4NOo6yjP/YCfODryvUU7yWHzMqeXwhq8 user@host.example.com
The key's randomart image is:
+---[RSA 2048]----+
| |
| |
| |
| . o.. |
| .S*+*o |
| . O=Oo . . |
| = Oo= oo..|
| .oB.* +.oo.|
| =OE**.o..=|
+----[SHA256]-----+
1 | 在此輸入密碼,密碼不可含有空白或符號。 |
2 | 再輸入一次密碼驗證。 |
私鑰會儲存於 ~/.ssh/id_rsa 而公鑰會儲存於 ~/.ssh/id_rsa.pub。公鑰必須複製到遠端主機的~/.ssh/authorized_keys 來讓以金鑰為基礎的認証可以運作。
許多使用者認為金鑰的設計是安全的並在產生金鑰時未使用密碼,這樣的行為其實很危險。管理者可以手動查看私鑰來檢查金鑰對是否受密碼保護,如果私鑰檔案中包含 |
不同版本 OpenSSH 的選項與檔案會不同,要避免發生問題請參考 ssh-keygen(1)。
若使用了密碼,在每次連線到伺服器時都會提示使用者輸入密碼。要將 SSH 金鑰載入到記憶體並讓每次連線時不必再輸入密碼,可使用 ssh-agent(1) 與 ssh-add(1)。
認証可用 ssh-agent
來管理,只要將私鑰載入,ssh-agent
可用在執行其他應用程式,如 Shell 或視窗管理程式。
要在 Shell 使用 ssh-agent
,使用 Shell 做為參數來啟動 ssh-agent
。執行 ssh-add
來加入識別碼,然後輸入私鑰的密碼。使用者將可使用 ssh
連線到任何有安裝對應公鑰的主機,例如:
% ssh-agent csh
% ssh-add
Enter passphrase for key '/usr/home/user/.ssh/id_rsa': (1)
Identity added: /usr/home/user/.ssh/id_rsa (/usr/home/user/.ssh/id_rsa)
%
1 | 輸入金鑰的密碼。 |
要在 Xorg 使用 ssh-agent
可在 ~/.xinitrc 加入一個設定項目,這可讓 ssh-agent
對所有在 Xorg 中執行的程式提供服務。~/.xinitrc 範例如下:
exec ssh-agent startxfce4
這會在每次啟動 Xorg 時,反過來先執行 ssh-agent
再由執行 XFCE,一但 Xorg 被重新啟動,要讓所有變更生效需執行 ssh-add
來載入所有的 SSH 金鑰。
13.8.1.2. SSH 通道
OpenSSH 可以建立一個通道 (Tunnel) 來封裝其他通訊協定到一個加密的連線。
以下指令會告訴 ssh
建立一個供 telnet 使用的通道:
% ssh -2 -N -f -L 5023:localhost:23 user@foo.example.com
%
這個例子使用了以下選項:
-2
強制
ssh
使用版本 2 的通訊協定連線到伺服器。-N
代表不需下指令、只建立通道。若省略這個選項
ssh
會初始化一個正常的連線。-f
強制
ssh
在背景執行。-L
代表這是一個本地通道,使用 localport:remotehost:remoteport 格式。
user@foo.example.com
在指定的遠端 SSH 伺服器要使用的登入名稱。
SSH 通道會建立一個傾聽 localhost
指定 localport
的 Socket ,然後會透過 SSH 連線轉送任何在 localport
接收的連線。以這個例子來說在客戶端的 Port 5023
會被轉送到遠端主機的 Port 23
,由於 Port 23 是由 telnet 使用,所以這會透過 SSH 通道建立一個加密的 telnet 連線。
這個方法可用來包裝許多不安全的 TCP 通訊協定,例如 SMTP, POP3 以及 FTP,如下例所示。
% ssh -2 -N -f -L 5025:localhost:25 user@mailserver.example.com
user@mailserver.example.com's password: *****
% telnet localhost 5025
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 mailserver.example.com ESMTP
這可配合 ssh-keygen
與另一個使用者帳號與來建立一個更無縫的 SSH 通道環境,可使用金鑰來代替手動輸入密碼,然後該通道便可以另一個使用者執行。
在這個例子中有一個 SSH 伺服器會接受來自外部的連線,在同個網段下有一個郵件伺服器執行 POP3 伺服器。要使用較安全的方式檢查有沒有新郵件可建立一個 SSH 連線到 SSH 伺服器然後透過通道連線到郵件伺服器:
% ssh -2 -N -f -L 2110:mail.example.com:110 user@ssh-server.example.com
user@ssh-server.example.com's password: ******
一但通道啟動並執行後,指定郵件客戶端將 POP3 請求傳送到 localhost
的 Port 2110,這個連線將會被安全的透過通道轉送到 mail.example.com
。
有些防火牆會同時過濾傳入與傳出的連線。例如,防火牆很可能會限制來自遠端主機只能存取 Port 22 與 80 來只讓 SSH 與網頁瀏覽器連線,這會使得 Port 使用 22 或 80 以外的服務無法存取。
這問題的解決方法是建立一個 SSH 連線到在防火牆防護之外主機然後使用該連線的通道連到想要使用的服務:
% ssh -2 -N -f -L 8888:music.example.com:8000 user@unfirewalled-system.example.org
user@unfirewalled-system.example.org's password: *******
在這個例子中,串流 Ogg Vorbis 客戶端現在可以指向 localhost
Port 8888,連線將會被轉送到 music.example.com
於 Port 8000,成功的跳過防火牆。
13.8.2. 開啟 SSH 伺服器
除了提供內建的 SSH 客戶端工具外,還可以設定 FreeBSD 系統為一個 SSH 伺服器,以接受來自其他 SSH 客戶端的連線。
要查看 sshd 是否正在運作,可使用 service(8) 指令:
# service sshd status
若服務未執行,請加入下行到 /etc/rc.conf。
sshd_enable="YES"
這會讓下次系統開機時啟動 OpenSSH 的 Daemon 程式 sshd。若要立即啟動:
# service sshd start
在 FreeBSD 系統第一次啟動 sshd 時便會自動產生系統的主機金鑰且會顯示指紋在 Console 上,這個指紋可供使用者在第一次連線到伺服器時驗證用。
請參考 sshd(8) 可取得在啟動 sshd 時可用選項的清單以及更多完整有關認証、登入程序與各種設定檔的資訊。
現在,sshd 應可供所有在系統上有使用者名稱及密碼的使用者使用。
13.8.3. SSH 伺服器安全性
在 FreeBSD 廣泛使用 sshd 做為遠端管理基礎設施的同時,所有暴露在公有網路上的系統也會時常受到暴力攻擊 (Brute force attack) 與路過攻擊 (Drive by attack)。在本節會介紹一些可用來避免這些攻擊的參數。
使用在 OpenSSH 伺服器設定檔的 AllowUsers
關鍵字限制可以登入到 SSH 伺服器的使用者及來源是一個不錯的方式。例如要只允許來自 192.168.1.32
的 root
登入,可加入下行到 /etc/ssh/sshd_config:
AllowUsers root@192.168.1.32
要允許來自任何地方的 admin
登入,可只列出使用者名稱,不指定 IP 位址:
AllowUsers admin
有多位使用者也應列在同一行,例如:
AllowUsers root@192.168.1.32 admin
在對 /etc/ssh/sshd_config 做完變更後,執行以下指令告訴 sshd 重新載入設定檔:
# service sshd reload
在使用了這個關鍵字時,列出每一位需要登入此主機的使用者很重要,任何未被在該行指定的使用者將無法登入。同時,在 OpenSSH 伺服器設定檔使用的關鍵字是區分大小寫的,若關鍵字未正確的拼寫 (含其大小寫),則將會被忽略,永遠要記得測試對這個檔案所做的更改來確保伺服器有如預期的方式運作。請參考 sshd_config(5) 來檢查拼寫以及可用的關鍵字。 |
此外,使用者可能被強制要透過公鑰與私鑰使用雙重認證 (Two factor authentication)。當需要時,使用者可以透過使用 ssh-keygen(1) 產生一堆金鑰然後將公鑰傳送給管理者,這個金鑰檔會如以上在客戶端章節所述的被放在 authorized_keys。要強制使用者只能使用這個金鑰,可能需要設定以下選項:
AuthenticationMethods publickey
請不要將 /etc/ssh/sshd_config 以及 /etc/ssh/ssh_config 搞混 (注意在第一節檔名有多出個 |
13.9. 存取控制清單
Access Control Lists (ACLs) extend the standard UNIX™ permission model in a POSIX™.1e compatible way. This permits an administrator to take advantage of a more fine-grained permissions model.
The FreeBSD GENERIC kernel provides ACL support for UFS file systems. Users who prefer to compile a custom kernel must include the following option in their custom kernel configuration file:
options UFS_ACL
If this option is not compiled in, a warning message will be displayed when attempting to mount a file system with ACL support. ACLs rely on extended attributes which are natively supported in UFS2.
This chapter describes how to enable ACL support and provides some usage examples.
13.9.1. 開啟 ACL 支援
ACLs are enabled by the mount-time administrative flag, acls
, which may be added to /etc/fstab. The mount-time flag can also be automatically set in a persistent manner using tunefs(8) to modify a superblock ACLs flag in the file system header. In general, it is preferred to use the superblock flag for several reasons:
The superblock flag cannot be changed by a remount using
mount -u
as it requires a completeumount
and freshmount
. This means that ACLs cannot be enabled on the root file system after boot. It also means that ACL support on a file system cannot be changed while the system is in use.Setting the superblock flag causes the file system to always be mounted with ACLs enabled, even if there is not an fstab entry or if the devices re-order. This prevents accidental mounting of the file system without ACL support.
It is desirable to discourage accidental mounting without ACLs enabled because nasty things can happen if ACLs are enabled, then disabled, then re-enabled without flushing the extended attributes. In general, once ACLs are enabled on a file system, they should not be disabled, as the resulting file protections may not be compatible with those intended by the users of the system, and re-enabling ACLs may re-attach the previous ACLs to files that have since had their permissions changed, resulting in unpredictable behavior. |
File systems with ACLs enabled will show a plus (+
) sign in their permission settings:
drwx------ 2 robert robert 512 Dec 27 11:54 private drwxrwx---+ 2 robert robert 512 Dec 23 10:57 directory1 drwxrwx---+ 2 robert robert 512 Dec 22 10:20 directory2 drwxrwx---+ 2 robert robert 512 Dec 27 11:57 directory3 drwxr-xr-x 2 robert robert 512 Nov 10 11:54 public_html
In this example, directory1, directory2, and directory3 are all taking advantage of ACLs, whereas public_html is not.
13.9.2. 使用 ACL
File system ACLs can be viewed using getfacl
. For instance, to view the ACL settings on test:
% getfacl test
#file:test
#owner:1001
#group:1001
user::rw-
group::r--
other::r--
To change the ACL settings on this file, use setfacl
. To remove all of the currently defined ACLs from a file or file system, include -k
. However, the preferred method is to use -b
as it leaves the basic fields required for ACLs to work.
% setfacl -k test
To modify the default ACL entries, use -m
:
% setfacl -m u:trhodes:rwx,group:web:r--,o::--- test
In this example, there were no pre-defined entries, as they were removed by the previous command. This command restores the default options and assigns the options listed. If a user or group is added which does not exist on the system, an Invalid argument
error will be displayed.
Refer to getfacl(1) and setfacl(1) for more information about the options available for these commands.
13.10. 監視第三方安全性問題
In recent years, the security world has made many improvements to how vulnerability assessment is handled. The threat of system intrusion increases as third party utilities are installed and configured for virtually any operating system available today.
Vulnerability assessment is a key factor in security. While FreeBSD releases advisories for the base system, doing so for every third party utility is beyond the FreeBSD Project’s capability. There is a way to mitigate third party vulnerabilities and warn administrators of known security issues. A FreeBSD add on utility known as pkg includes options explicitly for this purpose.
pkg polls a database for security issues. The database is updated and maintained by the FreeBSD Security Team and ports developers.
Please refer to instructions for installing pkg.
Installation provides periodic(8) configuration files for maintaining the pkg audit database, and provides a programmatic method of keeping it updated. This functionality is enabled if daily_status_security_pkgaudit_enable
is set to YES
in periodic.conf(5). Ensure that daily security run emails, which are sent to root
's email account, are being read.
After installation, and to audit third party utilities as part of the Ports Collection at any time, an administrator may choose to update the database and view known vulnerabilities of installed packages by invoking:
# pkg audit -F
pkg displays messages any published vulnerabilities in installed packages:
Affected package: cups-base-1.1.22.0_1 Type of problem: cups-base -- HPGL buffer overflow vulnerability. Reference: <https://www.FreeBSD.org/ports/portaudit/40a3bca2-6809-11d9-a9e7-0001020eed82.html> 1 problem(s) in your installed packages found. You are advised to update or deinstall the affected package(s) immediately.
By pointing a web browser to the displayed URL, an administrator may obtain more information about the vulnerability. This will include the versions affected, by FreeBSD port version, along with other web sites which may contain security advisories.
pkg is a powerful utility and is extremely useful when coupled with ports-mgmt/portmaster.
13.11. FreeBSD 安全報告
Like many producers of quality operating systems, the FreeBSD Project has a security team which is responsible for determining the End-of-Life (EoL) date for each FreeBSD release and to provide security updates for supported releases which have not yet reached their EoL. More information about the FreeBSD security team and the supported releases is available on the FreeBSD security page.
One task of the security team is to respond to reported security vulnerabilities in the FreeBSD operating system. Once a vulnerability is confirmed, the security team verifies the steps necessary to fix the vulnerability and updates the source code with the fix. It then publishes the details as a "Security Advisory". Security advisories are published on the FreeBSD website and mailed to the freebsd-security-notifications, freebsd-security, and freebsd-announce mailing lists.
This section describes the format of a FreeBSD security advisory.
13.11.1. 安全報告的格式
Here is an example of a FreeBSD security advisory:
============================================================================= -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 ============================================================================= FreeBSD-SA-14:04.bind Security Advisory The FreeBSD Project Topic: BIND remote denial of service vulnerability Category: contrib Module: bind Announced: 2014-01-14 Credits: ISC Affects: FreeBSD 8.x and FreeBSD 9.x Corrected: 2014-01-14 19:38:37 UTC (stable/9, 9.2-STABLE) 2014-01-14 19:42:28 UTC (releng/9.2, 9.2-RELEASE-p3) 2014-01-14 19:42:28 UTC (releng/9.1, 9.1-RELEASE-p10) 2014-01-14 19:38:37 UTC (stable/8, 8.4-STABLE) 2014-01-14 19:42:28 UTC (releng/8.4, 8.4-RELEASE-p7) 2014-01-14 19:42:28 UTC (releng/8.3, 8.3-RELEASE-p14) CVE Name: CVE-2014-0591 For general information regarding FreeBSD Security Advisories, including descriptions of the fields above, security branches, and the following sections, please visit <URL:http://security.FreeBSD.org/>. I. Background BIND 9 is an implementation of the Domain Name System (DNS) protocols. The named(8) daemon is an Internet Domain Name Server. II. Problem Description Because of a defect in handling queries for NSEC3-signed zones, BIND can crash with an "INSIST" failure in name.c when processing queries possessing certain properties. This issue only affects authoritative nameservers with at least one NSEC3-signed zone. Recursive-only servers are not at risk. III. Impact An attacker who can send a specially crafted query could cause named(8) to crash, resulting in a denial of service. IV. Workaround No workaround is available, but systems not running authoritative DNS service with at least one NSEC3-signed zone using named(8) are not vulnerable. V. Solution Perform one of the following: 1) Upgrade your vulnerable system to a supported FreeBSD stable or release / security branch (releng) dated after the correction date. 2) To update your vulnerable system via a source code patch: The following patches have been verified to apply to the applicable FreeBSD release branches. a) Download the relevant patch from the location below, and verify the detached PGP signature using your PGP utility. [FreeBSD 8.3, 8.4, 9.1, 9.2-RELEASE and 8.4-STABLE] # fetch http://security.FreeBSD.org/patches/SA-14:04/bind-release.patch # fetch http://security.FreeBSD.org/patches/SA-14:04/bind-release.patch.asc # gpg --verify bind-release.patch.asc [FreeBSD 9.2-STABLE] # fetch http://security.FreeBSD.org/patches/SA-14:04/bind-stable-9.patch # fetch http://security.FreeBSD.org/patches/SA-14:04/bind-stable-9.patch.asc # gpg --verify bind-stable-9.patch.asc b) Execute the following commands as root: # cd /usr/src # patch < /path/to/patch Recompile the operating system using buildworld and installworld as described in <URL:https://www.FreeBSD.org/handbook/makeworld.html>. Restart the applicable daemons, or reboot the system. 3) To update your vulnerable system via a binary patch: Systems running a RELEASE version of FreeBSD on the i386 or amd64 platforms can be updated via the freebsd-update(8) utility: # freebsd-update fetch # freebsd-update install VI. Correction details The following list contains the correction revision numbers for each affected branch. Branch/path Revision - ------------------------------------------------------------------------- stable/8/ r260646 releng/8.3/ r260647 releng/8.4/ r260647 stable/9/ r260646 releng/9.1/ r260647 releng/9.2/ r260647 - ------------------------------------------------------------------------- To see which files were modified by a particular revision, run the following command, replacing NNNNNN with the revision number, on a machine with Subversion installed: # svn diff -cNNNNNN --summarize svn://svn.freebsd.org/base Or visit the following URL, replacing NNNNNN with the revision number: <URL:https://svnweb.freebsd.org/base?view=revision&revision=NNNNNN> VII. References <URL:https://kb.isc.org/article/AA-01078> <URL:http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-0591> The latest revision of this advisory is available at <URL:http://security.FreeBSD.org/advisories/FreeBSD-SA-14:04.bind.asc> -----BEGIN PGP SIGNATURE----- iQIcBAEBCgAGBQJS1ZTYAAoJEO1n7NZdz2rnOvQP/2/68/s9Cu35PmqNtSZVVxVG ZSQP5EGWx/lramNf9566iKxOrLRMq/h3XWcC4goVd+gZFrvITJSVOWSa7ntDQ7TO XcinfRZ/iyiJbs/Rg2wLHc/t5oVSyeouyccqODYFbOwOlk35JjOTMUG1YcX+Zasg ax8RV+7Zt1QSBkMlOz/myBLXUjlTZ3Xg2FXVsfFQW5/g2CjuHpRSFx1bVNX6ysoG 9DT58EQcYxIS8WfkHRbbXKh9I1nSfZ7/Hky/kTafRdRMrjAgbqFgHkYTYsBZeav5 fYWKGQRJulYfeZQ90yMTvlpF42DjCC3uJYamJnwDIu8OhS1WRBI8fQfr9DRzmRua OK3BK9hUiScDZOJB6OqeVzUTfe7MAA4/UwrDtTYQ+PqAenv1PK8DZqwXyxA9ThHb zKO3OwuKOVHJnKvpOcr+eNwo7jbnHlis0oBksj/mrq2P9m2ueF9gzCiq5Ri5Syag Wssb1HUoMGwqU0roS8+pRpNC8YgsWpsttvUWSZ8u6Vj/FLeHpiV3mYXPVMaKRhVm 067BA2uj4Th1JKtGleox+Em0R7OFbCc/9aWC67wiqI6KRyit9pYiF3npph+7D5Eq 7zPsUdDd+qc+UTiLp3liCRp5w6484wWdhZO6wRtmUgxGjNkxFoNnX8CitzF8AaqO UWWemqWuz3lAZuORQ9KX =OQzQ -----END PGP SIGNATURE-----
Every security advisory uses the following format:
Each security advisory is signed by the PGP key of the Security Officer. The public key for the Security Officer can be verified at OpenPGP 金鑰.
The name of the security advisory always begins with
FreeBSD-SA-
(for FreeBSD Security Advisory), followed by the year in two digit format (14:
), followed by the advisory number for that year (04.
), followed by the name of the affected application or subsystem (bind
). The advisory shown here is the fourth advisory for 2014 and it affects BIND.The
Topic
field summarizes the vulnerability.The
Category
refers to the affected part of the system which may be one ofcore
,contrib
, orports
. Thecore
category means that the vulnerability affects a core component of the FreeBSD operating system. Thecontrib
category means that the vulnerability affects software included with FreeBSD, such as BIND. Theports
category indicates that the vulnerability affects software available through the Ports Collection.The
Module
field refers to the component location. In this example, thebind
module is affected; therefore, this vulnerability affects an application installed with the operating system.The
Announced
field reflects the date the security advisory was published. This means that the security team has verified that the problem exists and that a patch has been committed to the FreeBSD source code repository.The
Credits
field gives credit to the individual or organization who noticed the vulnerability and reported it.The
Affects
field explains which releases of FreeBSD are affected by this vulnerability.The
Corrected
field indicates the date, time, time offset, and releases that were corrected. The section in parentheses shows each branch for which the fix has been merged, and the version number of the corresponding release from that branch. The release identifier itself includes the version number and, if appropriate, the patch level. The patch level is the letterp
followed by a number, indicating the sequence number of the patch, allowing users to track which patches have already been applied to the system.The
CVE Name
field lists the advisory number, if one exists, in the public cve.mitre.org security vulnerabilities database.The
Background
field provides a description of the affected module.The
Problem Description
field explains the vulnerability. This can include information about the flawed code and how the utility could be maliciously used.The
Impact
field describes what type of impact the problem could have on a system.The
Workaround
field indicates if a workaround is available to system administrators who cannot immediately patch the system .The
Solution
field provides the instructions for patching the affected system. This is a step by step tested and verified method for getting a system patched and working securely.The
Correction Details
field displays each affected Subversion branch with the revision number that contains the corrected code.The
References
field offers sources of additional information regarding the vulnerability.
13.12. 程序追蹤
Process accounting is a security method in which an administrator may keep track of system resources used and their allocation among users, provide for system monitoring, and minimally track a user’s commands.
Process accounting has both positive and negative points. One of the positives is that an intrusion may be narrowed down to the point of entry. A negative is the amount of logs generated by process accounting, and the disk space they may require. This section walks an administrator through the basics of process accounting.
If more fine-grained accounting is needed, refer to 安全事件稽查. |
13.12.1. 開啟並使用程序追蹤
Before using process accounting, it must be enabled using the following commands:
# sysrc accounting_enable=yes
# service accounting start
The accounting information is stored in files located in /var/account, which is automatically created, if necessary, the first time the accounting service starts. These files contain sensitive information, including all the commands issued by all users. Write access to the files is limited to root
, and read access is limited to root
and members of the wheel
group. To also prevent members of wheel
from reading the files, change the mode of the /var/account directory to allow access only by root
.
Once enabled, accounting will begin to track information such as CPU statistics and executed commands. All accounting logs are in a non-human readable format which can be viewed using sa
. If issued without any options, sa
prints information relating to the number of per-user calls, the total elapsed time in minutes, total CPU and user time in minutes, and the average number of I/O operations. Refer to sa(8) for the list of available options which control the output.
To display the commands issued by users, use lastcomm
. For example, this command prints out all usage of ls
by trhodes
on the ttyp1
terminal:
# lastcomm ls trhodes ttyp1
Many other useful options exist and are explained in lastcomm(1), acct(5), and sa(8).
13.13. 限制資源
FreeBSD provides several methods for an administrator to limit the amount of system resources an individual may use. Disk quotas limit the amount of disk space available to users. Quotas are discussed in 磁碟配額.
Limits to other resources, such as CPU and memory, can be set using either a flat file or a command to configure a resource limits database. The traditional method defines login classes by editing /etc/login.conf. While this method is still supported, any changes require a multi-step process of editing this file, rebuilding the resource database, making necessary changes to /etc/master.passwd, and rebuilding the password database. This can become time consuming, depending upon the number of users to configure.
rctl
can be used to provide a more fine-grained method for controlling resource limits. This command supports more than user limits as it can also be used to set resource constraints on processes and jails.
This section demonstrates both methods for controlling resources, beginning with the traditional method.
13.13.1. 設定登入類別
In the traditional method, login classes and the resource limits to apply to a login class are defined in /etc/login.conf. Each user account can be assigned to a login class, where default
is the default login class. Each login class has a set of login capabilities associated with it. A login capability is a name=value
pair, where name is a well-known identifier and value is an arbitrary string which is processed accordingly depending on the name.
Whenever /etc/login.conf is edited, the /etc/login.conf.db must be updated by executing the following command:
|
Resource limits differ from the default login capabilities in two ways. First, for every limit, there is a soft and hard limit. A soft limit may be adjusted by the user or application, but may not be set higher than the hard limit. The hard limit may be lowered by the user, but can only be raised by the superuser. Second, most resource limits apply per process to a specific user.
登入類別限制資源類型 lists the most commonly used resource limits. All of the available resource limits and capabilities are described in detail in login.conf(5).
限制資源 | 說明 |
---|---|
coredumpsize | The limit on the size of a core file generated by a program is subordinate to other limits on disk usage, such as |
cputime | The maximum amount of CPU time a user’s process may consume. Offending processes will be killed by the kernel. This is a limit on CPU time consumed, not the percentage of the CPU as displayed in some of the fields generated by |
filesize | The maximum size of a file the user may own. Unlike disk quotas (磁碟配額), this limit is enforced on individual files, not the set of all files a user owns. |
maxproc | The maximum number of foreground and background processes a user can run. This limit may not be larger than the system limit specified by |
memorylocked | The maximum amount of memory a process may request to be locked into main memory using mlock(2). Some system-critical programs, such as amd(8), lock into main memory so that if the system begins to swap, they do not contribute to disk thrashing. |
memoryuse | The maximum amount of memory a process may consume at any given time. It includes both core memory and swap usage. This is not a catch-all limit for restricting memory consumption, but is a good start. |
openfiles | The maximum number of files a process may have open. In FreeBSD, files are used to represent sockets and IPC channels, so be careful not to set this too low. The system-wide limit for this is defined by |
sbsize | The limit on the amount of network memory a user may consume. This can be generally used to limit network communications. |
stacksize | The maximum size of a process stack. This alone is not sufficient to limit the amount of memory a program may use, so it should be used in conjunction with other limits. |
There are a few other things to remember when setting resource limits:
Processes started at system startup by /etc/rc are assigned to the
daemon
login class.Although the default /etc/login.conf is a good source of reasonable values for most limits, they may not be appropriate for every system. Setting a limit too high may open the system up to abuse, while setting it too low may put a strain on productivity.
Xorg takes a lot of resources and encourages users to run more programs simultaneously.
Many limits apply to individual processes, not the user as a whole. For example, setting
openfiles
to50
means that each process the user runs may open up to50
files. The total amount of files a user may open is the value ofopenfiles
multiplied by the value ofmaxproc
. This also applies to memory consumption.
For further information on resource limits and login classes and capabilities in general, refer to cap_mkdb(1), getrlimit(2), and login.conf(5).
13.13.2. 開啟並設定資源限制
The kern.racct.enable
tunable must be set to a non-zero value. Custom kernels require specific configuration:
options RACCT options RCTL
Once the system has rebooted into the new kernel, rctl
may be used to set rules for the system.
Rule syntax is controlled through the use of a subject, subject-id, resource, and action, as seen in this example rule:
user:trhodes:maxproc:deny=10/user
In this rule, the subject is user
, the subject-id is trhodes
, the resource, maxproc
, is the maximum number of processes, and the action is deny
, which blocks any new processes from being created. This means that the user, trhodes
, will be constrained to no greater than 10
processes. Other possible actions include logging to the console, passing a notification to devd(8), or sending a sigterm to the process.
Some care must be taken when adding rules. Since this user is constrained to 10
processes, this example will prevent the user from performing other tasks after logging in and executing a screen
session. Once a resource limit has been hit, an error will be printed, as in this example:
% man test
/usr/bin/man: Cannot fork: Resource temporarily unavailable
eval: Cannot fork: Resource temporarily unavailable
As another example, a jail can be prevented from exceeding a memory limit. This rule could be written as:
# rctl -a jail:httpd:memoryuse:deny=2G/jail
Rules will persist across reboots if they have been added to /etc/rctl.conf. The format is a rule, without the preceding command. For example, the previous rule could be added as:
# Block jail from using more than 2G memory: jail:httpd:memoryuse:deny=2G/jail
To remove a rule, use rctl
to remove it from the list:
# rctl -r user:trhodes:maxproc:deny=10/user
A method for removing all rules is documented in rctl(8). However, if removing all rules for a single user is required, this command may be issued:
# rctl -r user:trhodes
Many other resources exist which can be used to exert additional control over various subjects
. See rctl(8) to learn about them.
13.14. 使用 Sudo 分享管理權限
系統管理者通常會要能夠授予額外的權限給其他使用者,以讓這些使用者可以執行需權限的工作。要讓團隊成員可以存取 FreeBSD 系統來完成其特定的工作對所有管理者都會帶來挑戰,這些團隊成員通常只需要比一般使用者多出一些存取權限便可作業,但他們總是會告訴管理者若沒有超級使用者的存取權便無法完成其工作。幸好,有工具可以管理這類的需求,這樣便不需提供這麼大的權限給一般使用者。
到目前為止,安全性章節已說明了如何允許已授權的使用者存取以及嘗試防止未經授權的存取,而現在有另一個問題,是由已授權的使用者擁有權限存取系統資源造成的。在很多的情況,使用者會需要存取應用程式啟動 Script 的權限或是管理者團隊需要維護系統,以往會使用標準的使用者與群組、檔案權限、甚至是 su(1) 指令來管理存取權,但當應用程式需要更多存取權,更多使用者需要使用系統資源時,便需要更好的解決方案,目前最常用來解決此問題的應用程式便是 Sudo。
Sudo 讓管理者可以對系統指令的存取設下更嚴格的限制並提供進階的記錄功能。如同其他工具,它可自 Port 套件集取得,於其中的 security/sudo,或使用 pkg(8) 工具取得,若要使用 pkg(8) 工具可:
# pkg install sudo
安裝完成之後,可用安裝的 visudo
以文字編輯器開啟設定檔,強烈建議使用 visudo
來編輯設定檔,由於它有內建的語法檢查程式可在檔案儲存之前檢驗是否有誤。
設定檔由個小節所組成,透過這些小節可做常廣泛的設定,在以下的範例中,網站應用程式維護人員 user1 需要啟動、停止與重新啟動名稱為 webservice 的網站應用程式 。要授權此使用者執行這些工作的權限,可加入此行到 /usr/local/etc/sudoers 的最後:
user1 ALL=(ALL) /usr/sbin/service webservice *
現在使用者可使用此指令來啟動 webservice:
% sudo /usr/sbin/service webservice start
雖然這項設定可以讓一位使用者存取 webservice 服務,但在大部份組織中會有一整個網站小組負責管理該服務,因此也可以一行來授予整個群組存取權,以下步驟會建立一個網站群組、加入使用者到這個群組,然後讓該群組中的所有成員能夠管理服務:
# pw groupadd -g 6001 -n webteam
同樣使用 pw(8) 指令來加入該使用到 webteam 群組:
# pw groupmod -m user1 -n webteam
最後,在 /usr/local/etc/sudoers 中的這行設定可以讓 webteam 群組的所有成員可以管理 webservice:
%webteam ALL=(ALL) /usr/sbin/service webservice *
與 su(1) 不同的是 Sudo 只需要一般使用者的密碼,這有一個使用者不需要共用密碼的優點,在大多數安全稽查都會發現共用密碼的問題且這種情況只有壞處可言。
大多數組織已正在導入或已導入雙重認証 (Two factor authentication),在這個情境下使用者可以不用輸入密碼,Sudo 提供了 %webteam ALL=(ALL) NOPASSWD: /usr/sbin/service webservice * |
13.14.1. 記錄輸出
採用 Sudo 的另一個優點是能夠開啟連線階段的記錄。使用內建立記錄機制與內含的 sudoreplay 指令,所有透過 Sudo 初始化的指令會被記錄下來供往後檢驗用。要開啟這個功能要加入預設記錄目錄的項目,在以下範例中使用了使用者變數來做目錄名稱,也還有許多其他記錄檔名稱慣例,可參考 sudoreplay 的操作手冊來取得進一步資訊。
Defaults iolog_dir=/var/log/sudo-io/%{user}
這個目錄會在記錄功能設定之後自動建立,最好讓系統以預設的權限來建立目錄比較保險,除此之外,這個設定項目也會記錄使用 sudoreplay 指令的管理者,要更改設定請閱讀並取消在 sudoers 中記錄選項的註解。 |
一旦這個設定加入至 sudoers 檔案之後,所有的使用者設定項目便可加上記錄存取動作的項目,在 webteam 項目加入額外設定之後的範例如下:
%webteam ALL=(ALL) NOPASSWD: LOG_INPUT: LOG_OUTPUT: /usr/sbin/service webservice *
從此之後,所有 webteam 修改 webservice 應用程式狀態的成員將會被記錄下來。要列出先前與目前連線階段的記錄可:
# sudoreplay -l
在輸出結果中要重播指定連線階段的記錄可搜尋 TSID=
項目,然後傳送給 sudoreplay 且不加其他選項便可以一般速度重播連線階段,例如:
# sudoreplay user1/00/00/02
雖然所有連線階段都會被記錄,但任何管理者都可以移除連線階段,使得沒人知道它們做了什麼事,所以非常值得在入侵偵測系統 (IDS) 或類似的軟體加入每日檢查,以便在有人為修改時通知其他管理人員。 |
sudoreplay
的擴充空間非常大,請參考說明文件來取得更多資訊。
Chapter 14. Jail
14.1. 概述
由於系統管理是一項困難的工作,許多工具開發來讓系統管理者能夠更輕鬆。這些工具通常可以強化系統安裝、設定以及維護的方式。這些工具之可以用來強化 FreeBSD 系統的安全性之一的就是 Jail。Jail 早在 FreeBSD 4.X 便可使用並持續強化它的功能、效率、穩定性以及安全性。
Jail 建立在 chroot(2) 概念之上,會更改一系列程序的根目錄。這可以創造一個安全的環境,將程序與系統的其他部份分隔。在 chroot 的環境所建立的程序不能存取該環境以外的檔案或資源。也因此,滲透一個在 chroot 的環境執行的服務並不會讓整個系統被攻擊者滲透。但 chroot 有許多限制,只適合用在簡單的工作,不需要許多彈性或複雜性、進階功能的工作。隨著時間推移,許多可以逃離 chroot 的環境的方法已經被找到,讓這個方法不再是確保服務安全的理想方案。
Jail 用許多方式改進了傳統 chroot 環境的概念。在傳統 chroot 環境,程序僅限制在一部份檔案系統可存取的地方。其餘的系統資源、系統使用者、執行的程序以及網路子系統被 chroot 的程序及主機系統的程序所共享。Jail 透過虛擬化存取檔案系統、使用者及網路子系統來擴展這個模型,可使用更多細微的控制參數來調校 Jail 的環境存取方式,Jail 可算是一種作業系統層級的虛擬化。
Jail 的四個要素:
一個子樹狀目錄:進入 Jail 的起點目錄,一但在 Jail 中,程序便沒有權限離開此目錄之外。
一個主機名稱:將會由 Jail 所使用。
一個 IP 位址:用來分配給 Jail。Jail 的 IP 位址通常是現有網路介面的別名位址。
一個指令:要在 Jail 中可執行的執行檔路徑名稱。該路徑是 Jail 環境根目錄的相對路徑。
Jail 有自己使用者及自己的 root
帳號,皆受到 Jail 環境的限制。Jail 中的 root
帳號不允許對指定 Jail 環境之外的系統執行操作。
本章將提供 FreeBSD Jail 術語及管理指令的概述,Jail 對系統管理者及進階的使用者來二者來說皆是強大的工具。
讀完這章,您將了解:
Jail 是什麼及它在 FreeBSD 中提供的目的。
如何建立、啟動及停止 Jail。
Jail 管理基礎,不論從內部或外部。
Jail 是強大的工具,但它不是安全性問題的萬靈丹。雖然 Jail 的程序不可能自己獨自打破規則,但有許多方法可以讓在 Jail 之外無權限的使用者與在 Jail 之內有權限的使用者串通來取得主機環境的更高權限。 大多數這類型的攻擊者可以由確保 Jail 根目錄不會被無權限使用者存取來減少。基本上,不受信任的使用者有 Jail 的存取權限並不會讓其可存取主機環境。 |
14.2. Jail 相關術語
為協助更容易理解 FreeBSD 系統有關 Jail 部份, 以及它們與 FreeBSD 其他部分的相互作用關係, 以下列出本章將使用的術語:
- chroot(8) (指令)
工具,用來使用 chroot(2) FreeBSD 系統呼叫 (System call) 來更改程予及其衍伸程序的根目錄。
- chroot(2) (環境)
指程序在 "chroot" 中執行的環境。包含的資源如:一部份可見的檔案系統、可用的使用者及群組 ID、網路介面及其他 IPC 機制等。
- jail(8) (指令)
允許在 Jail 環境下執行程序的系統管理工具。
- 主機 (系統、程序、使用者等)
Jail 環境的控制系統。 主機系統可以存取所有可用的硬體資源,並能控制 Jail 環境內外的程序。主機系統與 Jail 最大的差別在於:在主機系統中的超級使用者程序並不像在 Jail 環境那樣受到限制。
- 託管 (主機、程序、使用者等)
存取資源受到 FreeBSD Jail 限制的託管程序、使用者或其他實體。
14.3. 建立和控制 Jail
部份管理者將 Jail 分成兩種類型:"完整的" Jail,它像一個真正的 FreeBSD 系統以及 "服務的" Jail,專門用於某個應用程式或服務,可能使用管理權限執行。但這些只是概念上的區分,建立 Jail 的程序並不受這個概念的影響。當要建立一個 "完整的" Jail,Userland 有兩個來源選項:使用預先編譯的 Binary (如安裝媒體上提供的 Binary) 或從原始碼編譯。
要從安裝媒體安裝 Userland,需要先建立根目錄供 Jail 使用。這個動作可以透過設定 DESTDIR
來到適當的位置來完成。
啟動 Shell 並定義 DESTDIR
:
# sh
# export DESTDIR=/here/is/the/jail
當使用安裝 ISO 時,可依 mdconfig(8) 中的說明掛載安裝媒體:
# mount -t cd9660 /dev/`mdconfig -f cdimage.iso` /mnt
# cd /mnt/usr/freebsd-dist/
或者自鏡像站下載 Tarball 壓縮檔:
# sh
# export DESTRELEASE=12.0-RELEASE
# export DESTARCH=`uname -m`
# export SOURCEURL=http://ftp.freebsd.org/pub/FreeBSD/releases/$DESTARCH/$DESTRELEASE/
# for set in base ports; do fetch $SOURCEURL/$set.txz ; done
從安裝媒體上的 Tarball 中取出 Binary 並放到宣告的位置,至少需要取出 Base set 的部份,若需要也可完整安裝。
只安裝基礎系統 (Base system):
# tar -xf base.txz -C $DESTDIR
安裝全部不含核心:
# for set in base ports; do tar -xf $set.txz -C $DESTDIR ; done
依 jail(8) 操作手冊說明的程序建置 Jail:
# setenv D /here/is/the/jail
# mkdir -p $D (1)
# cd /usr/src
# make buildworld (2)
# make installworld DESTDIR=$D (3)
# make distribution DESTDIR=$D (4)
# mount -t devfs devfs $D/dev (5)
1 | 選擇 Jail 的位置是建置 Jail 最好的起點,這是在 Jail 主機上儲存 Jail 的實體位置。較好的選擇是 /usr/jail/jailname,其中 jailname 是用來辦識 Jail 的主機名稱。通常在 /usr/ 會有足夠的空間供 Jail 檔案系統使用,對 "完整的" Jail 來說,便是複製 FreeBSD 基礎系統預設安裝的每一個檔案。 |
2 | 若您已經使用 make world 或 make buildworld 重新編譯您的 Userland,您可以跳過這個步驟並安裝您已存在的 Userland 到新的 Jail。 |
3 | 這個指令將會在檔案系統中 Jail 所在的實體位置產生樹狀目錄及必要的 Binary、程式庫、操作手冊與相關檔案。 |
4 | make 的 distribution 目標會安裝所有需要的設定檔。簡單來說,它會安裝所有 /usr/src/etc/ 中可安裝的檔案到 Jail 環境的 /etc目錄:$D/etc/。 |
5 | 在 Jail 中掛載 devfs(8) 檔案系統並非必要的動作。從另一個角度來說,任何或大部份的應用程式會依該程式的目的會需要存取至少一個裝置,在 Jail 中控制存取的裝置非常重要,不恰當的設定可能會讓攻擊者可以在 Jail 中做不軌的事。對 devfs(8) 的控制是透過 Ruleset,在 devfs(8) 及 devfs.conf(5) 操作手冊中有詳細說明。 |
Jail 安裝完成之後,便可使用 jail(8) 工具來啟動。jail(8) 工具需要四個必要參數,在 概述 有說明。其他參數也可能需要指定,例如要使用特定使用者的身份來執行要 Jail 的程序。command
參數依 Jail 的類型所需而定,對一個 虛擬系統 來說,/etc/rc 是不錯的選擇,因為該檔案可以模仿真實 FreeBSD 的啟動順序。對於 服務型 的 Jail 來說,則看在 Jail 中要執行的服務或應用程式來決定。
Jail 通常會需要隨著開機執行,使用 FreeBSD rc 機制可讓以簡單的達成這件事。
在 jail.conf 中設定 jail 參數:
www { host.hostname = www.example.org; # Hostname ip4.addr = 192.168.0.10; # IP address of the jail path ="/usr/jail/www"; # Path to the jail devfs_ruleset = "www_ruleset"; # devfs ruleset mount.devfs; # Mount devfs inside the jail exec.start = "/bin/sh /etc/rc"; # Start command exec.stop = "/bin/sh /etc/rc.shutdown"; # Stop command }
在 rc.conf 中設定開機時啟動 Jail:
jail_enable="YES" # Set to NO to disable starting of any jails
預設要啟動的 Jail 可在 jail.conf(5) 設定,會把 Jail 當作是一個完全虛擬的系統,然後執行 Jail 中的 /etc/rc Script。針對服務型的 Jail 則需透過設定
exec.start
選項來適當更改 Jail 的預設啟動指令。要取得完整可用選項的清單,請參考 jail.conf(5)操作手冊。
若 Jail 項目已經在 jail.conf 中設定好,可以手動用 service(8) 來啟動或停止某個 Jail 項目:
# service jail start www
# service jail stop www
# jls
JID IP Address Hostname Path
3 192.168.0.10 www /usr/jail/www
# jexec 3 /etc/rc.shutdown
更多有關 Jail 的資訊可在 jail(8) 操作手冊取得。
14.4. 調校與管理
還有許多選項可以對所有 Jail 做設定,以及各種可讓 Jail 與主機 FreeBSD 系統結合的方法來提供更高層級的應用程式使用。 本節將介紹:
Some of the options available for tuning the behavior and security restrictions implemented by a jail installation.
Some of the high-level applications for jail management, which are available through the FreeBSD Ports Collection, and can be used to implement overall jail-based solutions.
14.4.1. 在 FreeBSD 中調校 Jail 的系統工具
Fine tuning of a jail’s configuration is mostly done by setting sysctl(8) variables. A special subtree of sysctl exists as a basis for organizing all the relevant options: the security.jail.*
hierarchy of FreeBSD kernel options. Here is a list of the main jail-related sysctls, complete with their default value. Names should be self-explanatory, but for more information about them, please refer to the jail(8) and sysctl(8) manual pages.
security.jail.set_hostname_allowed: 1
security.jail.socket_unixiproute_only: 1
security.jail.sysvipc_allowed: 0
security.jail.enforce_statfs: 2
security.jail.allow_raw_sockets: 0
security.jail.chflags_allowed: 0
security.jail.jailed: 0
These variables can be used by the system administrator of the host system to add or remove some of the limitations imposed by default on the root
user. Note that there are some limitations which cannot be removed. The root
user is not allowed to mount or unmount file systems from within a jail(8). The root
inside a jail may not load or unload devfs(8) rulesets, set firewall rules, or do many other administrative tasks which require modifications of in-kernel data, such as setting the securelevel
of the kernel.
The base system of FreeBSD contains a basic set of tools for viewing information about the active jails, and attaching to a jail to run administrative commands. The jls(8) and jexec(8) commands are part of the base FreeBSD system, and can be used to perform the following simple tasks:
Print a list of active jails and their corresponding jail identifier (JID), IP address, hostname and path.
Attach to a running jail, from its host system, and run a command inside the jail or perform administrative tasks inside the jail itself. This is especially useful when the
root
user wants to cleanly shut down a jail. The jexec(8) utility can also be used to start a shell in a jail to do administration in it; for example:# jexec 1 tcsh
14.4.2. 在 FreeBSD Port 套件集中的高層級管理工具
Among the many third-party utilities for jail administration, one of the most complete and useful is sysutils/ezjail. It is a set of scripts that contribute to jail(8) management. Please refer to the handbook section on ezjail for more information.
14.4.3. 持續 Jail 的修補與更新
Jails should be kept up to date from the host operating system as attempting to patch userland from within the jail may likely fail as the default behavior in FreeBSD is to disallow the use of chflags(1) in a jail which prevents the replacement of some files. It is possible to change this behavior but it is recommended to use freebsd-update(8) to maintain jails instead. Use -b
to specify the path of the jail to be updated.
# freebsd-update -b /here/is/the/jail fetch
# freebsd-update -b /here/is/the/jail install
14.5. 更新多個 Jail
The management of multiple jails can become problematic because every jail has to be rebuilt from scratch whenever it is upgraded. This can be time consuming and tedious if a lot of jails are created and manually updated.
This section demonstrates one method to resolve this issue by safely sharing as much as is possible between jails using read-only mount_nullfs(8) mounts, so that updating is simpler. This makes it more attractive to put single services, such as HTTP, DNS, and SMTP, into individual jails. Additionally, it provides a simple way to add, remove, and upgrade jails.
Simpler solutions exist, such as ezjail, which provides an easier method of administering FreeBSD jails but is less versatile than this setup. ezjail is covered in more detail in 使用 ezjail 管理 Jail. |
The goals of the setup described in this section are:
Create a simple and easy to understand jail structure that does not require running a full installworld on each and every jail.
Make it easy to add new jails or remove existing ones.
Make it easy to update or upgrade existing jails.
Make it possible to run a customized FreeBSD branch.
Be paranoid about security, reducing as much as possible the possibility of compromise.
Save space and inodes, as much as possible.
This design relies on a single, read-only master template which is mounted into each jail and one read-write device per jail. A device can be a separate physical disc, a partition, or a vnode backed memory device. This example uses read-write nullfs mounts.
The file system layout is as follows:
The jails are based under the /home partition.
Each jail will be mounted under the /home/j directory.
The template for each jail and the read-only partition for all of the jails is /home/j/mroot.
A blank directory will be created for each jail under the /home/j directory.
Each jail will have a /s directory that will be linked to the read-write portion of the system.
Each jail will have its own read-write system that is based upon /home/j/skel.
The read-write portion of each jail will be created in /home/js.
14.5.1. 建立範本
This section describes the steps needed to create the master template.
It is recommended to first update the host FreeBSD system to the latest -RELEASE branch using the instructions in 從原始碼更新 FreeBSD. Additionally, this template uses the sysutils/cpdup package or port and portsnap will be used to download the FreeBSD Ports Collection.
First, create a directory structure for the read-only file system which will contain the FreeBSD binaries for the jails. Then, change directory to the FreeBSD source tree and install the read-only file system to the jail template:
# mkdir /home/j /home/j/mroot # cd /usr/src # make installworld DESTDIR=/home/j/mroot
Next, prepare a FreeBSD Ports Collection for the jails as well as a FreeBSD source tree, which is required for mergemaster:
# cd /home/j/mroot # mkdir usr/ports # portsnap -p /home/j/mroot/usr/ports fetch extract # cpdup /usr/src /home/j/mroot/usr/src
Create a skeleton for the read-write portion of the system:
# mkdir /home/j/skel /home/j/skel/home /home/j/skel/usr-X11R6 /home/j/skel/distfiles # mv etc /home/j/skel # mv usr/local /home/j/skel/usr-local # mv tmp /home/j/skel # mv var /home/j/skel # mv root /home/j/skel
Use mergemaster to install missing configuration files. Then, remove the extra directories that mergemaster creates:
# mergemaster -t /home/j/skel/var/tmp/temproot -D /home/j/skel -i # cd /home/j/skel # rm -R bin boot lib libexec mnt proc rescue sbin sys usr dev
Now, symlink the read-write file system to the read-only file system. Ensure that the symlinks are created in the correct s/ locations as the creation of directories in the wrong locations will cause the installation to fail.
# cd /home/j/mroot # mkdir s # ln -s s/etc etc # ln -s s/home home # ln -s s/root root # ln -s ../s/usr-local usr/local # ln -s ../s/usr-X11R6 usr/X11R6 # ln -s ../../s/distfiles usr/ports/distfiles # ln -s s/tmp tmp # ln -s s/var var
As a last step, create a generic /home/j/skel/etc/make.conf containing this line:
WRKDIRPREFIX?= /s/portbuild
This makes it possible to compile FreeBSD ports inside each jail. Remember that the ports directory is part of the read-only system. The custom path for
WRKDIRPREFIX
allows builds to be done in the read-write portion of every jail.
14.5.2. 建立 Jail
The jail template can now be used to setup and configure the jails in /etc/rc.conf. This example demonstrates the creation of 3 jails: NS
, MAIL
and WWW
.
Add the following lines to /etc/fstab, so that the read-only template for the jails and the read-write space will be available in the respective jails:
/home/j/mroot /home/j/ns nullfs ro 0 0 /home/j/mroot /home/j/mail nullfs ro 0 0 /home/j/mroot /home/j/www nullfs ro 0 0 /home/js/ns /home/j/ns/s nullfs rw 0 0 /home/js/mail /home/j/mail/s nullfs rw 0 0 /home/js/www /home/j/www/s nullfs rw 0 0
To prevent fsck from checking nullfs mounts during boot and dump from backing up the read-only nullfs mounts of the jails, the last two columns are both set to
0
.Configure the jails in /etc/rc.conf:
jail_enable="YES" jail_set_hostname_allow="NO" jail_list="ns mail www" jail_ns_hostname="ns.example.org" jail_ns_ip="192.168.3.17" jail_ns_rootdir="/usr/home/j/ns" jail_ns_devfs_enable="YES" jail_mail_hostname="mail.example.org" jail_mail_ip="192.168.3.18" jail_mail_rootdir="/usr/home/j/mail" jail_mail_devfs_enable="YES" jail_www_hostname="www.example.org" jail_www_ip="62.123.43.14" jail_www_rootdir="/usr/home/j/www" jail_www_devfs_enable="YES"
The
jailnamerootdir
variable is set to /usr/home instead of /home because the physical path of /home on a default FreeBSD installation is /usr/home. Thejailnamerootdir
variable must not be set to a path which includes a symbolic link, otherwise the jails will refuse to start.Create the required mount points for the read-only file system of each jail:
# mkdir /home/j/ns /home/j/mail /home/j/www
Install the read-write template into each jail using sysutils/cpdup:
# mkdir /home/js # cpdup /home/j/skel /home/js/ns # cpdup /home/j/skel /home/js/mail # cpdup /home/j/skel /home/js/www
In this phase, the jails are built and prepared to run. First, mount the required file systems for each jail, and then start them:
# mount -a # service jail start
The jails should be running now. To check if they have started correctly, use jls
. Its output should be similar to the following:
# jls
JID IP Address Hostname Path
3 192.168.3.17 ns.example.org /home/j/ns
2 192.168.3.18 mail.example.org /home/j/mail
1 62.123.43.14 www.example.org /home/j/www
At this point, it should be possible to log onto each jail, add new users, or configure daemons. The JID
column indicates the jail identification number of each running jail. Use the following command to perform administrative tasks in the jail whose JID is 3
:
# jexec 3 tcsh
14.5.3. 升級
The design of this setup provides an easy way to upgrade existing jails while minimizing their downtime. Also, it provides a way to roll back to the older version should a problem occur.
The first step is to upgrade the host system. Then, create a new temporary read-only template in /home/j/mroot2.
# mkdir /home/j/mroot2 # cd /usr/src # make installworld DESTDIR=/home/j/mroot2 # cd /home/j/mroot2 # cpdup /usr/src usr/src # mkdir s
The
installworld
creates a few unnecessary directories, which should be removed:# chflags -R 0 var # rm -R etc var root usr/local tmp
Recreate the read-write symlinks for the master file system:
# ln -s s/etc etc # ln -s s/root root # ln -s s/home home # ln -s ../s/usr-local usr/local # ln -s ../s/usr-X11R6 usr/X11R6 # ln -s s/tmp tmp # ln -s s/var var
Next, stop the jails:
# service jail stop
Unmount the original file systems as the read-write systems are attached to the read-only system (/s):
# umount /home/j/ns/s # umount /home/j/ns # umount /home/j/mail/s # umount /home/j/mail # umount /home/j/www/s # umount /home/j/www
Move the old read-only file system and replace it with the new one. This will serve as a backup and archive of the old read-only file system should something go wrong. The naming convention used here corresponds to when a new read-only file system has been created. Move the original FreeBSD Ports Collection over to the new file system to save some space and inodes:
# cd /home/j # mv mroot mroot.20060601 # mv mroot2 mroot # mv mroot.20060601/usr/ports mroot/usr
At this point the new read-only template is ready, so the only remaining task is to remount the file systems and start the jails:
# mount -a # service jail start
Use jls
to check if the jails started correctly. Run mergemaster
in each jail to update the configuration files.
14.6. 使用 ezjail 管理 Jail
Creating and managing multiple jails can quickly become tedious and error-prone. Dirk Engling’s ezjail automates and greatly simplifies many jail tasks. A basejail is created as a template. Additional jails use mount_nullfs(8) to share many of the basejail directories without using additional disk space. Each additional jail takes only a few megabytes of disk space before applications are installed. Upgrading the copy of the userland in the basejail automatically upgrades all of the other jails.
Additional benefits and features are described in detail on the ezjail web site, https://erdgeist.org/arts/software/ezjail/.
14.6.1. 安裝 ezjail
Installing ezjail consists of adding a loopback interface for use in jails, installing the port or package, and enabling the service.
To keep jail loopback traffic off the host’s loopback network interface
lo0
, a second loopback interface is created by adding an entry to /etc/rc.conf:cloned_interfaces="lo1"
The second loopback interface
lo1
will be created when the system starts. It can also be created manually without a restart:# service netif cloneup Created clone interfaces: lo1.
Jails can be allowed to use aliases of this secondary loopback interface without interfering with the host.
Inside a jail, access to the loopback address
127.0.0.1
is redirected to the first IP address assigned to the jail. To make the jail loopback correspond with the newlo1
interface, that interface must be specified first in the list of interfaces and IP addresses given when creating a new jail.Give each jail a unique loopback address in the
127.0.0.0/8
netblock.Install sysutils/ezjail:
# cd /usr/ports/sysutils/ezjail # make install clean
Enable ezjail by adding this line to /etc/rc.conf:
ezjail_enable="YES"
The service will automatically start on system boot. It can be started immediately for the current session:
# service ezjail start
14.6.2. 初始設定
With ezjail installed, the basejail directory structure can be created and populated. This step is only needed once on the jail host computer.
In both of these examples, -p
causes the ports tree to be retrieved with portsnap(8) into the basejail. That single copy of the ports directory will be shared by all the jails. Using a separate copy of the ports directory for jails isolates them from the host. The ezjailFAQ explains in more detail: http://erdgeist.org/arts/software/ezjail/#FAQ.
To Populate the Jail with FreeBSD-RELEASE
For a basejail based on the FreeBSD RELEASE matching that of the host computer, use
install
. For example, on a host computer running FreeBSD 10-STABLE, the latest RELEASE version of FreeBSD -10 will be installed in the jail):# ezjail-admin install -p
To Populate the Jail with
installworld
The basejail can be installed from binaries created by
buildworld
on the host withezjail-admin update
.In this example, FreeBSD 10-STABLE has been built from source. The jail directories are created. Then
installworld
is executed, installing the host’s /usr/obj into the basejail.# ezjail-admin update -i -p
The host’s /usr/src is used by default. A different source directory on the host can be specified with
-s
and a path, or set withezjail_sourcetree
in /usr/local/etc/ezjail.conf.
The basejail’s ports tree is shared by other jails. However, downloaded distfiles are stored in the jail that downloaded them. By default, these files are stored in /var/ports/distfiles within each jail. /var/ports inside each jail is also used as a work directory when building ports. |
The FTP protocol is used by default to download packages for the installation of the basejail. Firewall or proxy configurations can prevent or interfere with FTP transfers. The HTTP protocol works differently and avoids these problems. It can be chosen by specifying a full URL for a particular download mirror in /usr/local/etc/ezjail.conf: ezjail_ftphost=http://ftp.FreeBSD.org See FTP 站 for a list of sites. |
14.6.3. 建立並啟動新的 Jail
New jails are created with ezjail-admin create
. In these examples, the lo1
loopback interface is used as described above.
Procedure: Create and Start a New Jail
Create the jail, specifying a name and the loopback and network interfaces to use, along with their IP addresses. In this example, the jail is named
dnsjail
.# ezjail-admin create dnsjail 'lo1|127.0.1.1,em0|192.168.1.50'
Most network services run in jails without problems. A few network services, most notably ping(8), use raw network sockets. In jails, raw network sockets are disabled by default for security. Services that require them will not work.
Occasionally, a jail genuinely needs raw sockets. For example, network monitoring applications often use ping(8) to check the availability of other computers. When raw network sockets are actually needed in a jail, they can be enabled by editing the ezjail configuration file for the individual jail, /usr/local/etc/ezjail/jailname. Modify the
parameters
entry:export jail_jailname_parameters="allow.raw_sockets=1"
Do not enable raw network sockets unless services in the jail actually require them.
Start the jail:
# ezjail-admin start dnsjail
Use a console on the jail:
# ezjail-admin console dnsjail
The jail is operating and additional configuration can be completed. Typical settings added at this point include:
Set the
root
PasswordConnect to the jail and set the
root
user’s password:# ezjail-admin console dnsjail # passwd Changing local password for root New Password: Retype New Password:
Time Zone Configuration
The jail’s time zone can be set with tzsetup(8). To avoid spurious error messages, the adjkerntz(8) entry in /etc/crontab can be commented or removed. This job attempts to update the computer’s hardware clock with time zone changes, but jails are not allowed to access that hardware.
DNS Servers
Enter domain name server lines in /etc/resolv.conf so DNS works in the jail.
Edit /etc/hosts
Change the address and add the jail name to the
localhost
entries in /etc/hosts.Configure /etc/rc.conf
Enter configuration settings in /etc/rc.conf. This is much like configuring a full computer. The host name and IP address are not set here. Those values are already provided by the jail configuration.
With the jail configured, the applications for which the jail was created can be installed.
Some ports must be built with special options to be used in a jail. For example, both of the network monitoring plugin packages net-mgmt/nagios-plugins and net-mgmt/monitoring-plugins have a |
14.6.4. 更新 Jail
14.6.4.1. 更新作業系統
Because the basejail’s copy of the userland is shared by the other jails, updating the basejail automatically updates all of the other jails. Either source or binary updates can be used.
To build the world from source on the host, then install it in the basejail, use:
# ezjail-admin update -b
If the world has already been compiled on the host, install it in the basejail with:
# ezjail-admin update -i
Binary updates use freebsd-update(8). These updates have the same limitations as if freebsd-update(8) were being run directly. The most important one is that only -RELEASE versions of FreeBSD are available with this method.
Update the basejail to the latest patched release of the version of FreeBSD on the host. For example, updating from RELEASE-p1 to RELEASE-p2.
# ezjail-admin update -u
To upgrade the basejail to a new version, first upgrade the host system as described in 執行主要及次要版號升級. Once the host has been upgraded and rebooted, the basejail can then be upgraded. freebsd-update(8) has no way of determining which version is currently installed in the basejail, so the original version must be specified. Use file(1) to determine the original version in the basejail:
# file /usr/jails/basejail/bin/sh
/usr/jails/basejail/bin/sh: ELF 64-bit LSB executable, x86-64, version 1 (FreeBSD), dynamically linked (uses shared libs), for FreeBSD 9.3, stripped
Now use this information to perform the upgrade from 9.3-RELEASE
to the current version of the host system:
# ezjail-admin update -U -s 9.3-RELEASE
After updating the basejail, mergemaster(8) must be run to update each jail’s configuration files.
How to use mergemaster(8) depends on the purpose and trustworthiness of a jail. If a jail’s services or users are not trusted, then mergemaster(8) should only be run from within that jail:
Delete the link from the jail’s /usr/src into the basejail and create a new /usr/src in the jail as a mountpoint. Mount the host computer’s /usr/src read-only on the jail’s new /usr/src mountpoint:
# rm /usr/jails/jailname/usr/src
# mkdir /usr/jails/jailname/usr/src
# mount -t nullfs -o ro /usr/src /usr/jails/jailname/usr/src
Get a console in the jail:
# ezjail-admin console jailname
Inside the jail, run mergemaster
. Then exit the jail console:
# cd /usr/src
# mergemaster -U
# exit
Finally, unmount the jail’s /usr/src:
# umount /usr/jails/jailname/usr/src
If the users and services in a jail are trusted, mergemaster(8) can be run from the host:
# mergemaster -U -D /usr/jails/jailname
14.6.4.2. 更新 Port
The ports tree in the basejail is shared by the other jails. Updating that copy of the ports tree gives the other jails the updated version also.
The basejail ports tree is updated with portsnap(8):
# ezjail-admin update -P
14.6.5. 控制 Jail
14.6.5.1. 停止與啟動 Jail
ezjail automatically starts jails when the computer is started. Jails can be manually stopped and restarted with stop
and start
:
# ezjail-admin stop sambajail
Stopping jails: sambajail.
By default, jails are started automatically when the host computer starts. Autostarting can be disabled with config
:
# ezjail-admin config -r norun seldomjail
This takes effect the next time the host computer is started. A jail that is already running will not be stopped.
Enabling autostart is very similar:
# ezjail-admin config -r run oftenjail
14.6.5.2. 封存與還原 Jail
Use archive
to create a .tar.gz archive of a jail. The file name is composed from the name of the jail and the current date. Archive files are written to the archive directory, /usr/jails/ezjail_archives. A different archive directory can be chosen by setting ezjail_archivedir
in the configuration file.
The archive file can be copied elsewhere as a backup, or an existing jail can be restored from it with restore
. A new jail can be created from the archive, providing a convenient way to clone existing jails.
Stop and archive a jail named wwwserver
:
# ezjail-admin stop wwwserver
Stopping jails: wwwserver.
# ezjail-admin archive wwwserver
# ls /usr/jails/ezjail-archives/
wwwserver-201407271153.13.tar.gz
Create a new jail named wwwserver-clone
from the archive created in the previous step. Use the em1 interface and assign a new IP address to avoid conflict with the original:
# ezjail-admin create -a /usr/jails/ezjail_archives/wwwserver-201407271153.13.tar.gz wwwserver-clone 'lo1|127.0.3.1,em1|192.168.1.51'
14.6.6. 完整範例:在 Jail 中安裝 BIND
Putting the BINDDNS server in a jail improves security by isolating it. This example creates a simple caching-only name server.
The jail will be called
dns1
.The jail will use IP address
192.168.1.240
on the host’sre0
interface.The upstream ISP’s DNS servers are at
10.0.0.62
and10.0.0.61
.The basejail has already been created and a ports tree installed as shown in 初始設定.
Create a cloned loopback interface by adding a line to /etc/rc.conf:
cloned_interfaces="lo1"
Immediately create the new loopback interface:
# service netif cloneup
Created clone interfaces: lo1.
Create the jail:
# ezjail-admin create dns1 'lo1|127.0.2.1,re0|192.168.1.240'
Start the jail, connect to a console running on it, and perform some basic configuration:
# ezjail-admin start dns1
# ezjail-admin console dns1
# passwd
Changing local password for root
New Password:
Retype New Password:
# tzsetup
# sed -i .bak -e '/adjkerntz/ s/^/#/' /etc/crontab
# sed -i .bak -e 's/127.0.0.1/127.0.2.1/g; s/localhost.my.domain/dns1.my.domain dns1/' /etc/hosts
Temporarily set the upstream DNS servers in /etc/resolv.conf so ports can be downloaded:
nameserver 10.0.0.62 nameserver 10.0.0.61
Still using the jail console, install dns/bind99.
# make -C /usr/ports/dns/bind99 install clean
Configure the name server by editing /usr/local/etc/namedb/named.conf.
Create an Access Control List (ACL) of addresses and networks that are permitted to send DNS queries to this name server. This section is added just before the options
section already in the file:
... // or cause huge amounts of useless Internet traffic. acl "trusted" { 192.168.1.0/24; localhost; localnets; }; options { ...
Use the jail IP address in the listen-on
setting to accept DNS queries from other computers on the network:
listen-on { 192.168.1.240; };
A simple caching-only DNS name server is created by changing the forwarders
section. The original file contains:
/* forwarders { 127.0.0.1; }; */
Uncomment the section by removing the /
and /
lines. Enter the IP addresses of the upstream DNS servers. Immediately after the forwarders
section, add references to the trusted
ACL defined earlier:
forwarders { 10.0.0.62; 10.0.0.61; }; allow-query { any; }; allow-recursion { trusted; }; allow-query-cache { trusted; };
Enable the service in /etc/rc.conf:
named_enable="YES"
Start and test the name server:
# service named start
wrote key file "/usr/local/etc/namedb/rndc.key"
Starting named.
# /usr/local/bin/dig @192.168.1.240 freebsd.org
A response that includes
;; Got answer;
shows that the new DNS server is working. A long delay followed by a response including
;; connection timed out; no servers could be reached
shows a problem. Check the configuration settings and make sure any local firewalls allow the new DNS access to the upstream DNS servers.
The new DNS server can use itself for local name resolution, just like other local computers. Set the address of the DNS server in the client computer’s /etc/resolv.conf:
nameserver 192.168.1.240
A local DHCP server can be configured to provide this address for a local DNS server, providing automatic configuration on DHCP clients.
Chapter 15. 強制存取控制 (MAC)
15.1. 概述
FreeBSD supports security extensions based on the POSIX™.1e draft. These security mechanisms include file system Access Control Lists (存取控制清單) and Mandatory Access Control (MAC). MAC allows access control modules to be loaded in order to implement security policies. Some modules provide protections for a narrow subset of the system, hardening a particular service. Others provide comprehensive labeled security across all subjects and objects. The mandatory part of the definition indicates that enforcement of controls is performed by administrators and the operating system. This is in contrast to the default security mechanism of Discretionary Access Control (DAC) where enforcement is left to the discretion of users.
This chapter focuses on the MAC framework and the set of pluggable security policy modules FreeBSD provides for enabling various security mechanisms.
讀完這章,您將了解:
The terminology associated with the MAC framework.
The capabilities of MAC security policy modules as well as the difference between a labeled and non-labeled policy.
The considerations to take into account before configuring a system to use the MAC framework.
Which MAC security policy modules are included in FreeBSD and how to configure them.
How to implement a more secure environment using the MAC framework.
How to test the MAC configuration to ensure the framework has been properly implemented.
在開始閱讀這章之前,您需要:
了解 UNIX™ 及 FreeBSD 基礎 (FreeBSD 基礎)。
Have some familiarity with security and how it pertains to FreeBSD (安全性).
Improper MAC configuration may cause loss of system access, aggravation of users, or inability to access the features provided by Xorg. More importantly, MAC should not be relied upon to completely secure a system. The MAC framework only augments an existing security policy. Without sound security practices and regular security checks, the system will never be completely secure. The examples contained within this chapter are for demonstration purposes and the example settings should not be implemented on a production system. Implementing any security policy takes a good deal of understanding, proper design, and thorough testing. |
While this chapter covers a broad range of security issues relating to the MAC framework, the development of new MAC security policy modules will not be covered. A number of security policy modules included with the MAC framework have specific characteristics which are provided for both testing and new module development. Refer to mac_test(4), mac_stub(4) and mac_none(4) for more information on these security policy modules and the various mechanisms they provide.