<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>温室小花.技术.博客 --纯粹的unix技术博客 &#187; pf</title>
	<atom:link href="http://www.evanjiang.net.cn/archives/category/network_security/pf/feed" rel="self" type="application/rss+xml" />
	<link>http://www.evanjiang.net.cn</link>
	<description>红颜弹指老，刹那芳华，与其天涯思君，恋恋不舍，莫若相忘于江湖！</description>
	<lastBuildDate>Sun, 05 Sep 2010 14:51:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>OpenBSD.Nginx.MySQL.PHP环境搭建手册(网上转摘）</title>
		<link>http://www.evanjiang.net.cn/archives/1176.html</link>
		<comments>http://www.evanjiang.net.cn/archives/1176.html#comments</comments>
		<pubDate>Mon, 08 Jun 2009 14:32:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[mysql]]></category>
		<category><![CDATA[openbsd unix]]></category>
		<category><![CDATA[pf]]></category>
		<category><![CDATA[www服务]]></category>

		<guid isPermaLink="false">http://www.evanjiang.net.cn/?p=1176</guid>
		<description><![CDATA[<p>


 <p>很久没弄过OPENBSD，而且，听说现在的NGINX很红，性能比传统的APACHE要好很多倍，因而，一直想弄个NGINX服务器环境。加上，俺也想熟悉回OPENBSD，就想着弄个OPENBSD，NGINX，MYSQL，PHP的环境。。弄来玩玩，就当复习一下技术。出于习惯，俺还是在网上找了这篇文档。初步看过，好像写得不错，，就先弄过来，暂没时间实操过，待俺忙过这段时间。就再次重点研究一下俺熟悉而喜欢的UNIX服务器与数据库技术。。。</p>
<p>本手册以在OpenBSD 4.4环境下搭建Nginx、MySQL、PHP环境为例进行讲解。按照惯例，root权限。</p>
<p>=====================================================</p>
<p>目录</p>
<p>一、OpenBSD的安装及注意事项
二、系统性能调优
Ⅰ、/etc/fstab调优
Ⅱ、/etc/sysctl.conf调优</p>
<p>三、O.N.M.P.软件环境的安装
四、Nginx配置
Ⅰ、Nginx配置文件的修改
Ⅱ、Nginx日志截断</p>
<p>五、MySQL与phpMyAdmin的配置
Ⅰ、MySQL的配置
Ⅱ、phpMyAdmin的配置</p>
<p>六、强化PHP的安全
七、强化SSH的安全
Ⅰ、SSH配置文件的修改
Ⅱ、使用KEY进行验证
Ⅲ、按需启动SSH
Ⅳ、一点安全小常识</p>
<p>八、启用Packet Filter防火墙
九、系统启动脚本的修改</p>
<p>=====================================================</p>
<p>一、OpenBSD的安装及注意事项</p>
<p>OpenBSD的安装这里就不多说了，主要是安装时系统组件的选择、分区和系统服务的部分。对于系统组件部分，作为生产系统来说，偶并不推荐安装comp44.tgz这个组件。因为comp44.tgz实际就是编译器，不装这个，可以在很大程度上避免安装一些非授权的软件，从而提高远程主机的安全性。如果真的需要安装什么软件，也可以在非重要的机器上进行编译，然后使用PSFTP等软件上传到远程主机上使用。关于PSFTP软件的使用，二楼有详细的介绍。</p>
<p>系统分区时，推荐将/usr、/usr/local、/var、/var/mysql、/var/mail、/var/log、/var/nginx等分区单独分出来，也就是说，进行比较细致的分区，防止某个目录中的文件膨胀占满整个分区导致的死锁等问题。假定你有一个80G的硬盘，一个分区示例在下面：</p>
<p>/	200M
(swap)	1G
/tmp	200M
/usr	500M
/usr/local	200M
/var	100M
/var/mysql	10G
/var/mail	100M
/var/log	5G~10G
/home	200M
/var/nginx	剩余空间</p>
<p>至于系统服务部分，建议所有的服务都选择“n”，亦即不随系统启动。

二、系统性能调优</p>
<p>对于多核的机器，使用bsd.mp这个核心。</p>
<p>[Copy to clipboard] [ - ]CODE:
mv /bsd /obsd
mv /bsd.mp /bsd</p>
<p>Ⅰ、/etc/fstab调优</p>
<p>[Copy to clipboard] [ - ]CODE:
vi /etc/fstab</p>
<p>在文件系统描述符部分，加入&#8221;noatime&#8221;和&#8221;softdep&#8221;。示例如下：</p>
<p>QUOTE:
/dev/wd0a / ffs rw,noatime,softdep 1 1
/dev/wd0l /home ffs rw,nodev,nosuid,noatime,softdep 1 2
/dev/wd0d /tmp ffs rw,nodev,nosuid,noatime,softdep 1 2
/dev/wd0e /usr ffs rw,nodev,noatime,softdep 1 2
/dev/wd0f /usr/local ffs rw,nodev,noatime,softdep 1 2
/dev/wd0g /var ffs rw,nodev,nosuid,noatime,softdep 1 2
/dev/wd0i /var/log ffs rw,nodev,nosuid,noatime,softdep 1 2
/dev/wd0j /var/mail [...]]]></description>
			<content:encoded><![CDATA[<p style="float: left;margin: 4px;"><script type="text/javascript"><!--
google_ad_client = "pub-8438729971248494";
/* 160x600, 创建于 10-2-7 */
google_ad_slot = "8970910006";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p> <p>很久没弄过OPENBSD，而且，听说现在的NGINX很红，性能比传统的APACHE要好很多倍，因而，一直想弄个NGINX服务器环境。加上，俺也想熟悉回OPENBSD，就想着弄个OPENBSD，NGINX，MYSQL，PHP的环境。。弄来玩玩，就当复习一下技术。出于习惯，俺还是在网上找了这篇文档。初步看过，好像写得不错，，就先弄过来，暂没时间实操过，待俺忙过这段时间。就再次重点研究一下俺熟悉而喜欢的UNIX服务器与数据库技术。。。</p>
<p>本手册以在OpenBSD 4.4环境下搭建Nginx、MySQL、PHP环境为例进行讲解。按照惯例，root权限。</p>
<p>=====================================================</p>
<p>目录</p>
<p>一、OpenBSD的安装及注意事项<br />
二、系统性能调优<br />
Ⅰ、/etc/fstab调优<br />
Ⅱ、/etc/sysctl.conf调优</p>
<p>三、O.N.M.P.软件环境的安装<br />
四、Nginx配置<br />
Ⅰ、Nginx配置文件的修改<br />
Ⅱ、Nginx日志截断</p>
<p>五、MySQL与phpMyAdmin的配置<br />
Ⅰ、MySQL的配置<br />
Ⅱ、phpMyAdmin的配置</p>
<p>六、强化PHP的安全<br />
七、强化SSH的安全<br />
Ⅰ、SSH配置文件的修改<br />
Ⅱ、使用KEY进行验证<br />
Ⅲ、按需启动SSH<br />
Ⅳ、一点安全小常识</p>
<p>八、启用Packet Filter防火墙<br />
九、系统启动脚本的修改</p>
<p>=====================================================</p>
<p>一、OpenBSD的安装及注意事项</p>
<p>OpenBSD的安装这里就不多说了，主要是安装时系统组件的选择、分区和系统服务的部分。对于系统组件部分，作为生产系统来说，偶并不推荐安装comp44.tgz这个组件。因为comp44.tgz实际就是编译器，不装这个，可以在很大程度上避免安装一些非授权的软件，从而提高远程主机的安全性。如果真的需要安装什么软件，也可以在非重要的机器上进行编译，然后使用PSFTP等软件上传到远程主机上使用。关于PSFTP软件的使用，二楼有详细的介绍。</p>
<p>系统分区时，推荐将/usr、/usr/local、/var、/var/mysql、/var/mail、/var/log、/var/nginx等分区单独分出来，也就是说，进行比较细致的分区，防止某个目录中的文件膨胀占满整个分区导致的死锁等问题。假定你有一个80G的硬盘，一个分区示例在下面：</p>
<p>/	200M<br />
(swap)	1G<br />
/tmp	200M<br />
/usr	500M<br />
/usr/local	200M<br />
/var	100M<br />
/var/mysql	10G<br />
/var/mail	100M<br />
/var/log	5G~10G<br />
/home	200M<br />
/var/nginx	剩余空间</p>
<p>至于系统服务部分，建议所有的服务都选择“n”，亦即不随系统启动。<br />
<span id="more-1176"></span><br />
二、系统性能调优</p>
<p>对于多核的机器，使用bsd.mp这个核心。</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
mv /bsd /obsd<br />
mv /bsd.mp /bsd</p>
<p>Ⅰ、/etc/fstab调优</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
vi /etc/fstab</p>
<p>在文件系统描述符部分，加入&#8221;noatime&#8221;和&#8221;softdep&#8221;。示例如下：</p>
<p>QUOTE:<br />
/dev/wd0a / ffs rw,noatime,softdep 1 1<br />
/dev/wd0l /home ffs rw,nodev,nosuid,noatime,softdep 1 2<br />
/dev/wd0d /tmp ffs rw,nodev,nosuid,noatime,softdep 1 2<br />
/dev/wd0e /usr ffs rw,nodev,noatime,softdep 1 2<br />
/dev/wd0f /usr/local ffs rw,nodev,noatime,softdep 1 2<br />
/dev/wd0g /var ffs rw,nodev,nosuid,noatime,softdep 1 2<br />
/dev/wd0i /var/log ffs rw,nodev,nosuid,noatime,softdep 1 2<br />
/dev/wd0j /var/mail ffs rw,nodev,nosuid,noatime,softdep 1 2<br />
/dev/wd0h /var/mysql ffs rw,nodev,nosuid,noatime,softdep 1 2<br />
/dev/wd0k /var/nginx ffs rw,nodev,nosuid,noatime,softdep 1 2</p>
<p>友情提醒：softdep是一种非同步的文件系统，意外掉电可能造成数据的遗失/损坏，生产系统请谨慎使用！</p>
<p>改完后保存退出，reboot，看能不能正常启动。</p>
<p>一般情况下是没有问题的，个别机器或虚拟机可能会因为兼容性的缘故，无法启动。那么就把根目录的softdep拿掉，其他目录保留，仍然会有作用。</p>
<p>更多关于OpenBSD环境下磁盘性能调优的内容，请参看偶博客的文章，地址在下面：</p>
<p>http://blog.chinaunix.net/u2/81136/showart_1841280.html</p>
<p>Ⅱ、/etc/sysctl.conf调优</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
vi /etc/sysctl.conf</p>
<p>跳到最后，加入下面的内容：</p>
<p>QUOTE:<br />
# 增大文件系统缓存到1M<br />
kern.maxvnodes=131072</p>
<p># 允许最多65536个进程<br />
kern.maxproc=65536</p>
<p># 同时最多打开65536个文件<br />
kern.maxfiles=65536</p>
<p># 并发连接最大65536<br />
kern.somaxconn=65536</p>
<p># 保留的最少连接数<br />
kern.sominconn=256<br />
kern.maxclusters=32768</p>
<p># 增大TCP接收/发送缓存到64K<br />
net.inet.tcp.recvspace=65536<br />
net.inet.tcp.sendspace=65536</p>
<p># 增大UDP接收/发送缓存到64K<br />
net.inet.udp.recvspace=65536<br />
net.inet.udp.sendspace=65536</p>
<p>注意：虚拟机测试只加最上面一行kern.maxvnodes=65536即可，其他的不必加了，否则会有各种问题。独立机器的可以加上。</p>
<p>保存退出，reboot。不能正常启动的就把除kern.maxvnodes以外的数字调小或者禁用再试。</p>
<p>三、OpenBSD.Nginx.MySQL.PHP软件环境的安装</p>
<p>OpenBSD环境下软件的安装是非常简单的，因为在官方的ftp中提供了已经编译好的二进制包，需要安装的软件都在ftp中，从ftp中安装即可。</p>
<p>小提示：如果你机器比较多，你可以把需要安装的软件包都down回来，其他机器再来这里安装，速度会非常快！</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
export PKG_PATH=ftp://ftp.openbsd.org/pub/OpenBSD/4.4/packages/i386/</p>
<p>pkg_add mysql-server php5-fastcgi php5-gd-5.2.6-no_x11 phpMyAdmin lighttpd-1.4.19p3 nginx pecl-APC</p>
<p>以偶的1M ADSL小水管为例，大约也就二十分钟左右就安装完毕了！真的是非常快！和其他系统的wget源码、./configure &amp;&amp; make &amp;&amp; make install&#8230;所需要的时间相比，效率是非常高！而且，由于OpenBSD默认采用比较高的安全策略，装上的环境安全性也比其他系统要高！</p>
<p>等所需的软件都安装完成后，按提示作链接并创建PHP临时工作目录：</p>
<p>QUOTE:<br />
ln -s /var/www/conf/modules.sample/php5.conf /var/www/conf/modules<br />
ln -fs /var/www/conf/php5.sample/apc.ini /var/www/conf/php5/apc.ini<br />
ln -fs /var/www/conf/php5.sample/gd.ini /var/www/conf/php5/gd.ini<br />
ln -fs /var/www/conf/php5.sample/mbstring.ini /var/www/conf/php5/mbstring.ini<br />
ln -fs /var/www/conf/php5.sample/mcrypt.ini /var/www/conf/php5/mcrypt.ini<br />
ln -fs /var/www/conf/php5.sample/mysql.ini /var/www/conf/php5/mysql.ini<br />
mkdir /var/nginx/sesstmp<br />
chmod 0777 /var/nginx/sesstmp</p>
<p>pkg_info检查一下系统中安装了些什么软件包：</p>
<p>可以看到，所需的软件包和依赖的包都安装好了！</p>
<p>四、Nginx配置</p>
<p>Ⅰ、Nginx配置文件的修改</p>
<p>修改nginx的默认配置文件：</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
vi /etc/nginx/nginx.conf</p>
<p>按下面的内容修改Nginx的配置文件。兰色表示需要手动修改的内容，红色表示增加的内容：</p>
<p>QUOTE:<br />
#user  nobody;</p>
<p># 指定子进程数，酌情修改<br />
worker_processes  4;</p>
<p>#error_log  logs/error.log;<br />
#error_log  logs/error.log  notice;<br />
#error_log  logs/error.log  info;</p>
<p>#pid        logs/nginx.pid;</p>
<p># 最多可打开文件数<br />
worker_rlimit_nofile 8196;</p>
<p>events {<br />
# 最大并发数<br />
worker_connections  1024;<br />
}</p>
<p>http {<br />
include       mime.types;<br />
default_type  application/octet-stream;</p>
<p># 关掉错误日志<br />
error_log       /dev/null  crit;<br />
# 如果需要错误日志，就用下面这行替换上面这行<br />
#error_log     /var/log/nginx/error.log  notice;</p>
<p># 定义日志格式，对日志使用缓存，避免频繁的磁盘I/O操作<br />
access_log   /var/log/nginx/access.log combined buffer=1m;</p>
<p>sendfile        on;<br />
tcp_nopush      on;<br />
tcp_nodelay     on;</p>
<p>keepalive_timeout  10;</p>
<p># 对静态文件和可压缩文件启用压缩，以节约网络带宽，提高访问速度<br />
gzip              on;<br />
gzip_min_length   1k;<br />
gzip_buffers      4 8k;<br />
gzip_http_version 1.1;<br />
gzip_comp_level   3;<br />
gzip_types        text/html text/css text/xml text/plain application/x-javascript application/xml application/pdf application/x-perl application/x-tcl application/msword application/rtf application/vnd.ms-excel application/vnd.ms-powerpoint application/vnd.wap.xhtml+xml image/x-ms-bmp;<br />
gzip_disable      &#8220;MSIE [1-6] \.&#8221;;<br />
gzip_vary         on;</p>
<p># 定义输出缓存大小<br />
output_buffers   4 32k;</p>
<p># 最大允许可上传文件大小<br />
client_max_body_size 20m;</p>
<p># 定义一个叫“myzone”的记录区，总容量为 10M<br />
# 和下面的limit_conn一起限制单个IP的并发连接数为10<br />
limit_zone myzone $binary_remote_addr  10m;</p>
<p>server {<br />
listen       80;<br />
server_name  localhost;</p>
<p>location / {<br />
root   /var/nginx/html;<br />
index  index.php index.html index.htm;<br />
limit_conn  myzone 10;<br />
}</p>
<p>error_page   500 502 503 504  /50x.html;</p>
<p>location = /50x.html {<br />
root   /var/nginx/html;<br />
}</p>
<p>location ~ \.php$ {<br />
root           html;<br />
fastcgi_pass   127.0.0.1:9000;<br />
fastcgi_index  index.php;<br />
fastcgi_param  SCRIPT_FILENAME  /var/nginx/html$fastcgi_script_name;<br />
include        fastcgi_params;<br />
}</p>
<p># 在浏览器本地暂存图片和静态文件，不记录日志，以节约机器资源<br />
location ~* \.(gif|png|jpg|jpeg|bmp|css|js|swf)$<br />
{<br />
root           /var/nginx/html;<br />
access_log off;<br />
expires max;<br />
}</p>
<p># 在浏览器中输入http://xxx.xxx.xxx/status可以看到Nginx的运行信息<br />
# 需要密码验证，不记录日志，限制IP访问<br />
location ~ /status<br />
{<br />
auth_basic  &#8220;O.N.M.P.&#8221;;<br />
auth_basic_user_file password;<br />
stub_status on;<br />
access_log   off;<br />
allow 192.168.0.0/24;<br />
deny all;<br />
}<br />
}</p>
<p>}</p>
<p>其他的部分请酌情修改。</p>
<p>运行下面的命令生成查看Nginx运行状态的密码文件：</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
htpasswd -c /etc/nginx/password webadmin</p>
<p>按提示输入两遍密码即可。</p>
<p>在查看status的时候，输入用户名webadmin（见上面这行）和密码就能够看到Nginx的运行数据了。</p>
<p>Nginx能够流行和它的高负载能力是分不开的，在追求性能表现的场合，推荐使用Nginx+PHP-fastcgi的组合以获得强健的性能表现。而对于那些重视安全性的场合来说，可能OpenBSD内核集成的Apache更合适。OpenBSD下搭建Apache、MySQL、PHP环境的详细内容请参见偶的另篇博文，地址在下面：（博客速度可能较慢，四楼有转帖）</p>
<p>http://blog.chinaunix.net/u2/81136/showart_1860332.html</p>
<p>当然，你也可以利用Nginx内置的负载均衡功能，在前端分配访问流量，后端由Apache来运行PHP环境。Nginx负载均衡的配置可以去Nginx的主页参看相关内容，地址：http://wiki.nginx.org/Main。</p>
<p>下面为一个Nginx负载均衡的示例：</p>
<p>QUOTE:<br />
http {<br />
upstream myproject {<br />
ip_hash;<br />
server 192.168.1.1:80;<br />
server 192.168.1.2:80;<br />
server 192.168.1.3:80;<br />
server 192.168.1.4:80;<br />
}</p>
<p>server {<br />
listen 80;<br />
server_name www.domain.com;<br />
location / {<br />
proxy_pass http://myproject;<br />
}<br />
}<br />
}</p>
<p>网络拓扑示意图如下：</p>
<p>Ⅱ、Nginx日志截断</p>
<p>OpenBSD默认每天00:00会执行/etc/daily.local脚本中的内容，我们只需要把Nginx日志截断的命令加入到这个文件中即可。</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
vi /etc/daily.local</p>
<p>加入下面的内容：</p>
<p>QUOTE:<br />
#!/bin/sh<br />
# 对Nginx日志进行截断和压缩，以节约log分区空间<br />
# 在张宴的基础上修改，感谢！<br />
mkdir -p /var/log/nginx/$(date -d &#8220;yesterday&#8221; +&#8221;%Y&#8221;)/$(date -d &#8220;yesterday&#8221; +&#8221;%m&#8221;)/<br />
mv /var/log/nginx/access.log /var/log/nginx/$(date -d &#8220;yesterday&#8221; +&#8221;%Y&#8221;)/$(date -d &#8220;yesterday&#8221; +&#8221;%m&#8221;)/access.$(date -d &#8220;yesterday&#8221; +&#8221;%Y%m%d&#8221;).log<br />
kill -USR1 `cat /var/run/nginx.pid`<br />
sleep 1<br />
gzip /var/log/nginx/$(date -d &#8220;yesterday&#8221; +&#8221;%Y&#8221;)/$(date -d &#8220;yesterday&#8221; +&#8221;%m&#8221;)/access.$(date -d &#8220;yesterday&#8221; +&#8221;%Y%m%d&#8221;).log</p>
<p>保存退出，为/etc/daily.local加上执行权限：</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
chmod 0755 /etc/daily.local</p>
<p>其他需要每天运行的命令也都可以加在这个脚本里面，各位自行处理。</p>
<p>五、MySQL与phpMyAdmin的配置</p>
<p>Ⅰ、MySQL的配置</p>
<p>安全起见，MySQL需要运行在自己的daemon下：</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
vi /etc/login.conf</p>
<p>跳到最后，加入MySQL所需的修改：</p>
<p>QUOTE:<br />
mysql:\<br />
 <img src='http://www.evanjiang.net.cn/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> penfiles-cur=2048:\<br />
 <img src='http://www.evanjiang.net.cn/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> penfiles-max=4096:\<br />
:tc=daemon:</p>
<p>使修改生效：<br />

<!-- Begin alimama Adserver code -->
<script type="text/javascript"><!--
google_ad_client = "pub-8438729971248494";
/* 728x90, ������ 10-2-7 */
google_ad_slot = "4752526529";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<!-- End Alimama Adserver code -->
<br />
[Copy to clipboard] [ - ]CODE:<br />
cap_mkdb /etc/login.conf</p>
<p>初始化MySQL数据库：</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
/usr/local/bin/mysql_install_db</p>
<p>MySQL自带了几个配置文件，在/usr/local/share/mysql目录中，可以拷贝为/etc/my.cnf使用。关于MySQL的配置和优化等内容，可以自行Google，这里不再赘述。<br />
MySQL安全须知<br />
不要用root身份运行数据库或PHP应用。并且，最好是数据库名和数据库用户名不同，以提高安全性。</p>
<p>例如，域名为example.net，则数据库名设为abcxyz，数据库用户名设为xyzabc。总之，关联度越低越好，数据库名和数据库用户名越复杂越难猜测越好。</p>
<p>控制权限的分配，PHP应用仅给予必要的权限。</p>
<p>例如，安装/升级Discuz!和PHPWind论坛程序，仅需要下图所示的权限即可：</p>
<p>在安装/升级完毕后，还可以把CREATE、ALTER、DROP权限去掉，不会影响论坛程序的运行，而且提高了安全性！<br />
Ⅱ、phpMyAdmin的配置</p>
<p>由于OpenBSD中的phpMyAdmin默认是安装在/var/www/phpMyAdmin目录中的，直接使用Nginx是无法访问的，我们需要把它拷贝到Nginx目录下，这样就可以通过浏览器来管理MySQL数据库了。</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
mkdir /var/nginx/html/pma/<br />
cp -rf /var/www/phpMyAdmin/* /var/nginx/html/pma/</p>
<p>修改phpMyAdmin的配置文件，使之可用。</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
vi +17 /var/nginx/html/pma/config.inc.php</p>
<p>将下面这行修改成：</p>
<p>QUOTE:<br />
$cfg['blowfish_secret'] = &#8216;a&#8217;; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */</p>
<p>（仅是加入了字母a而已）</p>
<p>保存退出。<br />
小提示：<br />
上面新建了/var/nginx/html/pma目录来保存phpMyAdmin的文件，目录名很简单。你可以用一个更复杂的目录名来代替，例如：pma2YAY5jRpfFfLXQVm这样的目录名，以防止黑客利用字典攻击等方法渗透你的phpMyAdmin！</p>
<p>你还可以在Nginx的配置文件中，将/var/nginx/html/pma配置成某个虚拟主机的根目录，并限定可以访问这个虚拟主机的IP。这样，就可以在很大程度上提高数据库的安全性了！一个配置示例在下面：</p>
<p>QUOTE:<br />
location / {<br />
allow   192.168.0.0/24;<br />
deny    all;<br />
}</p>
<p>假如平时只是偶尔用到phpMyAdmin，你还可以在用完后删除/var/nginx/html/pma目录，需要用的时候再拷贝过去。</p>
<p>你还可以将以上方法结合起来灵活使用，既建立一个无法被猜测的目录名，又限制IP访问，这样你的系统被黑的机会就会小了很多！<br />
六、强化PHP的安全</p>
<p>OpenBSD软件包中的PHP已经自带了suhosin这个补丁，可以在很大程度上提高PHP脚本的安全。本节主要讨论在php.ini文件中进行相关的设置，进一步提升安全性。具体来说，就是禁用某些危险函数和启用PHP安全模式。</p>
<p>偶一般是把对PHP的所有修改都放在一个单独的文件中进行，包括对PHP参数以及扩展模块的修改，都放在这个文件中一并处理，这样查找、修改和管理会方便许多：</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
vi /var/www/conf/php5/addphp.ini</p>
<p>加入下面的内容：</p>
<p>QUOTE:<br />
; 禁止动态加载模块<br />
enable_dl = Off</p>
<p>; 隐藏PHP信息<br />
expose_php = Off</p>
<p>; 限定可访问目录<br />
open_basedir = /var/nginx/html/</p>
<p>;设定session暂存目录<br />
session.save_path=/var/nginx/sesstmp</p>
<p>; 设定PHP上传文件的临时目录<br />
upload_tmp_dir=/var/nginx/tmp</p>
<p>; 禁用危险函数（注意下面的内容应该是一行，编排的原因分成了多行）<br />
disable_functions = phpinfo,com,shell,exec,system,passthru,error_log,<br />
stream_socket_server,putenv,ini_alter,ini_restore,ini_set,dl,openlog,<br />
syslog,readlink,symlink,link,leak,fsockopen,pfsockopen,proc_open,<br />
popepassthru,escapeshellcmd,escapeshellarg,chroot,scandir,<br />
chgrp,chown,shell_exec,proc_get_status,popen,shmop_close,<br />
shmop_delete,shmop_open,shmop_read,shmop_size,shmop_write</p>
<p>; 启用PHP的安全模式<br />
; PHP在安全模式下运行是用性能换安全。据简单测试，性能下降到50%左右，各位请酌情使用<br />
; 启用安全模式后，某些程序可能受到影响。例如，Discuz!将无法上传附件<br />
safe_mode = On</p>
<p>; pecl-APC只使用16M的共享内存用以加速PHP程序的运行<br />
apc.shm_size=16M</p>
<p>保存退出。<br />
七、强化SSH的安全<br />
Ⅰ、SSH配置文件的修改</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
vi /etc/ssh/sshd_config</p>
<p>跳到最后，加入下面的部分：</p>
<p>QUOTE:<br />
# 使用高位端口，防止黑客扫描22端口。可选范围1024~65535，推荐32768~65535。<br />
Port 58937</p>
<p># 登录时间控制在30秒内<br />
LoginGraceTime 30</p>
<p># 不允许root远程直接登录<br />
PermitRootLogin no<br />
StrictModes yes</p>
<p># 最多允许三次错误<br />
MaxAuthTries 3</p>
<p># 最多允许三个SSH线程<br />
MaxSessions 3</p>
<p># 使用SSH协议2<br />
Protocol 2</p>
<p># 不使用密码认证<br />
PasswordAuthentication no</p>
<p># 使用KEY的方式认证<br />
PubkeyAuthentication yes</p>
<p># KEY文件存放位置<br />
AuthorizedKeysFile      .ssh/authorized_keys</p>
<p>Ⅱ、使用KEY进行验证</p>
<p>下面以Windows环境下PuTTY为例讲解使用KEY验证的方法，Linux/UNIX下与此类似。</p>
<p>首先，从下面的网址下载PuTTY的安装包（Windows）：</p>
<p>http://the.earth.li/~sgtatham/putty/latest/x86/putty-0.60-installer.exe</p>
<p>下完后双击安装，不再赘述。这个软件包自带了下面几个非常实用的软件：</p>
<p>QUOTE:<br />
PuTTYgen:生成KEY；</p>
<p>Pageant:管理KEY；</p>
<p>PuTTY:SSH客户端；</p>
<p>PSFTP:使用SSH上传/下载文件。</p>
<p>下面就来实例讲解用PuTTY的这几个软件对远程主机进行KEY认证和管理的方法。假设我们要在192.168.0.132这个远程主机上使用young_king这个用户名进行KEY认证和登录。<br />
1.生成KEY</p>
<p>启动PuTTYgen，如下图：</p>
<p>在密钥长度栏输入想要的密钥长度，越大越安全。这里以最大的2048位为例，然后点“Generate”按钮，会开始生成KEY，生成过程中需要在下面的空白部分移动鼠标来生成随机数。</p>
<p>KEY生成完毕后，你可以输入一些标识信息，如下图：</p>
<p>还可以在下面的passphrase框内输入“保护码”，注意要输入两遍。“保护码”也就是密码的意思，用来保密私钥的，一定要记住这个哦！</p>
<p>都输入完毕后，点击下面的“Save public key”按钮保存公钥，如下图所示：</p>
<p>然后点击“Save private key”按钮保存私钥，如下图：</p>
<p>这个私钥最好不要保存在电脑上，我们把它拷贝到U盘上，随身带着，这就是我们的“KEY盘”。</p>
<p>要养成每月更换“保护码”的好习惯，更换“保护码”仍然要用到PuTTYgen这个软件，启动后点击“Load”，载入私钥，重新输入“保护码”，再确认一遍，然后点击“Save private key”保存即可！</p>
<p>2.启用KEY</p>
<p>上面生成了公钥和私钥，我们需要把公钥上传到远程主机的用户目录中，就要用到PSFTP这个软件了。启动它，如下图：</p>
<p>输入命令：open 192.168.0.132</p>
<p>接下来，PSFTP会列出远程主机上的RSA指纹以供识别，如下图：</p>
<p>这个指纹可以在远程主机上输入下面的命令查看：</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key</p>
<p>请把这个指纹记在纸上，随身携带，和远程主机连接的时候就拿出来对比一下（这么做主要是为了防止连接被人劫持和指纹被伪造）。</p>
<p>如果上面PSFTP显示的指纹和远程主机上的不一致，那么毫无疑问是伪造的了，直接回车断开连接。如果相符，你可以输入“y”来保存这个指纹到本地计算机上（不推荐），或输入“n”只是这次连接使用。</p>
<p>随后PSFTP会让你输入登录用户名和密码，并自动进入该用户的根目录，如下图（以root为例）：</p>
<p>现在我们要把第一步生成的公钥上传到远程主机上（请把这个公钥复制到C:\Documents and Settings\Administrator目录先，如果你的Windows不是用Administrtor登录的，就替换成你登录用的用户名）。输入命令：put young_king，可以看到，公钥已经上传到/root目录了，见下图：</p>
<p>PuTTY生成的KEY并不能直接使用，需要转换一下。用PuTTY登录（此时上面修改的端口尚未启用，还是默认的22端口），以root身份执行：</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
ssh-keygen -X -f /root/young_king &gt; /home/young_king/.ssh/authorized_keys</p>
<p>这就把公钥成功导入到young_king的目录中了，就可以被young_king这个用户使用了！</p>
<p>导入成功后，要删除多余的公钥：</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
rm /root/young_king</p>
<p>下面介绍几个PSFTP常用的命令：</p>
<p>QUOTE:<br />
open xxx.xxx.xxx.xxx：打开远程主机（xxx.xxx.xxx.xxx为IP或域名）；</p>
<p>put xxxxxxxx：向远程主机上传文件（该文件需要事先拷贝到C:\Documents and Settings\Administrator目录）；</p>
<p>get xxxxxxxx：从远程主机下载文件（下载后保存在C:\Documents and Settings\Administrator目录）；</p>
<p>cd xxxxxx:进入远程主机的相应目录；</p>
<p>exit：退出PSFTP（也可以点右上角的叉关闭，不过不推荐这样做）。</p>
<p>更多的命令可以参看PuTTY的帮助文件，这个帮助写得不错。</p>
<p>3.使用KEY登录</p>
<p>我们上面虽然修改了SSH的配置文件（/etc/ssh/sshd_config），但还没有启用。输入下面的命令启用新的SSH配置，以便我们用KEY登录：</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
kill -HUP `cat /var/run/sshd.pid`</p>
<p>PuTTY提供了一个KEY的管理程序，上面已经提到，是Pageant，我们使用这个程序来进行KEY登录。</p>
<p>启动Pageant，它会自动缩小到任务栏的通知区域，右键单击，选择“Add key”，会弹出个对话框让我们选择。插入上面制作好的“KEY盘”，并选择保存的私钥，会弹出个对话框让我们输入“保护码”，如下图：</p>
<p>如果安装PuTTY时选择了让Pageant关联.ppk文件，则双击私钥可以自动启动Pageant。</p>
<p>输入在生成KEY时输入的“保护码”，私钥就被导入到Pageant中了。再右键单击任务栏通知区的Pageant图标，选择第一项“New session”，Pageant会自动启动PuTTY，等待输入远程主机的相关信息，如下图：</p>
<p>输入IP（或域名）和端口号，点击最下面的“Open”按钮，PuTTY就会登录远程主机了。和PSFTP类似，会弹出个对话框让你确认远程主机的RSA指纹，如下图。同理，指纹不同就表示连接被劫持或指纹被伪造，点“取消”断开连接；指纹相同就点“否”，不保存主机公钥到本地计算机。</p>
<p>随后会让你输入用户名，输入“young_king”，看看，自动就登录上去了！</p>
<p>前面更改SSH配置的时候，已经禁用了root远程登录和使用密码登录，只能使用KEY才能登录进系统。想要维护系统的时候，就用这个KEY登录，再su成root。而且，需要上传/下载文件的时候，就用PSFTP，所有的操作都在SSH连接下进行，还有KEY的保护，安全性不知道提升了多少倍！黑客想要破解真是难于上青天！<br />
Ⅲ、按需启动SSH</p>
<p>我们只在必要的时候启动sshd服务，用完即停止，不给黑客扫描的机会。输入下面的命令：</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
crontab -e</p>
<p>跳到最后，输入下面的内容（中间的空白部分为Tab）：</p>
<p>QUOTE:<br />
# 每天的10:30启动sshd服务<br />
30      10      *       *       *       /usr/sbin/sshd</p>
<p># 10:35即停止sshd服务，也就是说，你只有五分钟的时间可以登录进系统<br />
35      10      *       *       *       kill `cat /var/run/sshd.pid`</p>
<p>保存退出。</p>
<p>上面的时间请酌情修改。sshd服务启动的时间尽量不要太长，5~10分钟应该够了！</p>
<p>Ⅳ、一点安全小常识<br />
私钥请一定保存在安全的地方，不要保存在本地计算机上，并加上足够强度的“保护码”；</p>
<p>本地计算机不要保存远程主机的“指纹”，用一次确认一次（远程主机的指纹保存在注册表的HKEY_CURRENT_USER\Software\SimonTatham\PuTTY项下，可以手动删除）；</p>
<p>不要使用DSA密钥，据说有漏洞的；</p>
<p>不要在公用计算机上连接远程主机，有键盘记录器、木马什么的就麻烦了；</p>
<p>多个远程主机不要使用相同的公钥，最好是使用各自的公钥、私钥；</p>
<p>少用，最好是不用无线网络，加密强度太差，容易被破解；</p>
<p>M$系统下的病毒、木马太多了，推荐客户端转换到Linux/UNIX环境，安全性更高，而且仍然有PuTTY及工具可用；</p>
<p>注意清除本地机器上不必要保留的文件（例如私钥、公钥、主机RSA指纹、C:\Documents and Settings\Administrator目录下的文件等等）。</p>
<p>八、启用Packet Filter防火墙</p>
<p>Packet Filter是非常优秀的包过滤防火墙，OpenBSD核心已经集成了Packet Filter防火墙，不过默认并没有启用，下面我们来启用Packet Filter的强大功能！</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
vi /etc/pf.conf</p>
<p>跳到最后，加入下面的内容：</p>
<p>QUOTE:<br />
# 宏定义<br />
# 请把下面的fxp0换成你自己用的外网网卡，不知道的可以输入ifconfig查看<br />
ext_if=&#8221;fxp0&#8243;</p>
<p># 指定可以使用SSH登录的IP，支持CIDR<br />
admin_add=&#8221;192.168.0.0/24&#8243;</p>
<p># 指定SSH端口。<br />
# 注意，如果在/etc/ssh/sshd_config文件中更改了SSH端口号，这里的也需要同样修改。否则连不上了不要怪偶没有提醒！<br />
ssh_port=&#8221;58937&#8243;</p>
<p># 维持一个持久的表，里面存放的是对本机发动DDoS攻击的IP<br />
table  persist</p>
<p># 选项设定<br />
set require-order yes<br />
set block-policy drop<br />
set optimization aggressive<br />
set loginterface none<br />
set skip on lo0</p>
<p># TCP参数设定<br />
set timeout {interval 3,frag 10}<br />
set timeout {tcp.first 10,tcp.opening 2,tcp.established 600,tcp.closing 20,tcp.finwait 10,tcp.closed 10}</p>
<p># UDP、ICMP及其它参数设定<br />
set timeout {udp.first 20,udp.single 10,udp.multiple 10}<br />
set timeout {icmp.first 10,icmp.error 5}<br />
set timeout {other.first 20,other.single 10,other.multiple 20}<br />
set timeout {adaptive.start 0,adaptive.end 0}</p>
<p># 允许最多有65536个连接<br />
set limit { states 65535, frags 200, src-nodes 65536, tables 65536, table-entries 1048576 }</p>
<p># 包整形<br />
scrub in all<br />
scrub out all</p>
<p># 阻止所有不匹配的包和从DDoS主机来的包<br />
block quick from<br />
block return<br />
block in all<br />
block out all</p>
<p># 防止IP欺骗<br />
antispoof quick for {lo0,$ext_if}</p>
<p># 允许本机访问其他机器<br />
pass out quick on $ext_if inet from $ext_if to any flags S/SA keep state</p>
<p># 允许IPv4地址的客户机访问本地80（www）端口，发起过快连接（DDoS）的主机加入阻止列表。注意是一行，下同<br />
pass in quick on $ext_if inet proto tcp from any to $ext_if port 80 flags S/SA synproxy state (source-track rule,max-src-nodes 200,max-src-states 100,max-src-conn 100,max-src-conn-rate 1000/10,overload  flush global )</p>
<p># 允许IPv6地址的客户机访问本地80（www）端口，发起过快连接（DDoS）的主机加入阻止列表<br />
pass in quick on $ext_if inet6 proto tcp from any to $ext_if port 80 flags S/SA synproxy state (source-track rule,max-src-nodes 200,max-src-states 100,max-src-conn 100,max-src-conn-rate 1000/10,overload  flush global )</p>
<p># 允许管理IP远程连接本机SSH端口<br />
pass in quick on $ext_if inet proto tcp from $admin_add to $ext_if port $ssh_port flags S/SA synproxy state</p>
<p>保存退出。</p>
<p>修改系统配置，使得开机启用PF防火墙：</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
vi /etc/rc.conf.local</p>
<p>跳到最后，加入下面这行：</p>
<p>QUOTE:<br />
pf=YES<br />

<!-- Begin alimama Adserver code -->
<script type="text/javascript"><!--
google_ad_client = "pub-8438729971248494";
/* 728x90, ������ 10-2-7 */
google_ad_slot = "4752526529";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<!-- End Alimama Adserver code -->
<br />
保存退出。</p>
<p>九、系统启动脚本的修改</p>
<p>修改系统启动脚本，使得MySQL、PHP(fastcgi)、Nginx可以在系统启动的时候自动启动，免去手动启动的麻烦。</p>
<p>[Copy to clipboard] [ - ]CODE:<br />
vi /etc/rc.local</p>
<p>跳到最后，加入下面的内容：</p>
<p>QUOTE:<br />
# 启动时校时。这行也可以加在/etc/daily.local文件的最前面，每天零点自动校时<br />
rdate -n 210.72.145.44<br />
# Start MySQL<br />
if [ -x /usr/local/bin/mysqld_safe ] ; then<br />
echo -n &#8216;Starting MySQL&#8230;&#8217;<br />
su -c mysql root -c &#8216;/usr/local/bin/mysqld_safe &gt;/dev/null 2&gt;&amp;1 &amp;&#8217;<br />
echo &#8220;DONE&#8221;<br />
fi<br />
# Start php-fastcgi<br />
if [ -x /usr/local/bin/spawn-fcgi ] ; then<br />
echo -n &#8216;Starting php-fastcgi&#8230;&#8217;<br />
/usr/local/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -C 6 -u www -f /usr/local/bin/php-fastcgi &gt; /var/run/fcgi.pid<br />
echo &#8220;DONE&#8221;<br />
fi<br />
# Start nginx<br />
if [ -x /usr/local/sbin/nginx ] ; then<br />
echo -n &#8216;Starting nginx&#8230;&#8217;<br />
/usr/local/sbin/nginx<br />
echo &#8220;DONE&#8221;<br />
fi</p>
<p>保存退出。</p>
<p>reboot重启，启动后输入top看看，O.N.M.P.环境已经搭建好！</p>
<p>系统启动后，还要把MySQL自带的测试数据库和匿名用户删除，防止被黑客利用。</p>
<p>默认情况下，新安装的MySQL数据库，root密码为空！同样需要第一时间进行设置，方法见下图：</p>
<p>好了，至此，O.N.M.P.环境的搭建已经结束，剩下的就看各位自行发挥了！</p>
<p>写在最后</p>
<p>其实，系统的安全是个整体工程，并不是用上了OpenBSD这个最安全的操作系统就算万事OK，还有很多事情要做。</p>
<p>更多的是需要在日常工作中积累经验，多分析系统整体的运行情况，多关注网络安全方面的内容，这样才能尽可能的打造安全的运维环境。</p>
<p>本手册只是起到抛砖引玉的作用，希望能吸引更多的人来关注系统安全，希望有更多的人能用上OpenBSD这个主动安全的操作系统，希望能推动OpenBSD在国内的更多普及。如此，则幸甚！</p>
]]></content:encoded>
			<wfw:commentRss>http://www.evanjiang.net.cn/archives/1176.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FREEBSD+PF 在6.2上的架设放DDOS 攻击的网站</title>
		<link>http://www.evanjiang.net.cn/archives/1058.html</link>
		<comments>http://www.evanjiang.net.cn/archives/1058.html#comments</comments>
		<pubDate>Wed, 20 May 2009 06:13:36 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[It Tips]]></category>
		<category><![CDATA[freebsd unix]]></category>
		<category><![CDATA[pf]]></category>

		<guid isPermaLink="false">http://www.evanjiang.net.cn/?p=1058</guid>
		<description><![CDATA[<p style="float: right;margin: 4px;">


</p> <p>现网站和外挂经常带arp和ddos攻击,本来用ros做网吧路由器顶不住ddos，只能换FB6.2+pf,前几天用FB6.2+PF，人多时出watchdog timeout,下面是安装步骤，操作一个写一个， </p>
<p>cd /usr/src/sys/i386/conf
cp GERENIC PFOK
ee FFOK </p>
<p>修改并加入下面东东 </p>
<p>ident PFOK
device pf
device pflog
device pfsync
options ALTQ
options ALTQ_CBQ
options ALTQ_RED
options ALTQ_RIO
options ALTQ_HFSC
options ALTQ_PRIQ
options ALTQ_NOPCC
options PANIC_REBOOT_WAIT_TIME=0
options DEVICE_POLLING
options HZ=2000
options IPSTEALTH
# options RANDOM_IP_ID
options TCP_DROP_SYNFIN </p>
<p>config PFOK
cd /usr/src/sys/i386/compile/PFOK
make depend
make
make install
reboot </p>
<p>ee /etc/sysctl.conf
net.inet.ip.forwarding=1
net.inet.ip.fastforwarding=1
net.inet.tcp.drop_synfin=1
net.inet.tcp.sendspace=65536
net.inet.tcp.recvspace=65536
#net.inet.udp.sendspace=65535
net.inet.udp.maxdgram=65535
net.local.stream.sendspace=65535
net.inet.tcp.rfc1323=1
#net.inet.tcp.rfc1644=1
net.inet.tcp.rfc3042=1
net.inet.tcp.rfc3390=1
kern.ipc.maxsockbuf=2097152
kern.maxfiles=65536
kern.maxfilesperproc=32768
kern.polling.enable=1
kern.polling.burst_max=500
kern.ipc.somaxconn=2048
kern.ipc.nmbclusters=32768
net.inet.tcp.delayed_ack=0
net.inet.icmp.icmplim=100
net.inet.icmp.icmplim_output=0
net.inet.tcp.drop_synfin=1

ee /boot/loader.conf
autobootdelay=&#8221;2&#8243; </p>
<p>ee /etc/rc.conf
sendmail_enable=&#8221;NONE&#8221;
sendmail_submit_enable=&#8221;NO&#8221;
sendmail_outbound_enable=&#8221;NO&#8221;
sendmail_msp_queue_enable=&#8221;NO&#8221;
clear_tmp_enable=&#8221;YES&#8221;
update_motd=&#8221;NO&#8221;
tcp_drop_synfin=&#8221;YES&#8221;
#icmp_drop_redirect=&#8221;YES&#8221;
#icmp_log_redirect=&#8221;YES&#8221;
#log_in_vain=&#8221;YES&#8221;
#accounting_enable=&#8221;YES&#8221;
pf_enable=&#8221;YES&#8221;
pf_rules=&#8221;/etc/pf.conf&#8221;
pf_flags=&#8221;"
#pflog_enable=&#8221;YES&#8221;
#pflog_logfile=&#8221;/var/log/pflog&#8221;








这里我就加了句pf_enable=&#8221;YES&#8221; </p>
<p>uname -a
FreeBSD pf.com 6.2-RC1 FreeBSD 6.2-RC1 #0: Thu Nov 23 04:20:46 CST 2006 sshpf@pf.com:/usr/src/sys/i386/compile/PFOK [...]]]></description>
			<content:encoded><![CDATA[<p>现网站和外挂经常带arp和ddos攻击,本来用ros做网吧路由器顶不住ddos，只能换FB6.2+pf,前几天用FB6.2+PF，人多时出watchdog timeout,下面是安装步骤，操作一个写一个， </p>
<p>cd /usr/src/sys/i386/conf<br />
cp GERENIC PFOK<br />
ee FFOK </p>
<p>修改并加入下面东东 </p>
<p>ident PFOK<br />
device pf<br />
device pflog<br />
device pfsync<br />
options ALTQ<br />
options ALTQ_CBQ<br />
options ALTQ_RED<br />
options ALTQ_RIO<br />
options ALTQ_HFSC<br />
options ALTQ_PRIQ<br />
options ALTQ_NOPCC<br />
options PANIC_REBOOT_WAIT_TIME=0<br />
options DEVICE_POLLING<br />
options HZ=2000<br />
options IPSTEALTH<br />
# options RANDOM_IP_ID<br />
options TCP_DROP_SYNFIN </p>
<p>config PFOK<br />
cd /usr/src/sys/i386/compile/PFOK<br />
make depend<br />
make<br />
make install<br />
reboot </p>
<p>ee /etc/sysctl.conf<br />
net.inet.ip.forwarding=1<br />
net.inet.ip.fastforwarding=1<br />
net.inet.tcp.drop_synfin=1<br />
net.inet.tcp.sendspace=65536<br />
net.inet.tcp.recvspace=65536<br />
#net.inet.udp.sendspace=65535<br />
net.inet.udp.maxdgram=65535<br />
net.local.stream.sendspace=65535<br />
net.inet.tcp.rfc1323=1<br />
#net.inet.tcp.rfc1644=1<br />
net.inet.tcp.rfc3042=1<br />
net.inet.tcp.rfc3390=1<br />
kern.ipc.maxsockbuf=2097152<br />
kern.maxfiles=65536<br />
kern.maxfilesperproc=32768<br />
kern.polling.enable=1<br />
kern.polling.burst_max=500<br />
kern.ipc.somaxconn=2048<br />
kern.ipc.nmbclusters=32768<br />
net.inet.tcp.delayed_ack=0<br />
net.inet.icmp.icmplim=100<br />
net.inet.icmp.icmplim_output=0<br />
net.inet.tcp.drop_synfin=1<br />
<span id="more-1058"></span><br />
ee /boot/loader.conf<br />
autobootdelay=&#8221;2&#8243; </p>
<p>ee /etc/rc.conf<br />
sendmail_enable=&#8221;NONE&#8221;<br />
sendmail_submit_enable=&#8221;NO&#8221;<br />
sendmail_outbound_enable=&#8221;NO&#8221;<br />
sendmail_msp_queue_enable=&#8221;NO&#8221;<br />
clear_tmp_enable=&#8221;YES&#8221;<br />
update_motd=&#8221;NO&#8221;<br />
tcp_drop_synfin=&#8221;YES&#8221;<br />
#icmp_drop_redirect=&#8221;YES&#8221;<br />
#icmp_log_redirect=&#8221;YES&#8221;<br />
#log_in_vain=&#8221;YES&#8221;<br />
#accounting_enable=&#8221;YES&#8221;<br />
pf_enable=&#8221;YES&#8221;<br />
pf_rules=&#8221;/etc/pf.conf&#8221;<br />
pf_flags=&#8221;"<br />
#pflog_enable=&#8221;YES&#8221;<br />
#pflog_logfile=&#8221;/var/log/pflog&#8221;<br />

<!-- Begin alimama Adserver code -->
<script type="text/javascript"><!--
google_ad_client = "pub-8438729971248494";
/* 728x90, ������ 10-2-7 */
google_ad_slot = "4752526529";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<!-- End Alimama Adserver code -->
<br />
这里我就加了句pf_enable=&#8221;YES&#8221; </p>
<p>uname -a<br />
FreeBSD pf.com 6.2-RC1 FreeBSD 6.2-RC1 #0: Thu Nov 23 04:20:46 CST 2006 sshpf@pf.com:/usr/src/sys/i386/compile/PFOK i386 </p>
<p>我的pf.conf </p>
<p>#pfctl -e -F all -f /etc/pf.conf </p>
<p>#只重新load过滤规则<br />
#pfctl -F rules -Rf /etc/pf.conf </p>
<p>#pfctl -f /etc/pf.conf # 重新加载pf.conf 设定档<br />
#pfctl -nf /etc/pf.conf # 确认语法有无符合，但不载入<br />
#pfctl -Nf /etc/pf.conf # 只加载 NAT 的设定档<br />
#pfctl -Rf /etc/pf.conf # 只加载防火墙的过滤设定档 </p>
<p>#pfctl -sn # 显示现阶段 NAT 的规则<br />
#pfctl -sr # 显示现阶段过滤的规则<br />
#pfctl -ss # 显示现阶段封包运作状态<br />
#pfctl -si # 显示现阶段过滤封包的统计资料<br />
#pfctl -sa # 显示现阶段所有统计的数据 </p>
<p>ext_if=&#8221;rl0&#8243;<br />
#edu_if=&#8221;"<br />
int_if=&#8221;fxp0&#8243; </p>
<p>ext_addr=&#8221;192.168.1.51&#8243; </p>
<p>int_net=&#8221;172.16.0.0/16&#8243;<br />
ext_net = &#8220;192.168.0.0/16&#8243;<br />
loop = &#8220;{lo0, 127.0.0.1}&#8221;<br />
OpenPorts = &#8220;{21, 22, 80, 88, 4899}&#8221;<br />
InsideManagerIPs = &#8220;{172.16.0.100}&#8221;<br />
InsiteManagerOpenPorts = &#8220;{21, 22, 23, 24, 25, 80, 4899}&#8221;<br />
priv_nets = &#8220;{ 127.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12}&#8221; # 定義符合 RFC 1918 私有IP 部份<br />
tcp_services = &#8220;{ 22, 88, 4899, 123 }&#8221; # 定義 port 22, 113 服務<br />
icmp_types = &#8220;echoreq&#8221; # 定義 tcmp 回應狀態 </p>
<p>## down inactive connection quickly<br />
set optimization aggressive </p>
<p># Normalization: reassemble fragments and resolve or reduce traffic ambiguities.<br />
scrub in all </p>
<p>nat on $ext_if from $int_net to any -> ($ext_if)<br />
#nat on $ext_if from $int_net to $ext_net -> ($ext_if) </p>
<p>#web server map<br />
#rdr pass on $ext_if proto tcp from any to $ext_if port {www,3389,4899,7745} -> $web_server </p>
<p>#&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-以下防DOS攻击&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<br />
#每个IP最大可以有120个非并发的连接（为局域网用户访问本站考虑）<br />
#每个IP最大连接建立的速率小于每秒8个<br />
#单个IP的最大持续连接数 30<br />
#违反以上规则，把这个ip添加到<abusive_hosts>表中<br />
table <abusive_hosts> persist #维持一个持续的表<br />
block in quick from <abusive_hosts> #阻止表中的ip<br />
pass in on $int_if inet proto tcp from any to $int_if flags S/SA keep state \<br />
(source-track rule,max-src-conn 100, max-src-conn-rate 15/3,max-src-states 30,overload <abusive_hosts> flush, src.track 1) </p>
<p>LSassVirusPort = &#8220;{445, 135, 139, 593, 512, 5554, 9996, 9995}&#8221;<br />
block quick on $int_if inet proto tcp from any to any port $LSassVirusPort </p>
<p>BitTorrentPort= &#8220;{ 512, 2049, 4662, 6880, 6881, 6882, 6883, 6884, 6885, 6886, 6887, 6888, 6889, \<br />
6890, 8880, 8881, 8882, 8883, 8884, 8885, 8886, 8887, 8888, 8889, 8890, 6969, 10700, 21881}&#8221;<br />
block quick on $int_if inet proto tcp from any to any port $BitTorrentPort<br />
block quick on $int_if inet proto tcp from any port $BitTorrentPort to any<br />
block quick on $ext_if inet proto tcp from any to any port $BitTorrentPort<br />
block quick on $ext_if inet proto tcp from any port $BitTorrentPort to any<br />

<!-- Begin alimama Adserver code -->
<script type="text/javascript"><!--
google_ad_client = "pub-8438729971248494";
/* 728x90, ������ 10-2-7 */
google_ad_slot = "4752526529";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<!-- End Alimama Adserver code -->
<br />
#gameClientPorts = &#8220;{4002, 2000, 3838, 4410, 4210, 4230, 5005, 4290, 10010 }&#8221;<br />
#GameDenyClients =&#8221;{192.168.128.0/24, 192.168.132.0/24}&#8221;<br />
#GameServerIps = &#8220;{204.251.15.167, 61.152.93.145}&#8221;<br />
#block quick on $int_if inet proto tcp from $GameDenyClients to any port $gameClientPorts<br />
#block quick on $ext_if from $GameServerIps to $GameDenyClients<br />
#block quick on $int_if from $GameDenyClients to $GameServerIps </p>
<p>denyserverips = &#8220;{202.108.193.21}&#8221;<br />
block quick on $int_if from any to $denyserverips </p>
<p>#LSassVirusIp =&#8221;{192.168.1.194}&#8221;<br />
#block quick on $int_if from $LSassVirusIp to any</p>
]]></content:encoded>
			<wfw:commentRss>http://www.evanjiang.net.cn/archives/1058.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction to OpenBSD  Firewall/Gateway  Unix Workstation</title>
		<link>http://www.evanjiang.net.cn/archives/849.html</link>
		<comments>http://www.evanjiang.net.cn/archives/849.html#comments</comments>
		<pubDate>Mon, 23 Mar 2009 14:34:10 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[It Tips]]></category>
		<category><![CDATA[cvs]]></category>
		<category><![CDATA[dns]]></category>
		<category><![CDATA[ftp]]></category>
		<category><![CDATA[openbsd unix]]></category>
		<category><![CDATA[pf]]></category>
		<category><![CDATA[samba]]></category>
		<category><![CDATA[www]]></category>
		<category><![CDATA[Introduction to OpenBSD  Firewall/Gateway  Unix Workstation]]></category>

		<guid isPermaLink="false">http://www.evanjiang.net.cn/?p=849</guid>
		<description><![CDATA[<p>Abstract
This is a quick tutorial on how to set up an OpenBSD 3.1 system. The first part covers setting up a firewall, NAT proxy, time and DHCP server on a system connected to the Internet via broadband like DSL or cable. The second part covers things that would be installed on a desktop machine: graphical [...]]]></description>
			<content:encoded><![CDATA[<p>Abstract<br />
This is a quick tutorial on how to set up an OpenBSD 3.1 system. The first part covers setting up a firewall, NAT proxy, time and DHCP server on a system connected to the Internet via broadband like DSL or cable. The second part covers things that would be installed on a desktop machine: graphical window managers etc. </p>
<p>The reader is not expected to be a Unix expert (why would a Unix expert need this how-to?) &#8212; if you don&#8217;t understand something, or something looks intimidating, read on and come back to it. If something still doesn&#8217;t make sense, let me know. </p>
<p>I don&#8217;t cover what I consider &#8220;advanced&#8221; usage such as tracking -CURRENT or CVS snapshots. If you want to do that, I assume you know which FAQs to read! </p>
<p>This document may be freely reproduced and redistributed under the terms of the GNU Free Documentation License Version 1.1; with the invariant section being this entire document, with no Front-Cover Texts and no Back-Cover Texts. </p>
<p>In other words, if you want to copy this document in its entirety, feel free to do so; if you wish to modify it (as in providing a translation, or taking sections to include in other documents) please send me email. Needless to say, documents that this document links to will have their own copyrights. </p>
<p>New!<br />
I have a shell script that sets up everything mentioned here. This is still experimental but if you try it, please let me know how it goes. Save this file to disk and run it by typing &#8220;sh config31-fw.sh&#8221;. (Doesn&#8217;t handle PPPoE [the beast].) </p>
<p>There is a new section called Tips and Stuff where I put things I&#8217;ve found or written that are useful sysadmin tools. </p>
<p>Introduction<br />
Why OpenBSD? It&#8217;s simple and secure. Your firewall machine should not have lots of things installed on it; therefore no exotic hardware, graphical desktops, X11 servers etc. &#8212; put those on your desktop machine. A simpler system is more robust and more secure; this machine only offers SMTP (email), ssh, ping/traceroute and optionally HTTP (web) to the outside world. And since it&#8217;s running Unix, you can log in to it &#8212; securely &#8212; using ssh from anywhere on the Internet and make any changes you need to. (N.B.: never use telnet to connect to a machine over the Internet! Anyone can eavesdrop and grab important information like passwords. Only use ssh, which encrypts all communication so that eavesdroppers don&#8217;t get any information. And verify those key fingerprints or you leave yourself open to a man-in-the-middle attack. For information do a web search for public key cryptosystems; a good place to start is OpenSSH.) </p>
<p>The utility and security of having this kind of machine: a firewall protects your data and systems from the Big, Bad Internet. When the bad guys are out to vandalise machines on the Internet, MS-Windows machines of various kinds are prime targets because they suck. Er, I mean, Windows is really hard to secure. (Not that an incompetently run Unix machine is any better, of course.) When you dialled in on the phone, your machine was on the &#8216;net for brief periods; with DSL or cable it&#8217;s vulnerable all the time. </p>
<p>This document also describes how to set up an OpenBSD system as a Unix workstation. We will go over setting up X11 (the window system) etc. I assume that you will be using a different machine as your workstation. Important: Unix systems can be set up in various ways; I do things a certain way and that&#8217;s what this document will cover. Other people (wizards and newbies alike) may do things differently. In case it matters, I&#8217;ve been using Unix since 1982, have been a sysadmin on-and-off since 1986 (VAX/BSD, SunOS 4.x, Solaris 2.x, HP/UX, AT&#038;T 3B5 SVR6 etc.) I&#8217;ve been a C programmer since the early 80s. Today I design and implement back-end network servers on Solaris. </p>
<p>This tutorial assumes that you have some familiarity with using Unix: what filenames look like, how to copy and edit files etc. There&#8217;s a decent Unix tutorial on the web. The most important command to remember is man (short for &#8220;manual&#8221;) &#8212; if I say something like &#8220;read the documentation for foobar it means you should type man foobar. One other piece of Unix argot: if you hear someone write select(2) it indicates that the manual for select is in section 2, i.e. you would read the manpage by typing man 2 select. You should also read the OpenBSD documentation: particularly the OpenBSD FAQ. Bookmark that link right now.<br />
<span id="more-849"></span><br />
NAT (Network Address Translation) allows you to connect lots of PCs up to one network connection. When any of the machines inside the firewall wants to make a connection to some server out there on the internet, the firewall/NAT box intercepts that request, and sends the request off as though it came from the firewall/NAT machine. When the reply arrives, it is sent off to the machine that made the connection. Neither the server nor the machines on the inside know that all this is going on. </p>
<p>Aside: NAT is also called PAT, for &#8220;Port Address Translation.&#8221; Also, read this interesting article by HRH Prince Philip, Duke of Edinburgh, on setting up PAT and DHCP on Cisco routers. The whole routergod.com site features many celebrities offering helpful tips on various network issues. </p>
<p>Even if you don&#8217;t want plan on having more than one PC at home, NAT is useful, because it allows the machine running your firewall to be different from your main workstation. You probably want to install fancy hardware and software on your machine; but every additional package installed on a firewall makes it more vulnerable. </p>
<p>Network Address Translation (NAT)</p>
<p>Note: if you only have one machine on the &#8220;inside&#8221;, you don&#8217;t need an ethernet hub; use a crossover cable to connect the two machines directly. This also has the advantage that you can get a full-duplex connection between the machines (a hub only allows a half-duplex connection). </p>
<p>Note: you can buy little NAT/DHCP boxes from various manufacturers for about $150, but where&#8217;s the fun in that? Besides, who knows how strong the security is on those things. With OpenBSD you know you&#8217;re getting the best. </p>
<p>Building the machine<br />
The machine itself: I prefer to build these machines up from individual components rather than buying a pre-made box. That way I can get name-brand supported components, and it works out slightly cheaper since I don&#8217;t have to get exotic video cards, sound cards, CD-ROM drives etc. (Not to mention a Fisher-Price operating system that you will be required to pay for.) </p>
<p>Can you build a PC? Well, no one showed me how, but I&#8217;ve managed to put together about 10 or so systems, so it can&#8217;t be that hard. If you&#8217;ve assembed anything with screwdrivers etc. you&#8217;ll be fine. There are numerous sites on the web that walk you through building a PC. Go do a Google search and read those. I especially like the one at Acme Labs by Jef Poskanzer. There&#8217;s also an excellent motherboard finder at Acme. </p>
<p>Caveat: specific recommendations will be outdated as soon as I write them! I like to use AMD CPUs because I believe Intel is evil and as far as possible I&#8217;d like to not buy their products. I&#8217;d get the current not-top-of-the-line CPU i.e. the one that costs about $50 and a compatible motherboard that costs in the range of $70. I stay away from integrated components because they&#8217;re usually garbage. (For a server that I don&#8217;t use directly I might get integrated video.) Spend about $30-50 on RAM, $30 on ethernet, $60 on an IDE disk, $30 for a case (with power supply). I usually find the best prices on components at Directron and CompuVest (warning: uses Java). These have both been non-sleazy (everything was as described in their catalog and shipping was prompt) in all my dealings with them &#8212; but let me know if you find any evidence of sleaziness. </p>
<p>All these components add up to around $300 &#8212; and that&#8217;s brand-new stuff. If you have any old components lying around, they will be fine. You don&#8217;t need a keyboard, mouse or monitor when the system is up and running &#8212; all maintenance on it can be done over the network. (While you&#8217;re installing the OS on the machine you will need to hook up a keyboard, monitor and CD-ROM drive to it, of course.) </p>
<p>While installing the system, I plug in a spare CD-ROM drive, keyboard and monitor. Change the BIOS settings so that the machine will boot without a keyboard etc. Boot off the OpenBSD 3.1 CD and install the system. All the hardware should be recognised without any problems. (The installation guide booklet that comes with the CDs is excellent.) </p>
<p>The easiest way to install OpenBSD is to buy the distribution on CDs. Although you can install it via the network, buying the CD will help make sure that the OpenBSD project will continue to improve and better the system. If you can afford an outlay of US$40, please buy the CDs from the OpenBSD ordering site. </p>
<p>When you&#8217;re installing OpenBSD, the installer program will ask you for disklabel information (partitions). On a Unix system, a group of files organised together is called a filesystem. The disk is partitioned into various pieces each of which will hold one filesystem. This is the filesystem breakup and partition sizes I&#8217;d use for a 12GB disk (if your disk is bigger, you can just increase the size of /var (for web files) or /home (for your personal files) &#8212; the system will be more than happy with these sizes for /, /tmp and /usr):</p>
<p>/dev/wd0a      100M     /<br />
/dev/wd0d      400M     /tmp<br />
/dev/wd0e      4GB      /var<br />
/dev/wd0g      2GB      /usr<br />
/dev/wd0h      5GB      /home<br />
(The convention is that a is always /, b is swap and c is the whole disk.) Your web files will live in /var, and your other files in /home. </p>
<p>This is all overkill; /usr only needs about 600M or so. Say pad it to 1GB. A 2GB disk would be plenty for the system, but if the cheapest disk you can get is 13GB&#8230;. </p>
<p>Note for Unix newcomers: the disk is named /dev/wd0, and in this case it has 5 partitions with names /dev/wd0a, /dev/wd0d, /dev/wd0e, /dev/wd0g and /dev/wd0h. And the different partitions don&#8217;t get different &#8220;drive letters&#8221; as in some primitive operating systems; once the system is installed, it looks to the user that there is just one bunch of files; Unix will figure out the right thing to do. After the system has been installed and you&#8217;ve booted off the hard disk, log in and (this is important!) type man afterboot; it will remind of some things that you need to do to complete the installation &#8212; pick passwords, create user accounts, check network settings etc. Also, man hier will introduce you to the way the system is organised &#8212; which files live where. In fact, let me say that again: </p>
<p>After the first normal boot of the system, be sure to read these manpages:<br />
$  man afterboot<br />
$  man hier<br />
Also run dmesg(8) to learn more about your hardware and the driver names that OpenBSD uses for them. </p>
<p>Which packages to install? A good starting point would be to accept the defaults. For a desktop system (workstation), you will want all the X11 packages also. I install everything. </p>
<p>There! And make sure you keep reading the manpages &#8212; OpenBSD manpages are a thing of beauty, complete, up-to-date and informative. And also read the OpenBSD FAQ on the web &#8212; much of this information is also found there. </p>
<p>Configuring the network<br />
For my outside connection I have DSL and a static IP number (from Speakeasy &#8212; I recommend them over PacBell etc. &#8212; I&#8217;m so happy I switched). Other DSL options are PPPoE that PacBell likes to set people up with, or DHCP which is what you usually get over cable. A completely bogus DSL installation is the USB device they try to foist on customers with Windows. Danger, Will Robinson! They stink; they&#8217;re unsupported on any free O/S, and even on Windows they work about half the time. </p>
<p>In *BSD the network cards are named according to the driver used. For the Lite-On (DEC Tulip) cards, the driver is called dc, and the Intel EtherExpress Pro is fxp; so my two ethernet cards are dc0 and fxp0. (If you had two cards that both used the dc driver, they would be dc0 and dc1.) For the inside network I use the &#8220;private&#8221; (non-routable) IP numbers 192.168.1.* which will make the inward-facing network card 192.168.1.1. The OpenBSD initialization asks you for IP numbers for the two cards. Enter the appropriate ones &#8211; the IP number your ISP gave you for dc0, and 192.168.1.1 for fxp0. For PPPoE, the outside interface is tun0 and it will figure out its own IP address. If you&#8217;re supposed use DHCP on your DSL or cable connection, type in dhcp. </p>
<p>It is important to remember which network will be the outside and which the inside. If the two cards are identical, the easiest way is to look at the MAC number. Every ethernet card ever made has a unique ID called its MAC number. This will be printed on the card, usually as a sticker. When the kernel boots up, it will print the MAC numbers of each card it finds:</p>
<p>fxp0 at pci0 dev 9 function 0 &#8220;Intel 82557&#8243; rev 0x0c: irq 11, address 00:02:b3:a0:3a:50<br />
dc0 at pci0 dev 10 function 0 &#8220;Lite-On PNIC&#8221; rev 0&#215;20: irq 10 address 00:a0:cc:55:ab:1c<br />
So the card that has a MAC number ending ab1c is dc0; the other is fxp0. (If the two network cards you have are different types, as in this case, there&#8217;s no problem, of course. The kernel bootup messages is still be useful to tell you what names the system is using for them.) </p>
<p>(There&#8217;s some rule about where the cards are plugged in so which one gets number 0 and which no. 1, but I can never remember that.) </p>
<p>PPPoE<br />
The beast! PPPoE is a pain in the ass but ISPs like it because it makes things simpler for them &#8212; they don&#8217;t have to maintain lists of IP numbers. Also, they can run a crappy service and keep dropping the connection and that&#8217;s ok, you&#8217;re expected to reconnect. It&#8217;s the Micros**t philosophy of &#8220;make something really crappy and expect people to just re-start the whole system a couple of times a day.&#8221; It&#8217;s a pain in the ass for us because its MTU is 1492 instead of 1500 which used to require changes on every machine inside the network &#8212; but now thanks to the &#8220;mssfixup&#8221; flag we don&#8217;t have to any more. </p>
<p>The files you will need to change for PPPoE all live in /etc/ppp/. </p>
<p>Configure system files<br />
To set up the system, the files you will be editing are:/etc/rc.conf, /etc/myname, /etc/mygate, /etc/pf.conf, /etc/nat.conf, /etc/*.conf, /etc/hostname.interface, /var/named/*. </p>
<p>Edit /etc/rc.conf. On my servers I run SMTP, Apache, and ssh. In other words, from the outside it handles email, web acess and secure shell for remote logins. For convenience, on the inside I have a private name server (DNS) and NTP server for accurate time. To get sendmail, NTP, httpd, and NAT to work, these are the lines to change: </p>
<p>sendmail_flags=&#8221;-bd -q30m&#8221;      # for normal use: &#8220;-bd -q30m&#8221;<br />
named_flags=&#8221;"                  # for normal use: &#8220;&#8221;<br />
ntpdate_flags=&#8221;put.server.here&#8221; # for normal use: NTP server; run before ntpd starts<br />
httpd_flags=&#8221;"                  # for normal use: &#8220;&#8221; (or &#8220;-DSSL&#8221; after reading ssl(8))<br />
dhcpd_flags=-q                  # for normal use: &#8220;-q&#8221;<br />
pf=YES                          # Packet filter / NAT<br />
ntpd=YES                        # run ntpd if it exists<br />
pf_rules=/etc/pf.conf           # Packet filter rules file<br />
nat_rules=/etc/nat.conf         # NAT rules file<br />
Make sure that /etc/sysctl.conf has this line in it:</p>
<p>net.inet.ip.forwarding=1        # 1=Permit forwarding (routing) of packets<br />
Get the names of NTP servers close to where you are and put that name in the ntpdate value. Here&#8217;s a list of public NTP servers. </p>
<p>Update ssh<br />
Warning: ssh in OpenBSD 3.1 has a bug!<br />
Upgrading openssh to 3.4 is strongly recommended. See the OpenSSH for OpenBSD page for details. In brief, you will download ftp://ftp.openbsd.org/pub/OpenBSD/OpenSSH/openssh-3.4.tgz and execute the following steps (as root): </p>
<p># cd /usr/src/usr.bin<br />
# tar xvfz &#8230;/openssh-3.4.tgz<br />
# cd ssh<br />
# make obj<br />
# make cleandir<br />
# make depend<br />
# make<br />
# make install<br />
# cp ssh_config sshd_config /etc/ssh<br />
# mkdir /var/empty<br />
Using vipw(8) you will add this line to your password file: </p>
<p>sshd:*:27:27::0:0:sshd privsep:/var/empty:/sbin/nologin<br />
Then add this line to /etc/group: </p>
<p>sshd:*:27:<br />
NAT and firewall rules<br />
OpenBSD 3.1 has a new packet filter &#8212; 2.9 used ipf but 3.x has a re-written from scratch one called pf. The details are not important; pf config files are much simpler. I decided that my outside interface would be dc0, and the inside one fxp0. (If you&#8217;re using PPPoE, the outside interface will be tun0.) Firewall rules (they tell the gateway what kind of network traffic should be allowed into the internal network) live in /etc/pf.conf; NAT configuration is in /etc/nat.conf. </p>
<p>Here&#8217;s a sample /etc/pf.conf &#8212; very little is accessible from the outside, but machines on the inside can go out with no restrictions. In your files you&#8217;d replace dc0 and fxp0 with the names of your outward- and inward-facing ethernet cards, respectively.</p>
<p>#####################################################################<br />
#<br />
# IP packet filtering rules (firewall)<br />
# Shamim Mohamed 3/2002</p>
<p># See pf.conf(5) for syntax and examples</p>
<p># If you change this file, run<br />
#    pfctl -R /etc/pf.conf<br />
# to update kernel tables (also run &#8220;pfctl -e&#8221; if pf was not running)</p>
<p># Network interfaces<br />
internal = &#8220;fxp0&#8243;<br />
external = &#8220;dc0&#8243;</p>
<p># Services visible from the outside &#8212; remove any you&#8217;re not using<br />
services = &#8220;{ ssh, http, https, smtp }&#8221;</p>
<p># You shouldn&#8217;t need to change anything below this line<br />
#####################################################################</p>
<p># Non-routable IP numbers<br />
nonroutable = &#8220;{ 192.168.0.0/16, 127.0.0.0/8, 172.16.0.0/12, 10.0.0.0/8,<br />
    0.0.0.0/8, 169.254.0.0/16, 192.0.2.0/24, 204.152.64.0/23, 224.0.0.0/3,<br />
    255.255.255.255/32 }&#8221;</p>
<p># All rules are &#8220;quick&#8221; so go strictly top to bottom</p>
<p># Fix fragmented packets<br />
scrub in all</p>
<p># Don&#8217;t bug loopback<br />
#<br />
pass out quick on lo0 from any to any<br />
pass in quick on lo0 from any to any</p>
<p># Don&#8217;t bother the inside interface either<br />
#<br />
pass out quick on $internal from any to any<br />
pass in quick on $internal from any to any</p>
<p>#####################################################################<br />
#<br />
# First, we deal with bogus packets.<br />
#</p>
<p># Block any inherently bad packets coming in from the outside world.<br />
# These include ICMP redirect packets and IP fragments so short the<br />
# filtering rules won&#8217;t be able to examine the whole UDP/TCP header.<br />
#<br />
block in log quick on $external inet proto icmp from any to any icmp-type redir</p>
<p># Block any IP spoofing atempts.  (Packets &#8220;from&#8221; non-routable<br />
# addresses shouldn&#8217;t be coming in from the outside).<br />
#<br />
block in quick on $external from $nonroutable to any</p>
<p># Don&#8217;t allow non-routable packets to leave our network<br />
#<br />
block out quick on $external from any to $nonroutable</p>
<p>#<br />
#####################################################################</p>
<p>#####################################################################<br />
#<br />
# Now the normal filtering rules<br />
#</p>
<p># ICMP: allow incoming ping and traceroute only<br />
#<br />
pass in quick on $external inet proto icmp from any to any icmp-type { \<br />
    echorep, echoreq, timex, unreach }<br />
block in log quick on $external inet proto icmp from any to any</p>
<p># TCP: Allow ssh, smtp, http and https incoming. Only match<br />
# SYN packets, and allow the state table to handle the rest of the<br />
# connection.<br />
#<br />
pass in quick on $external inet proto tcp from any to any port $services flags S/SA keep state</p>
<p># Of course we need to allow packets coming in as replies to our<br />
# connections so we keep state. Strictly speaking, with packets<br />
# coming from our network we don&#8217;t have to only match SYN, but<br />
# what the hell.<br />
#<br />
pass out quick on $external inet proto tcp  from any to any flags S/SA keep state<br />
pass out quick on $external inet proto udp  all keep state<br />
pass out quick on $external inet proto icmp from any to any keep state</p>
<p># End of rules. Block everything to all ports, all protocols and return<br />
# RST (TCP) or ICMP/port-unreachable (UDP).<br />
#<br />
block return-rst in log quick on $external inet proto tcp from any to any<br />
block return-icmp in log quick on $external inet proto udp from any to any<br />
block in quick on $external all</p>
<p>#<br />
# End of file<br />
#<br />
#####################################################################<br />
Read the pf documentation and understand these rules. </p>
<p>This is the NAT config /etc/nat.conf &#8212; this allows machines on the inside network to transparently make connections to the outside world:</p>
<p>#####################################################################<br />
#<br />
# NAT rules<br />
# Shamim Mohamed 3/2002</p>
<p># See nat.conf(5) for syntax and examples</p>
<p># replace dc0 with external interface name, 192.168.1.0/24 with internal<br />
# network (if different)</p>
<p># nat: packets going out through dc0 with source address 192.168.1.0/24 will<br />
# get translated as coming from 12.34.56.78 (or whatever the external IP no.<br />
# is). State is created for such packets, and incoming packets will be<br />
# redirected to the internal address.</p>
<p>nat on dc0 from 192.168.1.0/24 to any -> dc0</p>
<p># End of file<br />
#####################################################################<br />
The system should already have setup /etc/hostname.dc0 and /etc/hostname.fxp0 (or whatever your network device names are) for you. Each file will have the IP number and netmask. This is what these files would look like:</p>
<p>$ cat /etc/hostname.fxp0<br />
inet 192.168.1.1 255.255.255.0 NONE<br />
$ cat /etc/hostname.dc0<br />
inet 123.45.67.89 255.255.255.0 NONE<br />
(The $ is the prompt; cat types a file out to the output.) If you&#8217;re using DHCP, the outside interface&#8217;s hostname file will say dhcp. </p>
<p>Other important files are /etc/myname &#8212; your hostname &#8212; and /etc/mygate &#8212; your default gateway to the outside world (your ISP told you what this should be &#8212; it&#8217;s usually the same as your IP number except that the last number is replaced with a 1 or 254.) </p>
<p>PPPoe<br />
If you have PPPoE (you unfortunate soul!) things are different. You shouldn&#8217;t have /etc/mygate; and the file describing the outside interface, /etc/hostname.dc0 in my example, will only have one word in it: up. This tells the system to bring up the interface at boot time, but to do nothing else &#8212; pppoe will do the rest. </p>
<p>The main file is /etc/ppp/ppp.conf and this is what it should look like:</p>
<p>default:<br />
 set log Phase Chat LCP IPCP CCP tun command<br />
 set redial 15 0<br />
 set reconnect 15 10000</p>
<p>pppoe:<br />
 set device &#8220;!/usr/sbin/pppoe -i dc0&#8243;<br />
 disable acfcomp protocomp<br />
 deny acfcomp<br />
 set mtu 1492<br />
 set speed sync<br />
 enable lqr<br />
 set lqrperiod 5<br />
 set cd 5<br />
 set dial<br />
 set login<br />
 set timeout 0<br />
 set authname login<br />
 set authkey password<br />
 enable dns<br />
 enable mssfixup<br />
Use your login name and password where indicated. The &#8220;set device&#8221; line tells ppp which physical device to use to talk to the outside world. You also have to tell the system to start PPPoE at boot time. That can be done with this little snippet of shell script: </p>
<p>echo -n &#8220;Trying to establish PPPoE DSL&#8221;; ppp -ddial pppoe<br />
for i in 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0; do<br />
    sleep 5<br />
    echo -n.$i&#8221;<br />
    if /usr/local/sbin/adsl-status>/dev/null; then<br />
        break<br />
    fi<br />
done<br />
echo<br />
/usr/local/sbin/adsl-status<br />
Where adsl-status is a little shell-script that tests to see whether the PPP link has come up properly: </p>
<p>#!/bin/sh</p>
<p>IP=$(/sbin/ifconfig tun0 | awk &#8216;/netmask/{print $2}&#8217;)</p>
<p>if [ -z "$IP" ]; then<br />
   echo &#8220;ADSL link is down.&#8221;<br />
   exit 1<br />
else<br />
   echo &#8220;ADSL is up, IP address $IP&#8221;<br />
   exit 0<br />
fi<br />
Now the question is: where should we put the little loop that tries to get ppp going? The right place to put all these is in /etc/rc.local. However this has the drawback that the outside network hasn&#8217;t been initialised while the rest of the system is coming up, which causes some scary-looking error messages from NAT to be printed at boot time. So I do something a little un-kosher: I put the ppp initialisation in /etc/netstart right at the end: </p>
<p>&#8230;<br />
echo -n &#8216; ADSL&#8230; &#8216;; ; ppp -ddial pppoe<br />
for i in 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0; do<br />
    sleep 5<br />
    echo -n.$i&#8221;<br />
    if /usr/local/sbin/adsl-status>/dev/null; then<br />
        break<br />
    fi<br />
done<br />
echo<br />
/usr/local/sbin/adsl-status<br />
Now remember that each time the PPP link goes up or down, the IPF and NAT rules must be re-done. The files /etc/ppp/ppp.linkup and /etc/ppp/linkdown are scripts that get run by ppp. Here&#8217;s /etc/ppp/ppp.linkup: </p>
<p>MYADDR:<br />
 ! sh -c &#8220;/sbin/route del default&#8221;<br />
 ! sh -c &#8220;/sbin/route add default HISADDR -mtu 1492&#8243;<br />
 ! sh -c &#8220;/sbin/pfctl -F all -R /etc/pf.conf -N /etc/nat.conf -e&#8221;<br />
 ! sh -c &#8220;/usr/local/sbin/ntpd -p /var/run/ntpd.pid&#8221;<br />
And this is /etc/ppp/linkdown: </p>
<p>MYADDR:<br />
 ! sh -c &#8220;/sbin/pfctl -F all -d&#8221;<br />
Configuring email<br />
Sendmail should have been setup automatically since you edited /etc/rc.conf but I&#8217;ve occasionally had to make one change in /etc/mail/sendmail.cf: </p>
<p>Djmy-domain-name.com<br />
(If you don&#8217;t own a domain, or plan on having it point to your DSL machine, you don&#8217;t need sendmail.) </p>
<p>You should have a normal user account that you&#8217;re going to use (never log in as root! Always use su or sudo). Administrative email should be forwarded to you; if your normal username is zippy edit /etc/mail/aliases and make sure you make the appropriate lines look like this:</p>
<p># Well-known aliases &#8212; these should be filled in!<br />
root: zippy<br />
manager: zippy<br />
dumper: zippy<br />
One thing you should consider is being an email handler for friends. My DSL service goes down too often &#8212; every few months. This is too unreliable for my tastes. What I do is collaborate with friends to accept and queue email for them, and they do the same for me. Example: for my domain foo.com the primary mail exchanger is gateway.foo.com, the OpenBSD firewall/gateway. A friend of mine has bar.com, and his email gateway is gateway.bar.com. I set up a secondary mail exchanger in my domain records as gateway.bar.com. If my DSL line gateway.foo.com goes down and someone out there wants to send email to me at foo.com, her machine will use gateway.bar.com instead and email will wait on that machine until my machine is back on the network. I want to perform the same service for my friend &#8212; if gateway.bar.com is down, I want people to be able to send my machine the email destined for bar.com and fubar.org (another friend&#8217;s domain). This goes in the file /etc/mail/relay-domains on my gateway box: </p>
<p>bar.com<br />
fubar.org<br />
Now the machine will accept email for my friends&#8217; domains bar.com and fubar.org as well as for itself and forward their messages on. If the machine it&#8217;s trying to forward to is down, it will put them in the queue and keep re-trying for a while. (My friend at bar.com does similar things to his /etc/mail/relay-domains.) </p>
<p>Setting up DNS<br />
You probably shouldn&#8217;t be running the primary DNS server for your domain on your DSL box; DSL may not be reliable enough for that. Get someone else to do it for you for free, like http://www.zoneedit.com/. </p>
<p>However, it is nice to have a local private DNS because lots of daemons (services that run in the background, like the web server) like to do reverse lookups of IP numbers, so we should have a DNS server for the private network. Also, this installation will give you a caching nameserver which should improve your browsing speed. </p>
<p>The files live in /var/named. Assuming your domain is called fake-domain.org, edit named.boot and add these lines:</p>
<p>primary fake-domain.org                 fake-domain.db<br />
primary 1.168.192.in-addr.arpa          fake-domain.rev</p>
<p>; your static IP number, reversed<br />
primary 89.67.45.123.in-addr.arpa      dsl.rev</p>
<p>; remember to add your ISP&#8217;s nameservers here!<br />
forwarders			1.2.3.4 5.4.3.2<br />
(Anything starting with a semicolon is a comment.) Here fakedomain.org can be a real domain you have or a fake; and instead of 89.67.45.123 use your static IP but reversed i.e. you would use that line if your IP number were 123.45.67.89. And change the IP numbers on the forwarders line to the nameservers your ISP told you to use. </p>
<p>There are three files you need to create. The first is /var/named/namedb/fake-domain.db:</p>
<p>@       IN      SOA     gateway.fake-domain.org.     root.fake-domain.org.<br />
(<br />
                                14      ; Serial<br />
                                10800   ; Refresh<br />
                                3600    ; Retry<br />
                                604800  ; Expire<br />
                                86400 ) ; Minimum</p>
<p>        IN      NS      gateway.fake-domain.org.</p>
<p>gateway IN      A       192.168.1.1<br />
libelle IN      A       192.168.1.2<br />
discus  IN      A       192.168.1.4<br />
ventus  IN      A       192.168.1.3<br />
wander  IN      A       192.168.1.5<br />
brad    IN      A       192.168.1.12<br />
jack    IN      A       192.168.1.13</p>
<p>; your static IP number<br />
dsl     IN      A       123.45.67.89</p>
<p>www     IN      CNAME   dsl<br />
mail    IN      CNAME   dsl<br />
In this network, there are six machines on the inside and those are their names and IP Number assignments. The OpenBSD gateway machine is named &#8220;gateway&#8221;. Change these entries to names of the machines on your private network. You can give them any IP number that starts with 192.168.1. Of course if you have three machines on your network, there will only by three entries.) </p>
<p>This is the second file you need to create, /var/named/fake-domain.rev:</p>
<p>@       IN      SOA     gateway.fake-domain.org.     root.fake-domain.org.<br />
(<br />
                                14      ; Serial<br />
                                10800   ; Refresh<br />
                                3600    ; Retry<br />
                                604800  ; Expire<br />
                                86400 ) ; Minimum</p>
<p>        IN      NS      gateway.fake-domain.org.</p>
<p>1       IN      PTR     gateway.fake-domain.org.<br />
2       IN      PTR     libelle.fake-domain.org<br />
3       IN      PTR     ventus.fake-domain.org<br />
4       IN      PTR     discus.fake-domain.org.<br />
5       IN      PTR     wander.fake-domain.org.<br />
12      IN      PTR     brad.fake-domain.org.<br />
13      IN      PTR     jack.fake-domain.org.<br />
(Those trailing dots are important.) And here&#8217;s the third, /var/named/namedb/dsl.rev:</p>
<p>@       IN      SOA     gateway.fake-domain.org.     root.fake-domain.org.<br />
(<br />
                                14      ; Serial<br />
                                10800   ; Refresh<br />
                                3600    ; Retry<br />
                                604800  ; Expire<br />
                                86400 ) ; Minimum</p>
<p>        IN      NS      gateway.fake-domain.org.</p>
<p>        IN      PTR     dsl.fake-domain.org.<br />
PPPoE<br />
Yes, again more stupid special cases for PPPoE. For one thing, your IP address from the outside keeps changing so all the stuff about dsl.rev doesn&#8217;t apply. However, more important: you don&#8217;t know what your ISP&#8217;s DNS servers are! And they could change which machines you&#8217;re supposed to use each time you connect! What you have to do is: connect &#8220;by hand&#8221; one time, and see which DNS servers you got. After ppp.conf has been written, you can run ppp -ddial pppoe and pray. If all goes well, ifconfig tun0 should show you two lines: </p>
<p>$  /sbin/ifconfig tun0<br />
tun0: flags=11<UP,POINTOPOINT> mtu 1492<br />
        inet 63.201.32.40 &#8211;> 63.201.39.254 netmask 0xff000000<br />
That means everything worked. Now look at /etc/resolv.conf &#8212; there should be one or more lines in there that say which nameservers should be used. Put these IP numbers in the forwarders line in /var/named/named.boot. </p>
<p>One other wrinkle: the /etc/resolv.conf that ppp makes for you doesn&#8217;t know about your domain, or that you&#8217;re running a nameserver on your machine. To get around these problems, I created another file /etc/resolv.conf-working: </p>
<p>nameserver 192.168.1.1<br />
lookup file bind<br />
search fake-domain.org<br />
In /etc/ppp/ppp.linkup I tell it to overwrite the created resolv.conf with this one: </p>
<p> ! sh -c &#8220;cp /etc/resolv.conf-working /etc/resolv.conf&#8221;<br />
(Add that to the end of the file that you&#8217;ve already created.) This allows all programs running on the machine to be able to use all the good things about a local caching nameserver &#8212; things like being able to refer to internal hosts by short name etc. </p>
<p>Other machines on the internal network<br />
Go to the other machines on your network (the ones inside your firewall) and set them up with the static IP numbers you assigned above, e.g. the machine wander gets an IP number of 192.168.1.5. All the machines should use 192.168.1.1 for the gateway and use 192.168.1.1 for the DNS server. For more details on DNS, read the excellent O&#8217;Reilly book &#8220;DNS and BIND&#8221;; for more on setting up slightly more complex DNS servers than the one described here, go to the OpenBSD &#8212; DNS site maintained by Samiuela LV Taufa. </p>
<p>Setting up DHCP<br />
Above in the DNS setup all internal machines are assigned their own IP numbers. Running DHCP allows guest machines to hook up to the network without fuss. Depending on your comfort level with setting up your other machines, you might also prefer to use DHCP over assigning static IPs.This is what /etc/dhcpd.conf should look like:</p>
<p>#       $OpenBSD: dhcpd.conf,v 1.1 1998/08/19 04:25:45 form Exp $<br />
#<br />
# DHCP server options.<br />
# See dhcpd.conf(5) and dhcpd(8) for more information.<br />
#</p>
<p># Network:              192.168.1.0/255.255.255.0<br />
# Domain name:          my.domain<br />
# Name servers:         192.168.1.3 and 192.168.1.5<br />
# Default router:       192.168.1.1<br />
# Addresses:            192.168.1.32 &#8212; 192.168.1.127<br />
#<br />
shared-network LOCAL-NET {<br />
        option  domain-name &#8220;fake-domain.org&#8221;;<br />
        option  domain-name-servers 192.168.1.1;</p>
<p>        subnet 192.168.1.0 netmask 255.255.255.0 {<br />
                option routers 192.168.1.1;</p>
<p>                range 192.168.1.32 192.168.1.127;<br />
        }<br />
}<br />
This will allow up to 96 machines on your internal network, which should be more than sufficient. Create an empty temporary file for dhcpd to use:<br />
# touch /var/db/dhcpd.leases<br />
If you make any changes to this file, run dhcpd fxp0 (or whatever your inside network is). (Or you can reboot the machine &#8212; but that&#8217;s the Windows way, in the Unix world we prefer to never reboot any machines.)<br />
Install &#8220;ports&#8221;<br />
&#8220;Ports&#8221; is a *BSD term for a tree of Makefiles for all the software out there that&#8217;s not part of the standard install. I recommend this highly. It is on CD No. 3 of the OpenBSD 3.1 CD-ROM set as ports.tar.gz. Please read the Ports and Packages page on the OpenBSD web site. You install it by typing (as root) </p>
<p># mount /dev/cd0a /mnt<br />
# cd /usr<br />
# tar xzf /mnt/ports.tar.gz<br />
Once you&#8217;ve done this, if you want to install a package, you cd to the appropriate directory and simply type make all install &#8212; it will ftp the source from the appopriate site, handle all dependencies, apply any required patches, configure, build and install the tool. </p>
<p>How do you find the appropriate directory to go to? You can guess at where it might be (look around in /usr/ports to get an idea for the layout etc.). But remember: locate(1) is your friend. </p>
<p>If you have the disk space (about 500 MB), I strongly recommend that you install the source code to the system also. (The source is also on CD No. 3.) </p>
<p># mount /dev/cd0a /mnt<br />
# cd /usr/src<br />
# tar xzf /mnt/src.tar.gz<br />
Getting time from the Internet<br />
Set up NTP so that your machine will always have accurate time. Pick two servers from the public NTP server list and make sure /etc/ntp.conf looks like this: </p>
<p>server ntp.server.first<br />
server ntp.server.second<br />
Since xntpd is not part of the standard install, you have to compile xntpd from source. </p>
<p># cd /usr/ports/sysutils/xntpd<br />
# make all install<br />
The tools will be installed into /usr/local/sbin/ntpd. </p>
<p>Run ntpdate -b server where you pick a server from the list &#8212; this will perform a coarse adjustment of the system clock. The next time the machine reboots, it will sync your clock and record how much your clock drifts. </p>
<p>Setting up other hosts with NTP<br />
On Unix hosts, use the appropriate NTP client; on Linux, it&#8217;s xntpd. Set them up to use 192.168.1.1 as the NTP server. On Windows, use AboutTime &#8212; a free NTP client. In its configuration make sure it uses only SNTP as the protocol, with 192.168.1.1 as the server. Put AboutTime in the Startup folder so it&#8217;s started automatically. </p>
<p>For more details, go to Robert Mooney&#8217;s OpenBSD NTP site. </p>
<p>Tips and Stuff<br />
I have a useful shell script called pkg_install that&#8217;s a front-end to pkg_add &#8212; here&#8217;s an example of it being used:<br />
# pkg_install tex<br />
These files match:<br />
gettext-0.10.40.tgz<br />
jadetex-3.11.tgz<br />
latex2html-97.1.tgz<br />
php4-4.0.6p1-gettext-imap-mhash-no_x11-mcrypt-mysql.tgz<br />
php4-4.0.6p1-gettext-imap-mhash-no_x11-mcrypt-postgresql.tgz<br />
php4-4.0.6p1-gettext.tgz<br />
teTeX_texmf-1.0.2.tgz<br />
texi2html-1.64.tgz<br />
textutils-2.0.tgz<br />
# pkg_install -n 4 texi<br />
Using ftp5.usa.openbsd.org/pub/OpenBSD<br />
+ pkg_add -v ftp://ftp5.usa.openbsd.org/pub/OpenBSD/3.1/packages/i386//texi2html-1.64.tgz<br />
Trying to fetch ftp://ftp5.usa.openbsd.org/pub/OpenBSD/3.1/packages/i386//texi2html-1.64.tgz.<br />
Extracting from FTP connection into /var/tmp/instmp.BVMJM29414<br />
>>> ftp -o &#8212; ftp://ftp5.usa.openbsd.org/pub/OpenBSD/3.1/packages/i386//texi2html-1.64.tgz<br />
&#8230;<br />
It has a list of all the pre-compiled packages that are available. You type in a string and it installs the package. If more than one name matches, it shows you their names. (It uses egrep(1) so you can use regular expressions.) Save it to /usr/local/bin. It handles dependencies by recursively installing them also. </p>
<p>New in this version is in -n flag. The script has a list of mirrors, and this option picks one of the mirrors. (Currently in progress: it needs bash, and it needs some error checking but it works.) Don&#8217;t forget to edit the file &#8212; read http://www.openbsd.org/ftp.html and choosea list of mirrors closest to you. </p>
<p>Setting up a CVS server<br />
(This section is probably not of interest to most people; you only need this if you want to set up a cvs server so you can put files you&#8217;re working on under source control. So it&#8217;s a little terse too.) </p>
<p>The changes I made: added a user and group named cvs. All users of CVS should be in the cvs group. Create a directory for the repository: I put it in /var/cvsroot, you might put it in /home or wherever. This directory should be group writable (group cvs). Add a line to /etc/services: </p>
<p>      cvspserver	2401/tcp		# CVS pserver<br />
Add this line to /etc/inetd.conf:<br />
      cvspserver	stream	tcp	nowait	root	/usr/bin/cvs cvs -f &#8211;allow-root=/var/cvsroot -T /var/tmp pserver<br />
The server uses /var/tmp as its temp directory instead of /tmp since my root partitions are small, but I always make /var large. Now run cvs init in the cvs repository and restart inetd. Voila! Import your directory of files from a client machine, using a pserver CVSROOT and cvs import. </p>
<p>When importing a large set of files, you might want to put a .cvswrappers file in the directory you&#8217;re importing so CVS won&#8217;t try to put RCS ID strings inside your JPEG files etc. The syntax is: </p>
<p>      *.jpg -k &#8216;b&#8217;<br />
      *.png -k &#8216;b&#8217;<br />
      *.tgz -k &#8216;b&#8217;<br />
Coming soon: using ssh for CVS_RSH.<br />
Setting up X11<br />
You did select the packages xbase, xshare, xfont, and xserv when you installed OpenBSD, I hope? If not, never fear; you can install them directly off the CD: </p>
<p># mount /dev/cd0a /mnt<br />
# cd /<br />
# tar xzvpf /mnt/3.1/i386/xbase31.tgz<br />
# tar xzvpf /mnt/3.1/i386/xserv31.tgz<br />
# tar xzvpf /mnt/3.1/i386/xshare31.tgz<br />
# tar xzvpf /mnt/3.1/i386/xfont31.tgz<br />
etc. The X11 package for ix86 systems is called XFree86; visit their website for more information. Now run xf86cfg. (If the command is not found, you probably don&#8217;t have /usr/X11R6/bin in your PATH environment variable.) Of course this is not something you can do over a network login; you have to be sitting at the machine, with a monitor, keyboard and mouse actually plugged in. You should have your video card and monitor specs available. Follow the instructions to setup XFree86. More information is on the Configuring XFree86 page on the Xfree86 site.<br />
Installing a Desktop<br />
Many people also install a desktop suite such as KDE or Gnome. I prefer KDE of the two. There is nothing special about KDE (or Gnome); it&#8217;s just a set of packages to be installed. There are two versions of KDE available, KDE 2.2 and KDE 3.0. Decide which one you want to run, and install those packages. (KDE2 and KDE3 cannot co-exist on the same system.) </p>
<p>These are the KDE2 packages: </p>
<p>$ pkg_info -a | egrep kde<br />
kdelibs-2.2.2      X11 toolkit, libraries<br />
kdeartwork-2.2.2   X11 toolkit, additional artwork<br />
kdegraphics-2.2.2  X11 toolkit, graphics applications<br />
kdelibs-doc-2.2.2  X11 toolkit, libraries documentation<br />
kdebase-2.2.2      X11 toolkit, basic applications<br />
kdenetwork-2.2.2   X11 toolkit, network applications<br />
kdetoys-2.2.2      some useless kde applications<br />
And for KDE3, the corresponding packages are:<br />
kdeaddons-3.0.tgz<br />
kdeartwork-3.0.tgz<br />
kdebase-3.0.tgz<br />
kdeedu-3.0.tgz<br />
kdegames-3.0.tgz<br />
kdegraphics-3.0.tgz<br />
kdelibs-3.0.tgz<br />
kdenetwork-3.0.tgz<br />
kdetoys-3.0.tgz<br />
kdeutils-3.0.tgz<br />
koffice-1.1.1-kde3.tgz<br />
There are lots of I18N packages also, kde-i18n-*-3.0.tgz.<br />
Display managers xdm and kdm<br />
You may want to run a display manager like xdm or kdm. (A display manager is the program that gives you a graphical login display instead of a plain text message.) The config file for kdm is /usr/local/share/config/kdm/kdmrc; the xdm config file lives in /etc/X11/xdm/xdm-config. Edit /etc/rc.conf and set xdm_flags to an empty string (in quotes) to make xdm run on startup. (If you installed KDE, it will be kdm that&#8217;s started.) If you installed KDE3, add it to the list of available logins in kdmrc: in the [X-*-Greeter] section, look for the SessionTypes line and add &#8220;KDE3&#8243; to the list. </p>
<p>Setting up XDMCP<br />
If you have an X-Terminal (like the Sun Ray, or the ones NCD used to make) or run eXceed on Windows platforms, you may want to allow X11 logins to your OpenBSD machine from eXceed or the X-Terminal. The protocol that allows this is called XDMCP; to enable it: if using xdm, edit /etc/X11/xdm/Xaccess and remove the &#8216;#&#8217; from the first column of this line:</p>
<p>#*                                      #any host can get a login window<br />
Note: we don&#8217;t allow any X11 or XDMCP messages to go across our firewall. Only hosts inside the firewall can get a login screen.<br />
Also edit xdm-config and comment out this line by putting a &#8216;!&#8217; character in the first column:</p>
<p>DisplayManager.requestPort:     0<br />
If using kdm, edit /usr/local/share/config/kdm/kdmrc and look for the [Xdmcp] section. Uncomment lines so it looks like this:<br />
[Xdmcp]<br />
# Whether KDM should listen to XDMCP requests. Default is true.<br />
Enable=true<br />
# The UDP port KDM should listen on for XDMCP requests. Don&#8217;t change the 177.<br />
Port=177<br />
(followed by other stuff.)<br />
Amusements<br />
People like to do things like rip CDs to Ogg Vorbis or MP3 and listen to those files. I use grip as a front-end to rip music to Ogg Vorbis files, and xmms (package name xmms-vorbis) to listen to them. I use Gnu LilyPond and TeX/LaTeX (package teTeX_texmf) to typeset documents and music. The LaTeX files can be converted to HTML with latex2html. You can run Linux programs if you install the redhat_base, redhat_motif, and rpm packages. (The Linux version of Opera, the web browser, runs fine.) </p>
]]></content:encoded>
			<wfw:commentRss>http://www.evanjiang.net.cn/archives/849.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Step-by-Step Guide to Building an OpenBSD PPPoE Gateway, with Firewall</title>
		<link>http://www.evanjiang.net.cn/archives/845.html</link>
		<comments>http://www.evanjiang.net.cn/archives/845.html#comments</comments>
		<pubDate>Mon, 23 Mar 2009 14:21:18 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[dns]]></category>
		<category><![CDATA[ftp]]></category>
		<category><![CDATA[mail]]></category>
		<category><![CDATA[openbsd unix]]></category>
		<category><![CDATA[pf]]></category>
		<category><![CDATA[shell]]></category>
		<category><![CDATA[www]]></category>
		<category><![CDATA[Building  OpenBSD PPPoE Gateway]]></category>
		<category><![CDATA[with Firewall]]></category>

		<guid isPermaLink="false">http://www.evanjiang.net.cn/?p=845</guid>
		<description><![CDATA[<p>Introduction
Why would one install his own personal gateway to the Internet? Because it is quite easy to do. And also because it simply is the most reliable, safest way to connect machines to a dedicated xDSL modem. Moreover, we can stash a whole bunch of useful features in such a little box. Here is a [...]]]></description>
			<content:encoded><![CDATA[<p>Introduction<br />
Why would one install his own personal gateway to the Internet? Because it is quite easy to do. And also because it simply is the most reliable, safest way to connect machines to a dedicated xDSL modem. Moreover, we can stash a whole bunch of useful features in such a little box. Here is a list: </p>
<p>PPPoE Gateway<br />
PPPoE is a curious beast forced down our throats by some DSL providers. On one side, it does not really break anything, has low overhead and allows you to change IP adresses very easily &#038; quickly. On the other side, it sucks big time because it does add overhead to the IP packets, is proprietary, non-standard, forces you to change IP adresses unpredictably, and is unsupported in most operating systems. A good PPPoE gateway simply hides PPPoE from the machines on your internal network. It makes life much easier because you don&#8217;t have to install any special &#8220;access manager&#8221; software on your windoze boxen. They will just work (provided you set their IP address correctly). </p>
<p>Firewall<br />
A firewall is quite mandatory for any machine directly connected to the Big Bad Internet. We want an industrial-strength stateful inspection firewall and this is what we&#8217;ll get. </p>
<p>NAT (Network Adress Translation)<br />
The name seems complex, but it is really quite simple: this allows the gateway machine to act on the internet on behalf of all the machines located on the intranet (your internal home network). Even though you might have two, three or even ten computers on your local network, a NAT equipped gateway will hide them to outside observers. They will only see a single very busy machine, with a single IP address. </p>
<p>DNS (Domain Name Service) cache<br />
Having your own DNS server will lower the latency of getting DNS translations for all the machines on your intranet. This will not really decrease the traffic on your DSL modem by a large percentage, but it will improve the quality of the &#8220;internet experience&#8221; on your local network. </p>
<p>Dynamic DNS tracker<br />
Free dynamic DNS services are extremely useful to xDSL customers. They allow you to have your very own domain name, free of charge, which will follow in real-time your IP address changes. The catch is that the top-level part of your domain must be one of their supplied choices. They are not that bad, really&#8230; Personally, I use DYNDNS but any of the multiple free dynamic DNS providers out there will do just fine. Simply make sure they have a client &#8220;updater&#8221; which can compile and run under OpenBSD. </p>
<p>WEB server<br />
Most ISP&#8217;s only allow a few megabytes of disk for web service. Moreover, they never give you direct access to the web logs. Having your own web server allows you the luxury of using all the disk space you want, plus the added advantage of complete control over the web service (cgi-bin) and its logs. Moreover, OpenBSD comes with a crypto-enabled version of Apache and all the tools you need to create RSA-keyed certificates. </p>
<p>Mail server<br />
Have you ever wanted to create a temporary email address just to receive some password? Or simply wanted addresses tailored for specific domains of interest? These are only a few of the many advantages of having your own mail server. </p>
<p>NTP server<br />
The Network Time Protocol allow you to synchronize the gateway&#8217;s clock to one of the numerous atomic time references available on the internet. Moreover, the same program is also used as a local time server, so that all your intranet machines can themselves synchronize their clocks to the gateway&#8217;s clock. NTP synchronizations are made in tiers, like this, in order to lower the burden on the public time servers. </p>
<p>This page is for all those of you who have are lucky enough to enjoy a dedicated xDSL connection and would like to have a small firewall installation. In my search for the holy grail, i found the answer to most of my wishes in the OpenBSD package. This step-by-step guide is a collection of notes taken while I was installing the thing. They are intended to help my friends do their own setups very quickly and easily, without having to bug me too much <img src='http://www.evanjiang.net.cn/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  They should help you too.</p>
<p>Constructive comments can be sent there &#8230; Have fun and GOOD LUCK!</p>
<p><span id="more-845"></span><br />
Getting some hardware<br />
The first thing to think about when one embarks on the firewalling adventure is to establish on what hardware you are going to install the thing. This seems unimportant at first, but don&#8217;t forget that this box will be turned on 24/7, so the components you use must be reliable.</p>
<p>What are the minimum requirements? My system uses about 50% of its CPU to support Sympatico&#8217;s ADSL rate (around 900 kbps). It is built with the following components:</p>
<p>An ancient 486 motherboard (with an ISA bus) given to me by a friend (thanks Christian!). It runs at 66 MHz.<br />
32 MB of brand new RAM i bought for it.<br />
A 200 MB hard disk, which was dying after about 1 year of faithful use (it came with the motherboard). This disk was recently replaced with the cheapest brand new drive i could find. I didn&#8217;t know they still made those slow 3600 RPM drives <img src='http://www.evanjiang.net.cn/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  Anyway, the old drive is kept as a kind of extreme emergency backup.<br />
Two ISA-bus ethernet cards. I&#8217;ll talk more about this later.<br />
A CD-ROM drive. Very optional, but can make life easier.<br />
A &#8220;home&#8221; grade hub &#038; cat5 cabling. This is not strictly necessary if you&#8217;ll have only one machine connected to your firewall: you can make do with a special &#8220;crossover&#8221; cat5 cable instead. The cable that comes with xDSL modems is usually (always?) a crossover cable. Anyway, for two or more machines, the hub is mandatory. Small hubs can be bought for a very reasonable price (~40$ cdn).<br />
or<br />
Alternatively, many older ethernet cards come with a BNC female connector. This can be used to connect the machines on your network with coax cables, without any hub. However, be warned that a 10base-2 network must follow certain rules if you want it to work flawlessly. Follow them.<br />
This gives a good approximation of what you need. The MOST important part is the RAM. Make absolutely sure that whatever RAM you use is reliable. Old boxen were usually setup to run Windoze, and it was not a big deal if the machine had flaky RAM because of the way Windoze works&#8230;</p>
<p>OpenBSD (like any real OS out there) is much less tolerant of flaky RAM, because it actually uses all of it. It will crash quite quickly if your RAM is marginal, probably within 5-10 minutes. You have been warned.</p>
<p>Finally, the OpenBSD hardware list is there. Try to make sure that whatever hardware you use in your gateway box figures on that list. It&#8217;s a long list <img src='http://www.evanjiang.net.cn/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>The ethernet cards<br />
There is a boring thing of which we must talk about here. You see, there are many kinds of ethernet cards, and you must make sure you have the right ones for your machine. If you have a PCI-based machine, then all is well. Whatever ethernet card you put in there will probably be supported by OpenBSD. However, you must be a bit more careful if you have an ISA-based machine.</p>
<p>It is most likely that your box will not have any ethernet cards to start with since most people did not have networks at home in the pre-historic era of 4 years ago. You need two cards. One will be connected to the DSL modem (the big, bad outerworld), while the other is connected to your internal network hub (your intranet). The gateway&#8217;s job will be to pass (or block) packets between those two network cards. For security, its very important that the outside world packets cannot reach directly any of the intranet machines. This is the reason why we use two ethernet cards: complete logical and electrical isolation. Why so much isolation? For example, if someone(s) were launching a full (distributed or not) denial of service attack on your gateway box, its internet-connected ethernet card would be extremely busy, but your intranet would see nothing of this. While any communication with the outside world would probably fail, at least your intranet machines would still be able to talk to each other.</p>
<p>ISA cards use dedicated I/O ports and IRQ&#8217;s in your machine. Those must be setup either with jumpers directly on the card, or with a special DOS program if the card is of the more recent &#8220;Plug &#038; Play&#8221; type. This DOS program is always supplied with the card, when purchased brand new.</p>
<p>If your card is Plug&#038;Play, you must disable the Plug&#038;Play, and program specific I/O port and IRQ values with the setup software that comes with the card. Make sure that you program both cards with different sets of I/O ports and IRQs! Otherwise they will battle each other for cycles on the bus and the result will not be pretty. Once you have set the parameters on the card it will remember them and you don&#8217;t have to reprogram anything later on, even if the computer is turned off.</p>
<p>It is good at this point to know a few magic numbers:</p>
<p>Card Type I/O #1 IRQ #1 Mem #1 I/O #2 IRQ #2 Mem #2<br />
NE2000 (ne) 0&#215;240 9 &#8212; 0&#215;300 10 &#8212;<br />
SMC WD-8003 (we) 0&#215;280 9 0xd0000 0&#215;300 10 0xcc000 </p>
<p>For example, i use two cards made by AOpen: the model ALN-101. They are Plug&#038;Play and use the NE2000 chip. The first one is setup at I/O port 0&#215;240, IRQ 9. It is known as &#8220;ne0&#8243; in the GENERIC openBSD kernel. The second one is set at I/O port 0&#215;300, IRQ 10. It is known as &#8220;ne1&#8243;. If the cards were programmed differently, the GENERIC kernel would not recognize them &#8220;out of the box&#8221; and you would have to re-configure the kernel. It can be done, but its much easier to setup the hardware once than re-configure the kernel every time it gets upgraded.</p>
<p>Some of you might have problems setting the card to an arbitrary combination of IO port and IRQ number. This is allright, just let the card decide what it wants and simply reconfigure your kernel to accomodate that. What is important is that both ethernet cards are not set to conflicting values. Otherwise, any combination that the cards like will be programmable in the kernel.</p>
<p>Last but not least: some cards can be used in the so-called &#8220;full-duplex&#8221; mode. Be aware that if you want to use an ethernet card in full-duplex, your hub must also be full-duplex, as well as the other ethernet cards in the system. A full-duplex hub is much more expensive and not necessary at all. Unless you know what you are doing, program your ethernet cards to use the half-duplex mode, otherwise it won&#8217;t play nice with the other components in your local network, including the xDSL modem <img src='http://www.evanjiang.net.cn/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /><br />
(注，这里需要说NE2000等旧款的基于486机的网卡也可以用，但现在这些网卡，其本难找，所以至少要用8139系列芯片的10-100M自适应的网卡来做应用）</p>
<p>The hard disk<br />
The most secure storage medium is one which can&#8217;t be erased. Some firewalls actually use setups like this (with CD-ROMS) but we&#8217;ll build our firewall with a classic, writeable hard drive because:</p>
<p>We don&#8217;t need &#8220;Absolute Security&#8221;, do we? We can&#8217;t have it anyway <img src='http://www.evanjiang.net.cn/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /><br />
We want to use an &#8220;out-of-the-box&#8221; OpenBSD distro. This will make maintenance (security, patches, etc&#8230;) much easier.<br />
Almost any hard disk out there will work OK, since 200 MB is a safe minimum size. The only thing you must remember is that this disk will run 24/7, so if you use an old drive, it will likely die relatively soon. The venerable drive my friend gave me lasted 6 months before i had to change it, YMMV.</p>
<p>No keyboard?<br />
Of course you&#8217;ll need a keyboard&#8230; and a monitor too, but just for the installation. After the firewall is successfully installed, you will be able to talk to it through encrypted ssh connections over your internal network, so a keyboard &#038; monitor will not be really useful at that point.</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>Getting the software<br />
We will be using OpenBSD. Why? Because it is the most secure freely available operating system out there. All the source code included in the mainstream distribution CD&#8217;s has been audited for years by the OpenBSD team, which is why sometimes an exploit published on BugTraq is found not to work on OpenBSD simply because the faulty code was already fixed months ago.</p>
<p>I strongly suggest you buy their CD-ROM kit as it comes with a set of very cool stickers&#8230; You can also download their stuff for free, of course, but you won&#8217;t have the stickers then <img src='http://www.evanjiang.net.cn/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>This Guide is written for OpenBSD 3.0.</p>
<p>The easiest way to install the software is to use a CD-ROM drive on your firewall box. If you don&#8217;t have that, you can do a network install with the &#8220;ftp&#8221; protocol, either directly to an outside OpenBSD mirror, or to one of your own internal machines equipped with an ftp server. Be aware that if your DSL provider forces you to use PPPoE (boooo!), then of course your link to the outside world will not be functional yet at installation time, which is one more reason to use the CD-ROM. If your machine can boot a CD-ROM, great! It will gladly boot the OpenBSD disc. Otherwise, simply create a boot diskette according to the README and boot that. This diskette is also your rescue disk, so don&#8217;t lose it.<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>Installing OpenBSD<br />
The installation of OpenBSD is very easy, once you have the right hardware, and the right answers to some of the questions. In the following steps, i&#8217;ll assume you can follow the instructions of the install program and focus only on the tricky little things you should know to make your life easier.</p>
<p>fdisk &#038; disklabel<br />
After you boot the installer, one of the very first things you&#8217;ll have to do is partition your disk. This is done with the &#8220;fdisk&#8221; and &#8220;disklabel&#8221; programs. The installer will ask you if you want to use the entire hard disk for OpenBSD. Answer No, even if it is not entirely true. If you say yes, the whole fdisk step will be bypassed, and you will not be able to change the default cylinder/head/sector configuration in order to boot off the hard disk without resorting to the silly &#8220;FDISK /MBR&#8221; DOS command which is a stupid solution to a stupid problem.<br />
The default OpenBSD fdisk partition setup choice is in slot #3. If you want, you can move your OpenBSD partition in slot #0 with no ill effect.</p>
<p>Important: On some systems, to make sure your system boots off the hard disk, you must set the starting CHS (cylinder/head/sector) to C=0, H=0, S=1, because fdisk suggested an incorrect value for H in OpenBSD 2.7, and still does in 2.8 &#8230; If you use &#8220;1&#8243;, as it suggests, your system will not be able to boot from the hard disk.</p>
<p>After the disk is partitioned with fdisk, you use disklabel to further organize the partition. A label behaves like a traditional partition (as used in Linux, for example), except that you can put as many labels as you want in the single OpenBSD partition. This is useful.</p>
<p>On a fully partitioned system, the disk labels might look like this: </p>
<p>  a:  2097648        0    4.2BSD     1024  8192    16   # /               1 GB<br />
  b:   262080  2097648      swap                        # SWAP          128 MB<br />
  c: 20015856        0    unused        0     0         # (whole disk)   10 GB<br />
  d:  2097648  2359728    4.2BSD     1024  8192    16   # /usr            1 GB<br />
  e:  2097648  4457376    4.2BSD     1024  8192    16   # /tmp            1 GB<br />
  f:  2097648  6555024    4.2BSD     1024  8192    16   # /var            1 GB<br />
  g:  4194288  8652672    4.2BSD     1024  8192    16   # /usr/local      2 GB<br />
  h:  7168896 12846960    4.2BSD     1024  8192    16   # /home           3 GB<br />
On my firewall, i like to keep things simpler, so it goes like this: </p>
<p>#        size   offset    fstype   [fsize bsize   cpg]<br />
  a: 18874800        0    4.2BSD     1024  8192    16   # (Cyl.    0 &#8211; 18724)<br />
  b:  1141056 18874800      swap                        # (Cyl. 18725 &#8211; 19856)<br />
  c: 20015856        0    unused        0     0         # (Cyl.    0 &#8211; 19856)As you see, the &#8216;c&#8217; label is a placeholder for the whole disk, in all cases. Don&#8217;t delete or otherwise change this, or you&#8217;ll be in trouble. </p>
<p>One of the main disadvantages of having a single partition is that one could do bad things in such quantity that the log files would simply fill up the whole drive. OpenBSD doesn&#8217;t like it when all its disk space is full. You can guess the rest of the story. In practice, this is not an issue, since i monitor my log files daily, but it could be an issue for someone out there. </p>
<p>On a fully partitioned system, the &#8220;df&#8221; command says this, after the OS is installed, with its complete source trees: </p>
<p>Filesystem      1K-blocks     Used    Avail Capacity  Mounted on<br />
/dev/wd0a         1015269    25985   938521     3%    /<br />
/dev/wd0d         1015269   480284   484222    50%    /usr<br />
/dev/wd0e         1015269        1   964505     0%    /tmp<br />
/dev/wd0f         1015269     5141   959365     1%    /var<br />
/dev/wd0g         2030307     8698  1920094     0%    /usr/local<br />
/dev/wd0h         3470505       27  3296953     0%    /home</p>
<p>On my system i have this:</p>
<p>Filesystem                           1K-blocks     Used    Avail Capacity  Mounted on<br />
/dev/wd0a                              9137589   503054  8177656     6%    /</p>
<p>In this example, the full OpenBSD source tree is installed, which explains why the thing uses up about 500 MB. Without the source tree, you only need about 120 MB in there, but having the source tree allows you to make security patches as they are published. This is important and i&#8217;ll talk about it more later.</p>
<p>Active FTP<br />
If you do an FTP install to a private FTP server, it might be necessary to use active FTP. </p>
<p>Crypto, SSL, etc&#8230;<br />
The crytographic packages are included in the CD&#8217;s since release 2.9 of OpenBSD. They will be automatically installed. </p>
<p>UTC time zone<br />
Keep your server in the UTC time zone. This way, your firewall logs will be timestamped in UTC time and it will be simpler to have them interpreted by the abuse@&#8230; services of ISP&#8217;s. Also, it is important to make sure the gateway is time-synchronized to one of the numerous public NTP servers out there, because having only an IP address is not enough to pin down internet abusers. In this age of dynamic IP allocations you need both IP address and exact time in order to positively identify the origin of an IP packet. Keep your gateway synchronized.<br />
Why not GMT instead? Read all about it there.</p>
<p>Normally, the installer will ask you for a time zone at install time. If you want to change it later, simply make /etc/localtime point to /usr/share/zoneinfo/UTC with a soft link: </p>
<p>ln -s /usr/share/zoneinfo/UTC /etc/localtime</p>
<p>First Boot<br />
reboot &#8230; did your machine boot correctly? If not, please consult the numerous FAQ&#8217;s available at the OpenBSD site. Are you sure you set H=0 in fdisk? By the way, if it doesn&#8217;t boot from hard disk, you can probably still force it by first booting the install diskette, and entering &#8220;boot wd0a:/bsd&#8221; at the initial prompt. You have about 5 seconds to make your mind, when you see this prompt, act swiftly.<br />
On first boot, you will probably get a message like &#8220;ssh-keygen: generating new DSA host key&#8230;&#8221;, followed with an equivalent message for the RSA host key. They might take quite a long time on a 486 (5-10 minutes), so Don&#8217;t Panic! &#8482; , the machine is not crashed, and the boot process will eventually follow its course, given time. This will happen only on the first boot.</p>
<p>Kernel extra configuration<br />
If, at this point, the kernel sees all you devices (including both ethernet cards), congratulations. If not, you can reconfigure the kernel without having to recompile it by simply using the config utility. Typically, you would copy your current kernel (the &#8220;/bsd&#8221; file) to an appropriate backup name (e.g. &#8220;/bsd.ORIGINAL&#8221;), and issue this command: </p>
<p>config -e -f /bsd<br />
and make whatever changes you need. You should know what you&#8217;re doing in order to use this command without blowing your system up into tiny bits &#038; pieces. Don&#8217;t forget to save your changes. If this modified kernel doesn&#8217;t work OK, just boot the &#8220;/bsd.ORIGINAL&#8221; kernel instead, and you will have another chance. </p>
<p>Sys control files<br />
The services allowed by OpenBSD are configured by a couple of files in the /etc directory. Actually, this directory contains all the configuration files of OpenBSD, for your convenience, but this is something you&#8217;ll only appreciate later, when you become an experienced BSD maintainer&#8230; We&#8217;ll come back to that /etc directory quite often.<br />
For now, just make sure that the following are enabled:</p>
<p>In the file /etc/sysctl.conf:<br />
net.inet.ip.forwarding=1</p>
<p>and in /etc/rc.conf:<br />
sendmail_flags=&#8221;-L sm-mta -bd -q30m&#8221;<br />
named_flags=&#8221;"<br />
httpd_flags=&#8221;-DSSL&#8221;</p>
<p>Important: If you plan to use PPPoE, don&#8217;t enable pf here because you want to start it in a controlled manner, after PPPoE is started. Enabling &#8220;pf&#8221; here would make it start at the very beginning of the boot process and this would not work. </p>
<p>PPP &#038; PPPoE<br />
Ahhhh&#8230; the Evil Beast. Installing a good, working PPP and PPPoE can be quite a tricky task. In OpenBSD 3.0, it is included and works well, once properly configured. This version of PPP supports the &#8220;mssfixup&#8221; instruction which magically allows you to avoid setting MTU&#8217;s at 1492 or less on all of your intranet&#8217;s machines. This is very recommended as it avoids a whole bunch of problems with Windows machines, internet appliances, etc&#8230;<br />
Notice that there is an excellent Network FAQ available from the OpenBSD site. It contains a lot of information on what to do with those ethernet adapters. </p>
<p>The configuration file for ppp is in /etc/ppp/ppp.conf. Mine contains exactly this:</p>
<p>default:<br />
 set log Phase Chat IPCP CCP tun command<br />
 set redial 15 0<br />
 set reconnect 15 10000</p>
<p>pppoe:<br />
 set device &#8220;!/usr/sbin/pppoe -i ne0&#8243;<br />
 disable acfcomp protocomp<br />
 deny acfcomp<br />
 set mtu max 1492<br />
 set speed sync<br />
 enable lqr<br />
 set lqrperiod 5<br />
 set cd 5<br />
 set dial<br />
 set login<br />
 set timeout 0<br />
 set authname xxxxxxx<br />
 set authkey xxxxxx<br />
 add! default HISADDR<br />
 enable dns<br />
 enable mssfixupNotice how we specify the real network interface ne0 to pppoe (with double quotes), and that i use &#8220;max 1492&#8243; for the MTU value, as suggested by many people. Also, no value is specified for the MRU, the PPP network address translation is not enabled, the magic &#8220;mssfixup&#8221; is enabled and i use the &#8220;add!&#8221; command instead of plain &#8220;add&#8221; (suggested by Chris Pockele).</p>
<p>Also notice that the authname and authkey fields don&#8217;t contain double-quote characters. You should put in there your own ISP identification and password. Some ISPs require authname to have a full identification (e.g. &#8220;username@sympatico.ca&#8221;), while other ISPs will want to have only &#8220;username&#8221; in the authname field. Experiment.</p>
<p>Robert Jameson (thanks Robert!) reports that some ISPs require you to specify the pppoe service you want. This is done on the &#8220;set device&#8221; line. For example: </p>
<p>      set device &#8220;!/usr/sbin/pppoe -n Shasta_1 -i ne0&#8243;</p>
<p>VERY IMPORTANT!</p>
<p>For some reason, the routes setup automatically by ppp at linkup time were not correctly defined prior to OpenBSD version 3.0. The MTU&#8217;s were wrong, leading to all sorts of subtle problems. This is now fixed, and we can safely use the &#8220;add default HISADDR&#8221; command in the ppp config file, with no special route commands at all in the ppp.linkup file. The MTUs will be properly set to 1492 on all the routes which go through the external interface. </p>
<p>The command &#8220;netstat -rn&#8221; confirms this:</p>
<p>pcreal# netstat -rn<br />
Routing tables</p>
<p>Internet:<br />
Destination        Gateway            Flags     Refs     Use    Mtu  Interface<br />
default            65.92.185.1        UGS         3    13423   1492   tun0<br />
65.92.185.1        65.92.185.97       UH          1        0   1492   tun0<br />
127.0.0.1          127.0.0.1          UH          1     1045  33224   lo0<br />
192.168.1/24       link#2             UC          0        0   1500   ne1<br />
192.168.1.1        0:e0:18:90:a7:c7   UHL         3    10475   1500   ne1<br />
&#8230;</p>
<p>A friend from Australia (thanks Doug!) suggested i clarify the following points:</p>
<p>(1) The 64.229.x.x adresses will NOT be the same in your setup! Those are the adress blocks of my PPPoE service provider (Sympatico). Your own setup will use, most likely, different address blocks.</p>
<p>(2) The ppp daemon creates a virtual network interface (&#8220;tun0&#8243;) out of thin air. This virtual network interface is internally linked to the actual physical interface (&#8220;ne0&#8243; in my system), but you will never have to deal directly with &#8220;ne0&#8243; in your configuration files. For example, the firewall rules are written with the virtual &#8220;tun0&#8243; interface, not the physical &#8220;ne0&#8243; interface. In my setup, the internal interface is &#8220;ne1&#8243;, and the external interface is &#8220;tun0&#8243;. Here is Doug&#8217;s analogy with the Windows world:</p>
<p>&#8220;&#8230; think of the PPPoE adaptor like the dialup adaptor in a Windows<br />
control panel. it doesn&#8217;t really exist but you gotta have it&#8230;&#8221;(3) The ppp daemon takes care of automatically assigning the name servers and the routes. Consequently, make sure there is no file &#8220;/etc/mygate&#8221;, and bear in mind that &#8220;/etc/resolv.conf&#8221; will be automatically generated as well, at connection time. This has the advantage that you don&#8217;t need to know anything about the details of your connection (name server adresses, etc&#8230;) to your ISP. Your user ID and password are sufficient, as the ppp daemon will negociate with the server and obtain the information it needs to open the connection.</p>
<p>(4) Since the ppp daemon will take are of the external network interface, you don&#8217;t need a &#8220;/etc/hostname.ne0&#8243; file. However, you do need a file to describe your internal network interface (in my case, &#8220;ne1&#8243;):</p>
<p>pcreal# cat /etc/hostname.ne1<br />
inet 192.168.1.2 255.255.255.0 NONENormally, this file should have been built by the setup program of OpenBSD, but if not, you must manually put it there and replace the &#8220;192.168.1.2&#8243; with whatever address you want your gateway to have as seen from your internal network.</p>
<p>Another friend, from France (thanks Xavier!), sent me this ascii picture of the network connections:</p>
<p>           |                                      |<br />
   internet| ====> |DSL Modem| ====>|server|=====>|LAN (HUB)<br />
           |                   tun0           ne1 |<br />
           |                   =ne0               |</p>
<p>Note: I consider this PPP/PPPoE setup to be a work in progress. I continually discover new things about it&#8230; so, please bear with me and do send me your feedback about your own experience regarding PPP/PPPoE. It really is a pain, but apparently we will be stuck with it for a long long time, so we might as well learn how to tame the thing!</p>
<p>Second Boot<br />
reboot &#8230; your machine should boot correctly. You won&#8217;t have internet access yet because the ppp program is not activated. If you want to try it out, just issue </p>
<p>ifconfig ne0 up<br />
ppp -ddial pppoeand ping/telnet away. Don&#8217;t worry if you get &#8220;carrier settings ignored&#8221;, or &#8220;change route failed&#8221; messages. Be careful because at this point you have no firewall rules set, so you are very vulnerable. Also, make sure your xDSL modem is plugged in the correct ethernet card&#8230;</p>
<p>If all works well, then you should kill the &#8220;ppp&#8221; process. Only restart it when the firewall rules are in place.</p>
<p>The afterboot phase<br />
Follow the instructions obtained by issuing the &#8220;man afterboot&#8221; command. Actually, quoting FAQ section 2.3, here is a list of the most useful man pages for new users: </p>
<p>     * [15]afterboot(8) &#8211; things to check after the first complete boot<br />
     * [16]boot(8) &#8211; system boot strapping procedures<br />
     * [17]passwd.conf(5) &#8211; format of the password configuration file<br />
     * [18]adduser_proc(8) &#8211; procedure for adding new users<br />
     * [19]adduser(8) &#8211; command for adding new users<br />
     * [20]vipw(8) &#8211; edit the pass word file<br />
     * [21]man(1) &#8211; display the on-line manual pages<br />
     * [22]sendbug(1) &#8211; send a problem report (PR) about OpenBSD to a<br />
       central support site.<br />
     * [23]disklabel(8) &#8211; Read and write disk pack label.<br />
     * [24]ifconfig(8) &#8211; configure network interface parameters.<br />
     * [25]route(8) &#8211; manually manipulate the routing tables.<br />
     * [26]netstat(1) &#8211; show network status.<br />
     * [27]reboot, halt(8) &#8211; Stopping and restarting the system.<br />
     * [28]shutdown(8) &#8211; close down the system at a given time.<br />
     * [29]boot_config(8) &#8211; how to change kernel configuration at boot</p>
<p>One of the first things you should do at this point is to add an unprivileged user and make him member of the wheel group. This is because, for security reasons, it is never a good idea to log in directly as root. The preferred way to gain root privileges is to login as a wheel member, and then use the &#8220;su -&#8221; command to gain root privileges.</p>
<p>OpenBSD will not prevent you from logging in directly as root, but will warn you every time against doing it.</p>
<p>Have fun!</p>
<p>Firewall and NAT rule sets<br />
This is a tricky one. Many people earn a good living just by knowing how to write firewall rule sets! Moreover, the whole packet filter and NAT code was completely rewritten from scratch in OpenBSD 3.0. It is now called &#8220;pf&#8221;, and is completely free of any external licensing strings so we will always have the latest, fully audited versions in future OpenBSD releases.<br />
Here are my own pf rules, in all their glory. They were heavily influenced by the various man pages and HOW-TO&#8217;s pertaining to &#8220;pf&#8221;. Be aware that they might be either too restrictive, or not enough, depending on your context. My philosophy about this is to disallow everything by default, and only open whatever is known to be useful. This restrictive ruleset will prevent ftp from working correctly, from the firewall itself. However, the ftp proxy currently available will work correctly for client machines located on the intranet. </p>
<p>Don&#8217;t forget to send me your tips for better rules&#8230; Thanks!</p>
<p>/etc/nat.conf<br />
nat on tun0 from 192.168.1.0/24 to any -> tun0<br />
rdr on ne1 proto tcp from any to any port 21 -> 127.0.0.1 port 8081</p>
<p>/etc/pf.conf<br />
#&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<br />
# PF ruleset, 11 dec. 2001<br />
#<br />
# Liberally adapted from the pf man page, the OpenBSD &#8220;Network How-To&#8221;,<br />
# and my own rulesets.<br />
#&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>#&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<br />
# Definitions<br />
Ext = &#8220;tun0&#8243;            # External interface<br />
Int = &#8220;ne1&#8243;             # Internal interface<br />
Loop = &#8220;lo0&#8243;            # Loopback interface<br />
IntNet=&#8221;192.168.1.0/24&#8243; # Internal network</p>
<p>NoRoute = &#8220;{ 127.0.0.1/8, 192.168.0.0/16, 172.16.0.0/12, 10.0.0.0/8, 255.255.255.255/32 }&#8221;</p>
<p>InServicesTCP = &#8220;{ ssh, smtp, auth, http, https, pop3 }&#8221;<br />
#InServicesUDP = &#8220;{ domain }&#8221;<br />
OutServicesTCP = &#8220;{ http, https, smtp, pop3, whois, domain, ssh, telnet, ftp, ftp-data, nntp, auth, ntp }&#8221;<br />
OutServicesUDP = &#8220;{ ntp, domain }&#8221;</p>
<p>XMMS = &#8220;{ 6000, 7500, 8000, 8004, 8044, 8034, 8052, 8038, 8010, 8400, 8014, 8026, 8048, \<br />
          8002, 8024, 8028, 8080 }&#8221;<br />
RealAudio = &#8220;{ 554, 7070, 8080 }&#8221;</p>
<p>#&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<br />
#&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<br />
# Clean up fragmented and abnormal packets<br />
# By default in pf, packets which contain IP options are blocked. Good.<br />
scrub in on { $Ext, $Int } all<br />
#&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>#&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
# Defaults<br />
# block and log everything<br />
block             out log on $Ext           all<br />
block             in  log on $Ext           all<br />
block return-rst  out log on $Ext proto tcp all<br />
block return-rst  in  log on $Ext proto tcp all<br />
block return-icmp out log on $Ext proto udp all<br />
block return-icmp in  log on $Ext proto udp all</p>
<p>block in  quick inet6 all<br />
block out quick inet6 all<br />
#&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<p>#&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<br />
# loopback packets left unmolested<br />
pass in quick on $Loop all<br />
pass out quick on $Loop all<br />
#&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>#&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
# Immediate blocks<br />
# fuzz any &#8216;nmap&#8217; attempt<br />
block in log quick on $Ext inet proto tcp from any to any flags FUP/FUP<br />
block in log quick on $Ext inet proto tcp from any to any flags SF/SFRA<br />
block in log quick on $Ext inet proto tcp from any to any flags /SFRA</p>
<p># don&#8217;t allow anyone to spoof non-routeable addresses<br />
block in log quick on $Ext from $NoRoute to any<br />
block out log quick on $Ext from any to $NoRoute</p>
<p># silently drop broadcasts (cable modem noise)<br />
block in quick on $Ext from any to 255.255.255.255<br />
#&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<p>#&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
# PASS rules</p>
<p># ALL  &#8212; we don&#8217;t normally do that. For debugging only.<br />
#pass out quick on $Ext all keep state</p>
<p># pass in data mode connections for ftp-proxy running on this host.<br />
pass in quick on $Ext inet proto tcp from any to any port > 49151 flags S/SA keep state</p>
<p># ICMP<br />
pass out     quick on $Ext inet proto icmp all icmp-type 8 code 0 keep state<br />
pass in  log quick on $Ext inet proto icmp all icmp-type 8 code 0 keep state</p>
<p># Services we provide to the outside world<br />
#pass in quick on $Ext inet proto udp from any to any port $InServicesUDP keep state<br />
pass in quick on $Ext inet proto tcp from any to any port $InServicesTCP flags S/SA keep state</p>
<p># Standard services we want to access in the world<br />
pass out quick on $Ext inet proto udp from any to any port $OutServicesUDP keep state<br />
pass out quick on $Ext inet proto tcp from any to any port $OutServicesTCP flags S/SA modulate state</p>
<p># Special services<br />
pass out quick on $Ext inet proto tcp from any to any port $XMMS flags S/SA modulate state<br />
pass out quick on $Ext inet proto tcp from any to any port $RealAudio flags S/SA modulate state<br />
IMPORTANT: Note that the &#8220;rdr&#8221; rule in the NAT file refers to the INTERNAL network interface. Its purpose is to redirect all ftp-data requests from the intranet to be redirected to the ftp-proxy on the firewall. Then the ftp-proxy channels those into ports 49152-65535, and outputs them on the internet. This is why we have this hole in the firewall starting at port 49152. I know, it is in the IN direction, but that is how passive ftp works&#8230; It is quite a broken protocol.<br />
That&#8217;s it! Nothing too painful, as you see. Since pf is a stateful inspection firewall, we can keep our ingress rules to a strict minimum. Notice the sheer elegance of the ruleset, with all services defined at once in a single IN or OUT rule. </p>
<p>One last thing: in order to automagically enable your firewall when the link comes up, you can put the following lines in the /etc/ppp/ppp.linkup file. Notice the extra space in front of each &#8220;!&#8221; character:</p>
<p>MYADDR:<br />
 ! sh -c &#8220;/sbin/ifconfig pflog0 up&#8221;<br />
 ! sh -c &#8220;/sbin/pfctl -e -l tun0 -F all -O aggressive -R /etc/pf.conf -N /etc/nat.conf&#8221;</p>
<p>The FTP proxy<br />
If you want tight security, and no FTP available on your intranet, simply remove the hole at 49152, and the &#8220;rdr&#8221; command in the file &#8220;nat.conf&#8221;. However, if you want to be able to use FTP from the intranet, then you must keep those, as well as enable the &#8220;ftp-proxy&#8221; service in inetd. Simply add this line to inetd.conf : </p>
<p>8081            stream  tcp     nowait  root    /usr/libexec/ftp-proxy  ftp-proxyDon&#8217;t forget that you still won&#8217;t be able to do FTP&#8217;ing from the firewall itself, when the packet filtering is enabled. Hopefully, it is very easy to temporarily disable pf with the command &#8220;pfctl -d&#8221;, and later re-enable it with the command &#8220;pfctl -e&#8221;. This comes in handy when we install packages from ftp.openbsd.org with the command &#8220;pkg_add&#8221;. </p>
<p>We are confident that ftp-proxy will improve with time and eventually dynamically manipulate the state tables of the firewall in order to open/close needed connections on-the-fly. </p>
<p>Addinc stuff to /etc/rc.local<br />
This is where our custom startup instructions go. Those things are started while the kernel is in secure level 1. If you need anything started in a lower security level, modify /etc/rc.securelevel instead. In order to start up PPPoE correctly, I added this at the end of my /etc/rc.local : </p>
<p>ifconfig ne0 up<br />
route flush<br />
ppp -ddial pppoe</p>
<p>This starts PPP, PPPoE, the firewall and the NAT translator (because the firewall and the NAT are started automatically in the ppp.linkup file). If you&#8217;re curious, you can reboot at this point, and confirm that you have a fully firewalled internet access:</p>
<p>pcreal# ifconfig -a<br />
lo0: flags=8009 mtu 33224<br />
        inet6 fe80::1%lo0 prefixlen 64 scopeid 0&#215;5<br />
        inet6 ::1 prefixlen 128<br />
        inet 127.0.0.1 netmask 0xff000000<br />
lo1: flags=8008 mtu 33224<br />
ne0: flags=8863 mtu 1500<br />
        media: Ethernet autoselect (10baseT)<br />
        inet6 fe80::240:f4ff:fe2b:190d%ne0 prefixlen 64 scopeid 0&#215;1<br />
ne1: flags=8863 mtu 1500<br />
        media: Ethernet autoselect (10baseT)<br />
        inet 192.168.1.2 netmask 0xffffff00 broadcast 192.168.1.255<br />
        inet6 fe80::240:f4ff:fe2b:16b1%ne1 prefixlen 64 scopeid 0&#215;2<br />
pflog0: flags=141 mtu 33224<br />
sl0: flags=c010 mtu 296<br />
sl1: flags=c010 mtu 296<br />
ppp0: flags=8010 mtu 1500<br />
ppp1: flags=8010 mtu 1500<br />
tun0: flags=8011 mtu 1492<br />
        inet 65.92.185.97 &#8211;> 65.92.185.1 netmask 0xffffffff<br />
tun1: flags=10 mtu 3000<br />
enc0: flags=0<> mtu 1536<br />
bridge0: flags=0<> mtu 1500<br />
bridge1: flags=0<> mtu 1500<br />
vlan0: flags=0<> mtu 1500<br />
vlan1: flags=0<> mtu 1500<br />
gre0: flags=8010 mtu 1450<br />
gif0: flags=8010 mtu 1280<br />
gif1: flags=8010 mtu 1280<br />
gif2: flags=8010 mtu 1280<br />
gif3: flags=8010 mtu 1280</p>
<p>pcreal# pfctl -sr<br />
@0 scrub in on ne1 all<br />
@1 scrub in on tun0 all<br />
@2 block out log on tun0 all<br />
@3 block in log on tun0 all<br />
@4 block return-rst out log on tun0 proto tcp all<br />
@5 block return-rst in log on tun0 proto tcp all<br />
@6 block return-icmp out log on tun0 proto udp all<br />
@7 block return-icmp in log on tun0 proto udp all<br />
@8 block in quick inet6 all<br />
@9 block out quick inet6 all<br />
@10 pass in quick on lo0 all<br />
@11 pass out quick on lo0 all<br />
@12 block in log quick on tun0 inet proto tcp all flags FPU/FPU<br />
@13 block in log quick on tun0 inet proto tcp all flags FS/FSRA<br />
@14 block in log quick on tun0 inet proto tcp all flags /FSRA<br />
@15 block in log quick on tun0 inet from 255.255.255.255/32 to any<br />
@16 block in log quick on tun0 inet from 10.0.0.0/8 to any<br />
@17 block in log quick on tun0 inet from 172.16.0.0/12 to any<br />
@18 block in log quick on tun0 inet from 192.168.0.0/16 to any<br />
@19 block in log quick on tun0 inet from 127.0.0.1/8 to any<br />
@20 block out log quick on tun0 inet from any to 255.255.255.255/32<br />
@21 block out log quick on tun0 inet from any to 10.0.0.0/8<br />
@22 block out log quick on tun0 inet from any to 172.16.0.0/12<br />
@23 block out log quick on tun0 inet from any to 192.168.0.0/16<br />
@24 block out log quick on tun0 inet from any to 127.0.0.1/8<br />
@25 block in quick on tun0 inet from any to 255.255.255.255/32<br />
@26 pass in quick on tun0 inet proto tcp from any to any port > 49151 flags S/SA keep state<br />
@27 pass out quick on tun0 inet proto icmp all icmp-type echoreq code 0 keep state<br />
@28 pass in log quick on tun0 inet proto icmp all icmp-type echoreq code 0 keep state<br />
@29 pass in quick on tun0 inet proto tcp from any to any port = pop3 flags S/SA keep state<br />
@30 pass in quick on tun0 inet proto tcp from any to any port = https flags S/SA keep state<br />
@31 pass in quick on tun0 inet proto tcp from any to any port = www flags S/SA keep state<br />
@32 pass in quick on tun0 inet proto tcp from any to any port = auth flags S/SA keep state<br />
@33 pass in quick on tun0 inet proto tcp from any to any port = smtp flags S/SA keep state<br />
@34 pass in quick on tun0 inet proto tcp from any to any port = ssh flags S/SA keep state<br />
@35 pass out quick on tun0 inet proto udp from any to any port = domain keep state<br />
@36 pass out quick on tun0 inet proto udp from any to any port = ntp keep state<br />
@37 pass out quick on tun0 inet proto tcp from any to any port = ntp flags S/SA modulate state<br />
@38 pass out quick on tun0 inet proto tcp from any to any port = auth flags S/SA modulate state<br />
@39 pass out quick on tun0 inet proto tcp from any to any port = nntp flags S/SA modulate state<br />
@40 pass out quick on tun0 inet proto tcp from any to any port = ftp-data flags S/SA modulate state<br />
@41 pass out quick on tun0 inet proto tcp from any to any port = ftp flags S/SA modulate state<br />
@42 pass out quick on tun0 inet proto tcp from any to any port = telnet flags S/SA modulate state<br />
@43 pass out quick on tun0 inet proto tcp from any to any port = ssh flags S/SA modulate state<br />
@44 pass out quick on tun0 inet proto tcp from any to any port = domain flags S/SA modulate state<br />
@45 pass out quick on tun0 inet proto tcp from any to any port = whois flags S/SA modulate state<br />
@46 pass out quick on tun0 inet proto tcp from any to any port = pop3 flags S/SA modulate state<br />
@47 pass out quick on tun0 inet proto tcp from any to any port = smtp flags S/SA modulate state<br />
@48 pass out quick on tun0 inet proto tcp from any to any port = https flags S/SA modulate state<br />
@49 pass out quick on tun0 inet proto tcp from any to any port = www flags S/SA modulate state<br />
&#8230;<br />
@72 pass out quick on tun0 inet proto tcp from any to any port = 6000 flags S/SA modulate state<br />
@73 pass out quick on tun0 inet proto tcp from any to any port = 8080 flags S/SA modulate state<br />
@74 pass out quick on tun0 inet proto tcp from any to any port = 7070 flags S/SA modulate state<br />
@75 pass out quick on tun0 inet proto tcp from any to any port = 554 flags S/SA modulate state</p>
<p>pflogd and tcpdump<br />
With the new pf firewall code comes a new way to log firewalled packets and look at them. The log is actually taken care of by a separate daemon ( pflogd ) which should be started in &#8220;ppp.linkup&#8221; and killed in &#8220;ppp.linkdown&#8221;. This daemon puts its data in a special log file ( /var/log/pflog ) which is not directly human readable, for performance reasons. To get a dump of the file, simply issue the command &#8220;tcpdump -n -e -ttt -r /var/log/pflog&#8221;, or , if you want a real-time display of the logs, simply issue &#8220;tcpdump -n -e -ttt -i pflog0&#8243;. </p>
<p>The Dynamic DNS<br />
Dynamic DNS is a wonderful thing. Basically, you just go to a dyndns provider like those nice people and 10 minutes later you have your very own domain, for free. In order to make that domain dynamically follow your IP address changes, you must use a special client program which must be called whenever your IP changes. </p>
<p>Until recently I liked ddup, but now i use ipcheck. The latter is truly compliant with all of dyndns&#8217;s client specification, and maintains its state automatically in system files. You will have to install the python package if you use &#8220;ipcheck&#8221;. Also, you&#8217;ll need your user ID and password from the dyndns provider.</p>
<p>One more advice: it is perfectly acceptable to have more than one domain pointing at the same IP address. Remember this when choosing one or more domain names&#8230;</p>
<p>Keeping your xDSL link alive 24/7<br />
xDSL connections are very reliable, but ISP&#8217;s are not <img src='http://www.evanjiang.net.cn/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  For many reasons unfathomable, you will sometimes lose your connection. There are many methods of re-establishing that connection automatically, and i&#8217;ll describe here the one i use. </p>
<p>The Method<br />
Make sure you initialise ppp with the &#8220;-ddial&#8221; command, and NOT the &#8220;-background&#8221; command&#8230;</p>
<p>The automatic restart of the ppp link is handled by ppp itself (using the &#8220;-ddial&#8221; command), which is quite handy. This leaves us with the dyndns updates, which are performed intelligently by ipcheck.py . An easy way of doing it is to create an executable file named &#8220;do_ipcheck&#8221; which contains this:</p>
<p>#!/bin/sh<br />
/usr/local/sbin/ipcheck.py -q -d /etc/ipcheck -i tun0  -w Username Password DomainName1,DomainName2with your own Username, Password and Domain names, of course. Then, all you have to do is to add the following line to crontab:</p>
<p>*/5     *       *       *       *       /usr/local/sbin/do_ipcheckAlso, don&#8217;t forget to create the directory /etc/ipcheck and make sure your /etc/ppp/ppp.linkup file looks like this:</p>
<p>MYADDR:<br />
 ! sh -c &#8220;/sbin/ifconfig pflog0 up&#8221;<br />
 ! sh -c &#8220;/sbin/pfctl -e -l tun0 -F all -O aggressive -R /etc/pf.conf -N /etc/nat.conf&#8221;<br />
 ! sh -c &#8220;/usr/local/sbin/ResetNTP.sh&#8221;<br />
 !bg sh -c &#8220;/usr/local/sbin/do_ipcheck&#8221;<br />
You can call &#8220;do_ipcheck&#8221; from &#8220;ppp.linkup&#8221; &#8230; however, you must use the special &#8220;!bg&#8221; construct, in order to instruct ppp to fork it in the background. Nasty stuff happens if you don&#8217;t use &#8220;!bg&#8221; here. Big thanks to Dan for this update!</p>
<p>This setup should garantee the proper restart of the firewall &#038; ipnat each time the ppp link is brought up again.</p>
<p>Apache<br />
Now would be a good time to install your htdocs directory. The way i like to do this is to mount a read-only NFS file system over the current htdocs. This is easily accomplished by adding a line like this to your /etc/fstab : </p>
<p>192.168.1.1:/usr/local/Apache/htdocs /var/www/htdocs nfs ro  Moreover, the web logs are kept in /var/www/logs. Interesting stuff.</p>
<p>We are in full virus season and i&#8217;m sure your log files will fill up as fast as mine with useless garbage, once your Apache is up. In order to remove some clutter, you can filter out the virus attacks and channel them to a specialized attack_log file. Simply insert the following lines into your /var/www/conf/httpd.conf file: </p>
<p>SetEnvIf Request_URI &#8220;^/default.ida&#8221; attacks # For Code Red<br />
SetEnvIf Request_URI &#8220;^/scripts&#8221; attacks # For nimda<br />
SetEnvIf Request_URI &#8220;^/c/winnt&#8221; attacks # &#8230; ditto all the way down<br />
SetEnvIf Request_URI &#8220;^/_mem_bin&#8221; attacks<br />
SetEnvIf Request_URI &#8220;^/_vti_bin&#8221; attacks<br />
SetEnvIf Request_URI &#8220;^/MSADC&#8221; attacks<br />
SetEnvIf Request_URI &#8220;^/msadc&#8221; attacks<br />
SetEnvIf Request_URI &#8220;^/d/winnt&#8221; attacks</p>
<p>CustomLog /var/www/logs/access_log combined env=!attacks<br />
CustomLog /var/www/logs/attack_log combined env=attacks<br />
This will send all virus-related requests to &#8220;attack_log&#8221;, while still logging other activities normally in access_log.</p>
<p>Named<br />
Someone (Chavous P. Camp, thanks!) sent me advice on optimizing &#8220;named&#8221; for faster throughput. He recommends to add two lines to the &#8220;/var/named/named.boot&#8221; file:</p>
<p>options forward-only<br />
forwarders ip.addresses.of.ISPs.nameservers.separated.by.spacesThis forces named to always use the same servers for dns. If your ISP&#8217;s servers are always on fixed IP adresses, then it works well. However, ISP&#8217;s who force you to use PPPoE will also sometimes change dynamically the DNS servers allocated to you (in &#8220;/etc/resolv.conf&#8221;, automatically created by ppp at startup). In that case, there is no garantee that the name servers you hardwire as forwarders will always be available.</p>
<p>Removing IPv6 related errors<br />
The GENERIC OpenBSD kernel comes precompiled with IP v6 support. This is the reason why you might see many &#8220;/bsd: tun0: not multicast capable, IPv6 not enabled&#8221; error messages in your logs. Those messages are completely harmless and do not alter the performance of your system. However, should you want to get rid of them, you can simply remove IPv6 support from your kernel by modifying &#8220;/usr/src/sys/conf/GENERIC&#8221; and removing the &#8220;option INET6&#8243; line. Then recompile your kernel in the usual way. Thanks Chavous for this info!</p>
<p>Setting permissions of scripts &#038; config files<br />
Another excellent suggestion from Chavous. Scripts and config files with passwords should have their permissions changed to 500 (for scripts) or 400 (for config files), for greater security. This includes &#8220;ppp.conf&#8221;, &#8220;do_ipcheck&#8221;, etc&#8230;</p>
<p>The NTP daemon<br />
The ntpd daemon is not installed by default. However, you can download it as a package, and install it with the pkg_add command. Since you have internet connectivity by now, you can download &#038; install it in a single command:</p>
<p>pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/3.0/packages/i386/ntp-4.1.71.tgz Moreover, you will need a valid /etc/ntp.conf file:</p>
<p>pcreal# cat /etc/ntp.conf<br />
server 128.100.102.201<br />
driftfile /etc/ntp.driftFeel free to use any other atomic time server if you want. Also, the drift file will be created &#038; maintained automagically.</p>
<p>Important tip from Chavous:<br />
=========================================<br />
I found my ntp server would refuse to synchronize after a reboot because it<br />
had no route to the time server.  This was, of course, because PPPoE is<br />
loaded AFTER ntp, and sometimes the PPPoE negotiation after a reboot takes a<br />
few seconds.</p>
<p>Anyway, here is something you might want to add as a suggestion:</p>
<p>Turn ntpd OFF in the rc.conf file<br />
add this line to your ppp.linkup file &#8211; AFTER the firewall initialization</p>
<p> ! sh -c &#8220;/etc/ppp/ResetNTP.sh&#8221;</p>
<p>That script should then contain:</p>
<p>#!/bin/sh<br />
if [ -f /var/run/ntpd.pid ]; then<br />
        kill `cat /var/run/ntpd.pid`<br />
        rm -f /var/run/ntpd.pid<br />
fi<br />
/usr/local/sbin/ntpd -p /var/run/ntpd.pid</p>
<p>(as I have said before, remind your readers that this script is executed as<br />
root and should therefore be chmod 444 or less)</p>
<p>This kills the NTP daemon (if it exists) and restarts it.  On boot, it would<br />
not be restarted, but what if the link went down for a while? The ntp daemon<br />
would give up and stop sending queries because it couldn&#8217;t get a route to<br />
host.</p>
<p>REALLY, the ntp daemon SHOULD NOT stop querying the server just because it<br />
can&#8217;t get a route to the host, but it seems to be written as such now<br />
anyway.  I haven&#8217;t tested the ntp daemon over a long period of time (more<br />
than about a day) so I don&#8217;t know if it just gives up for some arbitrarily<br />
long period (MORE than a day) and then tries again. I seriously doubt it<br />
does, because a day is a LONG time.  This workaround isn&#8217;t ideal, because<br />
for time consistency, one would want the time server to stay running at all<br />
times.  According to the ntpd documentation, ntpd tends to become more<br />
accurate the longer it runs.</p>
<p>Chavous<br />
=========================================</p>
<p>Sendmail<br />
If you have followed all the steps of the recipe so far, your sendmail should be configured &#038; ready to receive mail from the internet, however you should know a few more things about this. First, if you want your gateway to receive mail for more than one domain, you must make sure the all fully qualified domains are setup as aliases for your host in the file /etc/hosts.</p>
<p>The mail popper<br />
All ingress mail is received &#038; kept on the gateway untill some POP client on the intranet gets it. I use the &#8220;popa3d&#8221; server package because it is written with security in mind. It is now part of the main OpenBSD 3.0 distribution, so you don&#8217;t have to download it as a separate package. Simply enable it in the file /etc/inetd.conf and you should be up &#038; running. </p>
<p>The installed packages<br />
Just to do a quick check, here are the packages i have installed on my system:</p>
<p>pcreal# pkg_info<br />
gmp-3.1.1          library for arbitrary precision arithmetic<br />
python-2.1.1       interpreted object-oriented programming language<br />
ntp-4.1.71         network time protocol implementation<br />
libiconv-1.7       character set conversion library<br />
gettext-0.10.40    GNU gettext<br />
mhash-0.8.9        strong hash library<br />
libtool-1.3.5p3    generic shared library support script<br />
postgresql-7.1.3   PostgreSQL RDBMS<br />
libmcrypt-2.4.15   interface to access block/stream encryption algorithms<br />
c-client-4.40p1    University of Washington&#8217;s c-client mail access routines<br />
php4-4.0.6p1-gettext-imap-mhash-no_x11-mcrypt-postgresql server-side HTML-embedded scripting language</p>
<p>The Secure Shell<br />
The secure shell looks &#038; feels exactly like telnet, except that all communication between the client and the server is encrypted. It is the only possible way to access your gateway, because the telnet daemon is disabled by default. Usage is very simple: just like telnet! </p>
<p>[real@pcreal Projects]$ ssh 192.168.1.2<br />
real@192.168.1.2&#8242;s password:<br />
Warning: Remote host denied X11 forwarding.<br />
Last login: Sun Nov  5 12:58:08 2000 from 192.168.1.1<br />
OpenBSD 2.7 (GENERIC) #1: Thu Nov  2 16:05:11 GMT 2000</p>
<p>pcreal:real {39}</p>
<p>Once you are logged in as an unprivileged user, member of the wheel group, you can use su to gain superuser privileges:</p>
<p>pcreal:real {39} su -<br />
Password:<br />
Terminal type? [nxterm]<br />
pcreal#</p>
<p>The log files<br />
There are many log files of high interest maintained automatically by your gateway. It is usually convenient to look at them with the &#8220;tail -f&#8221; command. The files i look at often are: </p>
<p>/var/log/messages<br />
/var/log/maillog<br />
/var/log/secure<br />
/var/www/logs/access_log</p>
<p>Moreover, you can grab interesting info about the blocked packets on your firewall with the &#8220;ipmon&#8221; utility.</p>
<p>There are many other log files available for all kinds of things. Dig around to find more about them.</p>
<p>Installing IPSEC<br />
Dave Cook has kindly provided us with a good description of how to install IPSEC on your OpenBSD boxen: file:///H:/OPENBSD/ipsec.pdf, in PDF (Acrobat) format. Be aware that it is a largish file (440K), and it might take some time for your Acrobat reader to load afterwards, so don&#8217;t hit the link repeatedly, it won&#8217;t make things load faster&#8230; <img src='http://www.evanjiang.net.cn/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Apply the security patches!<br />
Security patches are published there. APPLY THEM RELIGIOUSLY!<br />
It is not really difficult, but you will need a copy of the complete, original source tree of the distribution. The compressed source archives are to be found with the distribution files. These are the 3.0 source files:</p>
<p>      src.tar.gz      64447 Kb    Tue May  1 16:18:00 2001 Unix Tape Archive<br />
      srcsys.tar.gz   13837 Kb    Tue May  1 16:18:00 2001 Unix Tape ArchiveThey total about 80 MB. Once you have them, simply unpack them to &#8216;/usr/src&#8217; and &#8216;/usr/src/sys&#8217;. The latter is the kernel proper.</p>
<p>Once you have your source tree, you can start downloading the patches, and apply them. Usually, all the currently published patches are availble in a single file. For 3.0, it is there. After that, simply watch the patch page from time to time, to keep updated.</p>
<p>Patches are either applied to an application (in &#8216;/usr/src&#8217;), or to the kernel ( in &#8216;/usr/src/sys&#8217;). Since all kernel patches should be installed, the thing i do is to apply all the kernel patches in one session, then i recompile my kernel once.</p>
<p>The applications you don&#8217;t use (e.g. &#8216;X11&#8242;, for example) don&#8217;t have to be patched &#038; recompiled.</p>
<p>Reboot and enjoy!<br />
You should be able to ssh into your new gateway from any machine on the intranet. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.evanjiang.net.cn/archives/845.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>在OpenBSD下，使用ADSL拨号上网和启动PF防火墙</title>
		<link>http://www.evanjiang.net.cn/archives/700.html</link>
		<comments>http://www.evanjiang.net.cn/archives/700.html#comments</comments>
		<pubDate>Thu, 05 Mar 2009 05:24:20 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[openbsd unix]]></category>
		<category><![CDATA[pf]]></category>
		<category><![CDATA[openbsd  adsl拔号上网 启动pf防火墙]]></category>

		<guid isPermaLink="false">http://www.evanjiang.net.cn/?p=700</guid>
		<description><![CDATA[<p>在OpenBSD下，使用ADSL拨号上网和启动PF防火墙
o	目标
o	什么是PF防火墙
o	注意事项
o	编辑配置文件
我拿OpenBSD当桌面系统，平时也不打开任何网络服务，使用ADSL拨号上网，只有一个调制解调器，没有路由器。
加上PF，挡住所有不请自来的流量。
目标
ADSL拨号配置文件，PF配置文件。
什么是PF防火墙
OpenBSD的内置防火墙，功能强大，是OpenBSD系统上进行TCP/IP流量过滤和网络地址转换的软件系统。
配置文件默认的位置在 /etc/pf.conf。
注意事项
内核编译选项必需有:
•	seudo-device pf # packet filter
•	seudo-device pflog # pf log if
•	seudo-device tun # network tunneling over tty
设kern.securelevel最高为1，因为securelevel为2不可以手动刷新过滤规则。
编辑配置文件
vi /etc/ppp/ppp.conf
default:
 set log Phase Chat LCP IPCP CCP tun command
 set redial 15 0
 set reconnect 15 10000

pppoe:
 set device &#8220;!/usr/sbin/pppoe -i re0&#8243;  # re0: 使用的网卡
 disable acfcomp protocomp
 deny acfcomp
 set mtu max 1492
 set mru [...]]]></description>
			<content:encoded><![CDATA[<p>在OpenBSD下，使用ADSL拨号上网和启动PF防火墙<br />
o	目标<br />
o	什么是PF防火墙<br />
o	注意事项<br />
o	编辑配置文件<br />
我拿OpenBSD当桌面系统，平时也不打开任何网络服务，使用ADSL拨号上网，只有一个调制解调器，没有路由器。<br />
加上PF，挡住所有不请自来的流量。<br />
目标<br />
ADSL拨号配置文件，PF配置文件。<br />
什么是PF防火墙<br />
OpenBSD的内置防火墙，功能强大，是OpenBSD系统上进行TCP/IP流量过滤和网络地址转换的软件系统。<br />
配置文件默认的位置在 /etc/pf.conf。<br />
注意事项<br />
内核编译选项必需有:<br />
•	seudo-device pf # packet filter<br />
•	seudo-device pflog # pf log if<br />
•	seudo-device tun # network tunneling over tty<br />
设kern.securelevel最高为1，因为securelevel为2不可以手动刷新过滤规则。<br />
编辑配置文件<br />
vi /etc/ppp/ppp.conf<br />
default:<br />
 set log Phase Chat LCP IPCP CCP tun command<br />
 set redial 15 0<br />
 set reconnect 15 10000<br />
<span id="more-700"></span><br />
pppoe:<br />
 set device &#8220;!/usr/sbin/pppoe -i re0&#8243;  # re0: 使用的网卡<br />
 disable acfcomp protocomp<br />
 deny acfcomp<br />
 set mtu max 1492<br />
 set mru max 1492<br />
 set speed sync<br />
 set crtscts off<br />
 enable lqr<br />
 enable mssfixup<br />
 set lqrperiod 5<br />
 set cd 5<br />
 set dial<br />
 set login<br />
 set timeout 0<br />
 set authname xxxxxx                  # ADSL拨号帐号，xxx@163.gd<br />
 set authkey &#8220;xxxxxx&#8221;                 # ADSL拨号密码<br />
# enable dns                          # 每次都修改/etc/resolv.conf<br />
 add! default HISADDR                 # 成为默认路由<br />
设置开机自动拨号: vi /etc/rc.local:<br />
echo &#8216;/etc/rc.local: connect to ADSL&#8217;<br />
ppp -ddial pppoe                     # 拨号模式，掉线自动重拨<br />
vi /etc/pf.conf<br />
# Define interfaces<br />
int_if = &#8220;re0&#8243;<br />
ext_if = &#8220;tun0&#8243;<br />

<!-- Begin alimama Adserver code -->
<script type="text/javascript"><!--
google_ad_client = "pub-8438729971248494";
/* 728x90, ������ 10-2-7 */
google_ad_slot = "4752526529";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<!-- End Alimama Adserver code -->
<br />
# RFC1918<br />
priv_nets = &#8220;{ 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 }&#8221;</p>
<p># Those wonderful scrubbing bubbles<br />
scrub in all</p>
<p># Filtering begins<br />
block log all</p>
<p># Local machine stuff<br />
pass quick on lo0 all<br />
pass in on $int_if from $int_if:network to any<br />
pass out on $int_if from any to $int_if:network<br />
block in  quick on $ext_if from $priv_nets to any<br />
block out quick on $ext_if from any to $priv_nets<br />
antispoof log for { $int_if, $ext_if } </p>
<p># Out to the internet<br />
pass out on $ext_if proto tcp all modulate state flags S/SA<br />
pass out on $ext_if proto { udp, icmp, esp } all keep state<br />
设置拨号时启动PF: vi /etc/ppp/ppp.linkup:<br />
MYADDR:<br />
 ! sh -c &#8220;/sbin/ifconfig pflog0 up&#8221;<br />
 ! sh -c &#8220;/sbin/pflogd&#8221;<br />
 ! sh -c &#8220;/sbin/pfctl -e -F all -f /etc/pf.conf&#8221;<br />
vi /etc/ppp/ppp.linkdown:<br />
MYADDR:<br />
 ! sh -c &#8220;/sbin/pfctl -d -F all&#8221;<br />
 ! sh -c &#8220;kill $(cat /var/run/pflogd.pid)&#8221;<br />
 ! sh -c &#8220;/sbin/ifconfig pflog0 down&#8221;<br />
 ! sh -c &#8220;/sbin/route delete default&#8221;<br />

<!-- Begin alimama Adserver code -->
<script type="text/javascript"><!--
google_ad_client = "pub-8438729971248494";
/* 728x90, ������ 10-2-7 */
google_ad_slot = "4752526529";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<!-- End Alimama Adserver code -->
</p>
]]></content:encoded>
			<wfw:commentRss>http://www.evanjiang.net.cn/archives/700.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Freebsd上使用pf防火墙</title>
		<link>http://www.evanjiang.net.cn/archives/263.html</link>
		<comments>http://www.evanjiang.net.cn/archives/263.html#comments</comments>
		<pubDate>Fri, 16 Jan 2009 17:42:30 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[freebsd unix]]></category>
		<category><![CDATA[pf]]></category>
		<category><![CDATA[Freebsd pf 防火墙]]></category>

		<guid isPermaLink="false">http://www.hunttech.com.cn/wpblog/?p=263</guid>
		<description><![CDATA[<p>要在 FreeBSD 6.2上使用 PF 防火牆，有二個方式，一個是編譯進入核心，另外是以動態模組方式載入。
編譯進入核心的方式
#FreeBSD log traffic，如果有使用 pflog，就要編譯進核心
device bpf
#啟動 PF Firewall
device pf#啟動虛擬網路設備來記錄流量(經由 bpf)
device pflog
#啟動虛擬網路設備來監視網路狀態
device pfsync</p>
<p>以動態模組載入
vi /etc/rc.conf加入下面四行
#啟用 PF
pf_enable=&#8221;YES&#8221;
#PF 防火牆規則的設定檔
pf_rules=&#8221;/etc/pf.conf&#8221;
#啟用 inetd 服務
inetd_enable=&#8221;YES&#8221;
#啟動 pflogd
pflog_enable=&#8221;YES&#8221;
#pflogd 儲存記錄檔案的地方
pflog_logfile=&#8221;/var/log/pflog&#8221;
#轉送封包
gateway_enable=&#8221;YES&#8221;
</p>
<p>#開啟 ftp-proxy 功能
vi /etc/inetd.conf把下面這一行最前面的 # 刪除
ftp-proxy stream tcp nowait root /usr/libexec/ftp-proxy ftp-proxy</p>
<p>使用 sysctl 做設定(也可以重新開機讓設定生效)
sysctl -w net.inet.ip.forwarding=1</p>
<p>vi /etc/pf.conf
#對外的網路卡
ext_if = &#8220;sis0&#8243;
#對內的網路卡
int_if = &#8220;rl0&#8243;
#頻寬控管
#定義 std_out 總頻寬 512Kb
#altq on $ext_if cbq bandwidth 512Kb queue { std_out }
#定義 std_out [...]]]></description>
			<content:encoded><![CDATA[<p>要在 FreeBSD 6.2上使用 PF 防火牆，有二個方式，一個是編譯進入核心，另外是以動態模組方式載入。<br />
編譯進入核心的方式<br />
#FreeBSD log traffic，如果有使用 pflog，就要編譯進核心<br />
device bpf<br />
#啟動 PF Firewall<br />
device pf#啟動虛擬網路設備來記錄流量(經由 bpf)<br />
device pflog<br />
#啟動虛擬網路設備來監視網路狀態<br />
device pfsync</p>
<p>以動態模組載入<br />
vi /etc/rc.conf加入下面四行<br />
#啟用 PF<br />
pf_enable=&#8221;YES&#8221;<br />
#PF 防火牆規則的設定檔<br />
pf_rules=&#8221;/etc/pf.conf&#8221;<br />
#啟用 inetd 服務<br />
inetd_enable=&#8221;YES&#8221;<br />
#啟動 pflogd<br />
pflog_enable=&#8221;YES&#8221;<br />
#pflogd 儲存記錄檔案的地方<br />
pflog_logfile=&#8221;/var/log/pflog&#8221;<br />
#轉送封包<br />
gateway_enable=&#8221;YES&#8221;<br />
<span id="more-263"></span></p>
<p>#開啟 ftp-proxy 功能<br />
vi /etc/inetd.conf把下面這一行最前面的 # 刪除<br />
ftp-proxy stream tcp nowait root /usr/libexec/ftp-proxy ftp-proxy</p>
<p>使用 sysctl 做設定(也可以重新開機讓設定生效)<br />
sysctl -w net.inet.ip.forwarding=1</p>
<p>vi /etc/pf.conf<br />
#對外的網路卡<br />
ext_if = &#8220;sis0&#8243;<br />
#對內的網路卡<br />
int_if = &#8220;rl0&#8243;<br />
#頻寬控管<br />
#定義 std_out 總頻寬 512Kb<br />
#altq on $ext_if cbq bandwidth 512Kb queue { std_out }<br />
#定義 std_out 佇列頻寬 256Kb，使用預設佇列<br />
#queue std_out bandwith 256Kb cbq (default)<br />
#定義 std_in 總頻寬 2Mb<br />
#altq on $int_if cbq bandwidth 2Mb queue { std_in }<br />
#假設頻寬足夠的話，可以從父佇列借用額外的頻寬<br />
#queue std_in bandwidth 768Kb cbq (brrrow)</p>
<p>#對外開放的服務<br />
open_services = &#8220;{80, 443}&#8221;<br />
#內部私有的 IP<br />
priv_nets = &#8220;{ 127.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, 10.0.0.0/8 }&#8221;<br />

<!-- Begin alimama Adserver code -->
<script type="text/javascript"><!--
google_ad_client = "pub-8438729971248494";
/* 728x90, ������ 10-2-7 */
google_ad_slot = "4752526529";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<!-- End Alimama Adserver code -->
<br />
# options<br />
#設定拒絕連線封包的處理方式<br />
set block-policy return<br />
#<br />
set optimization aggressive<br />
#紀錄 $ext_if<br />
set loginterface $ext_if</p>
<p># scrub<br />
#整理封包<br />
scrub in all</p>
<p>#nat<br />
#NAT 位址轉譯處理<br />
nat on $ext_if from $int_if:network to any -> $ext_if</p>
<p>#ftp-proxy<br />
#ftp-proxy 重新導向<br />
rdr on $int_if proto tcp from any to any port 21 -> 127.0.0.1 port 8021<br />
#rdr on $ext_if proto tcp from any to 140.111.152.13 port 21 -> 192.168.13.253 port 21<br />
#Transparent Proxy Server<br />
rdr on rl0 proto tcp from 192.168.13.0/24 to any 80 -> 127.0.0.1 port 3128</p>
<p>#阻擋可疑封包在 $ext_if 網卡進出<br />
antispoof log quick for $ext_if</p>
<p>#阻擋所有進出的封包<br />
block all</p>
<p>#開放 loopback<br />
pass quick on lo0 all</p>
<p>#拒絕內部私有 IP 對 $ext_if 網路卡連線<br />
block drop in quick on $ext_if from $priv_nets to any<br />
block drop out quick on $ext_if from any to $priv_nets</p>
<p>#開放對外的 80, 443 埠<br />
pass in on $ext_if inet proto tcp from any to $ext_if port $open_services flags S/SA keep state<br />
#只容許 140.111.152.0/24 網段對本機做 22 埠連線<br />
pass in on $ext_if inet proto tcp from 140.111.152.0/24 to $ext_if port 22 flags S/SA keep state</p>
<p>#開放內部網路對外連線<br />
#pass in on $inf_if proto rcp from any to any queue std_in<br />
pass in on $int_if from $int_if:network to any keep state<br />
pass out on $int_if from any to $int_if:network keep state</p>
<p>#開放對外網路的連線<br />
#pass out $ext_if proto tcp from any to any queue std_out<br />
pass out on $ext_if proto tcp all modulate state flags S/SA<br />
pass out on $ext_if proto { udp, icmp } all keep state</p>
<p>啟動 PF，並讀取 pf 規則<br />
pfctl -e;pfctl -f /etc/pf.conf</p>
<p>PF 指令的用法<br />
#啟動 PF<br />
pfctl -e<br />
#載入 PF 規則<br />
pfctl -f /etc/pf.conf<br />
#檢查 PF 語法是否正確 (未載入)<br />
pfctl -nf /etc/pf.conf<br />
#停用 PF<br />
pfctl -d<br />
#重讀 PF 設定檔中的 NAT 部分<br />
pfctl -f /etc/pf.conf -N<br />
#重讀 PF 設定檔中的 filter rules<br />
pfctl -f /etc/pf.conf -R<br />
#重讀 PF 設定檔中的選項規則<br />
pfctl -f /etc/pf.conf -O</p>
<p>#查看 PF 資訊<br />
#顯示現階段過濾封包的統計資料<br />
pfctl -s info<br />
pfctl -si</p>
<p>pfctl -s memory</p>
<p>#顯示現階段過濾的規則<br />
pfctl -s rules<br />
pfctl -sr</p>
<p>pfctl -vs rules<br />

<!-- Begin alimama Adserver code -->
<script type="text/javascript"><!--
google_ad_client = "pub-8438729971248494";
/* 728x90, ������ 10-2-7 */
google_ad_slot = "4752526529";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<!-- End Alimama Adserver code -->
<br />
#顯示現階段過濾封包的統計資料<br />
pfctl -vsr </p>
<p>#顯示現階段 NAT 的規則<br />
pfctl -s nat<br />
pfctl -sn</p>
<p>#檢視目前佇列<br />
pfctl -s queue</p>
<p>#顯示現階段所有統計的資料<br />
pfctl -s all<br />
pfctl -sa</p>
<p>#清除 PF 規則<br />
#清空 NAT 規則<br />
pfctl -F nat<br />
#清空佇列<br />
pfctl -F queue<br />
#清空封包過濾規則<br />
pfctl -F rules<br />
#清空計數器<br />
pfctl -F info<br />
pfctl -F Tables<br />
#清空所有的規則<br />
pfctl -F all</p>
<p>#PF Tables 的使用<br />
#顯示 table 內資料<br />
pfctl -t ssh-bruteforce -Tshow<br />
pfctl -t table_name -T add spammers.org<br />
pfctl -t table_name -T delete spammers.org<br />
pfctl -t table_name -T flush<br />
pfctl -t table_name -T show<br />
pfctl -t table_name -T zero</p>
<p>過濾掃描偵測軟體<br />
block in quick proto tcp all flags SF/SFRA<br />
block in quick proto tcp all flags SFUP/SFRAU<br />
block in quick proto tcp all flags FPU/SFRAUP<br />
block in quick proto tcp all flags /SFRA<br />
block in quick proto tcp all flags F/SFRA<br />
block in quick proto tcp all flags U/SFRAU<br />
block in quick proto tcp all flags P<br />
如果防火牆和 Proxy Server 不在同一台主機<br />
Proxy Server：192.168.13.250<br />
no rdr on rl0 proto tcp from 192.168.13.250 to any port 80<br />
rdr on rl0 proto tcp from 192.168.13.0/24 to any port 80 -> 192.168.13.250 port 3128</p>
]]></content:encoded>
			<wfw:commentRss>http://www.evanjiang.net.cn/archives/263.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>用pf防止ssh、ftp暴力攻击</title>
		<link>http://www.evanjiang.net.cn/archives/261.html</link>
		<comments>http://www.evanjiang.net.cn/archives/261.html#comments</comments>
		<pubDate>Fri, 16 Jan 2009 17:39:11 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[pf]]></category>
		<category><![CDATA[pf 防止ssh ftp 暴力攻击]]></category>

		<guid isPermaLink="false">http://www.hunttech.com.cn/wpblog/?p=261</guid>
		<description><![CDATA[<p>1.在/etc/pf.conf加入底下規則</p>
<p>table  persist
table  persist
block quick from 
block quick from 
pass quick inet proto tcp from any to any port 22 keep state (max-src-conn 5, max-src-conn-rate 3/20,overload  flush global)
pass quick inet proto tcp from any to any port ftp keep state (max-src-conn 5, max-src-conn-rate 10/40,overload  flush global)</p>
<p>
2.再寫個script去紀錄每天的狀況</p>

?View Code SHELL1
2
3
4
5
6
7
8
9
#!/bin/sh
log_file=&#34;/var/log/bad_guy.log&#34;
date &#62;&#62; $log_file
&#160;
echo &#34; FTP:&#34; [...]]]></description>
			<content:encoded><![CDATA[<p>1.在/etc/pf.conf加入底下規則</p>
<p>table <SSHbruteforce> persist<br />
table <FTPbruteforce> persist<br />
block quick from <SSHbruteforce><br />
block quick from <FTPbruteforce><br />
pass quick inet proto tcp from any to any port 22 keep state (max-src-conn 5, max-src-conn-rate 3/20,overload <SSHbruteforce> flush global)<br />
pass quick inet proto tcp from any to any port ftp keep state (max-src-conn 5, max-src-conn-rate 10/40,overload <FTPbruteforce> flush global)</p>
<p><span id="more-261"></span><br />
2.再寫個script去紀錄每天的狀況</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p261code2'); return false;">View Code</a> SHELL</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p2612"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code" id="p261code2"><pre class="shell" style="font-family:monospace;">#!/bin/sh
log_file=&quot;/var/log/bad_guy.log&quot;
date &gt;&gt; $log_file
&nbsp;
echo &quot; FTP:&quot; &gt;&gt; $log_file
/sbin/pfctl -t SSHbruteforce -T show &gt;&gt; $log_file
&nbsp;
echo &quot; SSH:&quot; &gt;&gt; $log_file
/sbin/pfctl -t FTPbruteforce -T show &gt;&gt; $log_file</pre></td></tr></table></div>

<p>3.阻擋一日後,即清除IP紀錄,先裝套件/usr/ports/security/expiretable<br />

<!-- Begin alimama Adserver code -->
<script type="text/javascript"><!--
google_ad_client = "pub-8438729971248494";
/* 728x90, ������ 10-2-7 */
google_ad_slot = "4752526529";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<!-- End Alimama Adserver code -->
<br />
# /usr/local/sbin/expiretable -v -d -t 24h SSHbruteforce<br />
# /usr/local/sbin/expiretable -v -d -t 24h FTPbruteforce</p>
<p>並把設定加入rc.local</p>
]]></content:encoded>
			<wfw:commentRss>http://www.evanjiang.net.cn/archives/261.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
